Completed
Push — update/admin-menu-logo ( e63b33...b6eb41 )
by
unknown
09:40
created

Base_Admin_Menu::rest_api_init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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