Completed
Push — add/e2e-test-to-jetpack-assist... ( 225db1...26968f )
by
unknown
10:28
created

Base_Admin_Menu::override_svg_icons()   B

Complexity

Conditions 9
Paths 16

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 16
nop 0
dl 0
loc 47
rs 7.6008
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
	 * Base_Admin_Menu constructor.
39
	 */
40
	protected function __construct() {
41
		add_action( 'admin_menu', array( $this, 'set_is_api_request' ), 99997 );
42
		add_action( 'admin_menu', array( $this, 'reregister_menu_items' ), 99998 );
43
		add_filter( 'admin_menu', array( $this, 'override_svg_icons' ), 99999 );
44
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
45
		add_action( 'admin_head', array( $this, 'set_site_icon_inline_styles' ) );
46
		add_filter( 'rest_request_before_callbacks', array( $this, 'rest_api_init' ), 11 );
47
48
		$this->domain = ( new Status() )->get_site_suffix();
49
	}
50
51
	/**
52
	 * Determine if the current request is from API
53
	 */
54
	public function set_is_api_request() {
55
		// Constant is not defined until parse_request.
56
		if ( ! $this->is_api_request ) {
57
			$this->is_api_request = defined( 'REST_REQUEST' ) && REST_REQUEST;
58
		}
59
	}
60
61
	/**
62
	 * Returns class instance.
63
	 *
64
	 * @return Admin_Menu
65
	 */
66
	public static function get_instance() {
67
		$class = get_called_class();
68
69
		if ( empty( static::$instances[ $class ] ) ) {
70
			static::$instances[ $class ] = new $class();
71
		}
72
73
		return static::$instances[ $class ];
74
	}
75
76
	/**
77
	 * Sets up class properties for REST API requests.
78
	 *
79
	 * @param \WP_REST_Response $response Response from the endpoint.
80
	 */
81
	public function rest_api_init( $response ) {
82
		$this->is_api_request = true;
83
84
		return $response;
85
	}
86
87
	/**
88
	 * Updates the menu data of the given menu slug.
89
	 *
90
	 * @param string $slug Slug of the menu to update.
91
	 * @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...
92
	 * @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...
93
	 * @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...
94
	 * @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...
95
	 * @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...
96
	 * @return bool Whether the menu has been updated.
97
	 */
98
	public function update_menu( $slug, $url = null, $title = null, $cap = null, $icon = null, $position = null ) {
99
		global $menu, $submenu;
100
101
		$menu_item     = null;
102
		$menu_position = null;
103
104
		foreach ( $menu as $i => $item ) {
105
			if ( $slug === $item[2] ) {
106
				$menu_item     = $item;
107
				$menu_position = $i;
108
				break;
109
			}
110
		}
111
112
		if ( ! $menu_item ) {
113
			return false;
114
		}
115
116
		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...
117
			$menu_item[0] = $title;
118
			$menu_item[3] = esc_attr( $title );
119
		}
120
121
		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...
122
			$menu_item[1] = $cap;
123
		}
124
125
		// Change parent slug only if there are no submenus (the slug of the 1st submenu will be used if there are submenus).
126
		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...
127
			remove_submenu_page( $slug, $slug );
128
			if ( empty( $submenu[ $slug ] ) ) {
129
				$menu_item[2] = $url;
130
			}
131
		}
132
133
		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...
134
			$menu_item[4] = 'menu-top';
135
			$menu_item[6] = $icon;
136
		}
137
138
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
139
		unset( $menu[ $menu_position ] );
140
		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...
141
			$menu_position = $position;
142
		}
143
		$this->set_menu_item( $menu_item, $menu_position );
144
145
		// Only add submenu when there are other submenu items.
146
		if ( $url && ! empty( $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...
147
			add_submenu_page( $slug, $menu_item[3], $menu_item[0], $menu_item[1], $url, null, 0 );
148
		}
149
150
		return true;
151
	}
152
153
	/**
154
	 * Updates the submenus of the given menu slug.
155
	 *
156
	 * @param string $slug Menu slug.
157
	 * @param array  $submenus_to_update Array of new submenu slugs.
158
	 */
159
	public function update_submenus( $slug, $submenus_to_update ) {
160
		global $submenu;
161
162
		if ( ! isset( $submenu[ $slug ] ) ) {
163
			return;
164
		}
165
166
		foreach ( $submenu[ $slug ] as $i => $submenu_item ) {
167
			if ( array_key_exists( $submenu_item[2], $submenus_to_update ) ) {
168
				$submenu_item[2] = $submenus_to_update[ $submenu_item[2] ];
169
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
170
				$submenu[ $slug ][ $i ] = $submenu_item;
171
			}
172
		}
173
	}
174
175
	/**
176
	 * Adds a menu separator.
177
	 *
178
	 * @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...
179
	 * @param string $cap Optional. The capability required for this menu to be displayed to the user.
180
	 *                         Default: 'read'.
181
	 */
182
	public function add_admin_menu_separator( $position = null, $cap = 'read' ) {
183
		$menu_item = array(
184
			'',                                  // Menu title (ignored).
185
			$cap,                                // Required capability.
186
			wp_unique_id( 'separator-custom-' ), // URL or file (ignored, but must be unique).
187
			'',                                  // Page title (ignored).
188
			'wp-menu-separator',                 // CSS class. Identifies this item as a separator.
189
		);
190
191
		$this->set_menu_item( $menu_item, $position );
192
	}
193
194
	/**
195
	 * Enqueues scripts and styles.
196
	 */
197
	public function enqueue_scripts() {
198
		$is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM;
199
200
		if ( $this->is_rtl() ) {
201
			if ( $is_wpcom ) {
202
				$css_path = 'rtl/admin-menu-rtl.css';
203
			} else {
204
				$css_path = 'admin-menu-rtl.css';
205
			}
206
		} else {
207
			$css_path = 'admin-menu.css';
208
		}
209
210
		wp_enqueue_style(
211
			'jetpack-admin-menu',
212
			plugins_url( $css_path, __FILE__ ),
213
			array(),
214
			JETPACK__VERSION
215
		);
216
217
		wp_enqueue_script(
218
			'jetpack-admin-menu',
219
			plugins_url( 'admin-menu.js', __FILE__ ),
220
			array(),
221
			JETPACK__VERSION,
222
			true
223
		);
224
	}
225
226
	/**
227
	 * Injects inline-styles for site icon for when third-party plugins remove enqueued stylesheets.
228
	 * Unable to use wp_add_inline_style as plugins remove styles from all non-standard handles
229
	 */
230
	public function set_site_icon_inline_styles() {
231
		echo '<style>
232
			#adminmenu .toplevel_page_site-card .wp-menu-image,
233
			#adminmenu .toplevel_page_site-card .wp-menu-image img {
234
				height: 32px;
235
				width: 32px;
236
			}
237
		</style>';
238
	}
239
240
	/**
241
	 * Adds the given menu item in the specified position.
242
	 *
243
	 * @param array $item The menu item to add.
244
	 * @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...
245
	 */
246
	public function set_menu_item( $item, $position = null ) {
247
		global $menu;
248
249
		// Handle position (avoids overwriting menu items already populated in the given position).
250
		// Inspired by https://core.trac.wordpress.org/browser/trunk/src/wp-admin/menu.php?rev=49837#L160.
251
		if ( null === $position ) {
252
			$menu[] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
253
		} elseif ( isset( $menu[ "$position" ] ) ) {
254
			$position            = $position + substr( base_convert( md5( $item[2] . $item[0] ), 16, 10 ), -5 ) * 0.00001;
255
			$menu[ "$position" ] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
256
		} else {
257
			$menu[ $position ] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
258
		}
259
	}
260
261
	/**
262
	 * Determines whether the current locale is right-to-left (RTL).
263
	 */
264
	public function is_rtl() {
265
		return is_rtl();
266
	}
267
268
	/**
269
	 * Checks for any SVG icons in the menu, and overrides things so that
270
	 * we can display the icon in the correct colour for the theme.
271
	 */
272
	public function override_svg_icons() {
273
		global $menu;
274
275
		// Only do this if we're not in an API request, as we override the $menu global.
276
		if ( $this->is_api_request ) {
277
			return;
278
		}
279
280
		$svg_items = array();
281
		foreach ( $menu as $idx => $menu_item ) {
282
			if ( count( $menu_item ) > 6 && 0 === strpos( $menu_item[6], 'data:image/svg+xml' ) && 'site-card' !== $menu_item[3] ) {
283
				$svg_items[] = array(
284
					'icon' => $menu[ $idx ][6],
285
					'id'   => $menu[ $idx ][5],
286
				);
287
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
288
				$menu[ $idx ][6] = 'none';
289
				// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
290
				$menu[ $idx ][4] .= ' menu-svg-icon';
291
			}
292
		}
293
		if ( count( $svg_items ) > 0 ) {
294
			$styles = '.menu-svg-icon .wp-menu-image { background-repeat: no-repeat; background-position: center center } ';
295
			foreach ( $svg_items as $svg_item ) {
296
				$styles .= sprintf( '#%s .wp-menu-image { background-image: url( "%s" ) }', $svg_item['id'], $svg_item['icon'] );
297
			}
298
			$styles .= '@supports ( mask-image: none ) or ( -webkit-mask-image: none ) { ';
299
			$styles .= '.menu-svg-icon .wp-menu-image { background-image: none; } ';
300
			$styles .= '.menu-svg-icon .wp-menu-image::before { background-color: currentColor; ';
301
			$styles .= 'mask-size: contain; mask-position: center center; mask-repeat: no-repeat; ';
302
			$styles .= '-webkit-mask-size: contain; -webkit-mask-position: center center; -webkit-mask-repeat: no-repeat; content:"" } ';
303
			foreach ( $svg_items as $svg_item ) {
304
				$styles .= sprintf(
305
					'#%s .wp-menu-image { background-image: none; } #%s .wp-menu-image::before{ mask-image: url( "%s" ); -webkit-mask-image: url( "%s" ) }',
306
					$svg_item['id'],
307
					$svg_item['id'],
308
					$svg_item['icon'],
309
					$svg_item['icon']
310
				);
311
			}
312
			$styles .= '}';
313
314
			wp_register_style( 'svg-menu-overrides', false, array(), '20210331' );
315
			wp_enqueue_style( 'svg-menu-overrides' );
316
			wp_add_inline_style( 'svg-menu-overrides', $styles );
317
		}
318
	}
319
320
	/**
321
	 * Whether to use wp-admin pages rather than Calypso.
322
	 *
323
	 * Options:
324
	 * false - Calypso (Default).
325
	 * true  - wp-admin.
326
	 *
327
	 * @return bool
328
	 */
329
	abstract public function should_link_to_wp_admin();
330
331
	/**
332
	 * Create the desired menu output.
333
	 */
334
	abstract public function reregister_menu_items();
335
}
336