wsNewMenuHighlighter.php
9.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php
class wsNewMenuHighlighter {
const ITEM_SLUG_INDEX = 2;
const ITEM_TITLE_INDEX = 0;
const ITEM_CLASS_INDEX = 4;
const STORAGE_KEY = 'ws_nmh_seen_menus';
const AJAX_FLAG_ACTION = 'nmh-flag-as-seen';
const COOKIE_NAME = 'ws_nmh_pending_seen_urls';
const MAX_URLS_PER_USER = 700;
const MAX_URLS_PER_REQUEST = 100;
const MAX_URL_LENGTH = 512;
static $blacklist = array(
//These items are invisible when the theme customizer is available.
'themes.php?page=custom-header' => true,
'themes.php?page=custom-background' => true,
//Files in /wp-admin.
'customize.php' => true,
'edit-comments.php' => true,
'edit-tags.php' => true,
'edit.php' => true,
'export.php' => true,
'import.php' => true,
'index.php' => true,
'link-add.php' => true,
'link-manager.php' => true,
'media-new.php' => true,
'nav-menus.php' => true,
'options-discussion.php' => true,
'options-general.php' => true,
'options-media.php' => true,
'options-permalink.php' => true,
'options-reading.php' => true,
'options-writing.php' => true,
'plugin-editor.php' => true,
'plugin-install.php' => true,
'plugins.php' => true,
'post-new.php' => true,
'profile.php' => true,
'privacy.php' => true,
'site-health.php' => true,
'theme-editor.php' => true,
'themes.php' => true,
'tools.php' => true,
'update-core.php' => true,
'upload.php' => true,
'user-new.php' => true,
'users.php' => true,
'widgets.php' => true,
//Network admin items.
'settings.php' => true,
'site-new.php' => true,
'sites.php' => true,
'theme-install.php' => true,
'upgrade.php' => true,
//Hidden ACF menu. It's used to show the "Welcome to Advanced Custom Fields" page.
'edit.php?post_type=acf-field-group&page=acf-settings-info' => true,
);
private $menusWithNewSubmenus = array();
private $seenMenuUrls = array();
private $isFirstRun = false;
public function __construct() {
//Run after AME replaces the menu so that we don't pollute the menu editor with our flags and classes.
if ( class_exists('WPMenuEditor', false) ) {
add_action('admin_menu_editor-menu_replaced', array($this, 'parseAdminMenu'));
add_action('admin_menu_editor-menu_replacement_skipped', array($this, 'parseAdminMenu'));
} else {
add_action('admin_menu', array($this, 'parseAdminMenu'), 9000);
}
add_action('admin_enqueue_scripts', array($this, 'enqueueDependencies'));
add_action('wp_ajax_' . self::AJAX_FLAG_ACTION, array($this, 'ajaxFlagAsSeen'));
add_action('admin_init', array($this, 'flagUrlsFromCookie'));
}
public function parseAdminMenu() {
if ( !current_user_can('activate_plugins') ) {
return;
}
global $menu, $submenu;
$this->seenMenuUrls = $this->loadSeenMenus();
if ( empty($this->seenMenuUrls) ) {
$this->isFirstRun = true;
}
foreach ($submenu as $parent => &$items) {
foreach ($items as &$submenuItem) {
$submenuItem = $this->processItem($submenuItem, $parent);
}
}
unset($items, $submenuItem);
foreach ($menu as &$item) {
$item = $this->processItem($item);
}
if ( $this->isFirstRun ) {
$urls = array_keys($this->seenMenuUrls);
$this->seenMenuUrls = array();
$this->flagAsSeen($urls, true);
}
}
private function loadSeenMenus() {
$seenMenuUrls = get_user_meta(get_current_user_id(), self::STORAGE_KEY, true);
if ( !is_array($seenMenuUrls) ) {
$seenMenuUrls = array();
}
return $seenMenuUrls;
}
private function processItem($item, $parentSlug = null) {
if ( $this->isIgnoredItem($item) ) {
return $item;
}
$itemSlug = $item[self::ITEM_SLUG_INDEX];
$url = $this->getMenuUrl($itemSlug, $parentSlug);
$isBlacklisted = empty($url) || isset(self::$blacklist[$url]);
//On first run, just collect all items and flag them as seen.
if ( $this->isFirstRun ) {
if ( !$isBlacklisted ) {
$this->seenMenuUrls[$url] = true;
}
return $item;
}
if ( ($this->isNewMenu($url) && !$isBlacklisted) || $this->hasNewSubmenus($itemSlug) ) {
$item[self::ITEM_TITLE_INDEX] .= sprintf(
'<span class="ws-nmh-new-menu-flag" data-nmh-menu-url="%s"></span>',
esc_attr($url)
);
if ( ($parentSlug === null) && isset($item[self::ITEM_CLASS_INDEX]) ) {
$item[self::ITEM_CLASS_INDEX] .= ' ws-nmh-is-new-menu';
}
if ( $parentSlug !== null ) {
$this->menusWithNewSubmenus[$parentSlug] = true;
}
}
return $item;
}
private function getMenuUrl($itemSlug, $parentSlug) {
if ( class_exists('ameMenuItem') ) {
return ameMenuItem::generate_url($itemSlug, $parentSlug);
} else {
return $itemSlug;
}
}
private function isIgnoredItem($item) {
if ( !isset($item[self::ITEM_SLUG_INDEX]) ) {
return true; //That's either an invalid item or an improvised separator.
}
//Skip separators and unnamed menus.
$isSeparator = isset($item[self::ITEM_CLASS_INDEX])
&& (strpos($item[self::ITEM_CLASS_INDEX], 'wp-menu-separator') !== false);
if ( $isSeparator || empty($item[self::ITEM_SLUG_INDEX]) || ($item[self::ITEM_TITLE_INDEX] === '') ) {
return true;
}
//Skip customizer links. They have a different URL on every admin page, so they'd always show up as new.
if ( strpos($item[self::ITEM_SLUG_INDEX], 'customize.php') === 0 ) {
return true;
}
return false;
}
private function isNewMenu($url) {
return empty($this->seenMenuUrls[$url]);
}
private function hasNewSubmenus($slug) {
return !empty($this->menusWithNewSubmenus[$slug]);
}
public function enqueueDependencies() {
$dependencies = array('jquery');
if ( isset($GLOBALS['wp_menu_editor']) && is_callable(array(
$GLOBALS['wp_menu_editor'],
'register_jquery_plugins',
))
) {
$GLOBALS['wp_menu_editor']->register_jquery_plugins();
$dependencies[] = 'ame-jquery-cookie';
}
wp_enqueue_script(
'ws-nmh-admin-script',
plugins_url('assets/highlight-menus.js', __FILE__),
$dependencies,
'20191111'
);
wp_localize_script(
'ws-nmh-admin-script',
'wsNmhData',
array(
'flagAction' => self::AJAX_FLAG_ACTION,
'flagNonce' => wp_create_nonce(self::AJAX_FLAG_ACTION),
)
);
wp_enqueue_style(
'ws-nmh-admin-style',
plugins_url('assets/menu-highlights.css', __FILE__),
array(),
'20170503'
);
}
public function ajaxFlagAsSeen() {
check_ajax_referer(self::AJAX_FLAG_ACTION);
if ( empty($_POST['urls']) ) {
if ( function_exists('status_header') ) {
status_header(400);
}
exit('Error: The required "urls" parameter is missing.');
}
//JSON decoding will reject severely malformed data, and flagAsSeen() will
//further validate the input.
//phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$json = strval($_POST['urls']);
//Unfortunately, WP applies magic quotes to POST data.
if ( function_exists('wp_magic_quotes') && did_action('plugins_loaded') ) {
$json = stripslashes($json);
}
if ( $this->flagAsSeen(json_decode($json)) ) {
exit('Success');
} else {
exit('Failure');
}
}
public function flagUrlsFromCookie() {
if ( !is_user_logged_in() || empty($_COOKIE[self::COOKIE_NAME]) || defined('DOING_AJAX') ) {
return;
}
//As above, flagAsSeen() does some validation.
//phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$urls = json_decode(stripslashes($_COOKIE[self::COOKIE_NAME]), true);
if ( is_array($urls) ) {
$this->flagAsSeen(array_keys($urls));
}
if ( version_compare(phpversion(), '7.3', '>=') ) {
setcookie(self::COOKIE_NAME, '', array('expires' => time() - (24 * 3600), 'samesite' => 'Lax'));
} else {
setcookie(self::COOKIE_NAME, '', time() - (24 * 3600), '', '', is_ssl());
}
}
private function flagAsSeen($menuUrls, $isInternalCall = false) {
if ( empty($menuUrls) || !is_array($menuUrls) ) {
return false;
}
//Reduce the risk of DoS attacks by limiting the number of URLs per request.
if ( !$isInternalCall && (count($menuUrls) > self::MAX_URLS_PER_REQUEST) ) {
return false;
}
$menuUrls = array_filter($menuUrls, array($this, 'couldBeMenuUrl'));
$this->seenMenuUrls = $this->loadSeenMenus();
//Optimization: Save only if there are changes / new URLs.
$urlIndex = array_fill_keys($menuUrls, true);
$newUrls = array_diff_key($urlIndex, $this->seenMenuUrls);
if ( !empty($newUrls) ) {
$this->seenMenuUrls = array_merge($this->seenMenuUrls, $urlIndex);
//To avoid creating huge user meta rows, let's save only the most recent URLs.
if ( count($this->seenMenuUrls) > self::MAX_URLS_PER_USER ) {
$this->seenMenuUrls = array_slice(
$this->seenMenuUrls,
-self::MAX_URLS_PER_USER,
self::MAX_URLS_PER_USER,
true
);
}
return update_user_meta(get_current_user_id(), self::STORAGE_KEY, $this->seenMenuUrls);
} else {
return false;
}
}
private function couldBeMenuUrl($input) {
if ( !is_string($input) || ($input === '') ) {
return false;
}
$input = wp_check_invalid_utf8($input);
if ( !$input ) {
return false;
}
//Admin menu URLs are not necessarily fully qualified, or even valid
//URLs. Some plugins use weird hacks. Let's just verify that the "URL"
//is not too huge.
return (strlen($input) < self::MAX_URL_LENGTH);
}
}