Jetpack   F
last analyzed

Complexity

Total Complexity 1007

Size/Duplication

Total Lines 7533
Duplicated Lines 4.57 %

Coupling/Cohesion

Components 3
Dependencies 48

Importance

Changes 0
Metric Value
dl 344
loc 7533
rs 0.8
c 0
b 0
f 0
wmc 1007
lcom 3
cbo 48

267 Methods

Rating   Name   Duplication   Size   Complexity  
A late_initialization() 0 17 1
A setup_xmlrpc_handlers() 19 19 2
A initialize_rest_api_registration_connector() 9 9 2
A add_wpcom_to_allowed_redirect_hosts() 0 3 1
A allow_wpcom_domain() 0 7 2
A point_edit_post_links_to_calypso() 0 29 3
A point_edit_comment_links_to_calypso() 0 12 1
A filter_sync_callable_whitelist() 0 25 2
A filter_sync_multisite_callable_whitelist() 0 15 1
A init() 0 8 2
F plugin_upgrade() 0 88 17
A upgrade_on_load() 0 30 5
A update_active_modules() 0 53 3
A delete_active_modules() 0 3 1
A add_configure_hook() 0 21 4
A check_rest_api_compat() 0 14 2
A get_active_plugins() 0 16 3
A get_parsed_plugin_data() 0 21 3
A get_parsed_theme_data() 0 22 3
A is_plugin_active() 0 3 1
B check_open_graph() 0 27 7
A check_twitter_tags() 0 24 5
A submit_security_report() 0 3 1
A get_option_names() 0 3 1
A get_option() 0 3 1
A update_option() 0 4 1
A update_options() 0 4 1
A delete_option() 0 4 1
A update_user_token() 0 4 1
B glob_php() 0 29 7
C activate_new_modules() 6 59 11
D get_available_modules() 0 72 19
B get_default_modules() 0 33 6
B handle_deprecated_modules() 0 27 8
B filter_default_modules() 0 24 6
A get_module_slug() 0 3 1
A get_module_path() 0 11 1
F get_module() 12 100 14
B get_file_data() 0 33 7
A translate_module_tag() 0 3 1
A get_translated_modules() 0 13 4
B get_active_modules() 0 32 7
A is_module_active() 0 3 1
A is_module() 0 3 2
A catch_errors() 0 13 2
A catch_errors_on_shutdown() 0 3 1
A alias_directories() 0 8 1
F activate_default_modules() 21 172 36
D activate_module() 0 93 17
A activate_module_actions() 0 3 1
A deactivate_module() 0 17 1
A enable_module_configurable() 0 4 1
A module_configuration_url() 0 14 1
B bail_on_activation() 0 40 5
A plugin_activation() 0 20 3
C get_activation_source() 0 49 14
A deactivate_dialog_content() 0 5 1
A login_url() 0 7 2
A login_init() 0 17 2
A plugin_initialize() 6 17 3
A plugin_deactivation() 0 11 2
B disconnect() 0 46 6
A disconnect_user() 0 3 1
A try_registration() 0 4 1
A registration_check_domains() 0 18 5
A log() 0 40 3
B get_log() 0 36 11
A log_settings_change() 0 7 2
A get_stat_data() 0 14 3
A get_additional_stat_data() 0 11 2
A get_site_user_count() 0 15 4
B __construct() 0 163 6
C configure() 0 81 10
A jetpack_track_last_sync_callback() 0 4 1
A jetpack_connection_banner_callback() 0 14 3
A remove_non_jetpack_xmlrpc_methods() 9 9 2
A alternate_xmlrpc() 9 9 2
A jetpack_jitm_ajax_callback() 0 3 1
A push_stats() 0 5 2
B jetpack_custom_caps() 9 35 11
A require_jetpack_authentication() 9 9 2
B register_assets() 11 62 6
C guess_locale_from_lang() 39 39 12
A get_locale() 0 9 2
A jetpack_main_network_site_option() 0 3 1
A network_name() 0 4 1
A network_allow_new_registrations() 0 3 2
A network_add_new_users() 0 3 1
A network_site_upload_space() 0 4 2
A network_upload_file_types() 0 3 1
A network_max_upload_file_size() 0 4 1
A network_enable_administration_menus() 0 3 1
A maybe_clear_other_linked_admins_transient() 0 8 5
B get_other_linked_admins() 0 28 7
A is_main_network_option() 0 4 1
A is_multisite() 0 3 1
A is_multi_network() 15 15 3
A update_jetpack_main_network_site_option() 0 3 1
A update_jetpack_network_settings() 0 4 1
A is_single_user_site() 9 9 2
A file_system_write_access() 0 20 4
A is_version_controlled() 0 4 1
A featured_images_enabled() 0 4 2
A get_avatar_url() 0 11 1
A get_updates() 6 17 6
A get_update_details() 0 8 1
A refresh_update_data() 0 4 1
A refresh_theme_data() 0 3 1
A is_active() 0 3 1
A is_connection_ready() 0 13 1
A refresh_active_plan_from_wpcom() 0 4 1
A get_active_plan() 0 4 1
A active_plan_supports() 0 4 1
A is_development_mode() 0 4 1
A is_onboarding() 0 3 1
B development_mode_trigger_text() 0 23 9
A show_development_mode_notice() 17 28 4
A is_development_version() 0 15 1
A is_user_connected() 0 4 1
A get_connected_user_data() 0 4 1
A get_connected_user_email() 0 16 3
A get_master_user_email() 0 7 2
A current_user_is_connection_owner() 0 4 1
A current_user_ip() 0 20 5
A user_role_change() 0 4 1
D load_modules() 6 94 21
A do_version_bump() 0 11 2
A set_update_modal_display() 0 4 1
A enqueue_block_style() 0 5 2
C admin_init() 0 54 13
A admin_body_class() 0 8 2
A add_jetpack_pagestyles() 0 3 1
B throw_error_on_activate_plugin() 0 24 7
A intercept_plugin_error_scrape_init() 0 3 1
A intercept_plugin_error_scrape() 0 11 4
B add_remote_request_handlers() 0 29 7
B remote_request_handlers() 0 40 7
F upload_handler() 0 131 24
A admin_help() 0 43 2
A admin_menu_css() 0 3 1
A admin_menu_order() 0 3 1
A jetpack_menu_order() 0 15 4
A admin_banner_styles() 8 21 4
A plugin_action_links() 0 15 4
A deactivate_dialog() 0 42 4
B admin_notices() 0 125 7
A track_xmlrpc_error() 0 15 4
A initialize_stats() 0 5 2
A stat() 0 7 1
A do_stats() 0 11 2
A do_server_side_stat() 0 5 1
A build_stats_url() 0 6 1
C build_connect_url() 0 62 12
A build_authorize_url() 0 28 3
B filter_connect_request_body() 0 30 6
A filter_connect_processing_url() 0 6 1
A filter_connect_redirect_url() 0 12 3
A authorize_starting() 0 24 2
A handle_unique_registrations_stats() 0 15 2
A authorize_ending_linked() 0 4 1
A authorize_ending_authorized() 0 20 3
A activate_default_modules_on_site_register() 0 15 2
A reconnection_completed() 0 3 1
A get_assumed_site_creation_date() 0 4 1
A apply_activation_source_to_args() 11 11 3
A build_reconnect_url() 0 4 2
A admin_url() 0 5 1
A nonce_url_no_esc() 0 4 1
A dismiss_jetpack_notice() 0 17 5
A sort_modules() 0 7 3
A ajax_recheck_ssl() 0 10 1
A api_url() 0 5 1
A fix_url_for_bad_hosts() 0 4 1
C verify_onboarding_token() 0 45 15
A create_onboarding_token() 0 8 2
A invalidate_onboarding_token() 0 3 1
A validate_onboarding_token_action() 0 18 3
B permit_ssl() 0 29 7
A alert_auto_ssl_fail() 0 54 2
A xmlrpc_api_url() 0 4 1
A connection() 0 10 2
A generate_secrets() 0 4 1
A get_secrets() 0 13 3
A get_remote_query_timeout_limit() 0 4 1
A get_max_execution_time() 0 9 2
A set_min_time_limit() 8 8 2
A validate_remote_register_response() 0 3 1
A register() 0 4 1
A filter_register_request_body() 0 4 1
A filter_token_request_body() 12 12 1
A maybe_set_version_option() 0 14 3
A load_xml_rpc_client() 0 3 1
A reset_saved_auth_state() 0 4 1
A verify_xml_rpc_signature() 0 4 1
A internal_verify_xml_rpc_signature() 0 3 1
A authenticate_jetpack() 9 9 2
A wp_rest_authenticate() 0 4 1
A wp_rest_authentication_errors() 0 4 1
A xmlrpc_methods() 9 9 2
A public_xmlrpc_methods() 9 9 2
A jetpack_getOptions() 9 9 2
A xmlrpc_options() 9 9 2
F state() 0 56 20
A restate() 0 3 1
A should_set_cookie() 0 10 4
B check_privacy() 0 34 6
C xmlrpc_async_call() 0 42 12
A staticize_subdomain() 0 4 1
A login_form_json_api_authorization() 0 9 1
A post_login_form_to_signed_url() 0 14 5
A preserve_action_in_login_form_for_json_api_authorization() 0 4 1
A store_json_api_authorization_token() 0 6 1
A allow_wpcom_public_api_domain() 0 4 1
A is_redirect_encoded() 0 3 1
A allow_wpcom_environments() 0 7 1
A add_token_to_login_redirect_json_api_authorization() 0 12 1
F verify_json_api_authorization_request() 0 121 23
A login_message_json_api_authorization() 0 6 1
A get_content_width() 0 13 3
A get_cloud_site_options() 0 15 2
A check_identity_crisis() 0 7 4
A is_staging_site() 0 4 1
A validate_sync_error_idc_option() 0 4 1
A normalize_url_protocol_agnostic() 10 10 4
A get_sync_error_idc_option() 0 4 1
A sync_idc_optin() 0 4 1
B maybe_min_asset() 0 42 8
A set_suffix_on_min() 0 16 5
C maybe_inline_style() 0 50 13
A load_view() 0 11 2
B deprecated_hooks() 0 257 5
B absolutize_css_urls() 0 44 9
B implode_frontend_css() 0 57 10
A concat_remove_style_loader_tag() 0 10 4
A script_add_async() 0 3 1
B jetpack_check_heartbeat_data() 0 53 10
A get_jetpack_options_for_reset() 0 3 1
A build_raw_urls() 0 5 1
A dns_prefetch() 0 6 2
A wp_dashboard_setup() 0 38 5
A get_user_option_meta_box_order_dashboard() 0 25 5
A dashboard_widget() 0 8 1
B dashboard_widget_footer() 0 68 7
A jetpack_icon_user_connected() 0 4 1
A jetpack_show_user_connected_icon() 0 13 3
A jetpack_user_col_style() 0 19 3
B is_akismet_active() 0 35 9
A is_function_in_backtrace() 0 3 1
A get_file_url_for_environment() 0 3 1
B is_rewind_enabled() 0 20 6
A get_calypso_env() 0 15 5
A get_calypso_host() 0 13 4
A handle_post_authorization_actions() 0 28 4
A show_backups_ui() 0 10 2
A prepare_manage_jetpack_notice() 0 3 1
A manage_activate_screen() 0 3 1
A admin_jetpack_manage_notice() 0 3 1
A opt_out_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_url() 0 3 1
A opt_in_jetpack_manage_notice() 0 3 1
A can_display_jetpack_manage_notice() 0 3 1
A user_meta_cleanup() 0 15 3
A is_active_and_not_development_mode() 0 7 3
A is_active_and_not_offline_mode() 0 6 3
B get_products_for_purchase() 0 94 2
A current_user_can_purchase() 0 14 3
F admin_page_load() 38 321 64

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
use Automattic\Jetpack\Assets;
4
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Jetpack_Logo.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use Automattic\Jetpack\Config;
6
use Automattic\Jetpack\Connection\Client;
7
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
8
use Automattic\Jetpack\Connection\Nonce_Handler;
9
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
10
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
11
use Automattic\Jetpack\Connection\Secrets;
12
use Automattic\Jetpack\Connection\Tokens;
13
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
14
use Automattic\Jetpack\Connection\Webhooks as Connection_Webhooks;
15
use Automattic\Jetpack\Constants;
16
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
17
use Automattic\Jetpack\Identity_Crisis;
18
use Automattic\Jetpack\Licensing;
19
use Automattic\Jetpack\Partner;
20
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
21
use Automattic\Jetpack\Redirect;
22
use Automattic\Jetpack\Status;
23
use Automattic\Jetpack\Sync\Functions;
24
use Automattic\Jetpack\Sync\Health;
25
use Automattic\Jetpack\Sync\Sender;
26
use Automattic\Jetpack\Sync\Users;
27
use Automattic\Jetpack\Terms_Of_Service;
28
use Automattic\Jetpack\Tracking;
29
30
/*
31
Options:
32
jetpack_options (array)
33
	An array of options.
34
	@see Jetpack_Options::get_option_names()
35
36
jetpack_register (string)
37
	Temporary verification secrets.
38
39
jetpack_activated (int)
40
	1: the plugin was activated normally
41
	2: the plugin was activated on this site because of a network-wide activation
42
	3: the plugin was auto-installed
43
	4: the plugin was manually disconnected (but is still installed)
44
45
jetpack_active_modules (array)
46
	Array of active module slugs.
47
48
jetpack_do_activate (bool)
49
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
50
*/
51
52
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
53
54
class Jetpack {
55
	public $xmlrpc_server = null;
56
57
	/**
58
	 * @var array The handles of styles that are concatenated into jetpack.css.
59
	 *
60
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
61
	 */
62
	public $concatenated_style_handles = array(
63
		'jetpack-carousel',
64
		'grunion.css',
65
		'the-neverending-homepage',
66
		'jetpack_likes',
67
		'jetpack_related-posts',
68
		'sharedaddy',
69
		'jetpack-slideshow',
70
		'presentations',
71
		'quiz',
72
		'jetpack-subscriptions',
73
		'jetpack-responsive-videos-style',
74
		'jetpack-social-menu',
75
		'tiled-gallery',
76
		'jetpack_display_posts_widget',
77
		'gravatar-profile-widget',
78
		'goodreads-widget',
79
		'jetpack_social_media_icons_widget',
80
		'jetpack-top-posts-widget',
81
		'jetpack_image_widget',
82
		'jetpack-my-community-widget',
83
		'jetpack-authors-widget',
84
		'wordads',
85
		'eu-cookie-law-style',
86
		'flickr-widget-style',
87
		'jetpack-search-widget',
88
		'jetpack-simple-payments-widget-style',
89
		'jetpack-widget-social-icons-styles',
90
		'wpcom_instagram_widget',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'           => array(
151
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
152
			'Disqus'                         => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'comment-likes'      => array(
159
			'Epoch' => 'epoch/plugincore.php',
160
		),
161
		'contact-form'       => array(
162
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
168
		),
169
		'latex'              => array(
170
			'LaTeX for WordPress'     => 'latex/latex.php',
171
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
172
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
173
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
174
			'Enable Latex'            => 'enable-latex/enable-latex.php',
175
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
176
		),
177
		'protect'            => array(
178
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
179
			'Captcha'                           => 'captcha/captcha.php',
180
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
181
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
182
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
183
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
184
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
185
			'Security-protection'               => 'security-protection/security-protection.php',
186
			'Login Security'                    => 'login-security/login-security.php',
187
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
188
			'Wordfence Security'                => 'wordfence/wordfence.php',
189
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
190
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
191
		),
192
		'random-redirect'    => array(
193
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
194
		),
195
		'related-posts'      => array(
196
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
197
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
198
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
199
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
200
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
201
			'outbrain'                    => 'outbrain/outbrain.php',
202
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
203
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
204
		),
205
		'sharedaddy'         => array(
206
			'AddThis'     => 'addthis/addthis_social_widget.php',
207
			'Add To Any'  => 'add-to-any/add-to-any.php',
208
			'ShareThis'   => 'share-this/sharethis.php',
209
			'Shareaholic' => 'shareaholic/shareaholic.php',
210
		),
211
		'seo-tools'          => array(
212
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
213
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
214
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
215
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
216
			'The SEO Framework'              => 'autodescription/autodescription.php',
217
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
218
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
219
		),
220
		'verification-tools' => array(
221
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
222
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
223
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
224
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
225
			'The SEO Framework'              => 'autodescription/autodescription.php',
226
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
227
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
228
		),
229
		'widget-visibility'  => array(
230
			'Widget Logic'    => 'widget-logic/widget_logic.php',
231
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
232
		),
233
		'sitemaps'           => array(
234
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
235
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
236
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
237
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
238
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
239
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
240
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
241
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
242
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
243
			'The SEO Framework'                    => 'autodescription/autodescription.php',
244
			'Sitemap'                              => 'sitemap/sitemap.php',
245
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
246
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
247
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
248
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
249
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
250
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
251
		),
252
		'lazy-images'        => array(
253
			'Lazy Load'              => 'lazy-load/lazy-load.php',
254
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
255
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
256
		),
257
	);
258
259
	/**
260
	 * Plugins for which we turn off our Facebook OG Tags implementation.
261
	 *
262
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
263
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
264
	 *
265
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
266
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
267
	 */
268
	private $open_graph_conflicting_plugins = array(
269
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
270
		// 2 Click Social Media Buttons
271
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
272
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
273
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
274
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
275
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
276
		// Open Graph Meta Tags by Heateor
277
		'facebook/facebook.php',                                 // Facebook (official plugin)
278
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
279
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
280
		// Facebook Featured Image & OG Meta Tags
281
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
282
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
283
		// Facebook Open Graph Meta Tags for WordPress
284
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
285
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
286
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
287
		// Fedmich's Facebook Open Graph Meta
288
		'network-publisher/networkpub.php',                      // Network Publisher
289
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
290
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
291
		// NextScripts SNAP
292
		'og-tags/og-tags.php',                                   // OG Tags
293
		'opengraph/opengraph.php',                               // Open Graph
294
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
295
		// Open Graph Protocol Framework
296
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
297
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
298
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
299
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
300
		'sharepress/sharepress.php',                             // SharePress
301
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
302
		'social-discussions/social-discussions.php',             // Social Discussions
303
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
304
		'socialize/socialize.php',                               // Socialize
305
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
306
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
307
		// Tweet, Like, Google +1 and Share
308
		'wordbooker/wordbooker.php',                             // Wordbooker
309
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
310
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
311
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
312
		// WP Facebook Like Send & Open Graph Meta
313
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
314
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
315
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
316
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
317
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
318
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
319
		'slim-seo/slim-seo.php',                                 // Slim SEO
320
	);
321
322
	/**
323
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
324
	 */
325
	private $twitter_cards_conflicting_plugins = array(
326
		// 'twitter/twitter.php',                       // The official one handles this on its own.
327
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
328
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
329
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
330
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
331
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
332
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
333
		'twitter-cards/twitter-cards.php',           // Twitter Cards
334
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
335
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
336
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
337
		'seo-by-rank-math/rank-math.php',            // Rank Math.
338
		'slim-seo/slim-seo.php',                     // Slim SEO
339
	);
340
341
	/**
342
	 * Message to display in admin_notice
343
	 *
344
	 * @var string
345
	 */
346
	public $message = '';
347
348
	/**
349
	 * Error to display in admin_notice
350
	 *
351
	 * @var string
352
	 */
353
	public $error = '';
354
355
	/**
356
	 * Modules that need more privacy description.
357
	 *
358
	 * @var string
359
	 */
360
	public $privacy_checks = '';
361
362
	/**
363
	 * Stats to record once the page loads
364
	 *
365
	 * @var array
366
	 */
367
	public $stats = array();
368
369
	/**
370
	 * Jetpack_Sync object
371
	 */
372
	public $sync;
373
374
	/**
375
	 * Verified data for JSON authorization request
376
	 */
377
	public $json_api_authorization_request = array();
378
379
	/**
380
	 * @var Automattic\Jetpack\Connection\Manager
381
	 */
382
	protected $connection_manager;
383
384
	/**
385
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
386
	 */
387
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
388
389
	/**
390
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
391
	 *
392
	 * @var Automattic\Jetpack\A8c_Mc_Stats
393
	 */
394
	public $a8c_mc_stats_instance;
395
396
	/**
397
	 * Constant for login redirect key.
398
	 *
399
	 * @var string
400
	 * @since 8.4.0
401
	 */
402
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
403
404
	/**
405
	 * Holds the singleton instance of this class
406
	 *
407
	 * @since 2.3.3
408
	 * @var Jetpack
409
	 */
410
	static $instance = false;
411
412
	/**
413
	 * Singleton
414
	 *
415
	 * @static
416
	 */
417
	public static function init() {
418
		if ( ! self::$instance ) {
419
			self::$instance = new Jetpack();
420
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
421
		}
422
423
		return self::$instance;
424
	}
425
426
	/**
427
	 * Must never be called statically
428
	 */
429
	function plugin_upgrade() {
430
		if ( self::is_connection_ready() ) {
431
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
432
			if ( JETPACK__VERSION != $version ) {
433
				// Prevent multiple upgrades at once - only a single process should trigger
434
				// an upgrade to avoid stampedes
435
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
436
					return;
437
				}
438
439
				// Set a short lock to prevent multiple instances of the upgrade
440
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
441
442
				// check which active modules actually exist and remove others from active_modules list
443
				$unfiltered_modules = self::get_active_modules();
444
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
445
				if ( array_diff( $unfiltered_modules, $modules ) ) {
446
					self::update_active_modules( $modules );
447
				}
448
449
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
450
451
				// Upgrade to 4.3.0
452
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
453
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
454
				}
455
456
				// Make sure Markdown for posts gets turned back on
457
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
458
					update_option( 'wpcom_publish_posts_with_markdown', true );
459
				}
460
461
				/*
462
				 * Minileven deprecation. 8.3.0.
463
				 * Only delete options if not using
464
				 * the replacement standalone Minileven plugin.
465
				 */
466
				if (
467
					! self::is_plugin_active( 'minileven-master/minileven.php' )
468
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
469
				) {
470
					if ( get_option( 'wp_mobile_custom_css' ) ) {
471
						delete_option( 'wp_mobile_custom_css' );
472
					}
473
					if ( get_option( 'wp_mobile_excerpt' ) ) {
474
						delete_option( 'wp_mobile_excerpt' );
475
					}
476
					if ( get_option( 'wp_mobile_featured_images' ) ) {
477
						delete_option( 'wp_mobile_featured_images' );
478
					}
479
					if ( get_option( 'wp_mobile_app_promos' ) ) {
480
						delete_option( 'wp_mobile_app_promos' );
481
					}
482
				}
483
484
				// Upgrade to 8.4.0.
485
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
486
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
487
				}
488
489
				// Update to 8.8.x (WordPress 5.5 Compatibility).
490
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
491
					$updated = update_site_option(
492
						'auto_update_plugins',
493
						array_unique(
494
							array_merge(
495
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
496
								(array) get_site_option( 'auto_update_plugins', array() )
497
							)
498
						)
499
					);
500
501
					if ( $updated ) {
502
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
503
					} // Should we have some type of fallback if something fails here?
504
				}
505
506
				if ( did_action( 'wp_loaded' ) ) {
507
					self::upgrade_on_load();
508
				} else {
509
					add_action(
510
						'wp_loaded',
511
						array( __CLASS__, 'upgrade_on_load' )
512
					);
513
				}
514
			}
515
		}
516
	}
517
518
	/**
519
	 * Runs upgrade routines that need to have modules loaded.
520
	 */
521
	static function upgrade_on_load() {
522
523
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
524
		// This can happen in case Jetpack has been just upgraded and is
525
		// being initialized late during the page load. In this case we wait
526
		// until the next proper admin page load with Jetpack active.
527
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
528
			delete_transient( self::$plugin_upgrade_lock_key );
529
530
			return;
531
		}
532
533
		self::maybe_set_version_option();
534
535
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
536
			Jetpack_Widget_Conditions::migrate_post_type_rules();
537
		}
538
539
		if (
540
			class_exists( 'Jetpack_Sitemap_Manager' )
541
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
542
		) {
543
			do_action( 'jetpack_sitemaps_purge_data' );
544
		}
545
546
		// Delete old stats cache
547
		delete_option( 'jetpack_restapi_stats_cache' );
548
549
		delete_transient( self::$plugin_upgrade_lock_key );
550
	}
551
552
	/**
553
	 * Saves all the currently active modules to options.
554
	 * Also fires Action hooks for each newly activated and deactivated module.
555
	 *
556
	 * @param $modules Array Array of active modules to be saved in options.
557
	 *
558
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
559
	 */
560
	static function update_active_modules( $modules ) {
561
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
562
		$active_modules       = self::get_active_modules();
563
		$new_active_modules   = array_diff( $modules, $current_modules );
564
		$new_inactive_modules = array_diff( $active_modules, $modules );
565
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
566
		$reindexed_modules    = array_values( $new_current_modules );
567
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
568
569
		foreach ( $new_active_modules as $module ) {
570
			/**
571
			 * Fires when a specific module is activated.
572
			 *
573
			 * @since 1.9.0
574
			 *
575
			 * @param string $module Module slug.
576
			 * @param boolean $success whether the module was activated. @since 4.2
577
			 */
578
			do_action( 'jetpack_activate_module', $module, $success );
579
			/**
580
			 * Fires when a module is activated.
581
			 * The dynamic part of the filter, $module, is the module slug.
582
			 *
583
			 * @since 1.9.0
584
			 *
585
			 * @param string $module Module slug.
586
			 */
587
			do_action( "jetpack_activate_module_$module", $module );
588
		}
589
590
		foreach ( $new_inactive_modules as $module ) {
591
			/**
592
			 * Fired after a module has been deactivated.
593
			 *
594
			 * @since 4.2.0
595
			 *
596
			 * @param string $module Module slug.
597
			 * @param boolean $success whether the module was deactivated.
598
			 */
599
			do_action( 'jetpack_deactivate_module', $module, $success );
600
			/**
601
			 * Fires when a module is deactivated.
602
			 * The dynamic part of the filter, $module, is the module slug.
603
			 *
604
			 * @since 1.9.0
605
			 *
606
			 * @param string $module Module slug.
607
			 */
608
			do_action( "jetpack_deactivate_module_$module", $module );
609
		}
610
611
		return $success;
612
	}
613
614
	static function delete_active_modules() {
615
		self::update_active_modules( array() );
616
	}
617
618
	/**
619
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
620
	 * available.
621
	 */
622
	public function add_configure_hook() {
623
		global $wp_filter;
624
625
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
626
		if ( false !== $current_priority ) {
627
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
628
		}
629
630
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
631
		sort( $taken_priorities );
632
633
		$first_priority = array_shift( $taken_priorities );
634
635
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
636
			$new_priority = - PHP_INT_MAX;
637
		} else {
638
			$new_priority = $first_priority - 1;
639
		}
640
641
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
642
	}
643
644
	/**
645
	 * Constructor.  Initializes WordPress hooks
646
	 */
647
	private function __construct() {
648
		/*
649
		 * Check for and alert any deprecated hooks
650
		 */
651
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
652
653
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
654
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
656
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
657
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
658
659
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
660
661
		add_filter(
662
			'jetpack_signature_check_token',
663
			array( __CLASS__, 'verify_onboarding_token' ),
664
			10,
665
			3
666
		);
667
668
		/**
669
		 * Prepare Gutenberg Editor functionality
670
		 */
671
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
672
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
673
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
674
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
675
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
676
677
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
678
679
		// Unlink user before deleting the user from WP.com.
680
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
681
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
682
683
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
684
685
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
686
		add_action( 'login_init', array( $this, 'login_init' ) );
687
688
		// Set up the REST authentication hooks.
689
		Connection_Rest_Authentication::init();
690
691
		add_action( 'admin_init', array( $this, 'admin_init' ) );
692
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
693
694
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
695
696
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
697
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
698
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
699
700
		// returns HTTPS support status
701
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
702
703
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
704
705
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
706
707
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
708
709
		/**
710
		 * These actions run checks to load additional files.
711
		 * They check for external files or plugins, so they need to run as late as possible.
712
		 */
713
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
714
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
715
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
716
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
717
718
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
719
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
720
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
721
722
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
723
724
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
725
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
726
727
		require_once JETPACK__PLUGIN_DIR . 'class-jetpack-pre-connection-jitms.php';
728
		$jetpack_jitm_messages = ( new Jetpack_Pre_Connection_JITMs() );
729
		add_filter( 'jetpack_pre_connection_jitms', array( $jetpack_jitm_messages, 'add_pre_connection_jitms' ) );
730
731
		/*
732
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
733
		 * We should make sure to only do this for front end links.
734
		 */
735
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
736
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
737
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
738
739
			/*
740
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
741
			 * so they point moderation links on emails to Calypso.
742
			 */
743
			jetpack_require_lib( 'functions.wp-notify' );
744
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
745
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
746
		}
747
748
		add_action(
749
			'plugins_loaded',
750
			function () {
751
				if ( User_Agent_Info::is_mobile_app() ) {
752
					add_filter( 'get_edit_post_link', '__return_empty_string' );
753
				}
754
			}
755
		);
756
757
		// Update the site's Jetpack plan and products from API on heartbeats.
758
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
759
760
		/**
761
		 * This is the hack to concatenate all css files into one.
762
		 * For description and reasoning see the implode_frontend_css method.
763
		 *
764
		 * Super late priority so we catch all the registered styles.
765
		 */
766
		if ( ! is_admin() ) {
767
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
768
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
769
		}
770
771
		// Actually push the stats on shutdown.
772
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
773
			add_action( 'shutdown', array( $this, 'push_stats' ) );
774
		}
775
776
		// After a successful connection.
777
		add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
778
		add_action( 'jetpack_site_registered', array( $this, 'handle_unique_registrations_stats' ) );
779
780
		// Actions for Manager::authorize().
781
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
782
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
783
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
784
785
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
786
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
787
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
788
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
789
790
		// Filters for the Manager::get_token() urls and request body.
791
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
792
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
793
794
		// Actions for successful reconnect.
795
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
796
797
		// Actions for licensing.
798
		Licensing::instance()->initialize();
799
800
		// Filters for Sync Callables.
801
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
802
		add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
803
804
		// Make resources use static domain when possible.
805
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
806
807
		// Validate the domain names in Jetpack development versions.
808
		add_action( 'jetpack_pre_register', array( get_called_class(), 'registration_check_domains' ) );
809
	}
810
811
	/**
812
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
813
	 * Config object.
814
	 */
815
	public function configure() {
816
		$config = new Config();
817
818
		foreach (
819
			array(
820
				'sync',
821
				'jitm',
822
			)
823
			as $feature
824
		) {
825
			$config->ensure( $feature );
826
		}
827
828
		$config->ensure(
829
			'connection',
830
			array(
831
				'slug' => 'jetpack',
832
				'name' => 'Jetpack',
833
			)
834
		);
835
836
		if ( ! $this->connection_manager ) {
837
			$this->connection_manager = new Connection_Manager( 'jetpack' );
838
839
			/**
840
			 * Filter to activate Jetpack Connection UI.
841
			 * INTERNAL USE ONLY.
842
			 *
843
			 * @since 9.5.0
844
			 *
845
			 * @param bool false Whether to activate the Connection UI.
846
			 */
847
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
848
				Automattic\Jetpack\ConnectionUI\Admin::init();
849
			}
850
		}
851
852
		/*
853
		 * Load things that should only be in Network Admin.
854
		 *
855
		 * For now blow away everything else until a more full
856
		 * understanding of what is needed at the network level is
857
		 * available
858
		 */
859
		if ( is_multisite() ) {
860
			$network = Jetpack_Network::init();
861
			$network->set_connection( $this->connection_manager );
862
		}
863
864
		if ( self::is_connection_ready() ) {
865
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
866
867
			Jetpack_Heartbeat::init();
868
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
869
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
870
				Jetpack_Search_Performance_Logger::init();
871
			}
872
		}
873
874
		// Initialize remote file upload request handlers.
875
		$this->add_remote_request_handlers();
876
877
		/*
878
		 * Enable enhanced handling of previewing sites in Calypso
879
		 */
880
		if ( self::is_connection_ready() ) {
881
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
882
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
883
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
884
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
885
		}
886
887
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
new \Automattic\Jetpack\Terms_Of_Service() is of type object<Automattic\Jetpack\Terms_Of_Service>, but the function expects a object<Automattic\Jetpac...tpack\Terms_Of_Service>.

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...
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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...
888
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
889
		} else {
890
			/**
891
			 * Initialize tracking right after the user agrees to the terms of service.
892
			 */
893
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
894
		}
895
	}
896
897
	/**
898
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
899
	 * initialization code.
900
	 *
901
	 * @action plugins_loaded
902
	 */
903
	public function late_initialization() {
904
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
905
906
		Partner::init();
907
908
		/**
909
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
910
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
911
		 *
912
		 * @since 8.1.0
913
		 *
914
		 * @param Jetpack $jetpack the main plugin class object.
915
		 */
916
		do_action( 'jetpack_loaded', $this );
917
918
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
919
	}
920
921
	/**
922
	 * Sets up the XMLRPC request handlers.
923
	 *
924
	 * @deprecated since 7.7.0
925
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
926
	 *
927
	 * @param array                 $request_params Incoming request parameters.
928
	 * @param Boolean               $is_active      Whether the connection is currently active.
929
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
930
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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...
931
	 */
932 View Code Duplication
	public function setup_xmlrpc_handlers(
933
		$request_params,
934
		$is_active,
935
		$is_signed,
936
		Jetpack_XMLRPC_Server $xmlrpc_server = null
937
	) {
938
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
939
940
		if ( ! $this->connection_manager ) {
941
			$this->connection_manager = new Connection_Manager();
942
		}
943
944
		return $this->connection_manager->setup_xmlrpc_handlers(
945
			$request_params,
946
			$is_active,
947
			$is_signed,
948
			$xmlrpc_server
949
		);
950
	}
951
952
	/**
953
	 * Initialize REST API registration connector.
954
	 *
955
	 * @deprecated since 7.7.0
956
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
957
	 */
958 View Code Duplication
	public function initialize_rest_api_registration_connector() {
959
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
960
961
		if ( ! $this->connection_manager ) {
962
			$this->connection_manager = new Connection_Manager();
963
		}
964
965
		$this->connection_manager->initialize_rest_api_registration_connector();
966
	}
967
968
	/**
969
	 * This is ported over from the manage module, which has been deprecated and baked in here.
970
	 *
971
	 * @param $domains
972
	 */
973
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
974
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
975
	}
976
977
	/**
978
	 * Return $domains, with 'wordpress.com' appended.
979
	 * This is ported over from the manage module, which has been deprecated and baked in here.
980
	 *
981
	 * @param $domains
982
	 * @return array
983
	 */
984
	function allow_wpcom_domain( $domains ) {
985
		if ( empty( $domains ) ) {
986
			$domains = array();
987
		}
988
		$domains[] = 'wordpress.com';
989
		return array_unique( $domains );
990
	}
991
992
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
993
		$post = get_post( $post_id );
994
995
		if ( empty( $post ) ) {
996
			return $default_url;
997
		}
998
999
		$post_type = $post->post_type;
1000
1001
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1002
		// https://en.support.wordpress.com/custom-post-types/
1003
		$allowed_post_types = array(
1004
			'post',
1005
			'page',
1006
			'jetpack-portfolio',
1007
			'jetpack-testimonial',
1008
		);
1009
1010
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1011
			return $default_url;
1012
		}
1013
1014
		return Redirect::get_url(
1015
			'calypso-edit-' . $post_type,
1016
			array(
1017
				'path' => $post_id,
1018
			)
1019
		);
1020
	}
1021
1022
	function point_edit_comment_links_to_calypso( $url ) {
1023
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1024
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1025
1026
		return Redirect::get_url(
1027
			'calypso-edit-comment',
1028
			array(
1029
				'path' => $query_args['amp;c'],
1030
			)
1031
		);
1032
1033
	}
1034
1035
	/**
1036
	 * Extend Sync callables with Jetpack Plugin functions.
1037
	 *
1038
	 * @param array $callables list of callables.
1039
	 *
1040
	 * @return array list of callables.
1041
	 */
1042
	public function filter_sync_callable_whitelist( $callables ) {
1043
1044
		// Jetpack Functions.
1045
		$jetpack_callables = array(
1046
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1047
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1048
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1049
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1050
		);
1051
		$callables         = array_merge( $callables, $jetpack_callables );
1052
1053
		// Jetpack_SSO_Helpers.
1054
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1055
			$sso_helpers = array(
1056
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1057
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1058
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1059
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1060
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1061
			);
1062
			$callables   = array_merge( $callables, $sso_helpers );
1063
		}
1064
1065
		return $callables;
1066
	}
1067
1068
	/**
1069
	 * Extend Sync multisite callables with Jetpack Plugin functions.
1070
	 *
1071
	 * @param array $callables list of callables.
1072
	 *
1073
	 * @return array list of callables.
1074
	 */
1075
	public function filter_sync_multisite_callable_whitelist( $callables ) {
1076
1077
		// Jetpack Funtions.
1078
		$jetpack_multisite_callables = array(
1079
			'network_name'                        => array( 'Jetpack', 'network_name' ),
1080
			'network_allow_new_registrations'     => array( 'Jetpack', 'network_allow_new_registrations' ),
1081
			'network_add_new_users'               => array( 'Jetpack', 'network_add_new_users' ),
1082
			'network_site_upload_space'           => array( 'Jetpack', 'network_site_upload_space' ),
1083
			'network_upload_file_types'           => array( 'Jetpack', 'network_upload_file_types' ),
1084
			'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1085
		);
1086
		$callables                   = array_merge( $callables, $jetpack_multisite_callables );
1087
1088
		return $callables;
1089
	}
1090
1091
	/**
1092
	 * Deprecated
1093
	 * Please use Automattic\Jetpack\JITMS\JITM::jetpack_track_last_sync_callback instead.
1094
	 *
1095
	 * @param array $params The action parameters.
1096
	 *
1097
	 * @deprecated since 9.8.
1098
	 */
1099
	function jetpack_track_last_sync_callback( $params ) {
1100
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\Automattic\Jetpack\JITMS\JITM->jetpack_track_last_sync_callback' );
1101
		return Automattic\Jetpack\JITMS\JITM::get_instance()->jetpack_track_last_sync_callback( $params );
1102
	}
1103
1104
	function jetpack_connection_banner_callback() {
1105
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1106
1107
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1108
		if (
1109
			isset( $_REQUEST['dismissBanner'] ) &&
1110
			! Jetpack_Connection_Banner::force_display()
1111
		) {
1112
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1113
			wp_send_json_success();
1114
		}
1115
1116
		wp_die();
1117
	}
1118
1119
	/**
1120
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1121
	 * Only used in our alternate XML-RPC endpoint, where we want to
1122
	 * ensure that Core and other plugins' methods are not exposed.
1123
	 *
1124
	 * @deprecated since 7.7.0
1125
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1126
	 *
1127
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1128
	 * @return array Filtered $methods
1129
	 */
1130 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1131
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1132
1133
		if ( ! $this->connection_manager ) {
1134
			$this->connection_manager = new Connection_Manager();
1135
		}
1136
1137
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1138
	}
1139
1140
	/**
1141
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1142
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1143
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1144
	 * which is accessible via a different URI. Most of the below is copied directly
1145
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1146
	 *
1147
	 * @deprecated since 7.7.0
1148
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1149
	 */
1150 View Code Duplication
	public function alternate_xmlrpc() {
1151
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1152
1153
		if ( ! $this->connection_manager ) {
1154
			$this->connection_manager = new Connection_Manager();
1155
		}
1156
1157
		$this->connection_manager->alternate_xmlrpc();
1158
	}
1159
1160
	/**
1161
	 * The callback for the JITM ajax requests.
1162
	 *
1163
	 * @deprecated since 7.9.0
1164
	 */
1165
	function jetpack_jitm_ajax_callback() {
1166
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1167
	}
1168
1169
	/**
1170
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1171
	 */
1172
	function push_stats() {
1173
		if ( ! empty( $this->stats ) ) {
1174
			$this->do_stats( 'server_side' );
1175
		}
1176
	}
1177
1178
	/**
1179
	 * Sets the Jetpack custom capabilities.
1180
	 *
1181
	 * @param string[] $caps    Array of the user's capabilities.
1182
	 * @param string   $cap     Capability name.
1183
	 * @param int      $user_id The user ID.
1184
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1185
	 */
1186
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1187
		switch ( $cap ) {
1188
			case 'jetpack_manage_modules':
1189
			case 'jetpack_activate_modules':
1190
			case 'jetpack_deactivate_modules':
1191
				$caps = array( 'manage_options' );
1192
				break;
1193
			case 'jetpack_configure_modules':
1194
				$caps = array( 'manage_options' );
1195
				break;
1196
			case 'jetpack_manage_autoupdates':
1197
				$caps = array(
1198
					'manage_options',
1199
					'update_plugins',
1200
				);
1201
				break;
1202
			case 'jetpack_network_admin_page':
1203
			case 'jetpack_network_settings_page':
1204
				$caps = array( 'manage_network_plugins' );
1205
				break;
1206
			case 'jetpack_network_sites_page':
1207
				$caps = array( 'manage_sites' );
1208
				break;
1209 View Code Duplication
			case 'jetpack_admin_page':
1210
				$is_offline_mode = ( new Status() )->is_offline_mode();
1211
				if ( $is_offline_mode ) {
1212
					$caps = array( 'manage_options' );
1213
					break;
1214
				} else {
1215
					$caps = array( 'read' );
1216
				}
1217
				break;
1218
		}
1219
		return $caps;
1220
	}
1221
1222
	/**
1223
	 * Require a Jetpack authentication.
1224
	 *
1225
	 * @deprecated since 7.7.0
1226
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1227
	 */
1228 View Code Duplication
	public function require_jetpack_authentication() {
1229
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1230
1231
		if ( ! $this->connection_manager ) {
1232
			$this->connection_manager = new Connection_Manager();
1233
		}
1234
1235
		$this->connection_manager->require_jetpack_authentication();
1236
	}
1237
1238
	/**
1239
	 * Register assets for use in various modules and the Jetpack admin page.
1240
	 *
1241
	 * @uses wp_script_is, wp_register_script, plugins_url
1242
	 * @action wp_loaded
1243
	 * @return null
1244
	 */
1245
	public function register_assets() {
1246 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1247
			wp_register_script(
1248
				'jetpack-gallery-settings',
1249
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1250
				array( 'media-views' ),
1251
				'20121225'
1252
			);
1253
		}
1254
1255
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1256
			wp_register_script(
1257
				'jetpack-twitter-timeline',
1258
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1259
				array( 'jquery' ),
1260
				'4.0.0',
1261
				true
1262
			);
1263
		}
1264
1265
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1266
			wp_register_script(
1267
				'jetpack-facebook-embed',
1268
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1269
				array(),
1270
				null,
1271
				true
1272
			);
1273
1274
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1275
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1276
			if ( ! is_numeric( $fb_app_id ) ) {
1277
				$fb_app_id = '';
1278
			}
1279
			wp_localize_script(
1280
				'jetpack-facebook-embed',
1281
				'jpfbembed',
1282
				array(
1283
					'appid'  => $fb_app_id,
1284
					'locale' => $this->get_locale(),
1285
				)
1286
			);
1287
		}
1288
1289
		/**
1290
		 * As jetpack_register_genericons is by default fired off a hook,
1291
		 * the hook may have already fired by this point.
1292
		 * So, let's just trigger it manually.
1293
		 */
1294
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1295
		jetpack_register_genericons();
1296
1297
		/**
1298
		 * Register the social logos
1299
		 */
1300
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1301
		jetpack_register_social_logos();
1302
1303 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1304
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1305
		}
1306
	}
1307
1308
	/**
1309
	 * Guess locale from language code.
1310
	 *
1311
	 * @param string $lang Language code.
1312
	 * @return string|bool
1313
	 */
1314 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1315
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1316
			return 'en_US';
1317
		}
1318
1319
		if ( ! class_exists( 'GP_Locales' ) ) {
1320
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1321
				return false;
1322
			}
1323
1324
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1325
		}
1326
1327
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1328
			// WP.com: get_locale() returns 'it'
1329
			$locale = GP_Locales::by_slug( $lang );
1330
		} else {
1331
			// Jetpack: get_locale() returns 'it_IT';
1332
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1333
		}
1334
1335
		if ( ! $locale ) {
1336
			return false;
1337
		}
1338
1339
		if ( empty( $locale->facebook_locale ) ) {
1340
			if ( empty( $locale->wp_locale ) ) {
1341
				return false;
1342
			} else {
1343
				// Facebook SDK is smart enough to fall back to en_US if a
1344
				// locale isn't supported. Since supported Facebook locales
1345
				// can fall out of sync, we'll attempt to use the known
1346
				// wp_locale value and rely on said fallback.
1347
				return $locale->wp_locale;
1348
			}
1349
		}
1350
1351
		return $locale->facebook_locale;
1352
	}
1353
1354
	/**
1355
	 * Get the locale.
1356
	 *
1357
	 * @return string|bool
1358
	 */
1359
	function get_locale() {
1360
		$locale = $this->guess_locale_from_lang( get_locale() );
1361
1362
		if ( ! $locale ) {
1363
			$locale = 'en_US';
1364
		}
1365
1366
		return $locale;
1367
	}
1368
1369
	/**
1370
	 * Return the network_site_url so that .com knows what network this site is a part of.
1371
	 *
1372
	 * @param  bool $option
1373
	 * @return string
1374
	 */
1375
	public function jetpack_main_network_site_option( $option ) {
1376
		return network_site_url();
1377
	}
1378
	/**
1379
	 * Network Name.
1380
	 */
1381
	static function network_name( $option = null ) {
1382
		global $current_site;
1383
		return $current_site->site_name;
1384
	}
1385
	/**
1386
	 * Does the network allow new user and site registrations.
1387
	 *
1388
	 * @return string
1389
	 */
1390
	static function network_allow_new_registrations( $option = null ) {
1391
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1392
	}
1393
	/**
1394
	 * Does the network allow admins to add new users.
1395
	 *
1396
	 * @return boolian
1397
	 */
1398
	static function network_add_new_users( $option = null ) {
1399
		return (bool) get_site_option( 'add_new_users' );
1400
	}
1401
	/**
1402
	 * File upload psace left per site in MB.
1403
	 *  -1 means NO LIMIT.
1404
	 *
1405
	 * @return number
1406
	 */
1407
	static function network_site_upload_space( $option = null ) {
1408
		// value in MB
1409
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1410
	}
1411
1412
	/**
1413
	 * Network allowed file types.
1414
	 *
1415
	 * @return string
1416
	 */
1417
	static function network_upload_file_types( $option = null ) {
1418
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1419
	}
1420
1421
	/**
1422
	 * Maximum file upload size set by the network.
1423
	 *
1424
	 * @return number
1425
	 */
1426
	static function network_max_upload_file_size( $option = null ) {
1427
		// value in KB
1428
		return get_site_option( 'fileupload_maxk', 300 );
1429
	}
1430
1431
	/**
1432
	 * Lets us know if a site allows admins to manage the network.
1433
	 *
1434
	 * @return array
1435
	 */
1436
	static function network_enable_administration_menus( $option = null ) {
1437
		return get_site_option( 'menu_items' );
1438
	}
1439
1440
	/**
1441
	 * If a user has been promoted to or demoted from admin, we need to clear the
1442
	 * jetpack_other_linked_admins transient.
1443
	 *
1444
	 * @since 4.3.2
1445
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1446
	 *
1447
	 * @param int    $user_id   The user ID whose role changed.
1448
	 * @param string $role      The new role.
1449
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|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...
1450
	 */
1451
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1452
		if ( 'administrator' == $role
1453
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1454
			|| is_null( $old_roles )
1455
		) {
1456
			delete_transient( 'jetpack_other_linked_admins' );
1457
		}
1458
	}
1459
1460
	/**
1461
	 * Checks to see if there are any other users available to become primary
1462
	 * Users must both:
1463
	 * - Be linked to wpcom
1464
	 * - Be an admin
1465
	 *
1466
	 * @return mixed False if no other users are linked, Int if there are.
1467
	 */
1468
	static function get_other_linked_admins() {
1469
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1470
1471
		if ( false === $other_linked_users ) {
1472
			$admins = get_users( array( 'role' => 'administrator' ) );
1473
			if ( count( $admins ) > 1 ) {
1474
				$available = array();
1475
				foreach ( $admins as $admin ) {
1476
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1477
						$available[] = $admin->ID;
1478
					}
1479
				}
1480
1481
				$count_connected_admins = count( $available );
1482
				if ( count( $available ) > 1 ) {
1483
					$other_linked_users = $count_connected_admins;
1484
				} else {
1485
					$other_linked_users = 0;
1486
				}
1487
			} else {
1488
				$other_linked_users = 0;
1489
			}
1490
1491
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1492
		}
1493
1494
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1495
	}
1496
1497
	/**
1498
	 * Return whether we are dealing with a multi network setup or not.
1499
	 * The reason we are type casting this is because we want to avoid the situation where
1500
	 * the result is false since when is_main_network_option return false it cases
1501
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1502
	 * database which could be set to anything as opposed to what this function returns.
1503
	 *
1504
	 * @param  bool $option
1505
	 *
1506
	 * @return boolean
1507
	 */
1508
	public function is_main_network_option( $option ) {
1509
		// return '1' or ''
1510
		return (string) (bool) self::is_multi_network();
1511
	}
1512
1513
	/**
1514
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1515
	 *
1516
	 * @param  string $option
1517
	 * @return boolean
1518
	 */
1519
	public function is_multisite( $option ) {
1520
		return (string) (bool) is_multisite();
1521
	}
1522
1523
	/**
1524
	 * Implemented since there is no core is multi network function
1525
	 * Right now there is no way to tell if we which network is the dominant network on the system
1526
	 *
1527
	 * @since  3.3
1528
	 * @return boolean
1529
	 */
1530 View Code Duplication
	public static function is_multi_network() {
1531
		global  $wpdb;
1532
1533
		// if we don't have a multi site setup no need to do any more
1534
		if ( ! is_multisite() ) {
1535
			return false;
1536
		}
1537
1538
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1539
		if ( $num_sites > 1 ) {
1540
			return true;
1541
		} else {
1542
			return false;
1543
		}
1544
	}
1545
1546
	/**
1547
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1548
	 *
1549
	 * @return null
1550
	 */
1551
	function update_jetpack_main_network_site_option() {
1552
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1553
	}
1554
	/**
1555
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1556
	 */
1557
	function update_jetpack_network_settings() {
1558
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1559
		// Only sync this info for the main network site.
1560
	}
1561
1562
	/**
1563
	 * Get back if the current site is single user site.
1564
	 *
1565
	 * @return bool
1566
	 */
1567 View Code Duplication
	public static function is_single_user_site() {
1568
		global $wpdb;
1569
1570
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1571
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1572
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1573
		}
1574
		return 1 === (int) $some_users;
1575
	}
1576
1577
	/**
1578
	 * Returns true if the site has file write access false otherwise.
1579
	 *
1580
	 * @return string ( '1' | '0' )
1581
	 **/
1582
	public static function file_system_write_access() {
1583
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1584
			require_once ABSPATH . 'wp-admin/includes/file.php';
1585
		}
1586
1587
		require_once ABSPATH . 'wp-admin/includes/template.php';
1588
1589
		$filesystem_method = get_filesystem_method();
1590
		if ( $filesystem_method === 'direct' ) {
1591
			return 1;
1592
		}
1593
1594
		ob_start();
1595
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1596
		ob_end_clean();
1597
		if ( $filesystem_credentials_are_stored ) {
1598
			return 1;
1599
		}
1600
		return 0;
1601
	}
1602
1603
	/**
1604
	 * Finds out if a site is using a version control system.
1605
	 *
1606
	 * @return string ( '1' | '0' )
1607
	 **/
1608
	public static function is_version_controlled() {
1609
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1610
		return (string) (int) Functions::is_version_controlled();
1611
	}
1612
1613
	/**
1614
	 * Determines whether the current theme supports featured images or not.
1615
	 *
1616
	 * @return string ( '1' | '0' )
1617
	 */
1618
	public static function featured_images_enabled() {
1619
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1620
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1621
	}
1622
1623
	/**
1624
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1625
	 *
1626
	 * @deprecated 4.7 use get_avatar_url instead.
1627
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1628
	 * @param int               $size Size of the avatar image
1629
	 * @param string            $default URL to a default image to use if no avatar is available
1630
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1631
	 *
1632
	 * @return array
1633
	 */
1634
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1635
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1636
		return get_avatar_url(
1637
			$id_or_email,
1638
			array(
1639
				'size'          => $size,
1640
				'default'       => $default,
1641
				'force_default' => $force_display,
1642
			)
1643
		);
1644
	}
1645
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1646
	/**
1647
	 * jetpack_updates is saved in the following schema:
1648
	 *
1649
	 * array (
1650
	 *      'plugins'                       => (int) Number of plugin updates available.
1651
	 *      'themes'                        => (int) Number of theme updates available.
1652
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1653
	 *      'translations'                  => (int) Number of translation updates available.
1654
	 *      'total'                         => (int) Total of all available updates.
1655
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1656
	 * )
1657
	 *
1658
	 * @return array
1659
	 */
1660
	public static function get_updates() {
1661
		$update_data = wp_get_update_data();
1662
1663
		// Stores the individual update counts as well as the total count.
1664
		if ( isset( $update_data['counts'] ) ) {
1665
			$updates = $update_data['counts'];
1666
		}
1667
1668
		// If we need to update WordPress core, let's find the latest version number.
1669 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1670
			$cur = get_preferred_from_update_core();
1671
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1672
				$updates['wp_update_version'] = $cur->current;
1673
			}
1674
		}
1675
		return isset( $updates ) ? $updates : array();
1676
	}
1677
	// phpcs:enable
1678
1679
	public static function get_update_details() {
1680
		$update_details = array(
1681
			'update_core'    => get_site_transient( 'update_core' ),
1682
			'update_plugins' => get_site_transient( 'update_plugins' ),
1683
			'update_themes'  => get_site_transient( 'update_themes' ),
1684
		);
1685
		return $update_details;
1686
	}
1687
1688
	public static function refresh_update_data() {
1689
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1690
1691
	}
1692
1693
	public static function refresh_theme_data() {
1694
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1695
	}
1696
1697
	/**
1698
	 * Is Jetpack active?
1699
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1700
	 *
1701
	 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1702
	 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1703
	 *
1704
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1705
	 *
1706
	 * @deprecated 9.6.0
1707
	 *
1708
	 * @return bool
1709
	 */
1710
	public static function is_active() {
1711
		return self::connection()->is_active();
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1712
	}
1713
1714
	/**
1715
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1716
	 *
1717
	 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1718
	 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1719
	 * users and this option will be available by default for everybody.
1720
	 *
1721
	 * @since 9.6.0
1722
	 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1723
	 *
1724
	 * @return bool is the site connection ready to be used?
1725
	 */
1726
	public static function is_connection_ready() {
1727
		/**
1728
		 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1729
		 *
1730
		 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1731
		 *
1732
		 * @since 9.7.0
1733
		 *
1734
		 * @param bool                                  $is_connection_ready Is the connection ready?
1735
		 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1736
		 */
1737
		return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with self::connection().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1738
	}
1739
1740
	/**
1741
	 * Make an API call to WordPress.com for plan status
1742
	 *
1743
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1744
	 *
1745
	 * @return bool True if plan is updated, false if no update
1746
	 */
1747
	public static function refresh_active_plan_from_wpcom() {
1748
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1749
		return Jetpack_Plan::refresh_from_wpcom();
1750
	}
1751
1752
	/**
1753
	 * Get the plan that this Jetpack site is currently using
1754
	 *
1755
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1756
	 * @return array Active Jetpack plan details.
1757
	 */
1758
	public static function get_active_plan() {
1759
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1760
		return Jetpack_Plan::get();
1761
	}
1762
1763
	/**
1764
	 * Determine whether the active plan supports a particular feature
1765
	 *
1766
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1767
	 * @return bool True if plan supports feature, false if not.
1768
	 */
1769
	public static function active_plan_supports( $feature ) {
1770
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1771
		return Jetpack_Plan::supports( $feature );
1772
	}
1773
1774
	/**
1775
	 * Deprecated: Is Jetpack in development (offline) mode?
1776
	 *
1777
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1778
	 * and themes still use it, and we do not want to flood them with notices.
1779
	 *
1780
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1781
	 *
1782
	 * @deprecated since 8.0.
1783
	 */
1784
	public static function is_development_mode() {
1785
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1786
		return ( new Status() )->is_offline_mode();
1787
	}
1788
1789
	/**
1790
	 * Whether the site is currently onboarding or not.
1791
	 * A site is considered as being onboarded if it currently has an onboarding token.
1792
	 *
1793
	 * @since 5.8
1794
	 *
1795
	 * @access public
1796
	 * @static
1797
	 *
1798
	 * @return bool True if the site is currently onboarding, false otherwise
1799
	 */
1800
	public static function is_onboarding() {
1801
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1802
	}
1803
1804
	/**
1805
	 * Determines reason for Jetpack offline mode.
1806
	 */
1807
	public static function development_mode_trigger_text() {
1808
		$status = new Status();
1809
1810
		if ( ! $status->is_offline_mode() ) {
1811
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1812
		}
1813
1814
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1815
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1816
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1817
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1818
		} elseif ( $status->is_local_site() ) {
1819
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1820
			/** This filter is documented in packages/status/src/class-status.php */
1821
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1822
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1823
		} else {
1824
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1825
		}
1826
1827
		return $notice;
1828
1829
	}
1830
	/**
1831
	 * Get Jetpack offline mode notice text and notice class.
1832
	 *
1833
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1834
	 */
1835
	public static function show_development_mode_notice() {
1836 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1837
			$notice = sprintf(
1838
				/* translators: %s is a URL */
1839
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1840
				Redirect::get_url( 'jetpack-support-development-mode' )
1841
			);
1842
1843
			$notice .= ' ' . self::development_mode_trigger_text();
1844
1845
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1846
		}
1847
1848
		// Throw up a notice if using a development version and as for feedback.
1849
		if ( self::is_development_version() ) {
1850
			/* translators: %s is a URL */
1851
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1852
1853
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1854
		}
1855
		// Throw up a notice if using staging mode
1856 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1857
			/* translators: %s is a URL */
1858
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1859
1860
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1861
		}
1862
	}
1863
1864
	/**
1865
	 * Whether Jetpack's version maps to a public release, or a development version.
1866
	 */
1867
	public static function is_development_version() {
1868
		/**
1869
		 * Allows filtering whether this is a development version of Jetpack.
1870
		 *
1871
		 * This filter is especially useful for tests.
1872
		 *
1873
		 * @since 4.3.0
1874
		 *
1875
		 * @param bool $development_version Is this a develoment version of Jetpack?
1876
		 */
1877
		return (bool) apply_filters(
1878
			'jetpack_development_version',
1879
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1880
		);
1881
	}
1882
1883
	/**
1884
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1885
	 */
1886
	public static function is_user_connected( $user_id = false ) {
1887
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1888
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

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...
1889
	}
1890
1891
	/**
1892
	 * Get the wpcom user data of the current|specified connected user.
1893
	 */
1894
	public static function get_connected_user_data( $user_id = null ) {
1895
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1896
		return self::connection()->get_connected_user_data( $user_id );
1897
	}
1898
1899
	/**
1900
	 * Get the wpcom email of the current|specified connected user.
1901
	 */
1902
	public static function get_connected_user_email( $user_id = null ) {
1903
		if ( ! $user_id ) {
1904
			$user_id = get_current_user_id();
1905
		}
1906
1907
		$xml = new Jetpack_IXR_Client(
1908
			array(
1909
				'user_id' => $user_id,
1910
			)
1911
		);
1912
		$xml->query( 'wpcom.getUserEmail' );
1913
		if ( ! $xml->isError() ) {
1914
			return $xml->getResponse();
1915
		}
1916
		return false;
1917
	}
1918
1919
	/**
1920
	 * Get the wpcom email of the master user.
1921
	 */
1922
	public static function get_master_user_email() {
1923
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1924
		if ( $master_user_id ) {
1925
			return self::get_connected_user_email( $master_user_id );
1926
		}
1927
		return '';
1928
	}
1929
1930
	/**
1931
	 * Whether the current user is the connection owner.
1932
	 *
1933
	 * @deprecated since 7.7
1934
	 *
1935
	 * @return bool Whether the current user is the connection owner.
1936
	 */
1937
	public function current_user_is_connection_owner() {
1938
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1939
		return self::connection()->is_connection_owner();
1940
	}
1941
1942
	/**
1943
	 * Gets current user IP address.
1944
	 *
1945
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1946
	 *
1947
	 * @return string                  Current user IP address.
1948
	 */
1949
	public static function current_user_ip( $check_all_headers = false ) {
1950
		if ( $check_all_headers ) {
1951
			foreach ( array(
1952
				'HTTP_CF_CONNECTING_IP',
1953
				'HTTP_CLIENT_IP',
1954
				'HTTP_X_FORWARDED_FOR',
1955
				'HTTP_X_FORWARDED',
1956
				'HTTP_X_CLUSTER_CLIENT_IP',
1957
				'HTTP_FORWARDED_FOR',
1958
				'HTTP_FORWARDED',
1959
				'HTTP_VIA',
1960
			) as $key ) {
1961
				if ( ! empty( $_SERVER[ $key ] ) ) {
1962
					return $_SERVER[ $key ];
1963
				}
1964
			}
1965
		}
1966
1967
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1968
	}
1969
1970
	/**
1971
	 * Synchronize connected user role changes
1972
	 */
1973
	function user_role_change( $user_id ) {
1974
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1975
		Users::user_role_change( $user_id );
1976
	}
1977
1978
	/**
1979
	 * Loads the currently active modules.
1980
	 */
1981
	public static function load_modules() {
1982
		$is_offline_mode = ( new Status() )->is_offline_mode();
1983
		if (
1984
			! self::is_connection_ready()
1985
			&& ! $is_offline_mode
1986
			&& ! self::is_onboarding()
1987
			&& (
1988
				! is_multisite()
1989
				|| ! get_site_option( 'jetpack_protect_active' )
1990
			)
1991
		) {
1992
			return;
1993
		}
1994
1995
		$version = Jetpack_Options::get_option( 'version' );
1996 View Code Duplication
		if ( ! $version ) {
1997
			$version = $old_version = JETPACK__VERSION . ':' . time();
1998
			/** This action is documented in class.jetpack.php */
1999
			do_action( 'updating_jetpack_version', $version, false );
2000
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2001
		}
2002
		list( $version ) = explode( ':', $version );
2003
2004
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2005
2006
		$modules_data = array();
2007
2008
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2009
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2010
			$updated_modules = array();
2011
			foreach ( $modules as $module ) {
2012
				$modules_data[ $module ] = self::get_module( $module );
2013
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2014
					continue;
2015
				}
2016
2017
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2018
					continue;
2019
				}
2020
2021
				$updated_modules[] = $module;
2022
			}
2023
2024
			$modules = array_diff( $modules, $updated_modules );
2025
		}
2026
2027
		$is_site_connection = self::connection()->is_site_connection();
2028
2029
		foreach ( $modules as $index => $module ) {
2030
			// If we're in offline/site-connection mode, disable modules requiring a connection/user connection.
2031
			if ( $is_offline_mode || $is_site_connection ) {
2032
				// Prime the pump if we need to
2033
				if ( empty( $modules_data[ $module ] ) ) {
2034
					$modules_data[ $module ] = self::get_module( $module );
2035
				}
2036
				// If the module requires a connection, but we're in local mode, don't include it.
2037
				if ( $is_offline_mode && $modules_data[ $module ]['requires_connection'] ) {
2038
					continue;
2039
				}
2040
2041
				if ( $is_site_connection && $modules_data[ $module ]['requires_user_connection'] ) {
2042
					continue;
2043
				}
2044
			}
2045
2046
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2047
				continue;
2048
			}
2049
2050
			if ( ! include_once self::get_module_path( $module ) ) {
2051
				unset( $modules[ $index ] );
2052
				self::update_active_modules( array_values( $modules ) );
2053
				continue;
2054
			}
2055
2056
			/**
2057
			 * Fires when a specific module is loaded.
2058
			 * The dynamic part of the hook, $module, is the module slug.
2059
			 *
2060
			 * @since 1.1.0
2061
			 */
2062
			do_action( 'jetpack_module_loaded_' . $module );
2063
		}
2064
2065
		/**
2066
		 * Fires when all the modules are loaded.
2067
		 *
2068
		 * @since 1.1.0
2069
		 */
2070
		do_action( 'jetpack_modules_loaded' );
2071
2072
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
2073
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2074
	}
2075
2076
	/**
2077
	 * Check if Jetpack's REST API compat file should be included
2078
	 *
2079
	 * @action plugins_loaded
2080
	 * @return null
2081
	 */
2082
	public function check_rest_api_compat() {
2083
		/**
2084
		 * Filters the list of REST API compat files to be included.
2085
		 *
2086
		 * @since 2.2.5
2087
		 *
2088
		 * @param array $args Array of REST API compat files to include.
2089
		 */
2090
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2091
2092
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2093
			require_once $_jetpack_rest_api_compat_include;
2094
		}
2095
	}
2096
2097
	/**
2098
	 * Gets all plugins currently active in values, regardless of whether they're
2099
	 * traditionally activated or network activated.
2100
	 *
2101
	 * @todo Store the result in core's object cache maybe?
2102
	 */
2103
	public static function get_active_plugins() {
2104
		$active_plugins = (array) get_option( 'active_plugins', array() );
2105
2106
		if ( is_multisite() ) {
2107
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2108
			// whereas active_plugins stores them in the values.
2109
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2110
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2111
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2112
			}
2113
		}
2114
2115
		sort( $active_plugins );
2116
2117
		return array_unique( $active_plugins );
2118
	}
2119
2120
	/**
2121
	 * Gets and parses additional plugin data to send with the heartbeat data
2122
	 *
2123
	 * @since 3.8.1
2124
	 *
2125
	 * @return array Array of plugin data
2126
	 */
2127
	public static function get_parsed_plugin_data() {
2128
		if ( ! function_exists( 'get_plugins' ) ) {
2129
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2130
		}
2131
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2132
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2133
		$active_plugins = self::get_active_plugins();
2134
2135
		$plugins = array();
2136
		foreach ( $all_plugins as $path => $plugin_data ) {
2137
			$plugins[ $path ] = array(
2138
				'is_active' => in_array( $path, $active_plugins ),
2139
				'file'      => $path,
2140
				'name'      => $plugin_data['Name'],
2141
				'version'   => $plugin_data['Version'],
2142
				'author'    => $plugin_data['Author'],
2143
			);
2144
		}
2145
2146
		return $plugins;
2147
	}
2148
2149
	/**
2150
	 * Gets and parses theme data to send with the heartbeat data
2151
	 *
2152
	 * @since 3.8.1
2153
	 *
2154
	 * @return array Array of theme data
2155
	 */
2156
	public static function get_parsed_theme_data() {
2157
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2158
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2159
2160
		$themes = array();
2161
		foreach ( $all_themes as $slug => $theme_data ) {
2162
			$theme_headers = array();
2163
			foreach ( $header_keys as $header_key ) {
2164
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2165
			}
2166
2167
			$themes[ $slug ] = array(
2168
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2169
				'slug'            => $slug,
2170
				'theme_root'      => $theme_data->get_theme_root_uri(),
2171
				'parent'          => $theme_data->parent(),
2172
				'headers'         => $theme_headers,
2173
			);
2174
		}
2175
2176
		return $themes;
2177
	}
2178
2179
	/**
2180
	 * Checks whether a specific plugin is active.
2181
	 *
2182
	 * We don't want to store these in a static variable, in case
2183
	 * there are switch_to_blog() calls involved.
2184
	 */
2185
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2186
		return in_array( $plugin, self::get_active_plugins() );
2187
	}
2188
2189
	/**
2190
	 * Check if Jetpack's Open Graph tags should be used.
2191
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2192
	 *
2193
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2194
	 * @action plugins_loaded
2195
	 * @return null
2196
	 */
2197
	public function check_open_graph() {
2198
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2199
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2200
		}
2201
2202
		$active_plugins = self::get_active_plugins();
2203
2204
		if ( ! empty( $active_plugins ) ) {
2205
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2206
				if ( in_array( $plugin, $active_plugins ) ) {
2207
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2208
					break;
2209
				}
2210
			}
2211
		}
2212
2213
		/**
2214
		 * Allow the addition of Open Graph Meta Tags to all pages.
2215
		 *
2216
		 * @since 2.0.3
2217
		 *
2218
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2219
		 */
2220
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2221
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2222
		}
2223
	}
2224
2225
	/**
2226
	 * Check if Jetpack's Twitter tags should be used.
2227
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2228
	 *
2229
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2230
	 * @action plugins_loaded
2231
	 * @return null
2232
	 */
2233
	public function check_twitter_tags() {
2234
2235
		$active_plugins = self::get_active_plugins();
2236
2237
		if ( ! empty( $active_plugins ) ) {
2238
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2239
				if ( in_array( $plugin, $active_plugins ) ) {
2240
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2241
					break;
2242
				}
2243
			}
2244
		}
2245
2246
		/**
2247
		 * Allow Twitter Card Meta tags to be disabled.
2248
		 *
2249
		 * @since 2.6.0
2250
		 *
2251
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2252
		 */
2253
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2254
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2255
		}
2256
	}
2257
2258
	/**
2259
	 * Allows plugins to submit security reports.
2260
	 *
2261
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2262
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2263
	 * @param array  $args         See definitions above
2264
	 */
2265
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2266
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2267
	}
2268
2269
	/* Jetpack Options API */
2270
2271
	public static function get_option_names( $type = 'compact' ) {
2272
		return Jetpack_Options::get_option_names( $type );
2273
	}
2274
2275
	/**
2276
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2277
	 *
2278
	 * @param string $name    Option name
2279
	 * @param mixed  $default (optional)
2280
	 */
2281
	public static function get_option( $name, $default = false ) {
2282
		return Jetpack_Options::get_option( $name, $default );
2283
	}
2284
2285
	/**
2286
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2287
	 *
2288
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2289
	 * @param string $name  Option name
2290
	 * @param mixed  $value Option value
2291
	 */
2292
	public static function update_option( $name, $value ) {
2293
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2294
		return Jetpack_Options::update_option( $name, $value );
2295
	}
2296
2297
	/**
2298
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2299
	 *
2300
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2301
	 * @param array $array array( option name => option value, ... )
2302
	 */
2303
	public static function update_options( $array ) {
2304
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2305
		return Jetpack_Options::update_options( $array );
2306
	}
2307
2308
	/**
2309
	 * Deletes the given option.  May be passed multiple option names as an array.
2310
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2311
	 *
2312
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2313
	 * @param string|array $names
2314
	 */
2315
	public static function delete_option( $names ) {
2316
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2317
		return Jetpack_Options::delete_option( $names );
2318
	}
2319
2320
	/**
2321
	 * Enters a user token into the user_tokens option
2322
	 *
2323
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2324
	 *
2325
	 * @param int    $user_id The user id.
2326
	 * @param string $token The user token.
2327
	 * @param bool   $is_master_user Whether the user is the master user.
2328
	 * @return bool
2329
	 */
2330
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2331
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2332
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2333
	}
2334
2335
	/**
2336
	 * Returns an array of all PHP files in the specified absolute path.
2337
	 * Equivalent to glob( "$absolute_path/*.php" ).
2338
	 *
2339
	 * @param string $absolute_path The absolute path of the directory to search.
2340
	 * @return array Array of absolute paths to the PHP files.
2341
	 */
2342
	public static function glob_php( $absolute_path ) {
2343
		if ( function_exists( 'glob' ) ) {
2344
			return glob( "$absolute_path/*.php" );
2345
		}
2346
2347
		$absolute_path = untrailingslashit( $absolute_path );
2348
		$files         = array();
2349
		if ( ! $dir = @opendir( $absolute_path ) ) {
2350
			return $files;
2351
		}
2352
2353
		while ( false !== $file = readdir( $dir ) ) {
2354
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2355
				continue;
2356
			}
2357
2358
			$file = "$absolute_path/$file";
2359
2360
			if ( ! is_file( $file ) ) {
2361
				continue;
2362
			}
2363
2364
			$files[] = $file;
2365
		}
2366
2367
		closedir( $dir );
2368
2369
		return $files;
2370
	}
2371
2372
	public static function activate_new_modules( $redirect = false ) {
2373
		if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2374
			return;
2375
		}
2376
2377
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2378 View Code Duplication
		if ( ! $jetpack_old_version ) {
2379
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2380
			/** This action is documented in class.jetpack.php */
2381
			do_action( 'updating_jetpack_version', $version, false );
2382
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2383
		}
2384
2385
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2386
2387
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2388
			return;
2389
		}
2390
2391
		$active_modules     = self::get_active_modules();
2392
		$reactivate_modules = array();
2393
		foreach ( $active_modules as $active_module ) {
2394
			$module = self::get_module( $active_module );
2395
			if ( ! isset( $module['changed'] ) ) {
2396
				continue;
2397
			}
2398
2399
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2400
				continue;
2401
			}
2402
2403
			$reactivate_modules[] = $active_module;
2404
			self::deactivate_module( $active_module );
2405
		}
2406
2407
		$new_version = JETPACK__VERSION . ':' . time();
2408
		/** This action is documented in class.jetpack.php */
2409
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2410
		Jetpack_Options::update_options(
2411
			array(
2412
				'version'     => $new_version,
2413
				'old_version' => $jetpack_old_version,
2414
			)
2415
		);
2416
2417
		self::state( 'message', 'modules_activated' );
2418
2419
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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...
2420
2421
		if ( $redirect ) {
2422
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2423
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2424
				$page = $_GET['page'];
2425
			}
2426
2427
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2428
			exit;
2429
		}
2430
	}
2431
2432
	/**
2433
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2434
	 * Make sure to tuck away module "library" files in a sub-directory.
2435
	 *
2436
	 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2437
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2438
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2439
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2440
	 *
2441
	 * @return array $modules Array of module slugs
2442
	 */
2443
	public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2444
		static $modules = null;
2445
2446
		if ( ! isset( $modules ) ) {
2447
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2448
			// Use the cache if we're on the front-end and it's available...
2449
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2450
				$modules = $available_modules_option[ JETPACK__VERSION ];
2451
			} else {
2452
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2453
2454
				$modules = array();
2455
2456
				foreach ( $files as $file ) {
2457
					if ( ! $headers = self::get_module( $file ) ) {
2458
						continue;
2459
					}
2460
2461
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2462
				}
2463
2464
				Jetpack_Options::update_option(
2465
					'available_modules',
2466
					array(
2467
						JETPACK__VERSION => $modules,
2468
					)
2469
				);
2470
			}
2471
		}
2472
2473
		/**
2474
		 * Filters the array of modules available to be activated.
2475
		 *
2476
		 * @since 2.4.0
2477
		 *
2478
		 * @param array $modules Array of available modules.
2479
		 * @param string $min_version Minimum version number required to use modules.
2480
		 * @param string $max_version Maximum version number required to use modules.
2481
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2482
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2483
		 */
2484
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2485
2486
		if ( ! $min_version && ! $max_version && is_null( $requires_connection ) && is_null( $requires_user_connection ) ) {
2487
			return array_keys( $mods );
2488
		}
2489
2490
		$r = array();
2491
		foreach ( $mods as $slug => $introduced ) {
2492
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2493
				continue;
2494
			}
2495
2496
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2497
				continue;
2498
			}
2499
2500
			$mod_details = self::get_module( $slug );
2501
2502
			if ( null !== $requires_connection && (bool) $requires_connection !== $mod_details['requires_connection'] ) {
2503
				continue;
2504
			}
2505
2506
			if ( null !== $requires_user_connection && (bool) $requires_user_connection !== $mod_details['requires_user_connection'] ) {
2507
				continue;
2508
			}
2509
2510
			$r[] = $slug;
2511
		}
2512
2513
		return $r;
2514
	}
2515
2516
	/**
2517
	 * Get default modules loaded on activation.
2518
	 *
2519
	 * @param bool|string $min_version Onlu return modules introduced in this version or later. Default is false, do not filter.
2520
	 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2521
	 * @param bool|null   $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2522
	 * @param bool|null   $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2523
	 *
2524
	 * @return array $modules Array of module slugs
2525
	 */
2526
	public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2527
		$return = array();
2528
2529
		foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2530
			$module_data = self::get_module( $module );
2531
2532
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2533
				case 'yes':
2534
					$return[] = $module;
2535
					break;
2536
				case 'public':
2537
					if ( Jetpack_Options::get_option( 'public' ) ) {
2538
						$return[] = $module;
2539
					}
2540
					break;
2541
				case 'no':
2542
				default:
2543
					break;
2544
			}
2545
		}
2546
		/**
2547
		 * Filters the array of default modules.
2548
		 *
2549
		 * @since 2.5.0
2550
		 *
2551
		 * @param array $return Array of default modules.
2552
		 * @param string $min_version Minimum version number required to use modules.
2553
		 * @param string $max_version Maximum version number required to use modules.
2554
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
2555
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2556
		 */
2557
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2558
	}
2559
2560
	/**
2561
	 * Checks activated modules during auto-activation to determine
2562
	 * if any of those modules are being deprecated.  If so, close
2563
	 * them out, and add any replacement modules.
2564
	 *
2565
	 * Runs at priority 99 by default.
2566
	 *
2567
	 * This is run late, so that it can still activate a module if
2568
	 * the new module is a replacement for another that the user
2569
	 * currently has active, even if something at the normal priority
2570
	 * would kibosh everything.
2571
	 *
2572
	 * @since 2.6
2573
	 * @uses jetpack_get_default_modules filter
2574
	 * @param array $modules
2575
	 * @return array
2576
	 */
2577
	function handle_deprecated_modules( $modules ) {
2578
		$deprecated_modules = array(
2579
			'debug'            => null,  // Closed out and moved to the debugger library.
2580
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2581
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2582
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2583
		);
2584
2585
		// Don't activate SSO if they never completed activating WPCC.
2586
		if ( self::is_module_active( 'wpcc' ) ) {
2587
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2588
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2589
				$deprecated_modules['wpcc'] = null;
2590
			}
2591
		}
2592
2593
		foreach ( $deprecated_modules as $module => $replacement ) {
2594
			if ( self::is_module_active( $module ) ) {
2595
				self::deactivate_module( $module );
2596
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string 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...
2597
					$modules[] = $replacement;
2598
				}
2599
			}
2600
		}
2601
2602
		return array_unique( $modules );
2603
	}
2604
2605
	/**
2606
	 * Checks activated plugins during auto-activation to determine
2607
	 * if any of those plugins are in the list with a corresponding module
2608
	 * that is not compatible with the plugin. The module will not be allowed
2609
	 * to auto-activate.
2610
	 *
2611
	 * @since 2.6
2612
	 * @uses jetpack_get_default_modules filter
2613
	 * @param array $modules
2614
	 * @return array
2615
	 */
2616
	function filter_default_modules( $modules ) {
2617
2618
		$active_plugins = self::get_active_plugins();
2619
2620
		if ( ! empty( $active_plugins ) ) {
2621
2622
			// For each module we'd like to auto-activate...
2623
			foreach ( $modules as $key => $module ) {
2624
				// If there are potential conflicts for it...
2625
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2626
					// For each potential conflict...
2627
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2628
						// If that conflicting plugin is active...
2629
						if ( in_array( $plugin, $active_plugins ) ) {
2630
							// Remove that item from being auto-activated.
2631
							unset( $modules[ $key ] );
2632
						}
2633
					}
2634
				}
2635
			}
2636
		}
2637
2638
		return $modules;
2639
	}
2640
2641
	/**
2642
	 * Extract a module's slug from its full path.
2643
	 */
2644
	public static function get_module_slug( $file ) {
2645
		return str_replace( '.php', '', basename( $file ) );
2646
	}
2647
2648
	/**
2649
	 * Generate a module's path from its slug.
2650
	 */
2651
	public static function get_module_path( $slug ) {
2652
		/**
2653
		 * Filters the path of a modules.
2654
		 *
2655
		 * @since 7.4.0
2656
		 *
2657
		 * @param array $return The absolute path to a module's root php file
2658
		 * @param string $slug The module slug
2659
		 */
2660
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2661
	}
2662
2663
	/**
2664
	 * Load module data from module file. Headers differ from WordPress
2665
	 * plugin headers to avoid them being identified as standalone
2666
	 * plugins on the WordPress plugins page.
2667
	 */
2668
	public static function get_module( $module ) {
2669
		$headers = array(
2670
			'name'                      => 'Module Name',
2671
			'description'               => 'Module Description',
2672
			'sort'                      => 'Sort Order',
2673
			'recommendation_order'      => 'Recommendation Order',
2674
			'introduced'                => 'First Introduced',
2675
			'changed'                   => 'Major Changes In',
2676
			'deactivate'                => 'Deactivate',
2677
			'free'                      => 'Free',
2678
			'requires_connection'       => 'Requires Connection',
2679
			'requires_user_connection'  => 'Requires User Connection',
2680
			'auto_activate'             => 'Auto Activate',
2681
			'module_tags'               => 'Module Tags',
2682
			'feature'                   => 'Feature',
2683
			'additional_search_queries' => 'Additional Search Queries',
2684
			'plan_classes'              => 'Plans',
2685
		);
2686
2687
		static $modules_details;
2688
		$file = self::get_module_path( self::get_module_slug( $module ) );
2689
2690
		if ( isset( $modules_details[ $module ] ) ) {
2691
			$mod = $modules_details[ $module ];
2692
		} else {
2693
2694
			$mod = self::get_file_data( $file, $headers );
2695
			if ( empty( $mod['name'] ) ) {
2696
				return false;
2697
			}
2698
2699
			$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2700
			$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2701
			$mod['deactivate']               = empty( $mod['deactivate'] );
2702
			$mod['free']                     = empty( $mod['free'] );
2703
			$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2704
			$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2705
2706
			if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ), true ) ) {
2707
				$mod['auto_activate'] = 'No';
2708
			} else {
2709
				$mod['auto_activate'] = (string) $mod['auto_activate'];
2710
			}
2711
2712
			if ( $mod['module_tags'] ) {
2713
				$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2714
				$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2715
				$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2716
			} else {
2717
				$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2718
			}
2719
2720 View Code Duplication
			if ( $mod['plan_classes'] ) {
2721
				$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2722
				$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2723
			} else {
2724
				$mod['plan_classes'] = array( 'free' );
2725
			}
2726
2727 View Code Duplication
			if ( $mod['feature'] ) {
2728
				$mod['feature'] = explode( ',', $mod['feature'] );
2729
				$mod['feature'] = array_map( 'trim', $mod['feature'] );
2730
			} else {
2731
				$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2732
			}
2733
2734
			$modules_details[ $module ] = $mod;
2735
2736
		}
2737
2738
		/**
2739
		 * Filters the feature array on a module.
2740
		 *
2741
		 * This filter allows you to control where each module is filtered: Recommended,
2742
		 * and the default "Other" listing.
2743
		 *
2744
		 * @since 3.5.0
2745
		 *
2746
		 * @param array   $mod['feature'] The areas to feature this module:
2747
		 *     'Recommended' shows on the main Jetpack admin screen.
2748
		 *     'Other' should be the default if no other value is in the array.
2749
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2750
		 * @param array   $mod All the currently assembled module data.
2751
		 */
2752
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2753
2754
		/**
2755
		 * Filter the returned data about a module.
2756
		 *
2757
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2758
		 * so please be careful.
2759
		 *
2760
		 * @since 3.6.0
2761
		 *
2762
		 * @param array   $mod    The details of the requested module.
2763
		 * @param string  $module The slug of the module, e.g. sharedaddy
2764
		 * @param string  $file   The path to the module source file.
2765
		 */
2766
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2767
	}
2768
2769
	/**
2770
	 * Like core's get_file_data implementation, but caches the result.
2771
	 */
2772
	public static function get_file_data( $file, $headers ) {
2773
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2774
		$file_name = basename( $file );
2775
2776
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2777
2778
		$file_data_option = get_transient( $cache_key );
2779
2780
		if ( ! is_array( $file_data_option ) ) {
2781
			delete_transient( $cache_key );
2782
			$file_data_option = false;
2783
		}
2784
2785
		if ( false === $file_data_option ) {
2786
			$file_data_option = array();
2787
		}
2788
2789
		$key           = md5( $file_name . serialize( $headers ) );
2790
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2791
2792
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2793
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2794
			return $file_data_option[ $key ];
2795
		}
2796
2797
		$data = get_file_data( $file, $headers );
2798
2799
		$file_data_option[ $key ] = $data;
2800
2801
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2802
2803
		return $data;
2804
	}
2805
2806
	/**
2807
	 * Return translated module tag.
2808
	 *
2809
	 * @param string $tag Tag as it appears in each module heading.
2810
	 *
2811
	 * @return mixed
2812
	 */
2813
	public static function translate_module_tag( $tag ) {
2814
		return jetpack_get_module_i18n_tag( $tag );
2815
	}
2816
2817
	/**
2818
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2819
	 *
2820
	 * @since 3.9.2
2821
	 *
2822
	 * @param array $modules
2823
	 *
2824
	 * @return string|void
2825
	 */
2826
	public static function get_translated_modules( $modules ) {
2827
		foreach ( $modules as $index => $module ) {
2828
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2829
			if ( isset( $module['name'] ) ) {
2830
				$modules[ $index ]['name'] = $i18n_module['name'];
2831
			}
2832
			if ( isset( $module['description'] ) ) {
2833
				$modules[ $index ]['description']       = $i18n_module['description'];
2834
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2835
			}
2836
		}
2837
		return $modules;
2838
	}
2839
2840
	/**
2841
	 * Get a list of activated modules as an array of module slugs.
2842
	 */
2843
	public static function get_active_modules() {
2844
		$active = Jetpack_Options::get_option( 'active_modules' );
2845
2846
		if ( ! is_array( $active ) ) {
2847
			$active = array();
2848
		}
2849
2850
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2851
			$active[] = 'vaultpress';
2852
		} else {
2853
			$active = array_diff( $active, array( 'vaultpress' ) );
2854
		}
2855
2856
		// If protect is active on the main site of a multisite, it should be active on all sites.
2857
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2858
			$active[] = 'protect';
2859
		}
2860
2861
		/**
2862
		 * Allow filtering of the active modules.
2863
		 *
2864
		 * Gives theme and plugin developers the power to alter the modules that
2865
		 * are activated on the fly.
2866
		 *
2867
		 * @since 5.8.0
2868
		 *
2869
		 * @param array $active Array of active module slugs.
2870
		 */
2871
		$active = apply_filters( 'jetpack_active_modules', $active );
2872
2873
		return array_unique( $active );
2874
	}
2875
2876
	/**
2877
	 * Check whether or not a Jetpack module is active.
2878
	 *
2879
	 * @param string $module The slug of a Jetpack module.
2880
	 * @return bool
2881
	 *
2882
	 * @static
2883
	 */
2884
	public static function is_module_active( $module ) {
2885
		return in_array( $module, self::get_active_modules() );
2886
	}
2887
2888
	public static function is_module( $module ) {
2889
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2890
	}
2891
2892
	/**
2893
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2894
	 *
2895
	 * @param bool $catch True to start catching, False to stop.
2896
	 *
2897
	 * @static
2898
	 */
2899
	public static function catch_errors( $catch ) {
2900
		static $display_errors, $error_reporting;
2901
2902
		if ( $catch ) {
2903
			$display_errors  = @ini_set( 'display_errors', 1 );
2904
			$error_reporting = @error_reporting( E_ALL );
2905
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2906
		} else {
2907
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2908
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2909
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2910
		}
2911
	}
2912
2913
	/**
2914
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2915
	 */
2916
	public static function catch_errors_on_shutdown() {
2917
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2918
	}
2919
2920
	/**
2921
	 * Rewrite any string to make paths easier to read.
2922
	 *
2923
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2924
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2925
	 *
2926
	 * @param $string
2927
	 * @return mixed
2928
	 */
2929
	public static function alias_directories( $string ) {
2930
		// ABSPATH has a trailing slash.
2931
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2932
		// WP_CONTENT_DIR does not have a trailing slash.
2933
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2934
2935
		return $string;
2936
	}
2937
2938
	public static function activate_default_modules(
2939
		$min_version = false,
2940
		$max_version = false,
2941
		$other_modules = array(),
2942
		$redirect = null,
2943
		$send_state_messages = null,
2944
		$requires_connection = null,
2945
		$requires_user_connection = null
2946
	) {
2947
		$jetpack = self::init();
2948
2949
		if ( is_null( $redirect ) ) {
2950
			if (
2951
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2952
			||
2953
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2954
			||
2955
				( defined( 'WP_CLI' ) && WP_CLI )
2956
			||
2957
				( defined( 'DOING_CRON' ) && DOING_CRON )
2958
			||
2959
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2960
			) {
2961
				$redirect = false;
2962
			} elseif ( is_admin() ) {
2963
				$redirect = true;
2964
			} else {
2965
				$redirect = false;
2966
			}
2967
		}
2968
2969
		if ( is_null( $send_state_messages ) ) {
2970
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2971
		}
2972
2973
		$modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2974
		$modules = array_merge( $other_modules, $modules );
2975
2976
		// Look for standalone plugins and disable if active.
2977
2978
		$to_deactivate = array();
2979
		foreach ( $modules as $module ) {
2980
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2981
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2982
			}
2983
		}
2984
2985
		$deactivated = array();
2986
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2987
			list( $probable_file, $probable_title ) = $deactivate_me;
2988
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2989
				$deactivated[] = $module;
2990
			}
2991
		}
2992
2993
		if ( $deactivated ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2994
			if ( $send_state_messages ) {
2995
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2996
			}
2997
2998
			if ( $redirect ) {
2999
				$url = add_query_arg(
3000
					array(
3001
						'action'   => 'activate_default_modules',
3002
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3003
					),
3004
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3005
				);
3006
				wp_safe_redirect( $url );
3007
				exit;
3008
			}
3009
		}
3010
3011
		/**
3012
		 * Fires before default modules are activated.
3013
		 *
3014
		 * @since 1.9.0
3015
		 *
3016
		 * @param string    $min_version Minimum version number required to use modules.
3017
		 * @param string    $max_version Maximum version number required to use modules.
3018
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3019
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3020
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3021
		 */
3022
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3023
3024
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3025
		if ( $send_state_messages ) {
3026
			self::restate();
3027
			self::catch_errors( true );
3028
		}
3029
3030
		$active = self::get_active_modules();
3031
3032
		foreach ( $modules as $module ) {
3033
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3034
				$active[] = $module;
3035
				self::update_active_modules( $active );
3036
				continue;
3037
			}
3038
3039
			if ( $send_state_messages && in_array( $module, $active ) ) {
3040
				$module_info = self::get_module( $module );
3041 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3042
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3043
					if ( $active_state = self::state( $state ) ) {
3044
						$active_state = explode( ',', $active_state );
3045
					} else {
3046
						$active_state = array();
3047
					}
3048
					$active_state[] = $module;
3049
					self::state( $state, implode( ',', $active_state ) );
3050
				}
3051
				continue;
3052
			}
3053
3054
			$file = self::get_module_path( $module );
3055
			if ( ! file_exists( $file ) ) {
3056
				continue;
3057
			}
3058
3059
			// we'll override this later if the plugin can be included without fatal error
3060
			if ( $redirect ) {
3061
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3062
			}
3063
3064
			if ( $send_state_messages ) {
3065
				self::state( 'error', 'module_activation_failed' );
3066
				self::state( 'module', $module );
3067
			}
3068
3069
			ob_start();
3070
			require_once $file;
3071
3072
			$active[] = $module;
3073
3074 View Code Duplication
			if ( $send_state_messages ) {
3075
3076
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3077
				if ( $active_state = self::state( $state ) ) {
3078
					$active_state = explode( ',', $active_state );
3079
				} else {
3080
					$active_state = array();
3081
				}
3082
				$active_state[] = $module;
3083
				self::state( $state, implode( ',', $active_state ) );
3084
			}
3085
3086
			self::update_active_modules( $active );
3087
3088
			ob_end_clean();
3089
		}
3090
3091
		if ( $send_state_messages ) {
3092
			self::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
3093
			self::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
3094
		}
3095
3096
		self::catch_errors( false );
3097
		/**
3098
		 * Fires when default modules are activated.
3099
		 *
3100
		 * @since 1.9.0
3101
		 *
3102
		 * @param string    $min_version Minimum version number required to use modules.
3103
		 * @param string    $max_version Maximum version number required to use modules.
3104
		 * @param array     $other_modules Array of other modules to activate alongside the default modules.
3105
		 * @param bool|null $requires_connection Value of the Requires Connection filter.
3106
		 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
3107
		 */
3108
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
3109
	}
3110
3111
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3112
		/**
3113
		 * Fires before a module is activated.
3114
		 *
3115
		 * @since 2.6.0
3116
		 *
3117
		 * @param string $module Module slug.
3118
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3119
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3120
		 */
3121
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3122
3123
		$jetpack = self::init();
3124
3125
		if ( ! strlen( $module ) ) {
3126
			return false;
3127
		}
3128
3129
		if ( ! self::is_module( $module ) ) {
3130
			return false;
3131
		}
3132
3133
		// If it's already active, then don't do it again
3134
		$active = self::get_active_modules();
3135
		foreach ( $active as $act ) {
3136
			if ( $act == $module ) {
3137
				return true;
3138
			}
3139
		}
3140
3141
		$module_data = self::get_module( $module );
3142
3143
		$is_offline_mode = ( new Status() )->is_offline_mode();
3144
		if ( ! self::is_connection_ready() ) {
3145
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3146
				return false;
3147
			}
3148
3149
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3150
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3151
				return false;
3152
			}
3153
		}
3154
3155
		// Check and see if the old plugin is active
3156
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3157
			// Deactivate the old plugin
3158
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3159
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3160
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3161
				self::state( 'deactivated_plugins', $module );
3162
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3163
				exit;
3164
			}
3165
		}
3166
3167
		// Protect won't work with mis-configured IPs
3168
		if ( 'protect' === $module ) {
3169
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3170
			if ( ! jetpack_protect_get_ip() ) {
3171
				self::state( 'message', 'protect_misconfigured_ip' );
3172
				return false;
3173
			}
3174
		}
3175
3176
		if ( ! Jetpack_Plan::supports( $module ) ) {
3177
			return false;
3178
		}
3179
3180
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3181
		self::state( 'module', $module );
3182
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3183
3184
		self::catch_errors( true );
3185
		ob_start();
3186
		require self::get_module_path( $module );
3187
		/** This action is documented in class.jetpack.php */
3188
		do_action( 'jetpack_activate_module', $module );
3189
		$active[] = $module;
3190
		self::update_active_modules( $active );
3191
3192
		self::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
3193
		ob_end_clean();
3194
		self::catch_errors( false );
3195
3196
		if ( $redirect ) {
3197
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3198
		}
3199
		if ( $exit ) {
3200
			exit;
3201
		}
3202
		return true;
3203
	}
3204
3205
	function activate_module_actions( $module ) {
3206
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3207
	}
3208
3209
	public static function deactivate_module( $module ) {
3210
		/**
3211
		 * Fires when a module is deactivated.
3212
		 *
3213
		 * @since 1.9.0
3214
		 *
3215
		 * @param string $module Module slug.
3216
		 */
3217
		do_action( 'jetpack_pre_deactivate_module', $module );
3218
3219
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3220
3221
		$active = self::get_active_modules();
3222
		$new    = array_filter( array_diff( $active, (array) $module ) );
3223
3224
		return self::update_active_modules( $new );
3225
	}
3226
3227
	public static function enable_module_configurable( $module ) {
3228
		$module = self::get_module_slug( $module );
3229
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3230
	}
3231
3232
	/**
3233
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3234
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3235
	 *
3236
	 * @param string $module Module slug
3237
	 * @return string $url module configuration URL
3238
	 */
3239
	public static function module_configuration_url( $module ) {
3240
		$module      = self::get_module_slug( $module );
3241
		$default_url = self::admin_url() . "#/settings?term=$module";
3242
		/**
3243
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3244
		 *
3245
		 * @since 6.9.0
3246
		 *
3247
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3248
		 */
3249
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3250
3251
		return $url;
3252
	}
3253
3254
	/* Installation */
3255
	public static function bail_on_activation( $message, $deactivate = true ) {
3256
		?>
3257
<!doctype html>
3258
<html>
3259
<head>
3260
<meta charset="<?php bloginfo( 'charset' ); ?>">
3261
<style>
3262
* {
3263
	text-align: center;
3264
	margin: 0;
3265
	padding: 0;
3266
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3267
}
3268
p {
3269
	margin-top: 1em;
3270
	font-size: 18px;
3271
}
3272
</style>
3273
<body>
3274
<p><?php echo esc_html( $message ); ?></p>
3275
</body>
3276
</html>
3277
		<?php
3278
		if ( $deactivate ) {
3279
			$plugins = get_option( 'active_plugins' );
3280
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3281
			$update  = false;
3282
			foreach ( $plugins as $i => $plugin ) {
3283
				if ( $plugin === $jetpack ) {
3284
					$plugins[ $i ] = false;
3285
					$update        = true;
3286
				}
3287
			}
3288
3289
			if ( $update ) {
3290
				update_option( 'active_plugins', array_filter( $plugins ) );
3291
			}
3292
		}
3293
		exit;
3294
	}
3295
3296
	/**
3297
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3298
	 *
3299
	 * @static
3300
	 */
3301
	public static function plugin_activation( $network_wide ) {
3302
		Jetpack_Options::update_option( 'activated', 1 );
3303
3304
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3305
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3306
		}
3307
3308
		if ( $network_wide ) {
3309
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
3310
		}
3311
3312
		// For firing one-off events (notices) immediately after activation
3313
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3314
3315
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3316
3317
		Health::on_jetpack_activated();
3318
3319
		self::plugin_initialize();
3320
	}
3321
3322
	public static function get_activation_source( $referer_url ) {
3323
3324
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3325
			return array( 'wp-cli', null );
3326
		}
3327
3328
		$referer = wp_parse_url( $referer_url );
3329
3330
		$source_type  = 'unknown';
3331
		$source_query = null;
3332
3333
		if ( ! is_array( $referer ) ) {
3334
			return array( $source_type, $source_query );
3335
		}
3336
3337
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3338
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3339
3340
		if ( isset( $referer['query'] ) ) {
3341
			parse_str( $referer['query'], $query_parts );
3342
		} else {
3343
			$query_parts = array();
3344
		}
3345
3346
		if ( $plugins_path === $referer['path'] ) {
3347
			$source_type = 'list';
3348
		} elseif ( $plugins_install_path === $referer['path'] ) {
3349
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3350
			switch ( $tab ) {
3351
				case 'popular':
3352
					$source_type = 'popular';
3353
					break;
3354
				case 'recommended':
3355
					$source_type = 'recommended';
3356
					break;
3357
				case 'favorites':
3358
					$source_type = 'favorites';
3359
					break;
3360
				case 'search':
3361
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3362
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3363
					break;
3364
				default:
3365
					$source_type = 'featured';
3366
			}
3367
		}
3368
3369
		return array( $source_type, $source_query );
3370
	}
3371
3372
	/**
3373
	 * Runs before bumping version numbers up to a new version
3374
	 *
3375
	 * @param string $version    Version:timestamp.
3376
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3377
	 */
3378
	public static function do_version_bump( $version, $old_version ) {
3379
		if ( $old_version ) { // For existing Jetpack installations.
3380
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3381
3382
			// If a front end page is visited after the update, the 'wp' action will fire.
3383
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3384
3385
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3386
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3387
		}
3388
	}
3389
3390
	/**
3391
	 * Sets the display_update_modal state.
3392
	 */
3393
	public static function set_update_modal_display() {
3394
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
3395
3396
	}
3397
3398
	/**
3399
	 * Enqueues the block library styles.
3400
	 *
3401
	 * @param string $hook The current admin page.
3402
	 */
3403
	public static function enqueue_block_style( $hook ) {
3404
		if ( 'toplevel_page_jetpack' === $hook ) {
3405
			wp_enqueue_style( 'wp-block-library' );
3406
		}
3407
	}
3408
3409
	/**
3410
	 * Sets the internal version number and activation state.
3411
	 *
3412
	 * @static
3413
	 */
3414
	public static function plugin_initialize() {
3415
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3416
			Jetpack_Options::update_option( 'activated', 2 );
3417
		}
3418
3419 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3420
			$version = $old_version = JETPACK__VERSION . ':' . time();
3421
			/** This action is documented in class.jetpack.php */
3422
			do_action( 'updating_jetpack_version', $version, false );
3423
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3424
		}
3425
3426
		self::load_modules();
3427
3428
		Jetpack_Options::delete_option( 'do_activate' );
3429
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3430
	}
3431
3432
	/**
3433
	 * Removes all connection options
3434
	 *
3435
	 * @static
3436
	 */
3437
	public static function plugin_deactivation() {
3438
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3439
		$tracking = new Tracking();
3440
		$tracking->record_user_event( 'deactivate_plugin', array() );
3441
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3442
			Jetpack_Network::init()->deactivate();
3443
		} else {
3444
			self::disconnect( false );
3445
			// Jetpack_Heartbeat::init()->deactivate();
3446
		}
3447
	}
3448
3449
	/**
3450
	 * Disconnects from the Jetpack servers.
3451
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3452
	 *
3453
	 * @static
3454
	 */
3455
	public static function disconnect( $update_activated_state = true ) {
3456
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3457
3458
		$connection = self::connection();
3459
3460
		( new Nonce_Handler() )->clean_all();
3461
3462
		// If the site is in an IDC because sync is not allowed,
3463
		// let's make sure to not disconnect the production site.
3464
		if ( ! Identity_Crisis::validate_sync_error_idc_option() ) {
3465
			$tracking = new Tracking();
3466
			$tracking->record_user_event( 'disconnect_site', array() );
3467
3468
			$connection->disconnect_site_wpcom( true );
3469
		}
3470
3471
		$connection->delete_all_connection_tokens( true );
3472
		Identity_Crisis::clear_all_idc_options();
3473
3474
		if ( $update_activated_state ) {
3475
			Jetpack_Options::update_option( 'activated', 4 );
3476
		}
3477
3478
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3479
			// Check then record unique disconnection if site has never been disconnected previously
3480
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3481
				$jetpack_unique_connection['disconnected'] = 1;
3482
			} else {
3483
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3484
					// track unique disconnect
3485
					$jetpack = self::init();
3486
3487
					$jetpack->stat( 'connections', 'unique-disconnect' );
3488
					$jetpack->do_stats( 'server_side' );
3489
				}
3490
				// increment number of times disconnected
3491
				$jetpack_unique_connection['disconnected'] += 1;
3492
			}
3493
3494
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3495
		}
3496
3497
		// Delete all the sync related data. Since it could be taking up space.
3498
		Sender::get_instance()->uninstall();
3499
3500
	}
3501
3502
	/**
3503
	 * Disconnects the user
3504
	 *
3505
	 * @param int $user_id The user ID to disconnect.
3506
	 */
3507
	public function disconnect_user( $user_id ) {
3508
		$this->connection_manager->disconnect_user( $user_id );
3509
	}
3510
3511
	/**
3512
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3513
	 *
3514
	 * @deprecated since Jetpack 9.7.0
3515
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
3516
	 *
3517
	 * @return bool|WP_Error
3518
	 */
3519
	public static function try_registration() {
3520
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
3521
		return static::connection()->try_registration();
3522
	}
3523
3524
	/**
3525
	 * Checking the domain names in beta versions.
3526
	 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3527
	 *
3528
	 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3529
	 *
3530
	 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3531
	 */
3532
	public static function registration_check_domains( $error ) {
3533
		if ( static::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3534
			$domains_to_check = array_unique(
3535
				array(
3536
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3537
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3538
				)
3539
			);
3540
			foreach ( $domains_to_check as $domain ) {
3541
				$result = static::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3540 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3542
				if ( is_wp_error( $result ) ) {
3543
					return $result;
3544
				}
3545
			}
3546
		}
3547
3548
		return $error;
3549
	}
3550
3551
	/**
3552
	 * Tracking an internal event log. Try not to put too much chaff in here.
3553
	 *
3554
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3555
	 */
3556
	public static function log( $code, $data = null ) {
3557
		// only grab the latest 200 entries
3558
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3559
3560
		// Append our event to the log
3561
		$log_entry = array(
3562
			'time'    => time(),
3563
			'user_id' => get_current_user_id(),
3564
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3565
			'code'    => $code,
3566
		);
3567
		// Don't bother storing it unless we've got some.
3568
		if ( ! is_null( $data ) ) {
3569
			$log_entry['data'] = $data;
3570
		}
3571
		$log[] = $log_entry;
3572
3573
		// Try add_option first, to make sure it's not autoloaded.
3574
		// @todo: Add an add_option method to Jetpack_Options
3575
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3576
			Jetpack_Options::update_option( 'log', $log );
3577
		}
3578
3579
		/**
3580
		 * Fires when Jetpack logs an internal event.
3581
		 *
3582
		 * @since 3.0.0
3583
		 *
3584
		 * @param array $log_entry {
3585
		 *  Array of details about the log entry.
3586
		 *
3587
		 *  @param string time Time of the event.
3588
		 *  @param int user_id ID of the user who trigerred the event.
3589
		 *  @param int blog_id Jetpack Blog ID.
3590
		 *  @param string code Unique name for the event.
3591
		 *  @param string data Data about the event.
3592
		 * }
3593
		 */
3594
		do_action( 'jetpack_log_entry', $log_entry );
3595
	}
3596
3597
	/**
3598
	 * Get the internal event log.
3599
	 *
3600
	 * @param $event (string) - only return the specific log events
3601
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3602
	 *
3603
	 * @return array of log events || WP_Error for invalid params
3604
	 */
3605
	public static function get_log( $event = false, $num = false ) {
3606
		if ( $event && ! is_string( $event ) ) {
3607
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3608
		}
3609
3610
		if ( $num && ! is_numeric( $num ) ) {
3611
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3612
		}
3613
3614
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3615
3616
		// If nothing set - act as it did before, otherwise let's start customizing the output
3617
		if ( ! $num && ! $event ) {
3618
			return $entire_log;
3619
		} else {
3620
			$entire_log = array_reverse( $entire_log );
3621
		}
3622
3623
		$custom_log_output = array();
3624
3625
		if ( $event ) {
3626
			foreach ( $entire_log as $log_event ) {
3627
				if ( $event == $log_event['code'] ) {
3628
					$custom_log_output[] = $log_event;
3629
				}
3630
			}
3631
		} else {
3632
			$custom_log_output = $entire_log;
3633
		}
3634
3635
		if ( $num ) {
3636
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3637
		}
3638
3639
		return $custom_log_output;
3640
	}
3641
3642
	/**
3643
	 * Log modification of important settings.
3644
	 */
3645
	public static function log_settings_change( $option, $old_value, $value ) {
3646
		switch ( $option ) {
3647
			case 'jetpack_sync_non_public_post_stati':
3648
				self::log( $option, $value );
3649
				break;
3650
		}
3651
	}
3652
3653
	/**
3654
	 * Return stat data for WPCOM sync
3655
	 */
3656
	public static function get_stat_data( $encode = true, $extended = true ) {
3657
		$data = Jetpack_Heartbeat::generate_stats_array();
3658
3659
		if ( $extended ) {
3660
			$additional_data = self::get_additional_stat_data();
3661
			$data            = array_merge( $data, $additional_data );
3662
		}
3663
3664
		if ( $encode ) {
3665
			return json_encode( $data );
3666
		}
3667
3668
		return $data;
3669
	}
3670
3671
	/**
3672
	 * Get additional stat data to sync to WPCOM
3673
	 */
3674
	public static function get_additional_stat_data( $prefix = '' ) {
3675
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3676
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3677
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3678
		$return[ "{$prefix}site-count" ]    = 0;
3679
3680
		if ( function_exists( 'get_blog_count' ) ) {
3681
			$return[ "{$prefix}site-count" ] = get_blog_count();
3682
		}
3683
		return $return;
3684
	}
3685
3686
	private static function get_site_user_count() {
3687
		global $wpdb;
3688
3689
		if ( function_exists( 'wp_is_large_network' ) ) {
3690
			if ( wp_is_large_network( 'users' ) ) {
3691
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3692
			}
3693
		}
3694
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3695
			// It wasn't there, so regenerate the data and save the transient
3696
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3697
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3698
		}
3699
		return $user_count;
3700
	}
3701
3702
	/* Admin Pages */
3703
3704
	function admin_init() {
3705
		// If the plugin is not connected, display a connect message.
3706
		if (
3707
			// the plugin was auto-activated and needs its candy
3708
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3709
		||
3710
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3711
			! Jetpack_Options::get_option( 'activated' )
3712
		) {
3713
			self::plugin_initialize();
3714
		}
3715
3716
		$is_offline_mode              = ( new Status() )->is_offline_mode();
3717
		$fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3718
		/** Already documented in automattic/jetpack-connection::src/class-client.php */
3719
		$client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3720
3721
		if ( ! $is_offline_mode ) {
3722
			Jetpack_Connection_Banner::init();
3723
		}
3724
3725
		if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3726
			// Upgrade: 1.1 -> 1.1.1
3727
			// Check and see if host can verify the Jetpack servers' SSL certificate
3728
			$args = array();
3729
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3730
		}
3731
3732
		Jetpack_Recommendations_Banner::init();
3733
3734
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3735
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3736
		}
3737
3738
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3739
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3740
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3741
3742
		if ( isset( $_COOKIE['jetpackState']['display_update_modal'] ) ) {
3743
			add_action( 'admin_enqueue_scripts', __CLASS__ . '::enqueue_block_style' );
3744
		}
3745
3746
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3747
3748
		if ( self::is_connection_ready() || $is_offline_mode ) {
3749
			// Artificially throw errors in certain specific cases during plugin activation.
3750
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3751
		}
3752
3753
		// Add custom column in wp-admin/users.php to show whether user is linked.
3754
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3755
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3756
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3757
	}
3758
3759
	function admin_body_class( $admin_body_class = '' ) {
3760
		$classes = explode( ' ', trim( $admin_body_class ) );
3761
3762
		$classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3763
3764
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3765
		return " $admin_body_class ";
3766
	}
3767
3768
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3769
		return $admin_body_class . ' jetpack-pagestyles ';
3770
	}
3771
3772
	/**
3773
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3774
	 * This function artificially throws errors for such cases (per a specific list).
3775
	 *
3776
	 * @param string $plugin The activated plugin.
3777
	 */
3778
	function throw_error_on_activate_plugin( $plugin ) {
3779
		$active_modules = self::get_active_modules();
3780
3781
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3782
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3783
			$throw = false;
3784
3785
			// Try and make sure it really was the stats plugin
3786
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3787
				if ( 'stats.php' == basename( $plugin ) ) {
3788
					$throw = true;
3789
				}
3790
			} else {
3791
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3792
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3793
					$throw = true;
3794
				}
3795
			}
3796
3797
			if ( $throw ) {
3798
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3799
			}
3800
		}
3801
	}
3802
3803
	function intercept_plugin_error_scrape_init() {
3804
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3805
	}
3806
3807
	function intercept_plugin_error_scrape( $action, $result ) {
3808
		if ( ! $result ) {
3809
			return;
3810
		}
3811
3812
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3813
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3814
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3815
			}
3816
		}
3817
	}
3818
3819
	/**
3820
	 * Register the remote file upload request handlers, if needed.
3821
	 *
3822
	 * @access public
3823
	 */
3824
	public function add_remote_request_handlers() {
3825
		// Remote file uploads are allowed only via AJAX requests.
3826
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3827
			return;
3828
		}
3829
3830
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3831
		$remote_request_actions = array(
3832
			'jetpack_upload_file',
3833
			'jetpack_update_file',
3834
		);
3835
3836
		// phpcs:ignore WordPress.Security.NonceVerification
3837
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3838
			return;
3839
		}
3840
3841
		// Require Jetpack authentication for the remote file upload AJAX requests.
3842
		if ( ! $this->connection_manager ) {
3843
			$this->connection_manager = new Connection_Manager();
3844
		}
3845
3846
		$this->connection_manager->require_jetpack_authentication();
3847
3848
		// Register the remote file upload AJAX handlers.
3849
		foreach ( $remote_request_actions as $action ) {
3850
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3851
		}
3852
	}
3853
3854
	/**
3855
	 * Handler for Jetpack remote file uploads.
3856
	 *
3857
	 * @access public
3858
	 */
3859
	public function remote_request_handlers() {
3860
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3861
3862
		switch ( current_filter() ) {
3863
			case 'wp_ajax_nopriv_jetpack_upload_file':
3864
				$response = $this->upload_handler();
3865
				break;
3866
3867
			case 'wp_ajax_nopriv_jetpack_update_file':
3868
				$response = $this->upload_handler( true );
3869
				break;
3870
			default:
3871
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3872
				break;
3873
		}
3874
3875
		if ( ! $response ) {
3876
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3877
		}
3878
3879
		if ( is_wp_error( $response ) ) {
3880
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

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...
3881
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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...
3882
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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...
3883
3884
			if ( ! is_int( $status_code ) ) {
3885
				$status_code = 400;
3886
			}
3887
3888
			status_header( $status_code );
3889
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3890
		}
3891
3892
		status_header( 200 );
3893
		if ( true === $response ) {
3894
			exit;
3895
		}
3896
3897
		die( json_encode( (object) $response ) );
3898
	}
3899
3900
	/**
3901
	 * Uploads a file gotten from the global $_FILES.
3902
	 * If `$update_media_item` is true and `post_id` is defined
3903
	 * the attachment file of the media item (gotten through of the post_id)
3904
	 * will be updated instead of add a new one.
3905
	 *
3906
	 * @param  boolean $update_media_item - update media attachment
3907
	 * @return array - An array describing the uploadind files process
3908
	 */
3909
	function upload_handler( $update_media_item = false ) {
3910
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3911
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3912
		}
3913
3914
		$user = wp_authenticate( '', '' );
3915
		if ( ! $user || is_wp_error( $user ) ) {
3916
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 403.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3917
		}
3918
3919
		wp_set_current_user( $user->ID );
3920
3921
		if ( ! current_user_can( 'upload_files' ) ) {
3922
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3923
		}
3924
3925
		if ( empty( $_FILES ) ) {
3926
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3927
		}
3928
3929
		foreach ( array_keys( $_FILES ) as $files_key ) {
3930
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3931
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_hmac'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3932
			}
3933
		}
3934
3935
		$media_keys = array_keys( $_FILES['media'] );
3936
3937
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3938
		if ( ! $token || is_wp_error( $token ) ) {
3939
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3940
		}
3941
3942
		$uploaded_files = array();
3943
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3944
		unset( $GLOBALS['post'] );
3945
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3946
			$file = array();
3947
			foreach ( $media_keys as $media_key ) {
3948
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3949
			}
3950
3951
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3952
3953
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3954
			if ( $hmac_provided !== $hmac_file ) {
3955
				$uploaded_files[ $index ] = (object) array(
3956
					'error'             => 'invalid_hmac',
3957
					'error_description' => 'The corresponding HMAC for this file does not match',
3958
				);
3959
				continue;
3960
			}
3961
3962
			$_FILES['.jetpack.upload.'] = $file;
3963
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3964
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3965
				$post_id = 0;
3966
			}
3967
3968
			if ( $update_media_item ) {
3969
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3970
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3971
				}
3972
3973
				$media_array = $_FILES['media'];
3974
3975
				$file_array['name']     = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3976
				$file_array['type']     = $media_array['type'][0];
3977
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3978
				$file_array['error']    = $media_array['error'][0];
3979
				$file_array['size']     = $media_array['size'][0];
3980
3981
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3982
3983
				if ( is_wp_error( $edited_media_item ) ) {
3984
					return $edited_media_item;
3985
				}
3986
3987
				$response = (object) array(
3988
					'id'   => (string) $post_id,
3989
					'file' => (string) $edited_media_item->post_title,
3990
					'url'  => (string) wp_get_attachment_url( $post_id ),
3991
					'type' => (string) $edited_media_item->post_mime_type,
3992
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3993
				);
3994
3995
				return (array) array( $response );
3996
			}
3997
3998
			$attachment_id = media_handle_upload(
3999
				'.jetpack.upload.',
4000
				$post_id,
4001
				array(),
4002
				array(
4003
					'action' => 'jetpack_upload_file',
4004
				)
4005
			);
4006
4007
			if ( ! $attachment_id ) {
4008
				$uploaded_files[ $index ] = (object) array(
4009
					'error'             => 'unknown',
4010
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
4011
				);
4012
			} elseif ( is_wp_error( $attachment_id ) ) {
4013
				$uploaded_files[ $index ] = (object) array(
4014
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
4015
					'error_description' => $attachment_id->get_error_message(),
4016
				);
4017
			} else {
4018
				$attachment               = get_post( $attachment_id );
4019
				$uploaded_files[ $index ] = (object) array(
4020
					'id'   => (string) $attachment_id,
4021
					'file' => $attachment->post_title,
4022
					'url'  => wp_get_attachment_url( $attachment_id ),
4023
					'type' => $attachment->post_mime_type,
4024
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4025
				);
4026
				// Zip files uploads are not supported unless they are done for installation purposed
4027
				// lets delete them in case something goes wrong in this whole process
4028
				if ( 'application/zip' === $attachment->post_mime_type ) {
4029
					// Schedule a cleanup for 2 hours from now in case of failed install.
4030
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4031
				}
4032
			}
4033
		}
4034
		if ( ! is_null( $global_post ) ) {
4035
			$GLOBALS['post'] = $global_post;
4036
		}
4037
4038
		return $uploaded_files;
4039
	}
4040
4041
	/**
4042
	 * Add help to the Jetpack page
4043
	 *
4044
	 * @since Jetpack (1.2.3)
4045
	 * @return false if not the Jetpack page
4046
	 */
4047
	function admin_help() {
4048
		$current_screen = get_current_screen();
4049
4050
		// Overview
4051
		$current_screen->add_help_tab(
4052
			array(
4053
				'id'      => 'home',
4054
				'title'   => __( 'Home', 'jetpack' ),
4055
				'content' =>
4056
					'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4057
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4058
					'<p>' . __( 'On this page, you are able to view the modules available within Jetpack, learn more about them, and activate or deactivate them as needed.', 'jetpack' ) . '</p>',
4059
			)
4060
		);
4061
4062
		// Screen Content
4063
		if ( current_user_can( 'manage_options' ) ) {
4064
			$current_screen->add_help_tab(
4065
				array(
4066
					'id'      => 'settings',
4067
					'title'   => __( 'Settings', 'jetpack' ),
4068
					'content' =>
4069
						'<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4070
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4071
						'<ol>' .
4072
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4073
							'<li>' . __( 'Using the checkboxes next to each module, you can select multiple modules to toggle via the Bulk Actions menu at the top of the list.', 'jetpack' ) . '</li>' .
4074
						'</ol>' .
4075
						'<p>' . __( 'Using the tools on the right, you can search for specific modules, filter by module categories or which are active, or change the sorting order.', 'jetpack' ) . '</p>',
4076
				)
4077
			);
4078
		}
4079
4080
		// Help Sidebar
4081
		$support_url = Redirect::get_url( 'jetpack-support' );
4082
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4083
		$current_screen->set_help_sidebar(
4084
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4085
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4086
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4087
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4088
		);
4089
	}
4090
4091
	function admin_menu_css() {
4092
		wp_enqueue_style( 'jetpack-icons' );
4093
	}
4094
4095
	function admin_menu_order() {
4096
		return true;
4097
	}
4098
4099
	function jetpack_menu_order( $menu_order ) {
4100
		$jp_menu_order = array();
4101
4102
		foreach ( $menu_order as $index => $item ) {
4103
			if ( $item != 'jetpack' ) {
4104
				$jp_menu_order[] = $item;
4105
			}
4106
4107
			if ( $index == 0 ) {
4108
				$jp_menu_order[] = 'jetpack';
4109
			}
4110
		}
4111
4112
		return $jp_menu_order;
4113
	}
4114
4115
	function admin_banner_styles() {
4116
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4117
4118 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4119
			wp_register_style(
4120
				'jetpack-dops-style',
4121
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4122
				array(),
4123
				JETPACK__VERSION
4124
			);
4125
		}
4126
4127
		wp_enqueue_style(
4128
			'jetpack',
4129
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4130
			array( 'jetpack-dops-style' ),
4131
			JETPACK__VERSION . '-20121016'
4132
		);
4133
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4134
		wp_style_add_data( 'jetpack', 'suffix', $min );
4135
	}
4136
4137
	function plugin_action_links( $actions ) {
4138
4139
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), __( 'My Jetpack', 'jetpack' ) ) );
4140
4141
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4142
			return array_merge(
4143
				$jetpack_home,
4144
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4145
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4146
				$actions
4147
			);
4148
		}
4149
4150
		return array_merge( $jetpack_home, $actions );
4151
	}
4152
4153
	/**
4154
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4155
	 *
4156
	 * @param string $hook The current admin page.
4157
	 *
4158
	 * @return void
4159
	 */
4160
	public function deactivate_dialog( $hook ) {
4161
		if (
4162
			'plugins.php' === $hook
4163
			&& self::is_connection_ready()
4164
		) {
4165
4166
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4167
4168
			if ( count( $active_plugins_using_connection ) > 1 ) {
4169
4170
				add_thickbox();
4171
4172
				// Register jp-tracks-functions dependency.
4173
				Tracking::register_tracks_functions_scripts();
4174
4175
				wp_enqueue_script(
4176
					'jetpack-deactivate-dialog-js',
4177
					Assets::get_file_url_for_environment(
4178
						'_inc/build/jetpack-deactivate-dialog.min.js',
4179
						'_inc/jetpack-deactivate-dialog.js'
4180
					),
4181
					array( 'jquery', 'jp-tracks-functions' ),
4182
					JETPACK__VERSION,
4183
					true
4184
				);
4185
4186
				wp_localize_script(
4187
					'jetpack-deactivate-dialog-js',
4188
					'deactivate_dialog',
4189
					array(
4190
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4191
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4192
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4193
					)
4194
				);
4195
4196
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4197
4198
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4199
			}
4200
		}
4201
	}
4202
4203
	/**
4204
	 * Outputs the content of the deactivation modal
4205
	 *
4206
	 * @return void
4207
	 */
4208
	public function deactivate_dialog_content() {
4209
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4210
		unset( $active_plugins_using_connection['jetpack'] );
4211
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4209 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4212
	}
4213
4214
	/**
4215
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4216
	 *
4217
	 * @param string $login_url The wp-login URL.
4218
	 * @param string $redirect  URL to redirect users after logging in.
4219
	 * @since Jetpack 8.4
4220
	 * @return string
4221
	 */
4222
	public function login_url( $login_url, $redirect ) {
4223
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4224
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4225
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4226
		}
4227
		return $login_url;
4228
	}
4229
4230
	/**
4231
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4232
	 *
4233
	 * @since Jetpack 8.4
4234
	 */
4235
	public function login_init() {
4236
		// phpcs:ignore WordPress.Security.NonceVerification
4237
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4238
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4239
			wp_safe_redirect(
4240
				add_query_arg(
4241
					array(
4242
						'forceInstall' => 1,
4243
						'url'          => rawurlencode( get_site_url() ),
4244
					),
4245
					// @todo provide way to go to specific calypso env.
4246
					self::get_calypso_host() . 'jetpack/connect'
4247
				)
4248
			);
4249
			exit;
4250
		}
4251
	}
4252
4253
	/*
4254
	 * Registration flow:
4255
	 * 1 - ::admin_page_load() action=register
4256
	 * 2 - ::try_registration()
4257
	 * 3 - ::register()
4258
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4259
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4260
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4261
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4262
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4263
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4264
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4265
	 *       jetpack_id, jetpack_secret, jetpack_public
4266
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4267
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4268
	 * 5 - user logs in with WP.com account
4269
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4270
	 *		- Manager::authorize()
4271
	 *		- Manager::get_token()
4272
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4273
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4274
	 *			- which responds with access_token, token_type, scope
4275
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4276
	 *		- Jetpack::activate_default_modules()
4277
	 *     		- Deactivates deprecated plugins
4278
	 *     		- Activates all default modules
4279
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4280
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4281
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4282
	 *     Done!
4283
	 */
4284
4285
	/**
4286
	 * Handles the page load events for the Jetpack admin page
4287
	 */
4288
	function admin_page_load() {
4289
		$error = false;
4290
4291
		// Make sure we have the right body class to hook stylings for subpages off of.
4292
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4293
4294
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4295
			// Should only be used in intermediate redirects to preserve state across redirects
4296
			self::restate();
4297
		}
4298
4299
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4300
			// @todo: Add validation against a known allowed list.
4301
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4302
			// User clicked in the iframe to link their accounts
4303
			if ( ! self::connection()->is_user_connected() ) {
4304
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4305
4306
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4307
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4308
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4309
4310
				if ( isset( $_GET['notes_iframe'] ) ) {
4311
					$connect_url .= '&notes_iframe';
4312
				}
4313
				wp_redirect( $connect_url );
4314
				exit;
4315
			} else {
4316
				if ( ! isset( $_GET['calypso_env'] ) ) {
4317
					self::state( 'message', 'already_authorized' );
4318
					wp_safe_redirect( self::admin_url() );
4319
					exit;
4320
				} else {
4321
					$connect_url  = $this->build_connect_url( true, false, $from );
4322
					$connect_url .= '&already_authorized=true';
4323
					wp_redirect( $connect_url );
4324
					exit;
4325
				}
4326
			}
4327
		}
4328
4329
		if ( isset( $_GET['action'] ) ) {
4330
			switch ( $_GET['action'] ) {
4331
				case 'authorize_redirect':
4332
					self::log( 'authorize_redirect' );
4333
4334
					add_filter(
4335
						'allowed_redirect_hosts',
4336
						function ( $domains ) {
4337
							$domains[] = 'jetpack.com';
4338
							$domains[] = 'jetpack.wordpress.com';
4339
							$domains[] = 'wordpress.com';
4340
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4341
							return array_unique( $domains );
4342
						}
4343
					);
4344
4345
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4346
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4347
4348
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4349
						// The destination URL is missing or invalid, nothing to do here.
4350
						exit;
4351
					}
4352
4353
					if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4354
						// The user is either already connected, or finished the connection process.
4355
						wp_safe_redirect( $dest_url );
4356
						exit;
4357
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4358
						// The user decided not to proceed with setting up the connection.
4359
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4360
						exit;
4361
					}
4362
4363
					$redirect_args = array(
4364
						'page'     => 'jetpack',
4365
						'action'   => 'authorize_redirect',
4366
						'dest_url' => rawurlencode( $dest_url ),
4367
						'done'     => '1',
4368
					);
4369
4370
					if ( ! empty( $_GET['from'] ) && 'jetpack_site_only_checkout' === $_GET['from'] ) {
4371
						$redirect_args['from'] = 'jetpack_site_only_checkout';
4372
					}
4373
4374
					wp_safe_redirect( static::build_authorize_url( self::admin_url( $redirect_args ) ) );
0 ignored issues
show
Documentation introduced by
self::admin_url($redirect_args) is of type string, but the function expects a boolean.

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...
4375
					exit;
4376
				case 'authorize':
4377
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4378
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4379
					exit;
4380
				case 'register':
4381
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4382
						$error = 'cheatin';
4383
						break;
4384
					}
4385
					check_admin_referer( 'jetpack-register' );
4386
					self::log( 'register' );
4387
					self::maybe_set_version_option();
4388
					$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4389
					if ( $from ) {
4390
						static::connection()->add_register_request_param( 'from', (string) $from );
4391
					}
4392
					$registered = static::connection()->try_registration();
4393
					if ( is_wp_error( $registered ) ) {
4394
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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...
4395
						self::state( 'error', $error );
4396
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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...
4397
4398
						/**
4399
						 * Jetpack registration Error.
4400
						 *
4401
						 * @since 7.5.0
4402
						 *
4403
						 * @param string|int $error The error code.
4404
						 * @param \WP_Error $registered The error object.
4405
						 */
4406
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4407
						break;
4408
					}
4409
4410
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4411
4412
					/**
4413
					 * Jetpack registration Success.
4414
					 *
4415
					 * @since 7.5.0
4416
					 *
4417
					 * @param string $from 'from' GET parameter;
4418
					 */
4419
					do_action( 'jetpack_connection_register_success', $from );
4420
4421
					$url = $this->build_connect_url( true, $redirect, $from );
4422
4423
					if ( ! empty( $_GET['onboarding'] ) ) {
4424
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4425
					}
4426
4427
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4428
						$url = add_query_arg( 'auth_approved', 'true', $url );
4429
					}
4430
4431
					wp_redirect( $url );
4432
					exit;
4433
				case 'activate':
4434
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4435
						$error = 'cheatin';
4436
						break;
4437
					}
4438
4439
					$module = stripslashes( $_GET['module'] );
4440
					check_admin_referer( "jetpack_activate-$module" );
4441
					self::log( 'activate', $module );
4442
					if ( ! self::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4443
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4444
					}
4445
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4446
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4447
					exit;
4448
				case 'activate_default_modules':
4449
					check_admin_referer( 'activate_default_modules' );
4450
					self::log( 'activate_default_modules' );
4451
					self::restate();
4452
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4453
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4454
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4455
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4456
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4457
					exit;
4458 View Code Duplication
				case 'disconnect':
4459
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4460
						$error = 'cheatin';
4461
						break;
4462
					}
4463
4464
					check_admin_referer( 'jetpack-disconnect' );
4465
					self::log( 'disconnect' );
4466
					self::disconnect();
4467
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4468
					exit;
4469 View Code Duplication
				case 'reconnect':
4470
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4471
						$error = 'cheatin';
4472
						break;
4473
					}
4474
4475
					check_admin_referer( 'jetpack-reconnect' );
4476
					self::log( 'reconnect' );
4477
					self::disconnect();
4478
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4479
					exit;
4480 View Code Duplication
				case 'deactivate':
4481
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4482
						$error = 'cheatin';
4483
						break;
4484
					}
4485
4486
					$modules = stripslashes( $_GET['module'] );
4487
					check_admin_referer( "jetpack_deactivate-$modules" );
4488
					foreach ( explode( ',', $modules ) as $module ) {
4489
						self::log( 'deactivate', $module );
4490
						self::deactivate_module( $module );
4491
						self::state( 'message', 'module_deactivated' );
4492
					}
4493
					self::state( 'module', $modules );
4494
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4495
					exit;
4496
				case 'unlink':
4497
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4498
					check_admin_referer( 'jetpack-unlink' );
4499
					self::log( 'unlink' );
4500
					$this->connection_manager->disconnect_user();
4501
					self::state( 'message', 'unlinked' );
4502
					if ( 'sub-unlink' == $redirect ) {
4503
						wp_safe_redirect( admin_url() );
4504
					} else {
4505
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4506
					}
4507
					exit;
4508
				case 'onboard':
4509
					if ( ! current_user_can( 'manage_options' ) ) {
4510
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4511
					} else {
4512
						self::create_onboarding_token();
4513
						$url = $this->build_connect_url( true );
4514
4515
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4516
							$url = add_query_arg( 'onboarding', $token, $url );
4517
						}
4518
4519
						$calypso_env = $this->get_calypso_env();
4520
						if ( ! empty( $calypso_env ) ) {
4521
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4522
						}
4523
4524
						wp_redirect( $url );
4525
						exit;
4526
					}
4527
					exit;
4528
				default:
4529
					/**
4530
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4531
					 *
4532
					 * @since 2.6.0
4533
					 *
4534
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4535
					 */
4536
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4537
			}
4538
		}
4539
4540
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4541
			self::activate_new_modules( true );
4542
		}
4543
4544
		$message_code = self::state( 'message' );
4545
		if ( self::state( 'optin-manage' ) ) {
4546
			$activated_manage = $message_code;
4547
			$message_code     = 'jetpack-manage';
4548
		}
4549
4550
		switch ( $message_code ) {
4551
			case 'jetpack-manage':
4552
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4553
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4554
				$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), $sites_url ) . '</strong>';
4555
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4556
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4557
				}
4558
				break;
4559
4560
		}
4561
4562
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4563
4564
		if ( ! empty( $deactivated_plugins ) ) {
4565
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4566
			$deactivated_titles  = array();
4567
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4568
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4569
					continue;
4570
				}
4571
4572
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4573
			}
4574
4575
			if ( $deactivated_titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4576
				if ( $this->message ) {
4577
					$this->message .= "<br /><br />\n";
4578
				}
4579
4580
				$this->message .= wp_sprintf(
4581
					_n(
4582
						'Jetpack contains the most recent version of the old %l plugin.',
4583
						'Jetpack contains the most recent versions of the old %l plugins.',
4584
						count( $deactivated_titles ),
4585
						'jetpack'
4586
					),
4587
					$deactivated_titles
4588
				);
4589
4590
				$this->message .= "<br />\n";
4591
4592
				$this->message .= _n(
4593
					'The old version has been deactivated and can be removed from your site.',
4594
					'The old versions have been deactivated and can be removed from your site.',
4595
					count( $deactivated_titles ),
4596
					'jetpack'
4597
				);
4598
			}
4599
		}
4600
4601
		$this->privacy_checks = self::state( 'privacy_checks' );
4602
4603
		if ( $this->message || $this->error || $this->privacy_checks ) {
4604
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4605
		}
4606
4607
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4608
	}
4609
4610
	function admin_notices() {
4611
4612
		if ( $this->error ) {
4613
			?>
4614
<div id="message" class="jetpack-message jetpack-err">
4615
	<div class="squeezer">
4616
		<h2>
4617
			<?php
4618
			echo wp_kses(
4619
				$this->error,
4620
				array(
4621
					'a'      => array( 'href' => array() ),
4622
					'small'  => true,
4623
					'code'   => true,
4624
					'strong' => true,
4625
					'br'     => true,
4626
					'b'      => true,
4627
				)
4628
			);
4629
			?>
4630
			</h2>
4631
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4632
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4633
<?php	endif; ?>
4634
	</div>
4635
</div>
4636
			<?php
4637
		}
4638
4639
		if ( $this->message ) {
4640
			?>
4641
<div id="message" class="jetpack-message">
4642
	<div class="squeezer">
4643
		<h2>
4644
			<?php
4645
			echo wp_kses(
4646
				$this->message,
4647
				array(
4648
					'strong' => array(),
4649
					'a'      => array( 'href' => true ),
4650
					'br'     => true,
4651
				)
4652
			);
4653
			?>
4654
			</h2>
4655
	</div>
4656
</div>
4657
			<?php
4658
		}
4659
4660
		if ( $this->privacy_checks ) :
4661
			$module_names = $module_slugs = array();
4662
4663
			$privacy_checks = explode( ',', $this->privacy_checks );
4664
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4665
			foreach ( $privacy_checks as $module_slug ) {
4666
				$module = self::get_module( $module_slug );
4667
				if ( ! $module ) {
4668
					continue;
4669
				}
4670
4671
				$module_slugs[] = $module_slug;
4672
				$module_names[] = "<strong>{$module['name']}</strong>";
4673
			}
4674
4675
			$module_slugs = join( ',', $module_slugs );
4676
			?>
4677
<div id="message" class="jetpack-message jetpack-err">
4678
	<div class="squeezer">
4679
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4680
		<p>
4681
			<?php
4682
			echo wp_kses(
4683
				wptexturize(
4684
					wp_sprintf(
4685
						_nx(
4686
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4687
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4688
							count( $privacy_checks ),
4689
							'%l = list of Jetpack module/feature names',
4690
							'jetpack'
4691
						),
4692
						$module_names
4693
					)
4694
				),
4695
				array( 'strong' => true )
4696
			);
4697
4698
			echo "\n<br />\n";
4699
4700
			echo wp_kses(
4701
				sprintf(
4702
					_nx(
4703
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4704
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4705
						count( $privacy_checks ),
4706
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4707
						'jetpack'
4708
					),
4709
					wp_nonce_url(
4710
						self::admin_url(
4711
							array(
4712
								'page'   => 'jetpack',
4713
								'action' => 'deactivate',
4714
								'module' => urlencode( $module_slugs ),
4715
							)
4716
						),
4717
						"jetpack_deactivate-$module_slugs"
4718
					),
4719
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4720
				),
4721
				array(
4722
					'a' => array(
4723
						'href'  => true,
4724
						'title' => true,
4725
					),
4726
				)
4727
			);
4728
			?>
4729
		</p>
4730
	</div>
4731
</div>
4732
			<?php
4733
endif;
4734
	}
4735
4736
	/**
4737
	 * We can't always respond to a signed XML-RPC request with a
4738
	 * helpful error message. In some circumstances, doing so could
4739
	 * leak information.
4740
	 *
4741
	 * Instead, track that the error occurred via a Jetpack_Option,
4742
	 * and send that data back in the heartbeat.
4743
	 * All this does is increment a number, but it's enough to find
4744
	 * trends.
4745
	 *
4746
	 * @param WP_Error $xmlrpc_error The error produced during
4747
	 *                               signature validation.
4748
	 */
4749
	function track_xmlrpc_error( $xmlrpc_error ) {
4750
		$code = is_wp_error( $xmlrpc_error )
4751
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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...
4752
			: 'should-not-happen';
4753
4754
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4755
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4756
			// No need to update the option if we already have
4757
			// this code stored.
4758
			return;
4759
		}
4760
		$xmlrpc_errors[ $code ] = true;
4761
4762
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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...
4763
	}
4764
4765
	/**
4766
	 * Initialize the jetpack stats instance only when needed
4767
	 *
4768
	 * @return void
4769
	 */
4770
	private function initialize_stats() {
4771
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4772
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4773
		}
4774
	}
4775
4776
	/**
4777
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4778
	 */
4779
	function stat( $group, $detail ) {
4780
		$this->initialize_stats();
4781
		$this->a8c_mc_stats_instance->add( $group, $detail );
4782
4783
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4784
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4785
	}
4786
4787
	/**
4788
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4789
	 */
4790
	function do_stats( $method = '' ) {
4791
		$this->initialize_stats();
4792
		if ( 'server_side' === $method ) {
4793
			$this->a8c_mc_stats_instance->do_server_side_stats();
4794
		} else {
4795
			$this->a8c_mc_stats_instance->do_stats();
4796
		}
4797
4798
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4799
		$this->stats = array();
4800
	}
4801
4802
	/**
4803
	 * Runs stats code for a one-off, server-side.
4804
	 *
4805
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4806
	 *
4807
	 * @return bool If it worked.
4808
	 */
4809
	static function do_server_side_stat( $args ) {
4810
		$url                   = self::build_stats_url( $args );
4811
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4812
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4813
	}
4814
4815
	/**
4816
	 * Builds the stats url.
4817
	 *
4818
	 * @param $args array|string The arguments to append to the URL.
4819
	 *
4820
	 * @return string The URL to be pinged.
4821
	 */
4822
	static function build_stats_url( $args ) {
4823
4824
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4825
		return $a8c_mc_stats_instance->build_stats_url( $args );
4826
4827
	}
4828
4829
	/**
4830
	 * Builds a URL to the Jetpack connection auth page
4831
	 *
4832
	 * @since 3.9.5
4833
	 *
4834
	 * @param bool        $raw If true, URL will not be escaped.
4835
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4836
	 *                              If string, will be a custom redirect.
4837
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4838
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4839
	 *
4840
	 * @return string Connect URL
4841
	 */
4842
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4843
		$site_id    = Jetpack_Options::get_option( 'id' );
4844
		$blog_token = ( new Tokens() )->get_access_token();
4845
4846
		if ( $register || ! $blog_token || ! $site_id ) {
4847
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4848
4849
			if ( ! empty( $redirect ) ) {
4850
				$url = add_query_arg(
4851
					'redirect',
4852
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4853
					$url
4854
				);
4855
			}
4856
4857
			if ( is_network_admin() ) {
4858
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4859
			}
4860
4861
			$calypso_env = self::get_calypso_env();
4862
4863
			if ( ! empty( $calypso_env ) ) {
4864
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4865
			}
4866
		} else {
4867
4868
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4869
			// because otherwise this logic can get us in to a loop.
4870
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4871
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4872
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4873
4874
				$response = Client::wpcom_json_api_request_as_blog(
4875
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4876
					'1.1'
4877
				);
4878
4879
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4880
4881
					// Generating a register URL instead to refresh the existing token
4882
					return $this->build_connect_url( $raw, $redirect, $from, true );
4883
				}
4884
			}
4885
4886
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4842 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4887
		}
4888
4889
		if ( $from ) {
4890
			$url = add_query_arg( 'from', $from, $url );
4891
		}
4892
4893
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4894
		/**
4895
		 * Filter the URL used when connecting a user to a WordPress.com account.
4896
		 *
4897
		 * @since 8.1.0
4898
		 *
4899
		 * @param string $url Connection URL.
4900
		 * @param bool   $raw If true, URL will not be escaped.
4901
		 */
4902
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4903
	}
4904
4905
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4906
4907
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4908
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4909
4910
		if ( $iframe ) {
4911
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4912
		}
4913
4914
		$c8n = self::connection();
4915
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect is of type boolean, but the function expects a string|null.

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...
4916
4917
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4918
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4919
4920
		if ( $iframe ) {
4921
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4922
		}
4923
4924
		/**
4925
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4926
		 *
4927
		 * @since 8.9.0
4928
		 *
4929
		 * @param string $url Connection URL.
4930
		 */
4931
		return apply_filters( 'jetpack_build_authorize_url', $url );
4932
	}
4933
4934
	/**
4935
	 * Filters the connection URL parameter array.
4936
	 *
4937
	 * @param array $args default URL parameters used by the package.
4938
	 * @return array the modified URL arguments array.
4939
	 */
4940
	public static function filter_connect_request_body( $args ) {
4941
		if (
4942
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4943
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4944
		) {
4945
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4946
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4947
				? $gp_locale->slug
4948
				: '';
4949
		}
4950
4951
		$tracking        = new Tracking();
4952
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4953
4954
		$args = array_merge(
4955
			$args,
4956
			array(
4957
				'_ui' => $tracks_identity['_ui'],
4958
				'_ut' => $tracks_identity['_ut'],
4959
			)
4960
		);
4961
4962
		$calypso_env = self::get_calypso_env();
4963
4964
		if ( ! empty( $calypso_env ) ) {
4965
			$args['calypso_env'] = $calypso_env;
4966
		}
4967
4968
		return $args;
4969
	}
4970
4971
	/**
4972
	 * Filters the URL that will process the connection data. It can be different from the URL
4973
	 * that we send the user to after everything is done.
4974
	 *
4975
	 * @param String $processing_url the default redirect URL used by the package.
4976
	 * @return String the modified URL.
4977
	 *
4978
	 * @deprecated since Jetpack 9.5.0
4979
	 */
4980
	public static function filter_connect_processing_url( $processing_url ) {
4981
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4982
4983
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4984
		return $processing_url;
4985
	}
4986
4987
	/**
4988
	 * Filters the redirection URL that is used for connect requests. The redirect
4989
	 * URL should return the user back to the Jetpack console.
4990
	 *
4991
	 * @param String $redirect the default redirect URL used by the package.
4992
	 * @return String the modified URL.
4993
	 */
4994
	public static function filter_connect_redirect_url( $redirect ) {
4995
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4996
		$redirect           = $redirect
4997
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4998
			: $jetpack_admin_page;
4999
5000
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5001
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5002
		}
5003
5004
		return $redirect;
5005
	}
5006
5007
	/**
5008
	 * This action fires at the beginning of the Manager::authorize method.
5009
	 */
5010
	public static function authorize_starting() {
5011
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5012
		// Checking if site has been active/connected previously before recording unique connection.
5013
		if ( ! $jetpack_unique_connection ) {
5014
			// jetpack_unique_connection option has never been set.
5015
			$jetpack_unique_connection = array(
5016
				'connected'    => 0,
5017
				'disconnected' => 0,
5018
				'version'      => '3.6.1',
5019
			);
5020
5021
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5022
5023
			// Track unique connection.
5024
			$jetpack = self::init();
5025
5026
			$jetpack->stat( 'connections', 'unique-connection' );
5027
			$jetpack->do_stats( 'server_side' );
5028
		}
5029
5030
		// Increment number of times connected.
5031
		$jetpack_unique_connection['connected'] += 1;
5032
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5033
	}
5034
5035
	/**
5036
	 * This action fires when the site is registered (connected at a site level).
5037
	 */
5038
	public function handle_unique_registrations_stats() {
5039
		$jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5040
		// Checking if site has been registered previously before recording unique connection.
5041
		if ( ! $jetpack_unique_registrations ) {
5042
5043
			$jetpack_unique_registrations = 0;
5044
5045
			$this->stat( 'connections', 'unique-registrations' );
5046
			$this->do_stats( 'server_side' );
5047
		}
5048
5049
		// Increment number of times connected.
5050
		$jetpack_unique_registrations ++;
5051
		Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5052
	}
5053
5054
	/**
5055
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5056
	 * linked.
5057
	 */
5058
	public static function authorize_ending_linked() {
5059
		// Don't activate anything since we are just connecting a user.
5060
		self::state( 'message', 'linked' );
5061
	}
5062
5063
	/**
5064
	 * This action fires at the end of the Manager::authorize method when the master user is
5065
	 * authorized.
5066
	 *
5067
	 * @param array $data The request data.
5068
	 */
5069
	public static function authorize_ending_authorized( $data ) {
5070
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5071
		self::invalidate_onboarding_token();
5072
5073
		// If redirect_uri is SSO, ensure SSO module is enabled.
5074
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5075
5076
		/** This filter is documented in class.jetpack-cli.php */
5077
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5078
5079
		$activate_sso = (
5080
			isset( $redirect_options['action'] ) &&
5081
			'jetpack-sso' === $redirect_options['action'] &&
5082
			$jetpack_start_enable_sso
5083
		);
5084
5085
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5086
5087
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5088
	}
5089
5090
	/**
5091
	 * Fires on the jetpack_site_registered hook and acitvates default modules
5092
	 */
5093
	public static function activate_default_modules_on_site_register() {
5094
		$active_modules = Jetpack_Options::get_option( 'active_modules' );
5095
		if ( $active_modules ) {
5096
			self::delete_active_modules();
5097
5098
			// If there was previously activated modules (a reconnection), re-activate them all including those that require a user, and do not re-activate those that have been deactivated.
5099
			self::activate_default_modules( 999, 1, $active_modules, false );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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...
5100
		} else {
5101
			// On a fresh new connection, at this point we activate only modules that do not require a user connection.
5102
			self::activate_default_modules( false, false, array(), false, null, null, false );
5103
		}
5104
5105
		// Since this is a fresh connection, be sure to clear out IDC options.
5106
		Identity_Crisis::clear_all_idc_options();
5107
	}
5108
5109
	/**
5110
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
5111
	 * reconnect process is completed.
5112
	 * Note that this currently only happens when we don't need the user to re-authorize
5113
	 * their WP.com account, eg in cases where we are restoring a connection with
5114
	 * unhealthy blog token.
5115
	 */
5116
	public static function reconnection_completed() {
5117
		self::state( 'message', 'reconnection_completed' );
5118
	}
5119
5120
	/**
5121
	 * Get our assumed site creation date.
5122
	 * Calculated based on the earlier date of either:
5123
	 * - Earliest admin user registration date.
5124
	 * - Earliest date of post of any post type.
5125
	 *
5126
	 * @since 7.2.0
5127
	 * @deprecated since 7.8.0
5128
	 *
5129
	 * @return string Assumed site creation date and time.
5130
	 */
5131
	public static function get_assumed_site_creation_date() {
5132
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5133
		return self::connection()->get_assumed_site_creation_date();
5134
	}
5135
5136 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5137
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5138
5139
		if ( $activation_source_name ) {
5140
			$args['_as'] = urlencode( $activation_source_name );
5141
		}
5142
5143
		if ( $activation_source_keyword ) {
5144
			$args['_ak'] = urlencode( $activation_source_keyword );
5145
		}
5146
	}
5147
5148
	function build_reconnect_url( $raw = false ) {
5149
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5150
		return $raw ? $url : esc_url( $url );
5151
	}
5152
5153
	public static function admin_url( $args = null ) {
5154
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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...
5155
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5156
		return $url;
5157
	}
5158
5159
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5160
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5161
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5162
	}
5163
5164
	function dismiss_jetpack_notice() {
5165
5166
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5167
			return;
5168
		}
5169
5170
		switch ( $_GET['jetpack-notice'] ) {
5171
			case 'dismiss':
5172
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5173
5174
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5175
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5176
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5177
				}
5178
				break;
5179
		}
5180
	}
5181
5182
	public static function sort_modules( $a, $b ) {
5183
		if ( $a['sort'] == $b['sort'] ) {
5184
			return 0;
5185
		}
5186
5187
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5188
	}
5189
5190
	function ajax_recheck_ssl() {
5191
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5192
		$result = self::permit_ssl( true );
5193
		wp_send_json(
5194
			array(
5195
				'enabled' => $result,
5196
				'message' => get_transient( 'jetpack_https_test_message' ),
5197
			)
5198
		);
5199
	}
5200
5201
	/* Client API */
5202
5203
	/**
5204
	 * Returns the requested Jetpack API URL
5205
	 *
5206
	 * @deprecated since 7.7
5207
	 * @return string
5208
	 */
5209
	public static function api_url( $relative_url ) {
5210
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5211
		$connection = self::connection();
5212
		return $connection->api_url( $relative_url );
5213
	}
5214
5215
	/**
5216
	 * @deprecated 8.0
5217
	 *
5218
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5219
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5220
	 */
5221
	public static function fix_url_for_bad_hosts( $url ) {
5222
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5223
		return $url;
5224
	}
5225
5226
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5227
		// Default to a blog token.
5228
		$token_type = 'blog';
5229
5230
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5231
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5232
			if ( ! empty( $_GET['onboarding'] ) ) {
5233
				$jpo = $_GET;
5234
			} else {
5235
				$jpo = json_decode( $request_data, true );
5236
			}
5237
5238
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5239
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5240
5241
			if (
5242
				isset( $jpo_user )
5243
				&& isset( $jpo_token )
5244
				&& is_email( $jpo_user )
5245
				&& ctype_alnum( $jpo_token )
5246
				&& isset( $_GET['rest_route'] )
5247
				&& self::validate_onboarding_token_action(
5248
					$jpo_token,
5249
					$_GET['rest_route']
5250
				)
5251
			) {
5252
				$jp_user = get_user_by( 'email', $jpo_user );
5253
				if ( is_a( $jp_user, 'WP_User' ) ) {
5254
					wp_set_current_user( $jp_user->ID );
5255
					$user_can = is_multisite()
5256
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5257
						: current_user_can( 'manage_options' );
5258
					if ( $user_can ) {
5259
						$token_type              = 'user';
5260
						$token->external_user_id = $jp_user->ID;
5261
					}
5262
				}
5263
			}
5264
5265
			$token_data['type']    = $token_type;
5266
			$token_data['user_id'] = $token->external_user_id;
5267
		}
5268
5269
		return $token_data;
5270
	}
5271
5272
	/**
5273
	 * Create a random secret for validating onboarding payload
5274
	 *
5275
	 * @return string Secret token
5276
	 */
5277
	public static function create_onboarding_token() {
5278
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5279
			$token = wp_generate_password( 32, false );
5280
			Jetpack_Options::update_option( 'onboarding', $token );
5281
		}
5282
5283
		return $token;
5284
	}
5285
5286
	/**
5287
	 * Remove the onboarding token
5288
	 *
5289
	 * @return bool True on success, false on failure
5290
	 */
5291
	public static function invalidate_onboarding_token() {
5292
		return Jetpack_Options::delete_option( 'onboarding' );
5293
	}
5294
5295
	/**
5296
	 * Validate an onboarding token for a specific action
5297
	 *
5298
	 * @return boolean True if token/action pair is accepted, false if not
5299
	 */
5300
	public static function validate_onboarding_token_action( $token, $action ) {
5301
		// Compare tokens, bail if tokens do not match
5302
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5303
			return false;
5304
		}
5305
5306
		// List of valid actions we can take
5307
		$valid_actions = array(
5308
			'/jetpack/v4/settings',
5309
		);
5310
5311
		// Only allow valid actions.
5312
		if ( ! in_array( $action, $valid_actions ) ) {
5313
			return false;
5314
		}
5315
5316
		return true;
5317
	}
5318
5319
	/**
5320
	 * Checks to see if the URL is using SSL to connect with Jetpack
5321
	 *
5322
	 * @since 2.3.3
5323
	 * @return boolean
5324
	 */
5325
	public static function permit_ssl( $force_recheck = false ) {
5326
		// Do some fancy tests to see if ssl is being supported
5327
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5328
			$message = '';
5329
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5330
				$ssl = 0;
5331
			} else {
5332
				$ssl = 1;
5333
5334
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5335
					$ssl     = 0;
5336
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5337
				} else {
5338
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5339
					if ( is_wp_error( $response ) ) {
5340
						$ssl     = 0;
5341
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5342
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5343
						$ssl     = 0;
5344
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5345
					}
5346
				}
5347
			}
5348
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5349
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5350
		}
5351
5352
		return (bool) $ssl;
5353
	}
5354
5355
	/*
5356
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5357
	 */
5358
	public function alert_auto_ssl_fail() {
5359
		if ( ! current_user_can( 'manage_options' ) ) {
5360
			return;
5361
		}
5362
5363
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5364
		?>
5365
5366
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5367
			<div class="jp-banner__content">
5368
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5369
				<p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
5370
				<p>
5371
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5372
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5373
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5374
				</p>
5375
				<p>
5376
					<?php
5377
					printf(
5378
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5379
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5380
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5381
					);
5382
					?>
5383
				</p>
5384
			</div>
5385
		</div>
5386
		<style>
5387
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5388
		</style>
5389
		<script type="text/javascript">
5390
			jQuery( document ).ready( function( $ ) {
5391
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5392
					var $this = $( this );
5393
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5394
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5395
					e.preventDefault();
5396
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5397
					$.post( ajaxurl, data )
5398
					  .done( function( response ) {
5399
						  if ( response.enabled ) {
5400
							  $( '#jetpack-ssl-warning' ).hide();
5401
						  } else {
5402
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5403
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5404
						  }
5405
					  }.bind( $this ) );
5406
				} );
5407
			} );
5408
		</script>
5409
5410
		<?php
5411
	}
5412
5413
	/**
5414
	 * Returns the Jetpack XML-RPC API
5415
	 *
5416
	 * @deprecated 8.0 Use Connection_Manager instead.
5417
	 * @return string
5418
	 */
5419
	public static function xmlrpc_api_url() {
5420
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5421
		return self::connection()->xmlrpc_api_url();
5422
	}
5423
5424
	/**
5425
	 * Returns the connection manager object.
5426
	 *
5427
	 * @return Automattic\Jetpack\Connection\Manager
5428
	 */
5429
	public static function connection() {
5430
		$jetpack = static::init();
5431
5432
		// If the connection manager hasn't been instantiated, do that now.
5433
		if ( ! $jetpack->connection_manager ) {
5434
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5435
		}
5436
5437
		return $jetpack->connection_manager;
5438
	}
5439
5440
	/**
5441
	 * Creates two secret tokens and the end of life timestamp for them.
5442
	 *
5443
	 * Note these tokens are unique per call, NOT static per site for connecting.
5444
	 *
5445
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5446
	 *
5447
	 * @since 2.6
5448
	 * @param String  $action  The action name.
5449
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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...
5450
	 * @param Integer $exp     Expiration time in seconds.
5451
	 * @return array
5452
	 */
5453
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5454
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5455
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5456
	}
5457
5458
	public static function get_secrets( $action, $user_id ) {
5459
		$secrets = ( new Secrets() )->get( $action, $user_id );
5460
5461
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5462
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5463
		}
5464
5465
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5466
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5467
		}
5468
5469
		return $secrets;
5470
	}
5471
5472
	/**
5473
	 * Builds the timeout limit for queries talking with the wpcom servers.
5474
	 *
5475
	 * Based on local php max_execution_time in php.ini
5476
	 *
5477
	 * @since 2.6
5478
	 * @return int
5479
	 * @deprecated
5480
	 **/
5481
	public function get_remote_query_timeout_limit() {
5482
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5483
		return self::get_max_execution_time();
5484
	}
5485
5486
	/**
5487
	 * Builds the timeout limit for queries talking with the wpcom servers.
5488
	 *
5489
	 * Based on local php max_execution_time in php.ini
5490
	 *
5491
	 * @since 5.4
5492
	 * @return int
5493
	 **/
5494
	public static function get_max_execution_time() {
5495
		$timeout = (int) ini_get( 'max_execution_time' );
5496
5497
		// Ensure exec time set in php.ini
5498
		if ( ! $timeout ) {
5499
			$timeout = 30;
5500
		}
5501
		return $timeout;
5502
	}
5503
5504
	/**
5505
	 * Sets a minimum request timeout, and returns the current timeout
5506
	 *
5507
	 * @since 5.4
5508
	 **/
5509 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5510
		$timeout = self::get_max_execution_time();
5511
		if ( $timeout < $min_timeout ) {
5512
			$timeout = $min_timeout;
5513
			set_time_limit( $timeout );
5514
		}
5515
		return $timeout;
5516
	}
5517
5518
	/**
5519
	 * Takes the response from the Jetpack register new site endpoint and
5520
	 * verifies it worked properly.
5521
	 *
5522
	 * @since 2.6
5523
	 * @deprecated since 7.7.0
5524
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5525
	 **/
5526
	public function validate_remote_register_response() {
5527
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5528
	}
5529
5530
	/**
5531
	 * @deprecated since Jetpack 9.7.0
5532
	 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5533
	 *
5534
	 * @return bool|WP_Error
5535
	 */
5536
	public static function register() {
5537
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5538
		return static::connection()->try_registration( false );
5539
	}
5540
5541
	/**
5542
	 * Filters the registration request body to include tracking properties.
5543
	 *
5544
	 * @deprecated since Jetpack 9.7.0
5545
	 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5546
	 *
5547
	 * @param array $properties
5548
	 * @return array amended properties.
5549
	 */
5550
	public static function filter_register_request_body( $properties ) {
5551
		_deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5552
		return Connection_Utils::filter_register_request_body( $properties );
5553
	}
5554
5555
	/**
5556
	 * Filters the token request body to include tracking properties.
5557
	 *
5558
	 * @param array $properties
5559
	 * @return array amended properties.
5560
	 */
5561 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5562
		$tracking        = new Tracking();
5563
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5564
5565
		return array_merge(
5566
			$properties,
5567
			array(
5568
				'_ui' => $tracks_identity['_ui'],
5569
				'_ut' => $tracks_identity['_ut'],
5570
			)
5571
		);
5572
	}
5573
5574
	/**
5575
	 * If the db version is showing something other that what we've got now, bump it to current.
5576
	 *
5577
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5578
	 */
5579
	public static function maybe_set_version_option() {
5580
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5581
		if ( JETPACK__VERSION != $version ) {
5582
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5583
5584
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5585
				/** This action is documented in class.jetpack.php */
5586
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5587
			}
5588
5589
			return true;
5590
		}
5591
		return false;
5592
	}
5593
5594
	/* Client Server API */
5595
5596
	/**
5597
	 * Loads the Jetpack XML-RPC client.
5598
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5599
	 *
5600
	 * @deprecated since 7.7.0
5601
	 */
5602
	public static function load_xml_rpc_client() {
5603
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5604
	}
5605
5606
	/**
5607
	 * Resets the saved authentication state in between testing requests.
5608
	 *
5609
	 * @deprecated since 8.9.0
5610
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5611
	 */
5612
	public function reset_saved_auth_state() {
5613
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5614
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5615
	}
5616
5617
	/**
5618
	 * Verifies the signature of the current request.
5619
	 *
5620
	 * @deprecated since 7.7.0
5621
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5622
	 *
5623
	 * @return false|array
5624
	 */
5625
	public function verify_xml_rpc_signature() {
5626
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5627
		return self::connection()->verify_xml_rpc_signature();
5628
	}
5629
5630
	/**
5631
	 * Verifies the signature of the current request.
5632
	 *
5633
	 * This function has side effects and should not be used. Instead,
5634
	 * use the memoized version `->verify_xml_rpc_signature()`.
5635
	 *
5636
	 * @deprecated since 7.7.0
5637
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5638
	 * @internal
5639
	 */
5640
	private function internal_verify_xml_rpc_signature() {
5641
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5642
	}
5643
5644
	/**
5645
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5646
	 *
5647
	 * @deprecated since 7.7.0
5648
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5649
	 *
5650
	 * @param \WP_User|mixed $user     User object if authenticated.
5651
	 * @param string         $username Username.
5652
	 * @param string         $password Password string.
5653
	 * @return \WP_User|mixed Authenticated user or error.
5654
	 */
5655 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5656
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5657
5658
		if ( ! $this->connection_manager ) {
5659
			$this->connection_manager = new Connection_Manager();
5660
		}
5661
5662
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5663
	}
5664
5665
	/**
5666
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5667
	 * Uses the existing XMLRPC request signing implementation.
5668
	 *
5669
	 * @deprecated since 8.9.0
5670
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5671
	 */
5672
	function wp_rest_authenticate( $user ) {
5673
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5674
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5675
	}
5676
5677
	/**
5678
	 * Report authentication status to the WP REST API.
5679
	 *
5680
	 * @deprecated since 8.9.0
5681
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5682
	 *
5683
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5684
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5685
	 */
5686
	public function wp_rest_authentication_errors( $value ) {
5687
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5688
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5689
	}
5690
5691
	/**
5692
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5693
	 * Capture it here so we can verify the signature later.
5694
	 *
5695
	 * @deprecated since 7.7.0
5696
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5697
	 *
5698
	 * @param array $methods XMLRPC methods.
5699
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5700
	 */
5701 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5702
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5703
5704
		if ( ! $this->connection_manager ) {
5705
			$this->connection_manager = new Connection_Manager();
5706
		}
5707
5708
		return $this->connection_manager->xmlrpc_methods( $methods );
5709
	}
5710
5711
	/**
5712
	 * Register additional public XMLRPC methods.
5713
	 *
5714
	 * @deprecated since 7.7.0
5715
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5716
	 *
5717
	 * @param array $methods Public XMLRPC methods.
5718
	 * @return array Public XMLRPC methods, with the getOptions one.
5719
	 */
5720 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5721
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5722
5723
		if ( ! $this->connection_manager ) {
5724
			$this->connection_manager = new Connection_Manager();
5725
		}
5726
5727
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5728
	}
5729
5730
	/**
5731
	 * Handles a getOptions XMLRPC method call.
5732
	 *
5733
	 * @deprecated since 7.7.0
5734
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5735
	 *
5736
	 * @param array $args method call arguments.
5737
	 * @return array an amended XMLRPC server options array.
5738
	 */
5739 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5740
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5741
5742
		if ( ! $this->connection_manager ) {
5743
			$this->connection_manager = new Connection_Manager();
5744
		}
5745
5746
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5747
	}
5748
5749
	/**
5750
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5751
	 *
5752
	 * @deprecated since 7.7.0
5753
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5754
	 *
5755
	 * @param array $options Standard Core options.
5756
	 * @return array Amended options.
5757
	 */
5758 View Code Duplication
	public function xmlrpc_options( $options ) {
5759
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5760
5761
		if ( ! $this->connection_manager ) {
5762
			$this->connection_manager = new Connection_Manager();
5763
		}
5764
5765
		return $this->connection_manager->xmlrpc_options( $options );
5766
	}
5767
5768
	/**
5769
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5770
	 * SET: state( $key, $value );
5771
	 * GET: $value = state( $key );
5772
	 *
5773
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key 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...
5774
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value 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...
5775
	 * @param bool   $restate private
5776
	 */
5777
	public static function state( $key = null, $value = null, $restate = false ) {
5778
		static $state = array();
5779
		static $path, $domain;
5780
		if ( ! isset( $path ) ) {
5781
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5782
			$admin_url = self::admin_url();
5783
			$bits      = wp_parse_url( $admin_url );
5784
5785
			if ( is_array( $bits ) ) {
5786
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5787
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5788
			} else {
5789
				$path = $domain = null;
5790
			}
5791
		}
5792
5793
		// Extract state from cookies and delete cookies
5794
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5795
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5796
			unset( $_COOKIE['jetpackState'] );
5797
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5798
				if ( strlen( $v ) ) {
5799
					$state[ $k ] = $v;
5800
				}
5801
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5802
			}
5803
		}
5804
5805
		if ( $restate ) {
5806
			foreach ( $state as $k => $v ) {
5807
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5808
			}
5809
			return;
5810
		}
5811
5812
		// Get a state variable.
5813
		if ( isset( $key ) && ! isset( $value ) ) {
5814
			if ( array_key_exists( $key, $state ) ) {
5815
				return $state[ $key ];
5816
			}
5817
			return null;
5818
		}
5819
5820
		// Set a state variable.
5821
		if ( isset( $key ) && isset( $value ) ) {
5822
			if ( is_array( $value ) && isset( $value[0] ) ) {
5823
				$value = $value[0];
5824
			}
5825
			$state[ $key ] = $value;
5826
			if ( ! headers_sent() ) {
5827
				if ( self::should_set_cookie( $key ) ) {
5828
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5829
				}
5830
			}
5831
		}
5832
	}
5833
5834
	public static function restate() {
5835
		self::state( null, null, true );
5836
	}
5837
5838
	/**
5839
	 * Determines whether the jetpackState[$key] value should be added to the
5840
	 * cookie.
5841
	 *
5842
	 * @param string $key The state key.
5843
	 *
5844
	 * @return boolean Whether the value should be added to the cookie.
5845
	 */
5846
	public static function should_set_cookie( $key ) {
5847
		global $current_screen;
5848
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5849
5850
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5851
			return false;
5852
		}
5853
5854
		return true;
5855
	}
5856
5857
	public static function check_privacy( $file ) {
5858
		static $is_site_publicly_accessible = null;
5859
5860
		if ( is_null( $is_site_publicly_accessible ) ) {
5861
			$is_site_publicly_accessible = false;
5862
5863
			$rpc = new Jetpack_IXR_Client();
5864
5865
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5866
			if ( $success ) {
5867
				$response = $rpc->getResponse();
5868
				if ( $response ) {
5869
					$is_site_publicly_accessible = true;
5870
				}
5871
			}
5872
5873
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5874
		}
5875
5876
		if ( $is_site_publicly_accessible ) {
5877
			return;
5878
		}
5879
5880
		$module_slug = self::get_module_slug( $file );
5881
5882
		$privacy_checks = self::state( 'privacy_checks' );
5883
		if ( ! $privacy_checks ) {
5884
			$privacy_checks = $module_slug;
5885
		} else {
5886
			$privacy_checks .= ",$module_slug";
5887
		}
5888
5889
		self::state( 'privacy_checks', $privacy_checks );
5890
	}
5891
5892
	/**
5893
	 * Helper method for multicall XMLRPC.
5894
	 *
5895
	 * @deprecated since 8.9.0
5896
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5897
	 *
5898
	 * @param ...$args Args for the async_call.
5899
	 */
5900
	public static function xmlrpc_async_call( ...$args ) {
5901
5902
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5903
5904
		global $blog_id;
5905
		static $clients = array();
5906
5907
		$client_blog_id = is_multisite() ? $blog_id : 0;
5908
5909
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5910
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5911
			if ( function_exists( 'ignore_user_abort' ) ) {
5912
				ignore_user_abort( true );
5913
			}
5914
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5915
		}
5916
5917
		if ( ! empty( $args[0] ) ) {
5918
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5919
		} elseif ( is_multisite() ) {
5920
			foreach ( $clients as $client_blog_id => $client ) {
5921
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5922
					continue;
5923
				}
5924
5925
				$switch_success = switch_to_blog( $client_blog_id, true );
5926
				if ( ! $switch_success ) {
5927
					continue;
5928
				}
5929
5930
				flush();
5931
				$client->query();
5932
5933
				restore_current_blog();
5934
			}
5935
		} else {
5936
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5937
				flush();
5938
				$clients[0]->query();
5939
			}
5940
		}
5941
	}
5942
5943
	/**
5944
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5945
	 *
5946
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5947
	 *
5948
	 * @param string $url WordPress.com static resource URL.
5949
	 */
5950
	public static function staticize_subdomain( $url ) {
5951
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5952
		return Assets::staticize_subdomain( $url );
5953
	}
5954
5955
	/* JSON API Authorization */
5956
5957
	/**
5958
	 * Handles the login action for Authorizing the JSON API
5959
	 */
5960
	function login_form_json_api_authorization() {
5961
		$this->verify_json_api_authorization_request();
5962
5963
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5964
5965
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5966
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5967
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5968
	}
5969
5970
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5971
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5972
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5973
			return $url;
5974
		}
5975
5976
		$parsed_url = wp_parse_url( $url );
5977
		$url        = strtok( $url, '?' );
5978
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5979
		if ( ! empty( $parsed_url['query'] ) ) {
5980
			$url .= "&{$parsed_url['query']}";
5981
		}
5982
5983
		return $url;
5984
	}
5985
5986
	// Make sure the POSTed request is handled by the same action
5987
	function preserve_action_in_login_form_for_json_api_authorization() {
5988
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5989
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5990
	}
5991
5992
	// If someone logs in to approve API access, store the Access Code in usermeta
5993
	function store_json_api_authorization_token( $user_login, $user ) {
5994
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5995
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5996
		$token = wp_generate_password( 32, false );
5997
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5998
	}
5999
6000
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6001
	function allow_wpcom_public_api_domain( $domains ) {
6002
		$domains[] = 'public-api.wordpress.com';
6003
		return $domains;
6004
	}
6005
6006
	static function is_redirect_encoded( $redirect_url ) {
6007
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6008
	}
6009
6010
	// Add all wordpress.com environments to the safe redirect allowed list.
6011
	function allow_wpcom_environments( $domains ) {
6012
		$domains[] = 'wordpress.com';
6013
		$domains[] = 'wpcalypso.wordpress.com';
6014
		$domains[] = 'horizon.wordpress.com';
6015
		$domains[] = 'calypso.localhost';
6016
		return $domains;
6017
	}
6018
6019
	// Add the Access Code details to the public-api.wordpress.com redirect
6020
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6021
		return add_query_arg(
6022
			urlencode_deep(
6023
				array(
6024
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6025
					'jetpack-user-id' => (int) $user->ID,
6026
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6027
				)
6028
			),
6029
			$redirect_to
6030
		);
6031
	}
6032
6033
	/**
6034
	 * Verifies the request by checking the signature
6035
	 *
6036
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6037
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6038
	 *
6039
	 * @param null|array $environment
6040
	 */
6041
	function verify_json_api_authorization_request( $environment = null ) {
6042
		$environment = is_null( $environment )
6043
			? $_REQUEST
6044
			: $environment;
6045
6046
		list( $env_token,, $env_user_id ) = explode( ':', $environment['token'] );
6047
		$token                            = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6048
		if ( ! $token || empty( $token->secret ) ) {
6049
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6050
		}
6051
6052
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
6053
6054
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6055
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6056
			/**
6057
			 * Jetpack authorisation request Error.
6058
			 *
6059
			 * @since 7.5.0
6060
			 */
6061
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6062
			$die_error = sprintf(
6063
				/* translators: %s is a URL */
6064
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
6065
				Redirect::get_url( 'jetpack-support-double-encoding' )
6066
			);
6067
		}
6068
6069
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6070
6071
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6072
			$signature = $jetpack_signature->sign_request(
6073
				$environment['token'],
6074
				$environment['timestamp'],
6075
				$environment['nonce'],
6076
				'',
6077
				'GET',
6078
				$environment['jetpack_json_api_original_query'],
6079
				null,
6080
				true
6081
			);
6082
		} else {
6083
			$signature = $jetpack_signature->sign_current_request(
6084
				array(
6085
					'body'   => null,
6086
					'method' => 'GET',
6087
				)
6088
			);
6089
		}
6090
6091
		if ( ! $signature ) {
6092
			wp_die( $die_error );
6093
		} elseif ( is_wp_error( $signature ) ) {
6094
			wp_die( $die_error );
6095
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6096
			if ( is_ssl() ) {
6097
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
6098
				$signature = $jetpack_signature->sign_current_request(
6099
					array(
6100
						'scheme' => 'http',
6101
						'body'   => null,
6102
						'method' => 'GET',
6103
					)
6104
				);
6105
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6106
					wp_die( $die_error );
6107
				}
6108
			} else {
6109
				wp_die( $die_error );
6110
			}
6111
		}
6112
6113
		$timestamp = (int) $environment['timestamp'];
6114
		$nonce     = stripslashes( (string) $environment['nonce'] );
6115
6116
		if ( ! $this->connection_manager ) {
6117
			$this->connection_manager = new Connection_Manager();
6118
		}
6119
6120
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6121
			// De-nonce the nonce, at least for 5 minutes.
6122
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
6123
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6124
			if ( $old_nonce_time < time() - 300 ) {
6125
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6126
			}
6127
		}
6128
6129
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6130
		$data_filters = array(
6131
			'state'        => 'opaque',
6132
			'client_id'    => 'int',
6133
			'client_title' => 'string',
6134
			'client_image' => 'url',
6135
		);
6136
6137
		foreach ( $data_filters as $key => $sanitation ) {
6138
			if ( ! isset( $data->$key ) ) {
6139
				wp_die( $die_error );
6140
			}
6141
6142
			switch ( $sanitation ) {
6143
				case 'int':
6144
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6145
					break;
6146
				case 'opaque':
6147
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6148
					break;
6149
				case 'string':
6150
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6151
					break;
6152
				case 'url':
6153
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6154
					break;
6155
			}
6156
		}
6157
6158
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6159
			wp_die( $die_error );
6160
		}
6161
	}
6162
6163
	function login_message_json_api_authorization( $message ) {
6164
		return '<p class="message">' . sprintf(
6165
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6166
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6167
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6168
	}
6169
6170
	/**
6171
	 * Get $content_width, but with a <s>twist</s> filter.
6172
	 */
6173
	public static function get_content_width() {
6174
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6175
			? $GLOBALS['content_width']
6176
			: false;
6177
		/**
6178
		 * Filter the Content Width value.
6179
		 *
6180
		 * @since 2.2.3
6181
		 *
6182
		 * @param string $content_width Content Width value.
6183
		 */
6184
		return apply_filters( 'jetpack_content_width', $content_width );
6185
	}
6186
6187
	/**
6188
	 * Pings the WordPress.com Mirror Site for the specified options.
6189
	 *
6190
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6191
	 *
6192
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6193
	 */
6194
	public function get_cloud_site_options( $option_names ) {
6195
		$option_names = array_filter( (array) $option_names, 'is_string' );
6196
6197
		$xml = new Jetpack_IXR_Client();
6198
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6199
		if ( $xml->isError() ) {
6200
			return array(
6201
				'error_code' => $xml->getErrorCode(),
6202
				'error_msg'  => $xml->getErrorMessage(),
6203
			);
6204
		}
6205
		$cloud_site_options = $xml->getResponse();
6206
6207
		return $cloud_site_options;
6208
	}
6209
6210
	/**
6211
	 * Checks if the site is currently in an identity crisis.
6212
	 *
6213
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6214
	 */
6215
	public static function check_identity_crisis() {
6216
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! Identity_Crisis::validate_sync_error_idc_option() ) {
6217
			return false;
6218
		}
6219
6220
		return Jetpack_Options::get_option( 'sync_error_idc' );
6221
	}
6222
6223
	/**
6224
	 * Checks whether the home and siteurl specifically are allowed.
6225
	 * Written so that we don't have re-check $key and $value params every time
6226
	 * we want to check if this site is allowed, for example in footer.php
6227
	 *
6228
	 * @since  3.8.0
6229
	 * @return bool True = already allowed False = not on the allowed list.
6230
	 */
6231
	public static function is_staging_site() {
6232
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6233
		return ( new Status() )->is_staging_site();
6234
	}
6235
6236
	/**
6237
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6238
	 *
6239
	 * @since 4.4.0
6240
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6241
	 *
6242
	 * @return bool
6243
	 */
6244
	public static function validate_sync_error_idc_option() {
6245
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::validate_sync_error_idc_option' );
6246
		return Identity_Crisis::validate_sync_error_idc_option();
6247
	}
6248
6249
	/**
6250
	 * Normalizes a url by doing three things:
6251
	 *  - Strips protocol
6252
	 *  - Strips www
6253
	 *  - Adds a trailing slash
6254
	 *
6255
	 * @since 4.4.0
6256
	 * @param string $url
6257
	 * @return WP_Error|string
6258
	 */
6259 View Code Duplication
	public static function normalize_url_protocol_agnostic( $url ) {
6260
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6261
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false 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...
6262
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
6263
		}
6264
6265
		// Strip www and protocols
6266
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6267
		return $url;
6268
	}
6269
6270
	/**
6271
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6272
	 *
6273
	 * @since 4.4.0
6274
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6275
	 *
6276
	 * @param array $response
6277
	 * @return array Array of the local urls, wpcom urls, and error code
6278
	 */
6279
	public static function get_sync_error_idc_option( $response = array() ) {
6280
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::get_sync_error_idc_option' );
6281
		return Identity_Crisis::get_sync_error_idc_option( $response );
6282
	}
6283
6284
	/**
6285
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6286
	 * If set to true, the site will be put into staging mode.
6287
	 *
6288
	 * @since 4.3.2
6289
	 * @return bool
6290
	 */
6291
	public static function sync_idc_optin() {
6292
		_deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::sync_idc_optin' );
6293
		return Identity_Crisis::sync_idc_optin();
6294
	}
6295
6296
	/**
6297
	 * Maybe Use a .min.css stylesheet, maybe not.
6298
	 *
6299
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6300
	 */
6301
	public static function maybe_min_asset( $url, $path, $plugin ) {
6302
		// Short out on things trying to find actual paths.
6303
		if ( ! $path || empty( $plugin ) ) {
6304
			return $url;
6305
		}
6306
6307
		$path = ltrim( $path, '/' );
6308
6309
		// Strip out the abspath.
6310
		$base = dirname( plugin_basename( $plugin ) );
6311
6312
		// Short out on non-Jetpack assets.
6313
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6314
			return $url;
6315
		}
6316
6317
		// File name parsing.
6318
		$file              = "{$base}/{$path}";
6319
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6320
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6321
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6322
		$extension         = array_shift( $file_name_parts_r );
6323
6324
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6325
			// Already pointing at the minified version.
6326
			if ( 'min' === $file_name_parts_r[0] ) {
6327
				return $url;
6328
			}
6329
6330
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6331
			if ( file_exists( $min_full_path ) ) {
6332
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6333
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6334
				if ( 'css' === $extension ) {
6335
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6336
					self::$min_assets[ $key ] = $path;
6337
				}
6338
			}
6339
		}
6340
6341
		return $url;
6342
	}
6343
6344
	/**
6345
	 * If the asset is minified, let's flag .min as the suffix.
6346
	 *
6347
	 * Attached to `style_loader_src` filter.
6348
	 *
6349
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6350
	 * @param string $handle The registered handle of the script in question.
6351
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6352
	 */
6353
	public static function set_suffix_on_min( $src, $handle ) {
6354
		if ( false === strpos( $src, '.min.css' ) ) {
6355
			return $src;
6356
		}
6357
6358
		if ( ! empty( self::$min_assets ) ) {
6359
			foreach ( self::$min_assets as $file => $path ) {
6360
				if ( false !== strpos( $src, $file ) ) {
6361
					wp_style_add_data( $handle, 'suffix', '.min' );
6362
					return $src;
6363
				}
6364
			}
6365
		}
6366
6367
		return $src;
6368
	}
6369
6370
	/**
6371
	 * Maybe inlines a stylesheet.
6372
	 *
6373
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6374
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6375
	 *
6376
	 * Attached to `style_loader_tag` filter.
6377
	 *
6378
	 * @param string $tag The tag that would link to the external asset.
6379
	 * @param string $handle The registered handle of the script in question.
6380
	 *
6381
	 * @return string
6382
	 */
6383
	public static function maybe_inline_style( $tag, $handle ) {
6384
		global $wp_styles;
6385
		$item = $wp_styles->registered[ $handle ];
6386
6387
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6388
			return $tag;
6389
		}
6390
6391
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6392
			$href = $matches[1];
6393
			// Strip off query string
6394
			if ( $pos = strpos( $href, '?' ) ) {
6395
				$href = substr( $href, 0, $pos );
6396
			}
6397
			// Strip off fragment
6398
			if ( $pos = strpos( $href, '#' ) ) {
6399
				$href = substr( $href, 0, $pos );
6400
			}
6401
		} else {
6402
			return $tag;
6403
		}
6404
6405
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6406
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6407
			return $tag;
6408
		}
6409
6410
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6411
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6412
			// And this isn't the pass that actually deals with the RTL version...
6413
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6414
				// Short out, as the RTL version will deal with it in a moment.
6415
				return $tag;
6416
			}
6417
		}
6418
6419
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6420
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6421
		if ( $css ) {
6422
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6423
			if ( empty( $item->extra['after'] ) ) {
6424
				wp_add_inline_style( $handle, $css );
6425
			} else {
6426
				array_unshift( $item->extra['after'], $css );
6427
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6428
			}
6429
		}
6430
6431
		return $tag;
6432
	}
6433
6434
	/**
6435
	 * Loads a view file from the views
6436
	 *
6437
	 * Data passed in with the $data parameter will be available in the
6438
	 * template file as $data['value']
6439
	 *
6440
	 * @param string $template - Template file to load
6441
	 * @param array  $data - Any data to pass along to the template
6442
	 * @return boolean - If template file was found
6443
	 **/
6444
	public function load_view( $template, $data = array() ) {
6445
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6446
6447
		if ( file_exists( $views_dir . $template ) ) {
6448
			require_once $views_dir . $template;
6449
			return true;
6450
		}
6451
6452
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6453
		return false;
6454
	}
6455
6456
	/**
6457
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6458
	 */
6459
	public function deprecated_hooks() {
6460
		$filter_deprecated_list = array(
6461
			'jetpack_bail_on_shortcode'                    => array(
6462
				'replacement' => 'jetpack_shortcodes_to_include',
6463
				'version'     => 'jetpack-3.1.0',
6464
			),
6465
			'wpl_sharing_2014_1'                           => array(
6466
				'replacement' => null,
6467
				'version'     => 'jetpack-3.6.0',
6468
			),
6469
			'jetpack-tools-to-include'                     => array(
6470
				'replacement' => 'jetpack_tools_to_include',
6471
				'version'     => 'jetpack-3.9.0',
6472
			),
6473
			'jetpack_identity_crisis_options_to_check'     => array(
6474
				'replacement' => null,
6475
				'version'     => 'jetpack-4.0.0',
6476
			),
6477
			'update_option_jetpack_single_user_site'       => array(
6478
				'replacement' => null,
6479
				'version'     => 'jetpack-4.3.0',
6480
			),
6481
			'audio_player_default_colors'                  => array(
6482
				'replacement' => null,
6483
				'version'     => 'jetpack-4.3.0',
6484
			),
6485
			'add_option_jetpack_featured_images_enabled'   => array(
6486
				'replacement' => null,
6487
				'version'     => 'jetpack-4.3.0',
6488
			),
6489
			'add_option_jetpack_update_details'            => array(
6490
				'replacement' => null,
6491
				'version'     => 'jetpack-4.3.0',
6492
			),
6493
			'add_option_jetpack_updates'                   => array(
6494
				'replacement' => null,
6495
				'version'     => 'jetpack-4.3.0',
6496
			),
6497
			'add_option_jetpack_network_name'              => array(
6498
				'replacement' => null,
6499
				'version'     => 'jetpack-4.3.0',
6500
			),
6501
			'add_option_jetpack_network_allow_new_registrations' => array(
6502
				'replacement' => null,
6503
				'version'     => 'jetpack-4.3.0',
6504
			),
6505
			'add_option_jetpack_network_add_new_users'     => array(
6506
				'replacement' => null,
6507
				'version'     => 'jetpack-4.3.0',
6508
			),
6509
			'add_option_jetpack_network_site_upload_space' => array(
6510
				'replacement' => null,
6511
				'version'     => 'jetpack-4.3.0',
6512
			),
6513
			'add_option_jetpack_network_upload_file_types' => array(
6514
				'replacement' => null,
6515
				'version'     => 'jetpack-4.3.0',
6516
			),
6517
			'add_option_jetpack_network_enable_administration_menus' => array(
6518
				'replacement' => null,
6519
				'version'     => 'jetpack-4.3.0',
6520
			),
6521
			'add_option_jetpack_is_multi_site'             => array(
6522
				'replacement' => null,
6523
				'version'     => 'jetpack-4.3.0',
6524
			),
6525
			'add_option_jetpack_is_main_network'           => array(
6526
				'replacement' => null,
6527
				'version'     => 'jetpack-4.3.0',
6528
			),
6529
			'add_option_jetpack_main_network_site'         => array(
6530
				'replacement' => null,
6531
				'version'     => 'jetpack-4.3.0',
6532
			),
6533
			'jetpack_sync_all_registered_options'          => array(
6534
				'replacement' => null,
6535
				'version'     => 'jetpack-4.3.0',
6536
			),
6537
			'jetpack_has_identity_crisis'                  => array(
6538
				'replacement' => 'jetpack_sync_error_idc_validation',
6539
				'version'     => 'jetpack-4.4.0',
6540
			),
6541
			'jetpack_is_post_mailable'                     => array(
6542
				'replacement' => null,
6543
				'version'     => 'jetpack-4.4.0',
6544
			),
6545
			'jetpack_seo_site_host'                        => array(
6546
				'replacement' => null,
6547
				'version'     => 'jetpack-5.1.0',
6548
			),
6549
			'jetpack_installed_plugin'                     => array(
6550
				'replacement' => 'jetpack_plugin_installed',
6551
				'version'     => 'jetpack-6.0.0',
6552
			),
6553
			'jetpack_holiday_snow_option_name'             => array(
6554
				'replacement' => null,
6555
				'version'     => 'jetpack-6.0.0',
6556
			),
6557
			'jetpack_holiday_chance_of_snow'               => array(
6558
				'replacement' => null,
6559
				'version'     => 'jetpack-6.0.0',
6560
			),
6561
			'jetpack_holiday_snow_js_url'                  => array(
6562
				'replacement' => null,
6563
				'version'     => 'jetpack-6.0.0',
6564
			),
6565
			'jetpack_is_holiday_snow_season'               => array(
6566
				'replacement' => null,
6567
				'version'     => 'jetpack-6.0.0',
6568
			),
6569
			'jetpack_holiday_snow_option_updated'          => array(
6570
				'replacement' => null,
6571
				'version'     => 'jetpack-6.0.0',
6572
			),
6573
			'jetpack_holiday_snowing'                      => array(
6574
				'replacement' => null,
6575
				'version'     => 'jetpack-6.0.0',
6576
			),
6577
			'jetpack_sso_auth_cookie_expirtation'          => array(
6578
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6579
				'version'     => 'jetpack-6.1.0',
6580
			),
6581
			'jetpack_cache_plans'                          => array(
6582
				'replacement' => null,
6583
				'version'     => 'jetpack-6.1.0',
6584
			),
6585
6586
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6587
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6588
				'version'     => 'jetpack-6.5.0',
6589
			),
6590
			'jetpack_enable_site_verification'             => array(
6591
				'replacement' => null,
6592
				'version'     => 'jetpack-6.5.0',
6593
			),
6594
			'can_display_jetpack_manage_notice'            => array(
6595
				'replacement' => null,
6596
				'version'     => 'jetpack-7.3.0',
6597
			),
6598
			'atd_http_post_timeout'                        => array(
6599
				'replacement' => null,
6600
				'version'     => 'jetpack-7.3.0',
6601
			),
6602
			'atd_service_domain'                           => array(
6603
				'replacement' => null,
6604
				'version'     => 'jetpack-7.3.0',
6605
			),
6606
			'atd_load_scripts'                             => array(
6607
				'replacement' => null,
6608
				'version'     => 'jetpack-7.3.0',
6609
			),
6610
			'jetpack_widget_authors_exclude'               => array(
6611
				'replacement' => 'jetpack_widget_authors_params',
6612
				'version'     => 'jetpack-7.7.0',
6613
			),
6614
			// Removed in Jetpack 7.9.0
6615
			'jetpack_pwa_manifest'                         => array(
6616
				'replacement' => null,
6617
				'version'     => 'jetpack-7.9.0',
6618
			),
6619
			'jetpack_pwa_background_color'                 => array(
6620
				'replacement' => null,
6621
				'version'     => 'jetpack-7.9.0',
6622
			),
6623
			'jetpack_check_mobile'                         => array(
6624
				'replacement' => null,
6625
				'version'     => 'jetpack-8.3.0',
6626
			),
6627
			'jetpack_mobile_stylesheet'                    => array(
6628
				'replacement' => null,
6629
				'version'     => 'jetpack-8.3.0',
6630
			),
6631
			'jetpack_mobile_template'                      => array(
6632
				'replacement' => null,
6633
				'version'     => 'jetpack-8.3.0',
6634
			),
6635
			'jetpack_mobile_theme_menu'                    => array(
6636
				'replacement' => null,
6637
				'version'     => 'jetpack-8.3.0',
6638
			),
6639
			'minileven_show_featured_images'               => array(
6640
				'replacement' => null,
6641
				'version'     => 'jetpack-8.3.0',
6642
			),
6643
			'minileven_attachment_size'                    => array(
6644
				'replacement' => null,
6645
				'version'     => 'jetpack-8.3.0',
6646
			),
6647
			'instagram_cache_oembed_api_response_body'     => array(
6648
				'replacement' => null,
6649
				'version'     => 'jetpack-9.1.0',
6650
			),
6651
			'jetpack_can_make_outbound_https'              => array(
6652
				'replacement' => null,
6653
				'version'     => 'jetpack-9.1.0',
6654
			),
6655
		);
6656
6657
		foreach ( $filter_deprecated_list as $tag => $args ) {
6658
			if ( has_filter( $tag ) ) {
6659
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6660
			}
6661
		}
6662
6663
		$action_deprecated_list = array(
6664
			'jetpack_updated_theme'        => array(
6665
				'replacement' => 'jetpack_updated_themes',
6666
				'version'     => 'jetpack-6.2.0',
6667
			),
6668
			'atd_http_post_error'          => array(
6669
				'replacement' => null,
6670
				'version'     => 'jetpack-7.3.0',
6671
			),
6672
			'mobile_reject_mobile'         => array(
6673
				'replacement' => null,
6674
				'version'     => 'jetpack-8.3.0',
6675
			),
6676
			'mobile_force_mobile'          => array(
6677
				'replacement' => null,
6678
				'version'     => 'jetpack-8.3.0',
6679
			),
6680
			'mobile_app_promo_download'    => array(
6681
				'replacement' => null,
6682
				'version'     => 'jetpack-8.3.0',
6683
			),
6684
			'mobile_setup'                 => array(
6685
				'replacement' => null,
6686
				'version'     => 'jetpack-8.3.0',
6687
			),
6688
			'jetpack_mobile_footer_before' => array(
6689
				'replacement' => null,
6690
				'version'     => 'jetpack-8.3.0',
6691
			),
6692
			'wp_mobile_theme_footer'       => array(
6693
				'replacement' => null,
6694
				'version'     => 'jetpack-8.3.0',
6695
			),
6696
			'minileven_credits'            => array(
6697
				'replacement' => null,
6698
				'version'     => 'jetpack-8.3.0',
6699
			),
6700
			'jetpack_mobile_header_before' => array(
6701
				'replacement' => null,
6702
				'version'     => 'jetpack-8.3.0',
6703
			),
6704
			'jetpack_mobile_header_after'  => array(
6705
				'replacement' => null,
6706
				'version'     => 'jetpack-8.3.0',
6707
			),
6708
		);
6709
6710
		foreach ( $action_deprecated_list as $tag => $args ) {
6711
			if ( has_action( $tag ) ) {
6712
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6713
			}
6714
		}
6715
	}
6716
6717
	/**
6718
	 * Converts any url in a stylesheet, to the correct absolute url.
6719
	 *
6720
	 * Considerations:
6721
	 *  - Normal, relative URLs     `feh.png`
6722
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6723
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6724
	 *  - Absolute URLs             `http://domain.com/feh.png`
6725
	 *  - Domain root relative URLs `/feh.png`
6726
	 *
6727
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6728
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6729
	 *
6730
	 * @return mixed|string
6731
	 */
6732
	public static function absolutize_css_urls( $css, $css_file_url ) {
6733
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6734
		$css_dir = dirname( $css_file_url );
6735
		$p       = wp_parse_url( $css_dir );
6736
		$domain  = sprintf(
6737
			'%1$s//%2$s%3$s%4$s',
6738
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6739
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6740
			$p['host'],
6741
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6742
		);
6743
6744
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6745
			$find = $replace = array();
6746
			foreach ( $matches as $match ) {
6747
				$url = trim( $match['path'], "'\" \t" );
6748
6749
				// If this is a data url, we don't want to mess with it.
6750
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6751
					continue;
6752
				}
6753
6754
				// If this is an absolute or protocol-agnostic url,
6755
				// we don't want to mess with it.
6756
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6757
					continue;
6758
				}
6759
6760
				switch ( substr( $url, 0, 1 ) ) {
6761
					case '/':
6762
						$absolute = $domain . $url;
6763
						break;
6764
					default:
6765
						$absolute = $css_dir . '/' . $url;
6766
				}
6767
6768
				$find[]    = $match[0];
6769
				$replace[] = sprintf( 'url("%s")', $absolute );
6770
			}
6771
			$css = str_replace( $find, $replace, $css );
6772
		}
6773
6774
		return $css;
6775
	}
6776
6777
	/**
6778
	 * This methods removes all of the registered css files on the front end
6779
	 * from Jetpack in favor of using a single file. In effect "imploding"
6780
	 * all the files into one file.
6781
	 *
6782
	 * Pros:
6783
	 * - Uses only ONE css asset connection instead of 15
6784
	 * - Saves a minimum of 56k
6785
	 * - Reduces server load
6786
	 * - Reduces time to first painted byte
6787
	 *
6788
	 * Cons:
6789
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6790
	 *      should not cause any issues with themes.
6791
	 * - Plugins/themes dequeuing styles no longer do anything. See
6792
	 *      jetpack_implode_frontend_css filter for a workaround
6793
	 *
6794
	 * For some situations developers may wish to disable css imploding and
6795
	 * instead operate in legacy mode where each file loads seperately and
6796
	 * can be edited individually or dequeued. This can be accomplished with
6797
	 * the following line:
6798
	 *
6799
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6800
	 *
6801
	 * @since 3.2
6802
	 **/
6803
	public function implode_frontend_css( $travis_test = false ) {
6804
		$do_implode = true;
6805
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6806
			$do_implode = false;
6807
		}
6808
6809
		// Do not implode CSS when the page loads via the AMP plugin.
6810
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6811
			$do_implode = false;
6812
		}
6813
6814
		/**
6815
		 * Allow CSS to be concatenated into a single jetpack.css file.
6816
		 *
6817
		 * @since 3.2.0
6818
		 *
6819
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6820
		 */
6821
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6822
6823
		// Do not use the imploded file when default behavior was altered through the filter
6824
		if ( ! $do_implode ) {
6825
			return;
6826
		}
6827
6828
		// We do not want to use the imploded file in dev mode, or if not connected
6829
		if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6830
			if ( ! $travis_test ) {
6831
				return;
6832
			}
6833
		}
6834
6835
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6836
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6837
			return;
6838
		}
6839
6840
		/*
6841
		 * Now we assume Jetpack is connected and able to serve the single
6842
		 * file.
6843
		 *
6844
		 * In the future there will be a check here to serve the file locally
6845
		 * or potentially from the Jetpack CDN
6846
		 *
6847
		 * For now:
6848
		 * - Enqueue a single imploded css file
6849
		 * - Zero out the style_loader_tag for the bundled ones
6850
		 * - Be happy, drink scotch
6851
		 */
6852
6853
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6854
6855
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6856
6857
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6858
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6859
	}
6860
6861
	function concat_remove_style_loader_tag( $tag, $handle ) {
6862
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6863
			$tag = '';
6864
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6865
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6866
			}
6867
		}
6868
6869
		return $tag;
6870
	}
6871
6872
	/**
6873
	 * @deprecated
6874
	 * @see Automattic\Jetpack\Assets\add_aync_script
6875
	 */
6876
	public function script_add_async( $tag, $handle, $src ) {
6877
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6878
	}
6879
6880
	/*
6881
	 * Check the heartbeat data
6882
	 *
6883
	 * Organizes the heartbeat data by severity.  For example, if the site
6884
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6885
	 *
6886
	 * Data will be added to "caution" array, if it either:
6887
	 *  - Out of date Jetpack version
6888
	 *  - Out of date WP version
6889
	 *  - Out of date PHP version
6890
	 *
6891
	 * $return array $filtered_data
6892
	 */
6893
	public static function jetpack_check_heartbeat_data() {
6894
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6895
6896
		$good    = array();
6897
		$caution = array();
6898
		$bad     = array();
6899
6900
		foreach ( $raw_data as $stat => $value ) {
6901
6902
			// Check jetpack version
6903
			if ( 'version' == $stat ) {
6904
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6905
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6906
					continue;
6907
				}
6908
			}
6909
6910
			// Check WP version
6911
			if ( 'wp-version' == $stat ) {
6912
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6913
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6914
					continue;
6915
				}
6916
			}
6917
6918
			// Check PHP version
6919
			if ( 'php-version' == $stat ) {
6920
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6921
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6922
					continue;
6923
				}
6924
			}
6925
6926
			// Check ID crisis
6927
			if ( 'identitycrisis' == $stat ) {
6928
				if ( 'yes' == $value ) {
6929
					$bad[ $stat ] = $value;
6930
					continue;
6931
				}
6932
			}
6933
6934
			// The rest are good :)
6935
			$good[ $stat ] = $value;
6936
		}
6937
6938
		$filtered_data = array(
6939
			'good'    => $good,
6940
			'caution' => $caution,
6941
			'bad'     => $bad,
6942
		);
6943
6944
		return $filtered_data;
6945
	}
6946
6947
	/*
6948
	 * This method is used to organize all options that can be reset
6949
	 * without disconnecting Jetpack.
6950
	 *
6951
	 * It is used in class.jetpack-cli.php to reset options
6952
	 *
6953
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6954
	 *
6955
	 * @return array of options to delete.
6956
	 */
6957
	public static function get_jetpack_options_for_reset() {
6958
		return Jetpack_Options::get_options_for_reset();
6959
	}
6960
6961
	/*
6962
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6963
	 * so we can bring them directly to their site in calypso.
6964
	 *
6965
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6966
	 *
6967
	 * @param string | url
6968
	 * @return string | url without the guff
6969
	 */
6970
	public static function build_raw_urls( $url ) {
6971
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6972
6973
		return ( new Status() )->get_site_suffix( $url );
6974
	}
6975
6976
	/**
6977
	 * Stores and prints out domains to prefetch for page speed optimization.
6978
	 *
6979
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6980
	 *
6981
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|array|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...
6982
	 */
6983
	public static function dns_prefetch( $urls = null ) {
6984
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6985
		if ( $urls ) {
6986
			Assets::add_resource_hint( $urls );
6987
		}
6988
	}
6989
6990
	public function wp_dashboard_setup() {
6991
		if ( self::is_connection_ready() ) {
6992
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6993
		}
6994
6995
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6996
			$jetpack_logo = new Jetpack_Logo();
6997
			$widget_title = sprintf(
6998
				/* translators: Placeholder is a Jetpack logo. */
6999
				__( 'Stats by %s', 'jetpack' ),
7000
				$jetpack_logo->get_jp_emblem( true )
7001
			);
7002
7003
			// Wrap title in span so Logo can be properly styled.
7004
			$widget_title = sprintf(
7005
				'<span>%s</span>',
7006
				$widget_title
7007
			);
7008
7009
			wp_add_dashboard_widget(
7010
				'jetpack_summary_widget',
7011
				$widget_title,
7012
				array( __CLASS__, 'dashboard_widget' )
7013
			);
7014
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7015
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7016
7017
			// If we're inactive and not in offline mode, sort our box to the top.
7018
			if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7019
				global $wp_meta_boxes;
7020
7021
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7022
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7023
7024
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7025
			}
7026
		}
7027
	}
7028
7029
	/**
7030
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
7031
	 * @return mixed
7032
	 */
7033
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7034
		if ( ! is_array( $sorted ) ) {
7035
			return $sorted;
7036
		}
7037
7038
		foreach ( $sorted as $box_context => $ids ) {
7039
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7040
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7041
				continue;
7042
			}
7043
7044
			$ids_array = explode( ',', $ids );
7045
			$key       = array_search( 'dashboard_stats', $ids_array );
7046
7047
			if ( false !== $key ) {
7048
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7049
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7050
				$sorted[ $box_context ] = implode( ',', $ids_array );
7051
				// We've found it, stop searching, and just return.
7052
				break;
7053
			}
7054
		}
7055
7056
		return $sorted;
7057
	}
7058
7059
	public static function dashboard_widget() {
7060
		/**
7061
		 * Fires when the dashboard is loaded.
7062
		 *
7063
		 * @since 3.4.0
7064
		 */
7065
		do_action( 'jetpack_dashboard_widget' );
7066
	}
7067
7068
	public static function dashboard_widget_footer() {
7069
		?>
7070
		<footer>
7071
7072
		<div class="protect">
7073
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7074
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7075
				<p class="blocked-count">
7076
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7077
				</p>
7078
				<p><?php echo esc_html_x( 'Blocked malicious login attempts', '{#} Blocked malicious login attempts -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
7079
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7080
				<a href="
7081
				<?php
7082
				echo esc_url(
7083
					wp_nonce_url(
7084
						self::admin_url(
7085
							array(
7086
								'action' => 'activate',
7087
								'module' => 'protect',
7088
							)
7089
						),
7090
						'jetpack_activate-protect'
7091
					)
7092
				);
7093
				?>
7094
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7095
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7096
				</a>
7097
			<?php else : ?>
7098
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7099
			<?php endif; ?>
7100
		</div>
7101
7102
		<div class="akismet">
7103
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7104
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7105
				<p class="blocked-count">
7106
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7107
				</p>
7108
				<p><?php echo esc_html_x( 'Blocked spam comments.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
7109
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7110
				<a href="
7111
				<?php
7112
				echo esc_url(
7113
					wp_nonce_url(
7114
						add_query_arg(
7115
							array(
7116
								'action' => 'activate',
7117
								'plugin' => 'akismet/akismet.php',
7118
							),
7119
							admin_url( 'plugins.php' )
7120
						),
7121
						'activate-plugin_akismet/akismet.php'
7122
					)
7123
				);
7124
				?>
7125
							" class="button button-jetpack">
7126
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7127
				</a>
7128
			<?php else : ?>
7129
				<p><a href="<?php echo esc_url( 'https://akismet.com/?utm_source=jetpack&utm_medium=link&utm_campaign=Jetpack%20Dashboard%20Widget%20Footer%20Link' ); ?>"><?php esc_html_e( 'Anti-spam can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
7130
			<?php endif; ?>
7131
		</div>
7132
7133
		</footer>
7134
		<?php
7135
	}
7136
7137
	/*
7138
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7139
	 */
7140
	function jetpack_icon_user_connected( $columns ) {
7141
		$columns['user_jetpack'] = '';
7142
		return $columns;
7143
	}
7144
7145
	/*
7146
	 * Show Jetpack icon if the user is linked.
7147
	 */
7148
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7149
		if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7150
			$jetpack_logo = new Jetpack_Logo();
7151
			$emblem_html  = sprintf(
7152
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7153
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7154
				$jetpack_logo->get_jp_emblem()
7155
			);
7156
			return $emblem_html;
7157
		}
7158
7159
		return $val;
7160
	}
7161
7162
	/*
7163
	 * Style the Jetpack user column
7164
	 */
7165
	function jetpack_user_col_style() {
7166
		global $current_screen;
7167
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7168
			?>
7169
			<style>
7170
				.fixed .column-user_jetpack {
7171
					width: 21px;
7172
				}
7173
				.jp-emblem-user-admin svg {
7174
					width: 20px;
7175
					height: 20px;
7176
				}
7177
				.jp-emblem-user-admin path {
7178
					fill: #00BE28;
7179
				}
7180
			</style>
7181
			<?php
7182
		}
7183
	}
7184
7185
	/**
7186
	 * Checks if Akismet is active and working.
7187
	 *
7188
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7189
	 * that implied usage of methods present since more recent version.
7190
	 * See https://github.com/Automattic/jetpack/pull/9585
7191
	 *
7192
	 * @since  5.1.0
7193
	 *
7194
	 * @return bool True = Akismet available. False = Aksimet not available.
7195
	 */
7196
	public static function is_akismet_active() {
7197
		static $status = null;
7198
7199
		if ( ! is_null( $status ) ) {
7200
			return $status;
7201
		}
7202
7203
		// Check if a modern version of Akismet is active.
7204
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7205
			$status = false;
7206
			return $status;
7207
		}
7208
7209
		// Make sure there is a key known to Akismet at all before verifying key.
7210
		$akismet_key = Akismet::get_api_key();
7211
		if ( ! $akismet_key ) {
7212
			$status = false;
7213
			return $status;
7214
		}
7215
7216
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7217
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7218
7219
		// Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
7220
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7221
		// We cache the result of the Akismet key verification for ten minutes.
7222
		if ( ! $akismet_key_state || $recheck ) {
7223
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7224
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7225
		}
7226
7227
		$status = 'valid' === $akismet_key_state;
7228
7229
		return $status;
7230
	}
7231
7232
	/**
7233
	 * @deprecated
7234
	 *
7235
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7236
	 */
7237
	public static function is_function_in_backtrace() {
7238
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7239
	}
7240
7241
	/**
7242
	 * Given a minified path, and a non-minified path, will return
7243
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7244
	 *
7245
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7246
	 * root Jetpack directory.
7247
	 *
7248
	 * @since 5.6.0
7249
	 *
7250
	 * @param string $min_path
7251
	 * @param string $non_min_path
7252
	 * @return string The URL to the file
7253
	 */
7254
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7255
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7256
	}
7257
7258
	/**
7259
	 * Checks for whether Jetpack Backup is enabled.
7260
	 * Will return true if the state of Backup is anything except "unavailable".
7261
	 *
7262
	 * @return bool|int|mixed
7263
	 */
7264
	public static function is_rewind_enabled() {
7265
		// Rewind is a paid feature, therefore requires a user-level connection.
7266
		if ( ! static::connection()->has_connected_owner() ) {
7267
			return false;
7268
		}
7269
7270
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7271
		if ( false === $rewind_enabled ) {
7272
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7273
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7274
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7275
				&& ! empty( $rewind_data['state'] )
7276
				&& 'active' === $rewind_data['state'] )
7277
				? 1
7278
				: 0;
7279
7280
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7281
		}
7282
		return $rewind_enabled;
7283
	}
7284
7285
	/**
7286
	 * Return Calypso environment value; used for developing Jetpack and pairing
7287
	 * it with different Calypso enrionments, such as localhost.
7288
	 *
7289
	 * @since 7.4.0
7290
	 *
7291
	 * @return string Calypso environment
7292
	 */
7293
	public static function get_calypso_env() {
7294
		if ( isset( $_GET['calypso_env'] ) ) {
7295
			return sanitize_key( $_GET['calypso_env'] );
7296
		}
7297
7298
		if ( getenv( 'CALYPSO_ENV' ) ) {
7299
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7300
		}
7301
7302
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7303
			return sanitize_key( CALYPSO_ENV );
7304
		}
7305
7306
		return '';
7307
	}
7308
7309
	/**
7310
	 * Returns the hostname with protocol for Calypso.
7311
	 * Used for developing Jetpack with Calypso.
7312
	 *
7313
	 * @since 8.4.0
7314
	 *
7315
	 * @return string Calypso host.
7316
	 */
7317
	public static function get_calypso_host() {
7318
		$calypso_env = self::get_calypso_env();
7319
		switch ( $calypso_env ) {
7320
			case 'development':
7321
				return 'http://calypso.localhost:3000/';
7322
			case 'wpcalypso':
7323
				return 'https://wpcalypso.wordpress.com/';
7324
			case 'horizon':
7325
				return 'https://horizon.wordpress.com/';
7326
			default:
7327
				return 'https://wordpress.com/';
7328
		}
7329
	}
7330
7331
	/**
7332
	 * Handles activating default modules as well general cleanup for the new connection.
7333
	 *
7334
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7335
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7336
	 * @param boolean $send_state_messages          Whether to send state messages.
7337
	 * @return void
7338
	 */
7339
	public static function handle_post_authorization_actions(
7340
		$activate_sso = false,
7341
		$redirect_on_activation_error = false,
7342
		$send_state_messages = true
7343
	) {
7344
		$other_modules = $activate_sso
7345
			? array( 'sso' )
7346
			: array();
7347
7348
		if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7349
			$active_modules = Jetpack_Options::get_option( 'active_modules' );
7350
			self::delete_active_modules();
7351
7352
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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...
7353
		} else {
7354
			// Default modules that don't require a user were already activated on site_register.
7355
			// This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was connected only at a site level.
7356
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7357
			Jetpack_Options::update_option( 'active_modules_initialized', true );
7358
		}
7359
7360
		// Since this is a fresh connection, be sure to clear out IDC options
7361
		Identity_Crisis::clear_all_idc_options();
7362
7363
		if ( $send_state_messages ) {
7364
			self::state( 'message', 'authorized' );
7365
		}
7366
	}
7367
7368
	/**
7369
	 * Returns a boolean for whether backups UI should be displayed or not.
7370
	 *
7371
	 * @return bool Should backups UI be displayed?
7372
	 */
7373
	public static function show_backups_ui() {
7374
		/**
7375
		 * Whether UI for backups should be displayed.
7376
		 *
7377
		 * @since 6.5.0
7378
		 *
7379
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7380
		 */
7381
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7382
	}
7383
7384
	/*
7385
	 * Deprecated manage functions
7386
	 */
7387
	function prepare_manage_jetpack_notice() {
7388
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7389
	}
7390
	function manage_activate_screen() {
7391
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7392
	}
7393
	function admin_jetpack_manage_notice() {
7394
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7395
	}
7396
	function opt_out_jetpack_manage_url() {
7397
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7398
	}
7399
	function opt_in_jetpack_manage_url() {
7400
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7401
	}
7402
	function opt_in_jetpack_manage_notice() {
7403
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7404
	}
7405
	function can_display_jetpack_manage_notice() {
7406
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7407
	}
7408
7409
	/**
7410
	 * Clean leftoveruser meta.
7411
	 *
7412
	 * Delete Jetpack-related user meta when it is no longer needed.
7413
	 *
7414
	 * @since 7.3.0
7415
	 *
7416
	 * @param int $user_id User ID being updated.
7417
	 */
7418
	public static function user_meta_cleanup( $user_id ) {
7419
		$meta_keys = array(
7420
			// AtD removed from Jetpack 7.3
7421
			'AtD_options',
7422
			'AtD_check_when',
7423
			'AtD_guess_lang',
7424
			'AtD_ignored_phrases',
7425
		);
7426
7427
		foreach ( $meta_keys as $meta_key ) {
7428
			if ( get_user_meta( $user_id, $meta_key ) ) {
7429
				delete_user_meta( $user_id, $meta_key );
7430
			}
7431
		}
7432
	}
7433
7434
	/**
7435
	 * Checks if a Jetpack site is both active and not in offline mode.
7436
	 *
7437
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7438
	 *
7439
	 * @deprecated 8.8.0
7440
	 *
7441
	 * @return bool True if Jetpack is active and not in offline mode.
7442
	 */
7443
	public static function is_active_and_not_development_mode() {
7444
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7445
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack::is_active() has been deprecated with message: 9.6.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
7446
			return false;
7447
		}
7448
		return true;
7449
	}
7450
7451
	/**
7452
	 * Checks if a Jetpack site is both active and not in offline mode.
7453
	 *
7454
	 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7455
	 *
7456
	 * @since 8.8.0
7457
	 *
7458
	 * @return bool True if Jetpack is active and not in offline mode.
7459
	 */
7460
	public static function is_active_and_not_offline_mode() {
7461
		if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7462
			return false;
7463
		}
7464
		return true;
7465
	}
7466
7467
	/**
7468
	 * Returns the list of products that we have available for purchase.
7469
	 */
7470
	public static function get_products_for_purchase() {
7471
		$products = array();
7472
		if ( ! is_multisite() ) {
7473
			$products[] = array(
7474
				'key'               => 'backup',
7475
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7476
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7477
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7478
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7479
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7480
				'options'           => array(
7481
					array(
7482
						'type'        => 'daily',
7483
						'slug'        => 'jetpack-backup-daily',
7484
						'key'         => 'jetpack_backup_daily',
7485
						'name'        => __( 'Daily Backups', 'jetpack' ),
7486
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7487
					),
7488
					array(
7489
						'type'        => 'realtime',
7490
						'slug'        => 'jetpack-backup-realtime',
7491
						'key'         => 'jetpack_backup_realtime',
7492
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7493
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7494
					),
7495
				),
7496
				'default_option'    => 'realtime',
7497
				'show_promotion'    => true,
7498
				'discount_percent'  => 70,
7499
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7500
			);
7501
7502
			$products[] = array(
7503
				'key'               => 'scan',
7504
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7505
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7506
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7507
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7508
				'show_promotion'    => true,
7509
				'discount_percent'  => 30,
7510
				'options'           => array(
7511
					array(
7512
						'type' => 'scan',
7513
						'slug' => 'jetpack-scan',
7514
						'key'  => 'jetpack_scan',
7515
						'name' => __( 'Daily Scan', 'jetpack' ),
7516
					),
7517
				),
7518
				'default_option'    => 'scan',
7519
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7520
			);
7521
		}
7522
7523
		$products[] = array(
7524
			'key'               => 'search',
7525
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7526
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7527
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7528
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7529
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7530
			'options'           => array(
7531
				array(
7532
					'type' => 'search',
7533
					'slug' => 'jetpack-search',
7534
					'key'  => 'jetpack_search',
7535
					'name' => __( 'Search', 'jetpack' ),
7536
				),
7537
			),
7538
			'tears'             => array(),
7539
			'default_option'    => 'search',
7540
			'show_promotion'    => false,
7541
			'included_in_plans' => array( 'search-plan' ),
7542
		);
7543
7544
		$products[] = array(
7545
			'key'               => 'anti-spam',
7546
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7547
			'short_description' => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7548
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7549
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7550
			'options'           => array(
7551
				array(
7552
					'type' => 'anti-spam',
7553
					'slug' => 'jetpack-anti-spam',
7554
					'key'  => 'jetpack_anti_spam',
7555
					'name' => __( 'Anti-Spam', 'jetpack' ),
7556
				),
7557
			),
7558
			'default_option'    => 'anti-spam',
7559
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7560
		);
7561
7562
		return $products;
7563
	}
7564
7565
	/**
7566
	 * Determine if the current user is allowed to make Jetpack purchases without
7567
	 * a WordPress.com account
7568
	 *
7569
	 * @return boolean True if the user can make purchases, false if not
7570
	 */
7571
	public static function current_user_can_purchase() {
7572
7573
		// The site must be site-connected to Jetpack (no users connected).
7574
		if ( ! self::connection()->is_site_connection() ) {
7575
			return false;
7576
		}
7577
7578
		// Make sure only administrators can make purchases.
7579
		if ( ! current_user_can( 'manage_options' ) ) {
7580
			return false;
7581
		}
7582
7583
		return true;
7584
	}
7585
7586
}
7587