Completed
Push — add/identity-crisis-package ( 18e8d1...15af76 )
by
unknown
176:45 queued 166:13
created

Base_Admin_Menu::set_menu_item()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
1
<?php
2
/**
3
 * Base Admin Menu file.
4
 *
5
 * @package automattic/jetpack
6
 */
7
8
namespace Automattic\Jetpack\Dashboard_Customizations;
9
10
use Automattic\Jetpack\Status;
11
12
/**
13
 * Class Base_Admin_Menu
14
 */
15
abstract class Base_Admin_Menu {
16
	/**
17
	 * Holds class instances.
18
	 *
19
	 * @var array
20
	 */
21
	protected static $instances;
22
23
	/**
24
	 * Whether the current request is a REST API request.
25
	 *
26
	 * @var bool
27
	 */
28
	protected $is_api_request = false;
29
30
	/**
31
	 * Domain of the current site.
32
	 *
33
	 * @var string
34
	 */
35
	protected $domain;
36
37
	/**
38
	 * The CSS classes used to hide the submenu items in navigation.
39
	 *
40
	 * @var string
41
	 */
42
	const HIDE_CSS_CLASS = 'hide-if-js';
43
44
	/**
45
	 * Base_Admin_Menu constructor.
46
	 */
47
	protected function __construct() {
48
		add_action( 'admin_menu', array( $this, 'set_is_api_request' ), 99997 );
49
		add_action( 'admin_menu', array( $this, 'reregister_menu_items' ), 99998 );
50
		add_filter( 'admin_menu', array( $this, 'override_svg_icons' ), 99999 );
51
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
52
		add_action( 'admin_head', array( $this, 'set_site_icon_inline_styles' ) );
53
		add_filter( 'rest_request_before_callbacks', array( $this, 'rest_api_init' ), 11 );
54
55
		$this->domain = ( new Status() )->get_site_suffix();
56
	}
57
58
	/**
59
	 * Determine if the current request is from API
60
	 */
61
	public function set_is_api_request() {
62
		// Constant is not defined until parse_request.
63
		if ( ! $this->is_api_request ) {
64
			$this->is_api_request = defined( 'REST_REQUEST' ) && REST_REQUEST;
65
		}
66
	}
67
68
	/**
69
	 * Returns class instance.
70
	 *
71
	 * @return Admin_Menu
72
	 */
73
	public static function get_instance() {
74
		$class = get_called_class();
75
76
		if ( empty( static::$instances[ $class ] ) ) {
77
			static::$instances[ $class ] = new $class();
78
		}
79
80
		return static::$instances[ $class ];
81
	}
82
83
	/**
84
	 * Sets up class properties for REST API requests.
85
	 *
86
	 * @param \WP_REST_Response $response Response from the endpoint.
87
	 */
88
	public function rest_api_init( $response ) {
89
		$this->is_api_request = true;
90
91
		return $response;
92
	}
93
94
	/**
95
	 * Updates the menu data of the given menu slug.
96
	 *
97
	 * @param string $slug Slug of the menu to update.
98
	 * @param string $url New menu URL.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $url not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
99
	 * @param string $title New menu title.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $title not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
100
	 * @param string $cap New menu capability.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cap not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
101
	 * @param string $icon New menu icon.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $icon not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
102
	 * @param int    $position New menu position.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $position not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
103
	 * @return bool Whether the menu has been updated.
104
	 */
105
	public function update_menu( $slug, $url = null, $title = null, $cap = null, $icon = null, $position = null ) {
106
		global $menu, $submenu;
107
108
		$menu_item     = null;
109
		$menu_position = null;
110
111
		foreach ( $menu as $i => $item ) {
112
			if ( $slug === $item[2] ) {
113
				$menu_item     = $item;
114
				$menu_position = $i;
115
				break;
116
			}
117
		}
118
119
		if ( ! $menu_item ) {
120
			return false;
121
		}
122
123
		if ( $title ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $title of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
124
			$menu_item[0] = $title;
125
			$menu_item[3] = esc_attr( $title );
126
		}
127
128
		if ( $cap ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cap of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
129
			$menu_item[1] = $cap;
130
		}
131
132
		// Change parent slug only if there are no submenus (the slug of the 1st submenu will be used if there are submenus).
133
		if ( $url ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
134
			$this->hide_submenu_page( $slug, $slug );
135
136
			if ( ! isset( $submenu[ $slug ] ) || ! $this->has_visible_items( $submenu[ $slug ] ) ) {
137
				$menu_item[2] = $url;
138
			}
139
		}
140
141
		if ( $icon ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $icon of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
142
			$menu_item[4] = 'menu-top';
143
			$menu_item[6] = $icon;
144
		}
145
146
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
147
		unset( $menu[ $menu_position ] );
148
		if ( $position ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $position of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
149
			$menu_position = $position;
150
		}
151
		$this->set_menu_item( $menu_item, $menu_position );
152
153
		// Only add submenu when there are other submenu items.
154
		if ( $url && isset( $submenu[ $slug ] ) && $this->has_visible_items( $submenu[ $slug ] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
155
			add_submenu_page( $slug, $menu_item[3], $menu_item[0], $menu_item[1], $url, null, 0 );
156
		}
157
158
		return true;
159
	}
160
161
	/**
162
	 * Updates the submenus of the given menu slug.
163
	 *
164
	 * It hides the menu by adding the `hide-if-js` css class and duplicates the submenu with the new slug.
165
	 *
166
	 * @param string $slug Menu slug.
167
	 * @param array  $submenus_to_update Array of new submenu slugs.
168
	 */
169
	public function update_submenus( $slug, $submenus_to_update ) {
170
		global $submenu;
171
172
		if ( ! isset( $submenu[ $slug ] ) ) {
173
			return;
174
		}
175
176
		// This is needed for cases when the submenus to update have the same new slug.
177
		$submenus_to_update = array_filter(
178
			$submenus_to_update,
179
			static function ( $item, $old_slug ) {
180
				return $item !== $old_slug;
181
			},
182
			ARRAY_FILTER_USE_BOTH
183
		);
184
185
		/**
186
		 * Iterate over all submenu items and add the hide the submenus with CSS classes.
187
		 * This is done separately of the second foreach because the position of the submenu might change.
188
		 */
189
		foreach ( $submenu[ $slug ] as $index => $item ) {
190
			if ( ! array_key_exists( $item[2], $submenus_to_update ) ) {
191
				continue;
192
			}
193
194
			$this->hide_submenu_element( $index, $slug, $item );
195
		}
196
197
		$submenu_items = array_values( $submenu[ $slug ] );
198
199
		/**
200
		 * Iterate again over the submenu array. We need a copy of the array because add_submenu_page will add new elements
201
		 * to submenu array that might cause an infinite loop.
202
		 */
203
		foreach ( $submenu_items as $i => $submenu_item ) {
204
			if ( ! array_key_exists( $submenu_item[2], $submenus_to_update ) ) {
205
				continue;
206
			}
207
208
			add_submenu_page(
209
				$slug,
210
				isset( $submenu_item[3] ) ? $submenu_item[3] : '',
211
				isset( $submenu_item[0] ) ? $submenu_item[0] : '',
212
				isset( $submenu_item[1] ) ? $submenu_item[1] : 'read',
213
				$submenus_to_update[ $submenu_item[2] ],
214
				'',
215
				$i
216
			);
217
		}
218
	}
219
220
	/**
221
	 * Adds a menu separator.
222
	 *
223
	 * @param int    $position The position in the menu order this item should appear.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $position not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
224
	 * @param string $cap Optional. The capability required for this menu to be displayed to the user.
225
	 *                         Default: 'read'.
226
	 */
227
	public function add_admin_menu_separator( $position = null, $cap = 'read' ) {
228
		$menu_item = array(
229
			'',                                  // Menu title (ignored).
230
			$cap,                                // Required capability.
231
			wp_unique_id( 'separator-custom-' ), // URL or file (ignored, but must be unique).
232
			'',                                  // Page title (ignored).
233
			'wp-menu-separator',                 // CSS class. Identifies this item as a separator.
234
		);
235
236
		$this->set_menu_item( $menu_item, $position );
237
	}
238
239
	/**
240
	 * Enqueues scripts and styles.
241
	 */
242
	public function enqueue_scripts() {
243
		$is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM;
244
245
		if ( $this->is_rtl() ) {
246
			if ( $is_wpcom ) {
247
				$css_path = 'rtl/admin-menu-rtl.css';
248
			} else {
249
				$css_path = 'admin-menu-rtl.css';
250
			}
251
		} else {
252
			$css_path = 'admin-menu.css';
253
		}
254
255
		wp_enqueue_style(
256
			'jetpack-admin-menu',
257
			plugins_url( $css_path, __FILE__ ),
258
			array(),
259
			JETPACK__VERSION
260
		);
261
262
		wp_style_add_data( 'jetpack-admin-menu', 'rtl', $this->is_rtl() );
263
		$this->configure_colors_for_rtl_stylesheets();
264
265
		wp_enqueue_script(
266
			'jetpack-admin-menu',
267
			plugins_url( 'admin-menu.js', __FILE__ ),
268
			array(),
269
			JETPACK__VERSION,
270
			true
271
		);
272
	}
273
274
	/**
275
	 * Mark the core colors stylesheets as RTL depending on the value from the environment.
276
	 * This fixes a core issue where the extra RTL data is not added to the colors stylesheet.
277
	 * https://core.trac.wordpress.org/ticket/53090
278
	 */
279
	public function configure_colors_for_rtl_stylesheets() {
280
		wp_style_add_data( 'colors', 'rtl', $this->is_rtl() );
281
	}
282
283
	/**
284
	 * Injects inline-styles for site icon for when third-party plugins remove enqueued stylesheets.
285
	 * Unable to use wp_add_inline_style as plugins remove styles from all non-standard handles
286
	 */
287
	public function set_site_icon_inline_styles() {
288
		echo '<style>
289
			#adminmenu .toplevel_page_site-card .wp-menu-image,
290
			#adminmenu .toplevel_page_site-card .wp-menu-image img {
291
				height: 32px;
292
				width: 32px;
293
			}
294
		</style>';
295
	}
296
297
	/**
298
	 * Hide the submenu page based on slug and return the item that was hidden.
299
	 *
300
	 * Instead of actually removing the submenu item, a safer approach is to hide it and filter it in the API response.
301
	 * In this manner we'll avoid breaking third-party plugins depending on items that no longer exist.
302
	 *
303
	 * A false|array value is returned to be consistent with remove_submenu_page() function
304
	 *
305
	 * @param string $menu_slug The parent menu slug.
306
	 * @param string $submenu_slug The submenu slug that should be hidden.
307
	 * @return false|array
308
	 */
309
	public function hide_submenu_page( $menu_slug, $submenu_slug ) {
310
		global $submenu;
311
312
		if ( ! isset( $submenu[ $menu_slug ] ) ) {
313
			return false;
314
		}
315
316
		foreach ( $submenu[ $menu_slug ] as $i => $item ) {
317
			if ( $submenu_slug !== $item[2] ) {
318
				continue;
319
			}
320
321
			$this->hide_submenu_element( $i, $menu_slug, $item );
322
323
			return $item;
324
		}
325
326
		return false;
327
	}
328
329
	/**
330
	 * Apply the hide-if-js CSS class to a submenu item.
331
	 *
332
	 * @param int    $index The position of a submenu item in the submenu array.
333
	 * @param string $parent_slug The parent slug.
334
	 * @param array  $item The submenu item.
335
	 */
336
	public function hide_submenu_element( $index, $parent_slug, $item ) {
337
		global $submenu;
338
339
		$css_classes = empty( $item[4] ) ? self::HIDE_CSS_CLASS : $item[4] . ' ' . self::HIDE_CSS_CLASS;
340
341
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
342
		$submenu [ $parent_slug ][ $index ][4] = $css_classes;
343
	}
344
345
	/**
346
	 * Check if the menu has submenu items visible
347
	 *
348
	 * @param array $submenu_items The submenu items.
349
	 * @return bool
350
	 */
351
	public function has_visible_items( $submenu_items ) {
352
		$visible_items = array_filter(
353
			$submenu_items,
354
			static function ( $item ) {
355
				return empty( $item[4] ) || strpos( $item[4], self::HIDE_CSS_CLASS ) === false;
356
			}
357
		);
358
359
		return array() !== $visible_items;
360
	}
361
362
	/**
363
	 * Return the number of existing submenu items under the supplied parent slug.
364
	 *
365
	 * @param string $parent_slug The slug of the parent menu.
366
	 * @return int The number of submenu items under $parent_slug.
367
	 */
368
	public function get_submenu_item_count( $parent_slug ) {
369
		global $submenu;
370
371
		if ( empty( $parent_slug ) || empty( $submenu[ $parent_slug ] ) || ! is_array( $submenu[ $parent_slug ] ) ) {
372
			return 0;
373
		}
374
375
		return count( $submenu[ $parent_slug ] );
376
	}
377
378
	/**
379
	 * Adds the given menu item in the specified position.
380
	 *
381
	 * @param array $item The menu item to add.
382
	 * @param int   $position The position in the menu order this item should appear.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $position not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
383
	 */
384
	public function set_menu_item( $item, $position = null ) {
385
		global $menu;
386
387
		// Handle position (avoids overwriting menu items already populated in the given position).
388
		// Inspired by https://core.trac.wordpress.org/browser/trunk/src/wp-admin/menu.php?rev=49837#L160.
389
		if ( null === $position ) {
390
			$menu[] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
391
		} elseif ( isset( $menu[ "$position" ] ) ) {
392
			$position            = $position + substr( base_convert( md5( $item[2] . $item[0] ), 16, 10 ), -5 ) * 0.00001;
393
			$menu[ "$position" ] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
394
		} else {
395
			$menu[ $position ] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
396
		}
397
	}
398
399
	/**
400
	 * Determines whether the current locale is right-to-left (RTL).
401
	 */
402
	public function is_rtl() {
403
		return is_rtl();
404
	}
405
406
	/**
407
	 * Checks for any SVG icons in the menu, and overrides things so that
408
	 * we can display the icon in the correct colour for the theme.
409
	 */
410
	public function override_svg_icons() {
411
		global $menu;
412
413
		// Only do this if we're not in an API request, as we override the $menu global.
414
		if ( $this->is_api_request ) {
415
			return;
416
		}
417
418
		$svg_items = array();
419
		foreach ( $menu as $idx => $menu_item ) {
420
			// Menu items that don't have icons, for example separators, have less than 7
421
			// elements, partly because the 7th is the icon. So, if we have less than 7,
422
			// let's skip it.
423
			if ( count( $menu_item ) < 7 ) {
424
				continue;
425
			}
426
427
			// If the hookname contain a URL than sanitize it by replacing invalid characters.
428
			if ( false !== strpos( $menu_item[5], '://' ) ) {
429
				$menu_item[5] = preg_replace( '![:/.]+!', '_', $menu_item[5] );
430
			}
431
432
			if ( 0 === strpos( $menu_item[6], 'data:image/svg+xml' ) && 'site-card' !== $menu_item[3] ) {
433
				$svg_items[]   = array(
434
					'icon' => $menu_item[6],
435
					'id'   => $menu_item[5],
436
				);
437
				$menu_item[4] .= ' menu-svg-icon';
438
				$menu_item[6]  = 'none';
439
			}
440
			// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
441
			$menu[ $idx ] = $menu_item;
442
		}
443
		if ( count( $svg_items ) > 0 ) {
444
			$styles = '.menu-svg-icon .wp-menu-image { background-repeat: no-repeat; background-position: center center } ';
445
			foreach ( $svg_items as $svg_item ) {
446
				$styles .= sprintf( '#%s .wp-menu-image { background-image: url( "%s" ) }', $svg_item['id'], $svg_item['icon'] );
447
			}
448
			$styles .= '@supports ( mask-image: none ) or ( -webkit-mask-image: none ) { ';
449
			$styles .= '.menu-svg-icon .wp-menu-image { background-image: none; } ';
450
			$styles .= '.menu-svg-icon .wp-menu-image::before { background-color: currentColor; ';
451
			$styles .= 'mask-size: contain; mask-position: center center; mask-repeat: no-repeat; ';
452
			$styles .= '-webkit-mask-size: contain; -webkit-mask-position: center center; -webkit-mask-repeat: no-repeat; content:"" } ';
453
			foreach ( $svg_items as $svg_item ) {
454
				$styles .= sprintf(
455
					'#%s .wp-menu-image { background-image: none; } #%s .wp-menu-image::before{ mask-image: url( "%s" ); -webkit-mask-image: url( "%s" ) }',
456
					$svg_item['id'],
457
					$svg_item['id'],
458
					$svg_item['icon'],
459
					$svg_item['icon']
460
				);
461
			}
462
			$styles .= '}';
463
464
			wp_register_style( 'svg-menu-overrides', false, array(), '20210331' );
465
			wp_enqueue_style( 'svg-menu-overrides' );
466
			wp_add_inline_style( 'svg-menu-overrides', $styles );
467
		}
468
	}
469
470
	/**
471
	 * Whether to use wp-admin pages rather than Calypso.
472
	 *
473
	 * Options:
474
	 * false - Calypso (Default).
475
	 * true  - wp-admin.
476
	 *
477
	 * @return bool
478
	 */
479
	abstract public function should_link_to_wp_admin();
480
481
	/**
482
	 * Create the desired menu output.
483
	 */
484
	abstract public function reregister_menu_items();
485
}
486