Completed
Push — try/search-config-via-wpadmin ( cb094f...014825 )
by
unknown
74:32 queued 64:33
created

WPcom_Admin_Menu::sync_sidebar_collapsed_state()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * WP.com Admin Menu file.
4
 *
5
 * @package automattic/jetpack
6
 */
7
8
namespace Automattic\Jetpack\Dashboard_Customizations;
9
10
use Automattic\Jetpack\Status;
11
use JITM;
12
13
require_once __DIR__ . '/class-admin-menu.php';
14
15
/**
16
 * Class WPcom_Admin_Menu.
17
 */
18
class WPcom_Admin_Menu extends Admin_Menu {
19
	/**
20
	 * WPcom_Admin_Menu constructor.
21
	 */
22
	protected function __construct() {
23
		parent::__construct();
24
25
		add_action( 'wp_ajax_sidebar_state', array( $this, 'ajax_sidebar_state' ) );
26
		add_action( 'admin_init', array( $this, 'sync_sidebar_collapsed_state' ) );
27
		add_action( 'admin_menu', array( $this, 'remove_submenus' ), 140 ); // After hookpress hook at 130.
28
	}
29
30
	/**
31
	 * Sets up class properties for REST API requests.
32
	 *
33
	 * @param WP_REST_Response $response Response from the endpoint.
34
	 */
35
	public function rest_api_init( $response ) {
36
		parent::rest_api_init( $response );
37
38
		// Get domain for requested site.
39
		$this->domain = ( new Status() )->get_site_suffix();
40
41
		return $response;
42
	}
43
44
	/**
45
	 * Create the desired menu output.
46
	 */
47 View Code Duplication
	public function reregister_menu_items() {
48
		parent::reregister_menu_items();
49
50
		$this->add_my_home_menu();
51
52
		// Not needed outside of wp-admin.
53
		if ( ! $this->is_api_request ) {
54
			$this->add_browse_sites_link();
55
			$this->add_site_card_menu();
56
			$nudge = $this->get_upsell_nudge();
57
			if ( $nudge ) {
58
				parent::add_upsell_nudge( $nudge );
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (add_upsell_nudge() instead of reregister_menu_items()). Are you sure this is correct? If so, you might want to change this to $this->add_upsell_nudge().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
Documentation introduced by
$nudge is of type array<string,?,{"content...s_click_cta_name":"?"}>, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
59
			}
60
			$this->add_new_site_link();
61
		}
62
63
		ksort( $GLOBALS['menu'] );
64
	}
65
66
	/**
67
	 * Adds the site switcher link if user has more than one site.
68
	 */
69
	public function add_browse_sites_link() {
70
		if ( count( get_blogs_of_user( get_current_user_id() ) ) < 2 ) {
71
			return;
72
		}
73
74
		// Add the menu item.
75
		add_menu_page( __( 'site-switcher', 'jetpack' ), __( 'Browse sites', 'jetpack' ), 'read', 'https://wordpress.com/home', null, 'dashicons-arrow-left-alt2', 0 );
76
		add_filter( 'add_menu_classes', array( $this, 'set_browse_sites_link_class' ) );
77
	}
78
79
	/**
80
	 * Adds a custom element class for Site Switcher menu item.
81
	 *
82
	 * @param array $menu Associative array of administration menu items.
83
	 * @return array
84
	 */
85 View Code Duplication
	public function set_browse_sites_link_class( array $menu ) {
86
		foreach ( $menu as $key => $menu_item ) {
87
			if ( 'site-switcher' !== $menu_item[3] ) {
88
				continue;
89
			}
90
91
			$menu[ $key ][4] = add_cssclass( 'site-switcher', $menu_item[4] );
92
			break;
93
		}
94
95
		return $menu;
96
	}
97
98
	/**
99
	 * Adds a link to the menu to create a new site.
100
	 */
101
	public function add_new_site_link() {
102
		if ( count( get_blogs_of_user( get_current_user_id() ) ) > 1 ) {
103
			return;
104
		}
105
106
		$this->add_admin_menu_separator();
107
		add_menu_page( __( 'Add New Site', 'jetpack' ), __( 'Add New Site', 'jetpack' ), 'read', 'https://wordpress.com/start?ref=calypso-sidebar', null, 'dashicons-plus-alt' );
108
	}
109
110
	/**
111
	 * Adds site card component.
112
	 */
113
	public function add_site_card_menu() {
114
		$default   = 'data:image/svg+xml,' . rawurlencode( '<svg class="gridicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Globe</title><rect fill-opacity="0" x="0" width="24" height="24"/><g><path fill="#fff" d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18l2-2 1-1v-2h-2v-1l-1-1H9v3l2 2v1.93c-3.94-.494-7-3.858-7-7.93l1 1h2v-2h2l3-3V6h-2L9 5v-.41C9.927 4.21 10.94 4 12 4s2.073.212 3 .59V6l-1 1v2l1 1 3.13-3.13c.752.897 1.304 1.964 1.606 3.13H18l-2 2v2l1 1h2l.286.286C18.03 18.06 15.24 20 12 20z"/></g></svg>' );
115
		$icon      = get_site_icon_url( 32, $default );
116
		$blog_name = get_option( 'blogname' ) !== '' ? get_option( 'blogname' ) : $this->domain;
117
118
		if ( $default === $icon && blavatar_exists( $this->domain ) ) {
119
			$icon = blavatar_url( $this->domain, 'img', 32 );
120
		}
121
122
		$badge = '';
123
		if ( is_private_blog() ) {
124
			$badge .= sprintf(
125
				'<span class="site__badge site__badge-private">%s</span>',
126
				wpcom_is_coming_soon() ? esc_html__( 'Coming Soon', 'jetpack' ) : esc_html__( 'Private', 'jetpack' )
127
			);
128
		}
129
130
		if ( function_exists( 'is_simple_site_redirect' ) && is_simple_site_redirect( $this->domain ) ) {
131
			$badge .= '<span class="site__badge site__badge-redirect">' . esc_html__( 'Redirect', 'jetpack' ) . '</span>';
132
		}
133
134
		if ( ! empty( get_option( 'options' )['is_domain_only'] ) ) {
135
			$badge .= '<span class="site__badge site__badge-domain-only">' . esc_html__( 'Domain', 'jetpack' ) . '</span>';
136
		}
137
138
		$site_card = '
139
<div class="site__info">
140
	<div class="site__title">%1$s</div>
141
	<div class="site__domain">%2$s</div>
142
	%3$s
143
</div>';
144
145
		$site_card = sprintf(
146
			$site_card,
147
			$blog_name,
148
			$this->domain,
149
			$badge
150
		);
151
152
		add_menu_page( 'site-card', $site_card, 'read', get_home_url(), null, $icon, 1 );
153
		add_filter( 'add_menu_classes', array( $this, 'set_site_card_menu_class' ) );
154
	}
155
156
	/**
157
	 * Adds a custom element class and id for Site Card's menu item.
158
	 *
159
	 * @param array $menu Associative array of administration menu items.
160
	 * @return array
161
	 */
162
	public function set_site_card_menu_class( array $menu ) {
163
		foreach ( $menu as $key => $menu_item ) {
164
			if ( 'site-card' !== $menu_item[3] ) {
165
				continue;
166
			}
167
168
			$classes = ' toplevel_page_site-card';
169
			if ( blavatar_exists( $this->domain ) ) {
170
				$classes .= ' has-site-icon';
171
			}
172
173
			$menu[ $key ][4] = $menu_item[4] . $classes;
174
			$menu[ $key ][5] = 'toplevel_page_site_card';
175
			break;
176
		}
177
178
		return $menu;
179
	}
180
181
	/**
182
	 * Returns the first available upsell nudge.
183
	 *
184
	 * @return array
185
	 */
186
	public function get_upsell_nudge() {
187
		require_lib( 'jetpack-jitm/jitm-engine' );
188
		$jitm_engine = new JITM\Engine();
189
190
		$message_path = 'calypso:sites:sidebar_notice';
191
		$current_user = wp_get_current_user();
192
		$user_id      = $current_user->ID;
193
		$user_roles   = implode( ',', $current_user->roles );
194
		$query_string = array(
195
			'message_path' => $message_path,
196
		);
197
198
		// Get the top message only.
199
		$message = $jitm_engine->get_top_messages( $message_path, $user_id, $user_roles, $query_string );
200
201
		if ( isset( $message[0] ) ) {
202
			$message = $message[0];
203
			return array(
204
				'content'                      => $message->content['message'],
205
				'cta'                          => $message->CTA['message'], // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
206
				'link'                         => $message->CTA['link'], // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
207
				'tracks_impression_event_name' => $message->tracks['display']['name'],
208
				'tracks_impression_cta_name'   => $message->tracks['display']['props']['cta_name'],
209
				'tracks_click_event_name'      => $message->tracks['click']['name'],
210
				'tracks_click_cta_name'        => $message->tracks['click']['props']['cta_name'],
211
			);
212
		}
213
	}
214
215
	/**
216
	 * Adds Stats menu.
217
	 */
218
	public function add_stats_menu() {
219
		$menu_title = __( 'Stats', 'jetpack' );
220
221
		if ( ! $this->is_api_request ) {
222
			$menu_title .= sprintf(
223
				'<img class="sidebar-unified__sparkline" width="80" height="20" src="%1$s" alt="%2$s">',
224
				esc_url( site_url( 'wp-includes/charts/admin-bar-hours-scale-2x.php?masterbar=1&s=' . get_current_blog_id() ) ),
225
				esc_attr__( 'Hourly views', 'jetpack' )
226
			);
227
		}
228
229
		add_menu_page( __( 'Stats', 'jetpack' ), $menu_title, 'edit_posts', 'https://wordpress.com/stats/day/' . $this->domain, null, 'dashicons-chart-bar', 3 );
230
	}
231
232
	/**
233
	 * Adds Upgrades menu.
234
	 *
235
	 * @param string $plan The current WPCOM plan of the blog.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plan 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...
236
	 */
237
	public function add_upgrades_menu( $plan = null ) {
238
		if ( class_exists( 'WPCOM_Store_API' ) ) {
239
			$products = \WPCOM_Store_API::get_current_plan( get_current_blog_id() );
240
			if ( array_key_exists( 'product_name_short', $products ) ) {
241
				$plan = $products['product_name_short'];
242
			}
243
		}
244
		parent::add_upgrades_menu( $plan );
245
246
		$last_upgrade_submenu_position = $this->get_submenu_item_count( 'paid-upgrades.php' );
247
248
		add_submenu_page( 'paid-upgrades.php', __( 'Domains', 'jetpack' ), __( 'Domains', 'jetpack' ), 'manage_options', 'https://wordpress.com/domains/manage/' . $this->domain, null, $last_upgrade_submenu_position - 1 );
249
250
		/** This filter is already documented in modules/masterbar/admin-menu/class-atomic-admin-menu.php */
251 View Code Duplication
		if ( apply_filters( 'jetpack_show_wpcom_upgrades_email_menu', false ) ) {
252
			add_submenu_page( 'paid-upgrades.php', __( 'Emails', 'jetpack' ), __( 'Emails', 'jetpack' ), 'manage_options', 'https://wordpress.com/email/' . $this->domain, null, $last_upgrade_submenu_position );
253
		}
254
	}
255
256
	/**
257
	 * Adds Appearance menu.
258
	 *
259
	 * @param bool $wp_admin_themes Optional. Whether Themes link should point to Calypso or wp-admin. Default false (Calypso).
260
	 * @param bool $wp_admin_customize Optional. Whether Customize link should point to Calypso or wp-admin. Default false (Calypso).
261
	 */
262
	public function add_appearance_menu( $wp_admin_themes = false, $wp_admin_customize = false ) {
263
		// $wp_admin_themes can have a `true` value here if the user has activated the "Show advanced dashboard pages" account setting.
264
		// We force $wp_admin_themes to `false` anyways, since Simple sites should always see the Calypso Theme showcase.
265
		$wp_admin_themes = false;
266
		$customize_url   = parent::add_appearance_menu( $wp_admin_themes, $wp_admin_customize );
267
268
		$this->hide_submenu_page( 'themes.php', 'theme-editor.php' );
269
270
		$user_can_customize = current_user_can( 'customize' );
271
272
		if ( $user_can_customize ) {
273
			// If the user does not have the custom CSS option then present them with the CSS nudge upsell section instead.
274
			$custom_css_section = '1' === get_option( 'custom-design-upgrade' ) ? 'jetpack_custom_css' : 'css_nudge'; //phpcs:ignore
275
			$customize_custom_css_url = add_query_arg( array( 'autofocus' => array( 'section' => $custom_css_section ) ), $customize_url );
276
			add_submenu_page( 'themes.php', esc_attr__( 'Additional CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'customize', esc_url( $customize_custom_css_url ), null, 20 );
277
		}
278
	}
279
280
	/**
281
	 * Adds Users menu.
282
	 *
283
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
284
	 */
285
	public function add_users_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
286
		if ( current_user_can( 'list_users' ) ) {
287
			$submenus_to_update = array(
288
				'users.php'              => 'https://wordpress.com/people/team/' . $this->domain,
289
				'grofiles-editor'        => 'https://wordpress.com/me',
290
				'grofiles-user-settings' => 'https://wordpress.com/me/account',
291
			);
292
			$this->update_submenus( 'users.php', $submenus_to_update );
293
		} else {
294
			$submenus_to_update = array(
295
				'grofiles-editor'        => 'https://wordpress.com/me',
296
				'grofiles-user-settings' => 'https://wordpress.com/me/account',
297
			);
298
			$this->update_submenus( 'profile.php', $submenus_to_update );
299
		}
300
		add_submenu_page( 'users.php', esc_attr__( 'Add New', 'jetpack' ), __( 'Add New', 'jetpack' ), 'promote_users', 'https://wordpress.com/people/new/' . $this->domain, null, 1 );
301
	}
302
303
	/**
304
	 * Adds Settings menu.
305
	 *
306
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
307
	 */
308
	public function add_options_menu( $wp_admin = false ) {
309
		parent::add_options_menu( $wp_admin );
310
311
		add_submenu_page( 'options-general.php', esc_attr__( 'Hosting Configuration', 'jetpack' ), __( 'Hosting Configuration', 'jetpack' ), 'manage_options', 'https://wordpress.com/hosting-config/' . $this->domain, null, 6 );
312
	}
313
314
	/**
315
	 * Also remove the Gutenberg plugin menu.
316
	 *
317
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
318
	 */
319
	public function add_gutenberg_menus( $wp_admin = false ) {
320
		// Always remove the Gutenberg menu.
321
		remove_menu_page( 'gutenberg' );
322
		parent::add_gutenberg_menus( $wp_admin );
323
	}
324
325
	/**
326
	 * Whether to use wp-admin pages rather than Calypso.
327
	 *
328
	 * @return bool
329
	 */
330
	public function should_link_to_wp_admin() {
331
		$result = false; // Calypso.
332
333
		$user_attribute = get_user_attribute( get_current_user_id(), 'calypso_preferences' );
334
		if ( ! empty( $user_attribute['linkDestination'] ) ) {
335
			$result = $user_attribute['linkDestination'];
336
		}
337
338
		return $result;
339
	}
340
341
	/**
342
	 * Adds Plugins menu.
343
	 *
344
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
345
	 */
346
	public function add_plugins_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
347
		// TODO: Remove wpcom_menu (/wp-content/admin-plugins/wpcom-misc.php).
348
		$count = '';
349
		if ( ! is_multisite() && current_user_can( 'update_plugins' ) ) {
350
			$update_data = wp_get_update_data();
351
			$count       = sprintf(
352
				'<span class="update-plugins count-%s"><span class="plugin-count">%s</span></span>',
353
				$update_data['counts']['plugins'],
354
				number_format_i18n( $update_data['counts']['plugins'] )
355
			);
356
		}
357
		/* translators: %s: Number of pending plugin updates. */
358
		add_menu_page( esc_attr__( 'Plugins', 'jetpack' ), sprintf( __( 'Plugins %s', 'jetpack' ), $count ), 'activate_plugins', 'plugins.php', null, 'dashicons-admin-plugins', 65 );
359
360
		// Plugins on Simple sites are always managed on Calypso.
361
		parent::add_plugins_menu( false );
362
	}
363
364
	/**
365
	 * Saves the sidebar state ( expanded / collapsed ) via an ajax request.
366
	 */
367
	public function ajax_sidebar_state() {
368
		$expanded    = filter_var( $_REQUEST['expanded'], FILTER_VALIDATE_BOOLEAN ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
369
		$user_id     = get_current_user_id();
370
		$preferences = get_user_attribute( $user_id, 'calypso_preferences' );
371
		if ( empty( $preferences ) ) {
372
			$preferences = array();
373
		}
374
375
		$value = array_merge( (array) $preferences, array( 'sidebarCollapsed' => ! $expanded ) );
376
		$value = array_filter(
377
			$value,
378
			function ( $preference ) {
379
				return null !== $preference;
380
			}
381
		);
382
383
		update_user_attribute( $user_id, 'calypso_preferences', $value );
384
385
		die();
386
	}
387
388
	/**
389
	 * Syncs the sidebar collapsed state from Calypso Preferences.
390
	 */
391
	public function sync_sidebar_collapsed_state() {
392
		$calypso_preferences = get_user_attribute( get_current_user_id(), 'calypso_preferences' );
393
394
		$sidebar_collapsed = isset( $calypso_preferences['sidebarCollapsed'] ) ? $calypso_preferences['sidebarCollapsed'] : false;
395
		set_user_setting( 'mfold', $sidebar_collapsed ? 'f' : 'o' );
396
	}
397
398
	/**
399
	 * Removes unwanted submenu items.
400
	 *
401
	 * These submenus are added across wp-content and should be removed together with these function calls.
402
	 */
403
	public function remove_submenus() {
404
		global $_registered_pages;
405
406
		remove_submenu_page( 'index.php', 'akismet-stats' );
407
		remove_submenu_page( 'index.php', 'my-comments' );
408
		remove_submenu_page( 'index.php', 'stats' );
409
		remove_submenu_page( 'index.php', 'subscriptions' );
410
411
		/* @see https://github.com/Automattic/wp-calypso/issues/49210 */
412
		remove_submenu_page( 'index.php', 'my-blogs' );
413
		$_registered_pages['admin_page_my-blogs'] = true; // phpcs:ignore
414
415
		remove_submenu_page( 'paid-upgrades.php', 'premium-themes' );
416
		remove_submenu_page( 'paid-upgrades.php', 'domains' );
417
		remove_submenu_page( 'paid-upgrades.php', 'my-upgrades' );
418
		remove_submenu_page( 'paid-upgrades.php', 'billing-history' );
419
420
		remove_submenu_page( 'themes.php', 'customize.php?autofocus[panel]=amp_panel&return=' . rawurlencode( admin_url() ) );
421
422
		remove_submenu_page( 'users.php', 'wpcom-invite-users' ); // Wpcom_Invite_Users::action_admin_menu.
423
424
		remove_submenu_page( 'options-general.php', 'adcontrol' );
425
426
		// Remove menu item but continue allowing access.
427
		foreach ( array( 'openidserver', 'webhooks' ) as $page_slug ) {
428
			remove_submenu_page( 'options-general.php', $page_slug );
429
			$_registered_pages[ 'admin_page_' . $page_slug ] = true; // phpcs:ignore
430
		}
431
	}
432
}
433