Completed
Push — update/admin-menu-sso-disabled ( 39bf4b...eefb5e )
by
unknown
10:52
created

WPcom_Admin_Menu::add_users_menu()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 17
rs 9.7
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
		if ( ! $this->should_override_nav() ) {
0 ignored issues
show
Bug introduced by
The method should_override_nav() does not seem to exist on object<Automattic\Jetpac...tions\WPcom_Admin_Menu>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
26
			return;
27
		}
28
29
		add_action( 'wp_ajax_sidebar_state', array( $this, 'ajax_sidebar_state' ) );
30
		add_action( 'admin_init', array( $this, 'sync_sidebar_collapsed_state' ) );
31
		add_action( 'admin_menu', array( $this, 'remove_submenus' ), 140 ); // After hookpress hook at 130.
32
	}
33
34
	/**
35
	 * Sets up class properties for REST API requests.
36
	 *
37
	 * @param WP_REST_Response $response Response from the endpoint.
38
	 */
39
	public function rest_api_init( $response ) {
40
		parent::rest_api_init( $response );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Automattic\Jetpack\Dashb...stomizations\Admin_Menu as the method rest_api_init() does only exist in the following sub-classes of Automattic\Jetpack\Dashb...stomizations\Admin_Menu: Automattic\Jetpack\Dashb...mizations\P2_Admin_Menu, Automattic\Jetpack\Dashb...ations\WPcom_Admin_Menu. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

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