updated plugin Jetpack Protect version 2.2.0

This commit is contained in:
2024-06-27 12:10:57 +00:00
committed by Gitium
parent ec9d8a5834
commit 938cef2946
218 changed files with 7469 additions and 1864 deletions

View File

@ -0,0 +1,281 @@
<?php
/**
* Authorize_Json_Api handler class.
* Used to handle connections via JSON API.
* Ported from the Jetpack class.
*
* @since 2.7.6 Ported from the Jetpack class.
*
* @package automattic/jetpack-connection
*/
namespace Automattic\Jetpack\Connection;
use Automattic\Jetpack\Redirect;
use Automattic\Jetpack\Status\Host;
use Jetpack_Options;
/**
* Authorize_Json_Api handler class.
*/
class Authorize_Json_Api {
/**
* Verified data for JSON authorization request
*
* @since 2.7.6
*
* @var array
*/
public $json_api_authorization_request = array();
/**
* Verifies the request by checking the signature
*
* @since jetpack-4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
* passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
* @since 2.7.6 Ported from Jetpack to the Connection package.
*
* @param null|array $environment Value to override $_REQUEST.
*
* @return void
*/
public function verify_json_api_authorization_request( $environment = null ) {
$environment = $environment === null
? $_REQUEST // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verification handled later in function and request data are 1) used to verify a cryptographic signature of the request data and 2) sanitized later in function.
: $environment;
if ( ! isset( $environment['token'] ) ) {
wp_die( esc_html__( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack-connection' ) );
}
list( $env_token,, $env_user_id ) = explode( ':', $environment['token'] );
$token = ( new Tokens() )->get_access_token( (int) $env_user_id, $env_token );
if ( ! $token || empty( $token->secret ) ) {
wp_die( esc_html__( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack-connection' ) );
}
$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-connection' );
// Host has encoded the request URL, probably as a result of a bad http => https redirect.
if (
preg_match( '/https?%3A%2F%2F/i', esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) ) > 0 // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- no site changes, we're erroring out.
) {
/**
* Jetpack authorisation request Error.
*
* @since jetpack-7.5.0
*/
do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
$die_error = sprintf(
/* translators: %s is a URL */
__( '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-connection' ),
esc_url( Redirect::get_url( 'jetpack-support-double-encoding' ) )
);
}
$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
$signature = $jetpack_signature->sign_request(
$environment['token'],
$environment['timestamp'],
$environment['nonce'],
'',
'GET',
$environment['jetpack_json_api_original_query'],
null,
true
);
} else {
$signature = $jetpack_signature->sign_current_request(
array(
'body' => null,
'method' => 'GET',
)
);
}
if ( ! $signature ) {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
} elseif ( is_wp_error( $signature ) ) {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
if ( is_ssl() ) {
// 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.
$signature = $jetpack_signature->sign_current_request(
array(
'scheme' => 'http',
'body' => null,
'method' => 'GET',
)
);
if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
}
} else {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
}
}
$timestamp = (int) $environment['timestamp'];
$nonce = stripslashes( (string) $environment['nonce'] );
if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
// De-nonce the nonce, at least for 5 minutes.
// 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).
$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
if ( $old_nonce_time < time() - 300 ) {
wp_die( esc_html__( 'The authorization process expired. Please go back and try again.', 'jetpack-connection' ) );
}
}
$data = json_decode(
base64_decode( stripslashes( $environment['data'] ) ) // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
);
$data_filters = array(
'state' => 'opaque',
'client_id' => 'int',
'client_title' => 'string',
'client_image' => 'url',
);
foreach ( $data_filters as $key => $sanitation ) {
if ( ! isset( $data->$key ) ) {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
}
switch ( $sanitation ) {
case 'int':
$this->json_api_authorization_request[ $key ] = (int) $data->$key;
break;
case 'opaque':
$this->json_api_authorization_request[ $key ] = (string) $data->$key;
break;
case 'string':
$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
break;
case 'url':
$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
break;
}
}
if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
wp_die(
wp_kses(
$die_error,
array(
'a' => array(
'href' => array(),
),
)
)
);
}
}
/**
* Add the Access Code details to the public-api.wordpress.com redirect.
*
* @since 2.7.6 Ported from Jetpack to the Connection package.
*
* @param string $redirect_to URL.
* @param string $original_redirect_to URL.
* @param \WP_User $user WP_User for the redirect.
*
* @return string
*/
public function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
return add_query_arg(
urlencode_deep(
array(
'jetpack-code' => get_user_meta(
$user->ID,
'jetpack_json_api_' . $this->json_api_authorization_request['client_id'],
true
),
'jetpack-user-id' => (int) $user->ID,
'jetpack-state' => $this->json_api_authorization_request['state'],
)
),
$redirect_to
);
}
/**
* If someone logs in to approve API access, store the Access Code in usermeta.
*
* @since 2.7.6 Ported from Jetpack to the Connection package.
*
* @param string $user_login Unused.
* @param \WP_User $user User logged in.
*
* @return void
*/
public function store_json_api_authorization_token( $user_login, $user ) {
add_filter( 'login_redirect', array( $this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_public_api_domain' ) );
$token = wp_generate_password( 32, false );
update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
}
/**
* HTML for the JSON API authorization notice.
*
* @since 2.7.6 Ported from Jetpack to the Connection package.
*
* @return string
*/
public function login_message_json_api_authorization() {
return '<p class="message">' . sprintf(
/* translators: Name/image of the client requesting authorization */
esc_html__( '%s wants to access your sites data. Log in to authorize that access.', 'jetpack-connection' ),
'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
}
}

View File

@ -8,6 +8,10 @@
namespace Automattic\Jetpack\Connection;
use Automattic\Jetpack\Constants;
use WP_Error;
// `wp_remote_request` returns an array with a particular format.
'@phan-type _WP_Remote_Response_Array = array{headers:\WpOrg\Requests\Utility\CaseInsensitiveDictionary,body:string,response:array{code:int,message:string},cookies:\WP_HTTP_Cookie[],filename:?string,http_response:WP_HTTP_Requests_Response}';
/**
* The Client class that is used to connect to WordPress.com Jetpack API.
@ -18,9 +22,10 @@ class Client {
/**
* Makes an authorized remote request using Jetpack_Signature
*
* @param array $args the arguments for the remote request.
* @param array|String $body the request body.
* @param array $args the arguments for the remote request.
* @param array|string|null $body the request body.
* @return array|WP_Error WP HTTP response on success
* @phan-return _WP_Remote_Response_Array|WP_Error
*/
public static function remote_request( $args, $body = null ) {
if ( isset( $args['url'] ) ) {
@ -35,7 +40,7 @@ class Client {
}
$result = self::build_signed_request( $args, $body );
if ( ! $result || is_wp_error( $result ) ) {
if ( is_wp_error( $result ) ) {
return $result;
}
@ -64,12 +69,12 @@ class Client {
/**
* Adds authorization signature to a remote request using Jetpack_Signature
*
* @param array $args the arguments for the remote request.
* @param array|String $body the request body.
* @return WP_Error|array {
* @param array $args the arguments for the remote request.
* @param array|string|null $body the request body.
* @return WP_Error|array{url:string,request:array,auth:array} {
* An array containing URL and request items.
*
* @type String $url The request URL.
* @type string $url The request URL.
* @type array $request Request arguments.
* @type array $auth Authorization data.
* }
@ -107,7 +112,7 @@ class Client {
$token = ( new Tokens() )->get_access_token( $args['user_id'] );
if ( ! $token ) {
return new \WP_Error( 'missing_token' );
return new WP_Error( 'missing_token' );
}
$method = strtoupper( $args['method'] );
@ -122,8 +127,8 @@ class Client {
$request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' );
@list( $token_key, $secret ) = explode( '.', $token->secret ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( empty( $token ) || empty( $secret ) ) {
return new \WP_Error( 'malformed_token' );
if ( ! $secret ) {
return new WP_Error( 'malformed_token' );
}
$token_key = sprintf(
@ -141,7 +146,7 @@ class Client {
if ( function_exists( 'wp_generate_password' ) ) {
$nonce = wp_generate_password( 10, false );
} else {
$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
$nonce = substr( sha1( (string) wp_rand( 0, 1000000 ) ), 0, 10 );
}
// Kind of annoying. Maybe refactor Jetpack_Signature to handle body-hashing.
@ -166,7 +171,7 @@ class Client {
}
if ( ! is_string( $body_to_hash ) ) {
return new \WP_Error( 'invalid_body', 'Body is malformed.' );
return new WP_Error( 'invalid_body', 'Body is malformed.' );
}
$body_hash = base64_encode( sha1( $body_to_hash, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
}
@ -195,7 +200,7 @@ class Client {
$signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
if ( ! $signature || is_wp_error( $signature ) ) {
if ( is_wp_error( $signature ) ) {
return $signature;
}
@ -232,10 +237,11 @@ class Client {
*
* @internal
*
* @param String $url the request URL.
* @param string $url the request URL.
* @param array $args request arguments.
* @param Boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
* @param boolean $set_fallback whether to allow flagging this request to use a fallback certficate override.
* @return array|WP_Error WP HTTP response on success
* @phan-return _WP_Remote_Response_Array|WP_Error
*/
public static function _wp_remote_request( $url, $args, $set_fallback = false ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
$fallback = \Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
@ -315,8 +321,9 @@ class Client {
/**
* Sets the time difference for correct signature computation.
*
* @param HTTP_Response $response the response object.
* @param Boolean $force_set whether to force setting the time difference.
* @param array|WP_Error $response Response array from `wp_remote_request`, or WP_Error on error.
* @param bool $force_set whether to force setting the time difference.
* @phan-param _WP_Remote_Response_Array|WP_Error $response
*/
public static function set_time_diff( &$response, $force_set = false ) {
$code = wp_remote_retrieve_response_code( $response );
@ -356,7 +363,7 @@ class Client {
* @param array $args Arguments to {@see WP_Http}. Default is `array()`.
* @param string $base_api_path REST API root. Default is `wpcom`.
*
* @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
* @return array Validated arguments.
*/
public static function validate_args_for_wpcom_json_api_request(
$path,
@ -407,13 +414,14 @@ class Client {
/**
* Queries the WordPress.com REST API with a user token.
*
* @param string $path REST API path.
* @param string $version REST API version. Default is `2`.
* @param array $args Arguments to {@see WP_Http}. Default is `array()`.
* @param string $body Body passed to {@see WP_Http}. Default is `null`.
* @param string $base_api_path REST API root. Default is `wpcom`.
* @param string $path REST API path.
* @param string $version REST API version. Default is `2`.
* @param array $args Arguments to {@see WP_Http}. Default is `array()`.
* @param null|string|array $body Body passed to {@see WP_Http}. Default is `null`.
* @param string $base_api_path REST API root. Default is `wpcom`.
*
* @return array|WP_Error $response Response data, else {@see WP_Error} on failure.
* @phan-return _WP_Remote_Response_Array|WP_Error
*/
public static function wpcom_json_api_request_as_user(
$path,
@ -439,12 +447,13 @@ class Client {
/**
* Query the WordPress.com REST API using the blog token
*
* @param String $path The API endpoint relative path.
* @param String $version The API version.
* @param array $args Request arguments.
* @param String $body Request body.
* @param String $base_api_path (optional) the API base path override, defaults to 'rest'.
* @param string $path The API endpoint relative path.
* @param string $version The API version.
* @param array $args Request arguments.
* @param array|string|null $body Request body.
* @param string $base_api_path (optional) the API base path override, defaults to 'rest'.
* @return array|WP_Error $response Data.
* @phan-return _WP_Remote_Response_Array|WP_Error
*/
public static function wpcom_json_api_request_as_blog(
$path,
@ -471,7 +480,7 @@ class Client {
* make sure that body hashes are made ith the string version, which is what will be seen after a
* server pulls up the data in the $_POST array.
*
* @param array|Mixed $data the data that needs to be stringified.
* @param mixed $data the data that needs to be stringified.
*
* @return array|string
*/

View File

@ -702,11 +702,15 @@ class Error_Handler {
return;
}
?>
<div class="notice notice-error is-dismissible jetpack-message jp-connect" style="display:block !important;">
<p><?php echo esc_html( $message ); ?></p>
</div>
<?php
wp_admin_notice(
esc_html( $message ),
array(
'type' => 'error',
'dismissible' => true,
'additional_classes' => array( 'jetpack-message', 'jp-connect' ),
'attributes' => array( 'style' => 'display:block !important;' ),
)
);
}
/**

View File

@ -7,8 +7,13 @@
namespace Automattic\Jetpack;
use Automattic\Jetpack\Connection\Rest_Authentication;
use Automattic\Jetpack\Connection\REST_Connector;
use Jetpack_Options;
use WP_CLI;
use WP_Error;
use WP_REST_Request;
use WP_REST_Server;
/**
* Heartbeat sends a batch of stats to wp.com once a day
@ -73,6 +78,8 @@ class Heartbeat {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'jetpack-heartbeat', array( $this, 'cli_callback' ) );
}
add_action( 'rest_api_init', array( $this, 'initialize_rest_api' ) );
}
/**
@ -249,4 +256,55 @@ class Heartbeat {
WP_CLI::line( sprintf( __( 'Last heartbeat sent at: %s', 'jetpack-connection' ), $last_date ) );
}
}
/**
* Initialize the heartbeat REST API.
*
* @return void
*/
public function initialize_rest_api() {
register_rest_route(
'jetpack/v4',
'/heartbeat/data',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'rest_heartbeat_data' ),
'permission_callback' => array( $this, 'rest_heartbeat_data_permission_check' ),
'args' => array(
'prefix' => array(
'description' => __( 'Prefix to add before the stats identifiers.', 'jetpack-connection' ),
'type' => 'string',
),
),
)
);
}
/**
* Endpoint to retrieve the heartbeat data.
*
* @param WP_REST_Request $request The request data.
*
* @since 2.7.0
*
* @return array
*/
public function rest_heartbeat_data( WP_REST_Request $request ) {
return static::generate_stats_array( $request->get_param( 'prefix' ) );
}
/**
* Check permissions for the `get_heartbeat_data` endpoint.
*
* @return true|WP_Error
*/
public function rest_heartbeat_data_permission_check() {
if ( current_user_can( 'jetpack_connect' ) ) {
return true;
}
return Rest_Authentication::is_signed_with_blog_token()
? true
: new WP_Error( 'invalid_permission_heartbeat_data', REST_Connector::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
}
}

View File

@ -16,8 +16,10 @@ use Automattic\Jetpack\Status;
use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\Terms_Of_Service;
use Automattic\Jetpack\Tracking;
use IXR_Error;
use Jetpack_IXR_Client;
use Jetpack_Options;
use Jetpack_XMLRPC_Server;
use WP_Error;
use WP_User;
@ -71,6 +73,13 @@ class Manager {
*/
private static $extra_register_params = array();
/**
* We store ID's of users already disconnected to prevent multiple disconnect requests.
*
* @var array
*/
private static $disconnected_users = array();
/**
* Initialize the object.
* Make sure to call the "Configure" first.
@ -102,7 +111,7 @@ class Manager {
);
$manager->setup_xmlrpc_handlers(
$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
null,
$manager->has_connected_owner(),
$manager->verify_xml_rpc_signature()
);
@ -127,6 +136,10 @@ class Manager {
Webhooks::init( $manager );
// Unlink user before deleting the user from WP.com.
add_action( 'deleted_user', array( $manager, 'disconnect_user_force' ), 9, 1 );
add_action( 'remove_user_from_blog', array( $manager, 'disconnect_user_force' ), 9, 1 );
// Set up package version hook.
add_filter( 'jetpack_package_versions', __NAMESPACE__ . '\Package_Version::send_package_version_to_tracker' );
@ -148,32 +161,31 @@ class Manager {
* Sets up the XMLRPC request handlers.
*
* @since 1.25.0 Deprecate $is_active param.
* @since 2.8.4 Deprecate $request_params param.
*
* @param array $request_params incoming request parameters.
* @param bool $has_connected_owner Whether the site has a connected owner.
* @param bool $is_signed whether the signature check has been successful.
* @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
* @param array|null $deprecated Deprecated. Not used.
* @param bool $has_connected_owner Whether the site has a connected owner.
* @param bool $is_signed whether the signature check has been successful.
* @param Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
*/
public function setup_xmlrpc_handlers(
$request_params,
$deprecated,
$has_connected_owner,
$is_signed,
\Jetpack_XMLRPC_Server $xmlrpc_server = null
Jetpack_XMLRPC_Server $xmlrpc_server = null
) {
add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
if (
! isset( $request_params['for'] )
|| 'jetpack' !== $request_params['for']
) {
if ( $deprecated !== null ) {
_deprecated_argument( __METHOD__, '2.8.4' );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- We are using the 'for' request param to early return unless it's 'jetpack'.
if ( ! isset( $_GET['for'] ) || 'jetpack' !== $_GET['for'] ) {
return false;
}
// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
if (
isset( $request_params['jetpack'] )
&& 'comms' === $request_params['jetpack']
) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This just determines whether to handle the request as an XML-RPC request. The actual XML-RPC endpoints do the appropriate nonce checking where applicable. Plus we make sure to clear all cookies via require_jetpack_authentication called later in method.
if ( isset( $_GET['jetpack'] ) && 'comms' === $_GET['jetpack'] ) {
if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
// Use the real constant here for WordPress' sake.
define( 'XMLRPC_REQUEST', true );
@ -193,7 +205,7 @@ class Manager {
if ( $xmlrpc_server ) {
$this->xmlrpc_server = $xmlrpc_server;
} else {
$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
}
$this->require_jetpack_authentication();
@ -442,9 +454,9 @@ class Manager {
}
$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
// phpcs:disable WordPress.Security.NonceVerification.Missing
// phpcs:disable WordPress.Security.NonceVerification.Missing -- Used to verify a cryptographic signature of the post data. Also a nonce is verified later in the function.
if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
$post_data = $_POST;
$post_data = $_POST; // We need all of $_POST in order to verify a cryptographic signature of the post data.
$file_hashes = array();
foreach ( $post_data as $post_data_key => $post_data_value ) {
if ( ! str_starts_with( $post_data_key, '_jetpack_file_hmac_' ) ) {
@ -863,6 +875,22 @@ class Manager {
exit();
}
/**
* Force user disconnect.
*
* @param int $user_id Local (external) user ID.
*
* @return bool
*/
public function disconnect_user_force( $user_id ) {
if ( ! (int) $user_id ) {
// Missing user ID.
return false;
}
return $this->disconnect_user( $user_id, true, true );
}
/**
* Unlinks the current user from the linked WordPress.com user.
*
@ -884,6 +912,11 @@ class Manager {
return false;
}
if ( in_array( $user_id, self::$disconnected_users, true ) ) {
// The user is already disconnected.
return false;
}
// Attempt to disconnect the user from WordPress.com.
$is_disconnected_from_wpcom = $this->unlink_user_from_wpcom( $user_id );
@ -913,6 +946,8 @@ class Manager {
}
}
self::$disconnected_users[] = $user_id;
return $is_disconnected_from_wpcom && $is_disconnected_locally;
}
@ -1842,11 +1877,16 @@ class Manager {
/**
* Builds a URL to the Jetpack connection auth page.
*
* @param WP_User $user (optional) defaults to the current logged in user.
* @param String $redirect (optional) a redirect URL to use instead of the default.
* @since 2.7.6 Added optional $from and $raw parameters.
*
* @param WP_User $user (optional) defaults to the current logged in user.
* @param string $redirect (optional) a redirect URL to use instead of the default.
* @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
* @param bool $raw If true, URL will not be escaped.
*
* @return string Connect URL.
*/
public function get_authorization_url( $user = null, $redirect = null ) {
public function get_authorization_url( $user = null, $redirect = null, $from = false, $raw = false ) {
if ( empty( $user ) ) {
$user = wp_get_current_user();
}
@ -1939,8 +1979,28 @@ class Manager {
$url = add_query_arg( $body, $api_url );
/** This filter is documented in plugins/jetpack/class-jetpack.php */
return apply_filters( 'jetpack_build_authorize_url', $url );
if ( is_network_admin() ) {
$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
}
if ( $from ) {
$url = add_query_arg( 'from', $from, $url );
}
if ( $raw ) {
$url = esc_url_raw( $url );
}
/**
* Filter the URL used when connecting a user to a WordPress.com account.
*
* @since 2.0.0
* @since 2.7.6 Added $raw parameter.
*
* @param string $url Connection URL.
* @param bool $raw If true, URL will not be escaped.
*/
return apply_filters( 'jetpack_build_authorize_url', $url, $raw );
}
/**
@ -2287,7 +2347,7 @@ class Manager {
* Handles a getOptions XMLRPC method call.
*
* @param array $args method call arguments.
* @return an amended XMLRPC server options array.
* @return array|IXR_Error An amended XMLRPC server options array.
*/
public function jetpack_get_options( $args ) {
global $wp_xmlrpc_server;

View File

@ -12,7 +12,7 @@ namespace Automattic\Jetpack\Connection;
*/
class Package_Version {
const PACKAGE_VERSION = '2.5.0';
const PACKAGE_VERSION = '2.8.4';
const PACKAGE_SLUG = 'connection';

View File

@ -24,6 +24,11 @@ class Plugin_Storage {
*/
const PLUGINS_DISABLED_OPTION_NAME = 'jetpack_connection_disabled_plugins';
/**
* Transient name used as flag to indicate that the active connected plugins list needs refreshing.
*/
const ACTIVE_PLUGINS_REFRESH_FLAG = 'jetpack_connection_active_plugins_refresh';
/**
* Whether this class was configured for the first time or not.
*
@ -31,13 +36,6 @@ class Plugin_Storage {
*/
private static $configured = false;
/**
* Refresh list of connected plugins upon intialization.
*
* @var boolean
*/
private static $refresh_connected_plugins = false;
/**
* Connected plugins.
*
@ -65,11 +63,6 @@ class Plugin_Storage {
public static function upsert( $slug, array $args = array() ) {
self::$plugins[ $slug ] = $args;
// if plugin is not in the list of active plugins, refresh the list.
if ( ! array_key_exists( $slug, (array) get_option( self::ACTIVE_PLUGINS_OPTION_NAME, array() ) ) ) {
self::$refresh_connected_plugins = true;
}
return true;
}
@ -167,6 +160,44 @@ class Plugin_Storage {
return;
}
self::$configured = true;
add_action( 'update_option_active_plugins', array( __CLASS__, 'set_flag_to_refresh_active_connected_plugins' ) );
self::maybe_update_active_connected_plugins();
}
/**
* Set a flag to indicate that the active connected plugins list needs to be updated.
* This will happen when the `active_plugins` option is updated.
*
* @see configure
*/
public static function set_flag_to_refresh_active_connected_plugins() {
set_transient( self::ACTIVE_PLUGINS_REFRESH_FLAG, time() );
}
/**
* Determine if we need to update the active connected plugins list.
*/
public static function maybe_update_active_connected_plugins() {
$maybe_error = self::ensure_configured();
if ( $maybe_error instanceof WP_Error ) {
return;
}
// Only attempt to update the option if the corresponding flag is set.
if ( ! get_transient( self::ACTIVE_PLUGINS_REFRESH_FLAG ) ) {
return;
}
// Only attempt to update the option on POST requests.
// This will prevent the option from being updated multiple times due to concurrent requests.
if ( ! ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] ) ) {
return;
}
delete_transient( self::ACTIVE_PLUGINS_REFRESH_FLAG );
if ( is_multisite() ) {
self::$current_blog_id = get_current_blog_id();
}
@ -175,11 +206,9 @@ class Plugin_Storage {
// self::$plugins is populated in Config::ensure_options_connection().
$number_of_plugins_differ = count( self::$plugins ) !== count( (array) get_option( self::ACTIVE_PLUGINS_OPTION_NAME, array() ) );
if ( $number_of_plugins_differ || true === self::$refresh_connected_plugins ) {
if ( $number_of_plugins_differ ) {
self::update_active_plugins_option();
}
self::$configured = true;
}
/**
@ -188,7 +217,7 @@ class Plugin_Storage {
* @return void
*/
public static function update_active_plugins_option() {
// Note: Since this options is synced to wpcom, if you change its structure, you have to update the sanitizer at wpcom side.
// Note: Since this option is synced to wpcom, if you change its structure, you have to update the sanitizer at wpcom side.
update_option( self::ACTIVE_PLUGINS_OPTION_NAME, self::$plugins );
if ( ! class_exists( 'Automattic\Jetpack\Sync\Settings' ) || ! \Automattic\Jetpack\Sync\Settings::is_sync_enabled() ) {

View File

@ -7,6 +7,8 @@
namespace Automattic\Jetpack\Connection;
use WP_Error;
/**
* The Jetpack Connection Rest Authentication class.
*/
@ -118,7 +120,7 @@ class Rest_Authentication {
}
if ( ! isset( $_SERVER['REQUEST_METHOD'] ) ) {
$this->rest_authentication_status = new \WP_Error(
$this->rest_authentication_status = new WP_Error(
'rest_invalid_request',
__( 'The request method is missing.', 'jetpack-connection' ),
array( 'status' => 400 )
@ -131,7 +133,7 @@ class Rest_Authentication {
// can be passed to the WP REST API via the '?_method=' parameter if
// needed.
if ( 'GET' !== $_SERVER['REQUEST_METHOD'] && 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
$this->rest_authentication_status = new \WP_Error(
$this->rest_authentication_status = new WP_Error(
'rest_invalid_request',
__( 'This request method is not supported.', 'jetpack-connection' ),
array( 'status' => 400 )
@ -139,7 +141,7 @@ class Rest_Authentication {
return null;
}
if ( 'POST' !== $_SERVER['REQUEST_METHOD'] && ! empty( file_get_contents( 'php://input' ) ) ) {
$this->rest_authentication_status = new \WP_Error(
$this->rest_authentication_status = new WP_Error(
'rest_invalid_request',
__( 'This request method does not support body parameters.', 'jetpack-connection' ),
array( 'status' => 400 )
@ -173,7 +175,7 @@ class Rest_Authentication {
}
// Something else went wrong. Probably a signature error.
$this->rest_authentication_status = new \WP_Error(
$this->rest_authentication_status = new WP_Error(
'rest_invalid_signature',
__( 'The request is not signed correctly.', 'jetpack-connection' ),
array( 'status' => 400 )

View File

@ -7,6 +7,7 @@
namespace Automattic\Jetpack\Connection;
use Automattic\Jetpack\Connection\Webhooks\Authorize_Redirect;
use Automattic\Jetpack\Constants;
use Automattic\Jetpack\Redirect;
use Automattic\Jetpack\Status;
@ -105,6 +106,28 @@ class REST_Connector {
)
);
// Connect a remote user.
register_rest_route(
'jetpack/v4',
'/remote_connect',
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'remote_connect' ),
'permission_callback' => array( $this, 'remote_connect_permission_check' ),
)
);
// The endpoint verifies blog connection and blog token validity.
register_rest_route(
'jetpack/v4',
'/connection/check',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'connection_check' ),
'permission_callback' => array( $this, 'connection_check_permission_check' ),
)
);
// Get current connection status of Jetpack.
register_rest_route(
'jetpack/v4',
@ -295,7 +318,7 @@ class REST_Connector {
*
* @param WP_REST_Request $request The request sent to the WP REST API.
*
* @return array|wp-error
* @return array|WP_Error
*/
public static function remote_authorize( $request ) {
$xmlrpc_server = new Jetpack_XMLRPC_Server();
@ -328,6 +351,26 @@ class REST_Connector {
return $result;
}
/**
* Connect a remote user.
*
* @since 2.6.0
*
* @param WP_REST_Request $request The request sent to the WP REST API.
*
* @return WP_Error|array
*/
public static function remote_connect( WP_REST_Request $request ) {
$xmlrpc_server = new Jetpack_XMLRPC_Server();
$result = $xmlrpc_server->remote_connect( $request );
if ( is_a( $result, 'IXR_Error' ) ) {
$result = new WP_Error( $result->code, $result->message );
}
return $result;
}
/**
* Register the site so that a plan can be provisioned.
*
@ -359,6 +402,17 @@ class REST_Connector {
: new WP_Error( 'invalid_permission_remote_provision', self::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
}
/**
* Remote connect endpoint permission check.
*
* @return true|WP_Error
*/
public function remote_connect_permission_check() {
return Rest_Authentication::is_signed_with_blog_token()
? true
: new WP_Error( 'invalid_permission_remote_connect', self::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
}
/**
* Remote register endpoint permission check.
*
@ -761,11 +815,7 @@ class REST_Connector {
$redirect_uri = $request->get_param( 'redirect_uri' ) ? admin_url( $request->get_param( 'redirect_uri' ) ) : null;
if ( class_exists( 'Jetpack' ) ) {
$authorize_url = \Jetpack::build_authorize_url( $redirect_uri );
} else {
$authorize_url = $this->connection->get_authorization_url( null, $redirect_uri );
}
$authorize_url = ( new Authorize_Redirect( $this->connection ) )->build_authorize_url( $redirect_uri );
/**
* Filters the response of jetpack/v4/connection/register endpoint
@ -885,7 +935,7 @@ class REST_Connector {
*
* @since 1.29.0
*
* @return bool|WP_Error.
* @return bool|WP_Error
*/
public static function update_user_token_permission_check() {
return Rest_Authentication::is_signed_with_blog_token()
@ -934,4 +984,41 @@ class REST_Connector {
return new WP_Error( 'invalid_user_permission_set_connection_owner', self::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
}
/**
* The endpoint verifies blog connection and blog token validity.
*
* @since 2.7.0
*
* @return mixed|null
*/
public function connection_check() {
/**
* Filters the successful response of the REST API test_connection method
*
* @param string $response The response string.
*/
$status = apply_filters( 'jetpack_rest_connection_check_response', 'success' );
return rest_ensure_response(
array(
'status' => $status,
)
);
}
/**
* Remote connect endpoint permission check.
*
* @return true|WP_Error
*/
public function connection_check_permission_check() {
if ( current_user_can( 'jetpack_connect' ) ) {
return true;
}
return Rest_Authentication::is_signed_with_blog_token()
? true
: new WP_Error( 'invalid_permission_connection_check', self::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
}
}

View File

@ -158,6 +158,7 @@ class Secrets {
*/
do_action( 'jetpack_verify_secrets_begin', $action, $user );
/** Closure to run the 'fail' action and return an error. */
$return_error = function ( WP_Error $error ) use ( $action, $user ) {
/**
* Verifying of the previously generated secret has failed.

View File

@ -223,7 +223,7 @@ class Server_Sandbox {
*
* Attached to the `admin_bar_menu` action.
*
* @param WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance.
* @param \WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance.
*/
public function admin_bar_add_sandbox_item( $wp_admin_bar ) {
if ( ! Constants::get_constant( 'JETPACK__SANDBOX_DOMAIN' ) ) {

View File

@ -38,8 +38,8 @@ class Tracking {
/**
* Creates the Tracking object.
*
* @param String $product_name the slug of the product that we are tracking.
* @param Automattic\Jetpack\Connection\Manager $connection the connection manager object.
* @param String $product_name the slug of the product that we are tracking.
* @param \Automattic\Jetpack\Connection\Manager $connection the connection manager object.
*/
public function __construct( $product_name = 'jetpack', $connection = null ) {
$this->product_name = $product_name;
@ -159,7 +159,7 @@ class Tracking {
*
* @param string $event_type Type of the event.
* @param array $data Data to send with the event.
* @param mixed $user Username, user_id, or WP_user object.
* @param mixed $user Username, user_id, or WP_User object.
* @param bool $use_product_prefix Whether to use the object's product name as a prefix to the event type. If
* set to false, the prefix will be 'jetpack_'.
*/
@ -189,7 +189,7 @@ class Tracking {
/**
* Record an event in Tracks - this is the preferred way to record events from PHP.
*
* @param mixed $user username, user_id, or WP_user object.
* @param mixed $user username, user_id, or WP_User object.
* @param string $event_name The name of the event.
* @param array $properties Custom properties to send with the event.
* @param int $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred.
@ -221,8 +221,8 @@ class Tracking {
/**
* Determines whether tracking should be enabled.
*
* @param Automattic\Jetpack\Terms_Of_Service $terms_of_service A Terms_Of_Service object.
* @param Automattic\Jetpack\Status $status A Status object.
* @param \Automattic\Jetpack\Terms_Of_Service $terms_of_service A Terms_Of_Service object.
* @param \Automattic\Jetpack\Status $status A Status object.
*
* @return boolean True if tracking should be enabled, else false.
*/
@ -238,10 +238,10 @@ class Tracking {
* Procedurally build a Tracks Event Object.
* NOTE: Use this only when the simpler Automattic\Jetpack\Tracking->jetpack_tracks_record_event() function won't work for you.
*
* @param WP_user $user WP_user object.
* @param string $event_name The name of the event.
* @param array $properties Custom properties to send with the event.
* @param int $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred.
* @param \WP_User $user WP_User object.
* @param string $event_name The name of the event.
* @param array $properties Custom properties to send with the event.
* @param int $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred.
*
* @return \Jetpack_Tracks_Event|\WP_Error
*/

View File

@ -82,8 +82,8 @@ class Urls {
/**
* Return URL with a normalized protocol.
*
* @param callable $callable Function to retrieve URL option.
* @param string $new_value URL Protocol to set URLs to.
* @param string $callable Function name that was used to retrieve URL option.
* @param string $new_value URL Protocol to set URLs to.
* @return string Normalized URL.
*/
public static function get_protocol_normalized_url( $callable, $new_value ) {

View File

@ -83,4 +83,53 @@ class Utils {
)
);
}
/**
* Generate a new user from a SSO attempt.
*
* @param object $user_data WordPress.com user information.
*/
public static function generate_user( $user_data ) {
$username = $user_data->login;
/**
* Determines how many times the SSO module can attempt to randomly generate a user.
*
* @module sso
*
* @since jetpack-4.3.2
*
* @param int 5 By default, SSO will attempt to random generate a user up to 5 times.
*/
$num_tries = (int) apply_filters( 'jetpack_sso_allowed_username_generate_retries', 5 );
$exists = username_exists( $username );
$tries = 0;
while ( $exists && $tries++ < $num_tries ) {
$username = $user_data->login . '_' . $user_data->ID . '_' . wp_rand();
$exists = username_exists( $username );
}
if ( $exists ) {
return false;
}
$user = (object) array();
$user->user_pass = wp_generate_password( 20 );
$user->user_login = wp_slash( $username );
$user->user_email = wp_slash( $user_data->email );
$user->display_name = $user_data->display_name;
$user->first_name = $user_data->first_name;
$user->last_name = $user_data->last_name;
$user->url = $user_data->url;
$user->description = $user_data->description;
if ( isset( $user_data->role ) && $user_data->role ) {
$user->role = $user_data->role;
}
$created_user_id = wp_insert_user( $user );
update_user_meta( $created_user_id, 'wpcom_user_id', $user_data->ID );
return get_userdata( $created_user_id );
}
}

View File

@ -107,7 +107,7 @@ class Webhooks {
}
do_action( 'jetpack_client_authorize_processing' );
$data = stripslashes_deep( $_GET );
$data = stripslashes_deep( $_GET ); // We need all request data under the context of an authorization request.
$data['auth_type'] = 'client';
$roles = new Roles();
$role = $roles->translate_current_user_to_role();

View File

@ -7,6 +7,8 @@
namespace Automattic\Jetpack\Connection;
use IXR_Error;
/**
* Registers the XML-RPC methods for Connections.
*/
@ -69,10 +71,10 @@ class XMLRPC_Connector {
$code = -10520;
}
if ( ! class_exists( \IXR_Error::class ) ) {
if ( ! class_exists( IXR_Error::class ) ) {
require_once ABSPATH . WPINC . '/class-IXR.php';
}
return new \IXR_Error(
return new IXR_Error(
$code,
sprintf( 'Jetpack: [%s] %s', $data->get_error_code(), $data->get_error_message() )
);

View File

@ -0,0 +1,184 @@
<?php
/**
* Force Jetpack 2FA Functionality
*
* Ported from original repo at https://github.com/automattic/jetpack-force-2fa
*
* @package automattic/jetpack-connection
*/
namespace Automattic\Jetpack\Connection\SSO;
use Automattic\Jetpack\Connection\SSO;
use Automattic\Jetpack\Modules;
use WP_Error;
/**
* Force users to use two factor authentication.
*/
class Force_2FA {
/**
* The role to force 2FA for.
*
* Defaults to manage_options via the plugins_loaded function.
* Can be modified with the jetpack_force_2fa_cap filter.
*
* @var string
*/
private $role;
/**
* Constructor.
*/
public function __construct() {
add_action( 'after_setup_theme', array( $this, 'plugins_loaded' ) );
}
/**
* Load the plugin via the plugins_loaded hook.
*/
public function plugins_loaded() {
/**
* Filter the role to force 2FA for.
* Defaults to manage_options.
*
* @param string $role The role to force 2FA for.
* @return string
* @since jetpack-12.7
* @module SSO
*/
$this->role = apply_filters( 'jetpack_force_2fa_cap', 'manage_options' );
// Bail if Jetpack SSO is not active
if ( ! ( new Modules() )->is_active( 'sso' ) ) {
add_action( 'admin_notices', array( $this, 'admin_notice' ) );
return;
}
$this->force_2fa();
}
/**
* Display an admin notice if Jetpack SSO is not active.
*/
public function admin_notice() {
/**
* Filter if an admin notice is deplayed when Force 2FA is required, but SSO is not enabled.
* Defaults to true.
*
* @param bool $display_notice Whether to display the notice.
* @return bool
* @since jetpack-12.7
* @module SSO
*/
if ( apply_filters( 'jetpack_force_2fa_dependency_notice', true ) && current_user_can( $this->role ) ) {
wp_admin_notice(
esc_html__( 'Jetpack Force 2FA requires Jetpacks SSO feature.', 'jetpack-connection' ),
array(
'type' => 'warning',
)
);
}
}
/**
* Force 2FA when using Jetpack SSO and force Jetpack SSO.
*
* @return void
*/
private function force_2fa() {
// Allows WP.com login to a local account if it matches the local account.
add_filter( 'jetpack_sso_match_by_email', '__return_true', 9999 );
// multisite
if ( is_multisite() ) {
// Hide the login form
add_filter( 'jetpack_remove_login_form', '__return_true', 9999 );
add_filter( 'jetpack_sso_bypass_login_forward_wpcom', '__return_true', 9999 );
add_filter( 'jetpack_sso_display_disclaimer', '__return_false', 9999 );
add_filter(
'wp_authenticate_user',
function () {
return new WP_Error( 'wpcom-required', $this->get_login_error_message() ); },
9999
);
add_filter( 'jetpack_sso_require_two_step', '__return_true' );
add_filter( 'allow_password_reset', '__return_false' );
} else {
// Not multisite.
// Completely disable the standard login form for admins.
add_filter(
'wp_authenticate_user',
function ( $user ) {
if ( is_wp_error( $user ) ) {
return $user;
}
if ( $user->has_cap( $this->role ) ) {
return new WP_Error( 'wpcom-required', $this->get_login_error_message(), $user->user_login );
}
return $user;
},
9999
);
add_filter(
'allow_password_reset',
function ( $allow, $user_id ) {
if ( user_can( $user_id, $this->role ) ) {
return false;
}
return $allow; },
9999,
2
);
add_action( 'jetpack_sso_pre_handle_login', array( $this, 'jetpack_set_two_step' ) );
}
}
/**
* Specifically set the two step filter for Jetpack SSO.
*
* @param Object $user_data The user data from WordPress.com.
*
* @return void
*/
public function jetpack_set_two_step( $user_data ) {
$user = SSO::get_user_by_wpcom_id( $user_data->ID );
// Borrowed from Jetpack. Ignores the match_by_email setting.
if ( empty( $user ) ) {
$user = get_user_by( 'email', $user_data->email );
}
if ( $user && $user->has_cap( $this->role ) ) {
add_filter( 'jetpack_sso_require_two_step', '__return_true' );
}
}
/**
* Get the login error message.
*
* @return string
*/
private function get_login_error_message() {
/**
* Filter the login error message.
* Defaults to a message that explains the user must use a WordPress.com account with 2FA enabled.
*
* @param string $message The login error message.
* @return string
* @since jetpack-12.7
* @module SSO
*/
return apply_filters(
'jetpack_force_2fa_login_error_message',
sprintf( 'For added security, please log in using your WordPress.com account.<br /><br />Note: Your account must have <a href="%1$s" target="_blank">Two Step Authentication</a> enabled, which can be configured from <a href="%2$s" target="_blank">Security Settings</a>.', 'https://support.wordpress.com/security/two-step-authentication/', 'https://wordpress.com/me/security/two-step' )
);
}
}

View File

@ -0,0 +1,387 @@
<?php
/**
* A collection of helper functions used in the SSO module.
*
* @package automattic/jetpack-connection
*/
namespace Automattic\Jetpack\Connection\SSO;
use Automattic\Jetpack\Constants;
use Jetpack_IXR_Client;
/**
* A collection of helper functions used in the SSO module.
*
* @since jetpack-4.1.0
*/
class Helpers {
/**
* Determine if the login form should be hidden or not
*
* @return bool
**/
public static function should_hide_login_form() {
/**
* Remove the default log in form, only leave the WordPress.com log in button.
*
* @module sso
*
* @since jetpack-3.1.0
*
* @param bool get_option( 'jetpack_sso_remove_login_form', false ) Should the default log in form be removed. Default to false.
*/
return (bool) apply_filters( 'jetpack_remove_login_form', get_option( 'jetpack_sso_remove_login_form', false ) );
}
/**
* Returns a boolean value for whether logging in by matching the WordPress.com user email to a
* Jetpack site user's email is allowed.
*
* @return bool
*/
public static function match_by_email() {
$match_by_email = defined( 'WPCC_MATCH_BY_EMAIL' ) ? \WPCC_MATCH_BY_EMAIL : (bool) get_option( 'jetpack_sso_match_by_email', true );
/**
* Link the local account to an account on WordPress.com using the same email address.
*
* @module sso
*
* @since jetpack-2.6.0
*
* @param bool $match_by_email Should we link the local account to an account on WordPress.com using the same email address. Default to false.
*/
return (bool) apply_filters( 'jetpack_sso_match_by_email', $match_by_email );
}
/**
* Returns a boolean for whether users are allowed to register on the Jetpack site with SSO,
* even though the site disallows normal registrations.
*
* @param object|null $user_data WordPress.com user information.
* @return bool|string
*/
public static function new_user_override( $user_data = null ) {
$new_user_override = defined( 'WPCC_NEW_USER_OVERRIDE' ) ? \WPCC_NEW_USER_OVERRIDE : false;
/**
* Allow users to register on your site with a WordPress.com account, even though you disallow normal registrations.
* If you return a string that corresponds to a user role, the user will be given that role.
*
* @module sso
*
* @since jetpack-2.6.0
* @since jetpack-4.6 $user_data object is now passed to the jetpack_sso_new_user_override filter
*
* @param bool|string $new_user_override Allow users to register on your site with a WordPress.com account. Default to false.
* @param object|null $user_data An object containing the user data returned from WordPress.com.
*/
$role = apply_filters( 'jetpack_sso_new_user_override', $new_user_override, $user_data );
if ( $role ) {
if ( is_string( $role ) && get_role( $role ) ) {
return $role;
} else {
return get_option( 'default_role' );
}
}
return false;
}
/**
* Returns a boolean value for whether two-step authentication is required for SSO.
*
* @since jetpack-4.1.0
*
* @return bool
*/
public static function is_two_step_required() {
/**
* Is it required to have 2-step authentication enabled on WordPress.com to use SSO?
*
* @module sso
*
* @since jetpack-2.8.0
*
* @param bool get_option( 'jetpack_sso_require_two_step' ) Does SSO require 2-step authentication?
*/
return (bool) apply_filters( 'jetpack_sso_require_two_step', get_option( 'jetpack_sso_require_two_step', false ) );
}
/**
* Returns a boolean for whether a user that is attempting to log in will be automatically
* redirected to WordPress.com to begin the SSO flow.
*
* @return bool
*/
public static function bypass_login_forward_wpcom() {
/**
* Redirect the site's log in form to WordPress.com's log in form.
*
* @module sso
*
* @since jetpack-3.1.0
*
* @param bool false Should the site's log in form be automatically forwarded to WordPress.com's log in form.
*/
return (bool) apply_filters( 'jetpack_sso_bypass_login_forward_wpcom', false );
}
/**
* Returns a boolean for whether the SSO login form should be displayed as the default
* when both the default and SSO login form allowed.
*
* @since jetpack-4.1.0
*
* @return bool
*/
public static function show_sso_login() {
if ( self::should_hide_login_form() ) {
return true;
}
/**
* Display the SSO login form as the default when both the default and SSO login forms are enabled.
*
* @module sso
*
* @since jetpack-4.1.0
*
* @param bool true Should the SSO login form be displayed by default when the default login form is also enabled?
*/
return (bool) apply_filters( 'jetpack_sso_default_to_sso_login', true );
}
/**
* Returns a boolean for whether the two step required checkbox, displayed on the Jetpack admin page, should be disabled.
*
* @since jetpack-4.1.0
*
* @return bool
*/
public static function is_require_two_step_checkbox_disabled() {
return (bool) has_filter( 'jetpack_sso_require_two_step' );
}
/**
* Returns a boolean for whether the match by email checkbox, displayed on the Jetpack admin page, should be disabled.
*
* @since jetpack-4.1.0
*
* @return bool
*/
public static function is_match_by_email_checkbox_disabled() {
return defined( 'WPCC_MATCH_BY_EMAIL' ) || has_filter( 'jetpack_sso_match_by_email' );
}
/**
* Returns an array of hosts that SSO will redirect to.
*
* Instead of accessing JETPACK__API_BASE within the method directly, we set it as the
* default for $api_base due to restrictions with testing constants in our tests.
*
* @since jetpack-4.3.0
* @since jetpack-4.6.0 Added public-api.wordpress.com as an allowed redirect
*
* @param array $hosts Allowed redirect hosts.
* @param string $api_base Base API URL.
*
* @return array
*/
public static function allowed_redirect_hosts( $hosts, $api_base = '' ) {
if ( empty( $api_base ) ) {
$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
}
if ( empty( $hosts ) ) {
$hosts = array();
}
$hosts[] = 'wordpress.com';
$hosts[] = 'jetpack.wordpress.com';
$hosts[] = 'public-api.wordpress.com';
$hosts[] = 'jetpack.com';
if ( ! str_contains( $api_base, 'jetpack.wordpress.com/jetpack' ) ) {
$base_url_parts = wp_parse_url( esc_url_raw( $api_base ) );
if ( $base_url_parts && ! empty( $base_url_parts['host'] ) ) {
$hosts[] = $base_url_parts['host'];
}
}
return array_unique( $hosts );
}
/**
* Determines how long the auth cookie is valid for when a user logs in with SSO.
*
* @return int result of the jetpack_sso_auth_cookie_expiration filter.
*/
public static function extend_auth_cookie_expiration_for_sso() {
/**
* Determines how long the auth cookie is valid for when a user logs in with SSO.
*
* @module sso
*
* @since jetpack-4.4.0
* @since jetpack-6.1.0 Fixed a typo. Filter was previously jetpack_sso_auth_cookie_expirtation.
*
* @param int YEAR_IN_SECONDS
*/
return (int) apply_filters( 'jetpack_sso_auth_cookie_expiration', YEAR_IN_SECONDS );
}
/**
* Determines if the SSO form should be displayed for the current action.
*
* @since jetpack-4.6.0
*
* @param string $action SSO action being performed.
*
* @return bool Is SSO allowed for the current action?
*/
public static function display_sso_form_for_action( $action ) {
/**
* Allows plugins the ability to overwrite actions where the SSO form is allowed to be used.
*
* @module sso
*
* @since jetpack-4.6.0
*
* @param array $allowed_actions_for_sso
*/
$allowed_actions_for_sso = (array) apply_filters(
'jetpack_sso_allowed_actions',
array(
'login',
'jetpack-sso',
'jetpack_json_api_authorization',
)
);
return in_array( $action, $allowed_actions_for_sso, true );
}
/**
* This method returns an environment array that is meant to simulate `$_REQUEST` when the initial
* JSON API auth request was made.
*
* @since jetpack-4.6.0
*
* @return array|bool
*/
public static function get_json_api_auth_environment() {
if ( empty( $_COOKIE['jetpack_sso_original_request'] ) ) {
return false;
}
$original_request = esc_url_raw( wp_unslash( $_COOKIE['jetpack_sso_original_request'] ) );
$parsed_url = wp_parse_url( $original_request );
if ( empty( $parsed_url ) || empty( $parsed_url['query'] ) ) {
return false;
}
$args = array();
wp_parse_str( $parsed_url['query'], $args );
if ( empty( $args ) || empty( $args['action'] ) ) {
return false;
}
if ( 'jetpack_json_api_authorization' !== $args['action'] ) {
return false;
}
return array_merge(
$args,
array( 'jetpack_json_api_original_query' => $original_request )
);
}
/**
* Check if the site has a custom login page URL, and return it.
* If default login page URL is used (`wp-login.php`), `null` will be returned.
*
* @return string|null
*/
public static function get_custom_login_url() {
$login_url = wp_login_url();
if ( str_ends_with( $login_url, 'wp-login.php' ) ) {
// No custom URL found.
return null;
}
$site_url = trailingslashit( site_url() );
if ( ! str_starts_with( $login_url, $site_url ) ) {
// Something went wrong, we can't properly extract the custom URL.
return null;
}
// Extracting the "path" part of the URL, because we don't need the `site_url` part.
return str_ireplace( $site_url, '', $login_url );
}
/**
* Clear the cookies that store the profile information for the last
* WPCOM user to connect.
*/
public static function clear_wpcom_profile_cookies() {
if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
setcookie(
'jetpack_sso_wpcom_name_' . COOKIEHASH,
' ',
time() - YEAR_IN_SECONDS,
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true
);
}
if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
setcookie(
'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
' ',
time() - YEAR_IN_SECONDS,
COOKIEPATH,
COOKIE_DOMAIN,
is_ssl(),
true
);
}
}
/**
* Remove an SSO connection for a user.
*
* @param int $user_id The local user id.
*/
public static function delete_connection_for_user( $user_id ) {
$wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true );
if ( ! $wpcom_user_id ) {
return;
}
$xml = new Jetpack_IXR_Client(
array(
'wpcom_user_id' => $user_id,
)
);
$xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
if ( $xml->isError() ) {
return false;
}
// Clean up local data stored for SSO.
delete_user_meta( $user_id, 'wpcom_user_id' );
delete_user_meta( $user_id, 'wpcom_user_data' );
self::clear_wpcom_profile_cookies();
return $xml->getResponse();
}
}

View File

@ -0,0 +1,241 @@
<?php
/**
* A collection of helper functions used in the SSO module.
*
* @package automattic/jetpack-connection
*/
namespace Automattic\Jetpack\Connection\SSO;
use Automattic\Jetpack\Redirect;
use WP_Error;
use WP_User;
/**
* A collection of helper functions used in the SSO module.
*
* @since jetpack-4.4.0
*/
class Notices {
/**
* Error message displayed on the login form when two step is required and
* the user's account on WordPress.com does not have two step enabled.
*
* @since jetpack-2.7
* @param string $message Error message.
* @return string
**/
public static function error_msg_enable_two_step( $message ) {
$error = sprintf(
wp_kses(
/* translators: URL to settings page */
__(
'Two-Step Authentication is required to access this site. Please visit your <a href="%1$s" rel="noopener noreferrer" target="_blank">Security Settings</a> to configure <a href="%2$s" rel="noopener noreferrer" target="_blank">Two-step Authentication</a> for your account.',
'jetpack-connection'
),
array( 'a' => array( 'href' => array() ) )
),
Redirect::get_url( 'calypso-me-security-two-step' ),
Redirect::get_url( 'wpcom-support-security-two-step-authentication' )
);
$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
return $message;
}
/**
* Error message displayed when the user tries to SSO, but match by email
* is off and they already have an account with their email address on
* this site.
*
* @param string $message Error message.
* @return string
*/
public static function error_msg_email_already_exists( $message ) {
$error = sprintf(
wp_kses(
/* translators: login URL */
__(
'You already have an account on this site. Please <a href="%1$s">sign in</a> with your username and password and then connect to WordPress.com.',
'jetpack-connection'
),
array( 'a' => array( 'href' => array() ) )
),
esc_url_raw( add_query_arg( 'jetpack-sso-show-default-form', '1', wp_login_url() ) )
);
$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
return $message;
}
/**
* Error message that is displayed when the current site is in an identity crisis and SSO can not be used.
*
* @since jetpack-4.3.2
*
* @param string $message Error Message.
*
* @return string
*/
public static function error_msg_identity_crisis( $message ) {
$error = esc_html__( 'Logging in with WordPress.com is not currently available because this site is experiencing connection problems.', 'jetpack-connection' );
$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
return $message;
}
/**
* Error message that is displayed when we are not able to verify the SSO nonce due to an XML error or
* failed validation. In either case, we prompt the user to try again or log in with username and password.
*
* @since jetpack-4.3.2
*
* @param string $message Error message.
*
* @return string
*/
public static function error_invalid_response_data( $message ) {
$error = esc_html__(
'There was an error logging you in via WordPress.com, please try again or try logging in with your username and password.',
'jetpack-connection'
);
$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
return $message;
}
/**
* Error message that is displayed when we were not able to automatically create an account for a user
* after a user has logged in via SSO. By default, this message is triggered after trying to create an account 5 times.
*
* @since jetpack-4.3.2
*
* @param string $message Error message.
*
* @return string
*/
public static function error_unable_to_create_user( $message ) {
$error = esc_html__(
'There was an error creating a user for you. Please contact the administrator of your site.',
'jetpack-connection'
);
$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
return $message;
}
/**
* When the default login form is hidden, this method is called on the 'authenticate' filter with a priority of 30.
* This method disables the ability to submit the default login form.
*
* @param WP_User|WP_Error $user Either the user attempting to login or an existing authentication failure.
*
* @return WP_Error
*/
public static function disable_default_login_form( $user ) {
if ( is_wp_error( $user ) ) {
return $user;
}
/**
* Since we're returning an error that will be shown as a red notice, let's remove the
* informational "blue" notice.
*/
remove_filter( 'login_message', array( static::class, 'msg_login_by_jetpack' ) );
return new WP_Error( 'jetpack_sso_required', self::get_sso_required_message() );
}
/**
* Message displayed when the site admin has disabled the default WordPress
* login form in Settings > General > Secure Sign On
*
* @since jetpack-2.7
* @param string $message Error message.
*
* @return string
**/
public static function msg_login_by_jetpack( $message ) {
$message .= sprintf( '<p class="message">%s</p>', self::get_sso_required_message() );
return $message;
}
/**
* Get the message for SSO required.
*
* @return string
*/
public static function get_sso_required_message() {
$msg = esc_html__(
'A WordPress.com account is required to access this site. Click the button below to sign in or create a free WordPress.com account.',
'jetpack-connection'
);
/**
* Filter the message displayed when the default WordPress login form is disabled.
*
* @module sso
*
* @since jetpack-2.8.0
*
* @param string $msg Disclaimer when default WordPress login form is disabled.
*/
return apply_filters( 'jetpack_sso_disclaimer_message', $msg );
}
/**
* Message displayed when the user can not be found after approving the SSO process on WordPress.com
*
* @param string $message Error message.
*
* @return string
*/
public static function cant_find_user( $message ) {
$error = __(
"We couldn't find your account. If you already have an account, make sure you have connected to WordPress.com.",
'jetpack-connection'
);
/**
* Filters the "couldn't find your account" notice after an attempted SSO.
*
* @module sso
*
* @since jetpack-10.5.0
*
* @param string $error Error text.
*/
$error = apply_filters( 'jetpack_sso_unknown_user_notice', $error );
$message .= sprintf( '<p class="message" id="login_error">%s</p>', esc_html( $error ) );
return $message;
}
/**
* Error message that is displayed when the current site is in an identity crisis and SSO can not be used.
*
* @since jetpack-4.4.0
*
* @param string $message Error message.
*
* @return string
*/
public static function sso_not_allowed_in_staging( $message ) {
$error = __(
'Logging in with WordPress.com is disabled for sites that are in staging mode.',
'jetpack-connection'
);
/**
* Filters the disallowed notice for staging sites attempting SSO.
*
* @module sso
*
* @since jetpack-10.5.0
*
* @param string $error Error text.
*/
$error = apply_filters( 'jetpack_sso_disallowed_staging_notice', $error );
$message .= sprintf( '<p class="message">%s</p>', esc_html( $error ) );
return $message;
}
}

View File

@ -0,0 +1,21 @@
.jetpack-sso-admin-create-user-invite-message {
width: 550px;
}
.jetpack-sso-admin-create-user-invite-message-link-sso {
text-decoration: none;
}
#createuser .form-field textarea {
width: 25em;
}
#createuser .form-field [type=checkbox] {
width: 1rem;
}
#custom_email_message_description {
max-width: 25rem;
color: #646970;
font-size: 12px;
}

View File

@ -0,0 +1,45 @@
document.addEventListener( 'DOMContentLoaded', function () {
const sendUserNotificationCheckbox = document.getElementById( 'send_user_notification' );
const userExternalContractorCheckbox = document.getElementById( 'user_external_contractor' );
const inviteUserWpcomCheckbox = document.getElementById( 'invite_user_wpcom' );
const customEmailMessageBlock = document.getElementById( 'custom_email_message_block' );
if ( inviteUserWpcomCheckbox && sendUserNotificationCheckbox && customEmailMessageBlock ) {
// Toggle Send User Notification checkbox enabled/disabled based on Invite User checkbox
// Enable External Contractor checkbox if Invite User checkbox is checked
// Show/hide the external email message field.
inviteUserWpcomCheckbox.addEventListener( 'change', function () {
sendUserNotificationCheckbox.disabled = inviteUserWpcomCheckbox.checked;
if ( inviteUserWpcomCheckbox.checked ) {
sendUserNotificationCheckbox.checked = false;
if ( userExternalContractorCheckbox ) {
userExternalContractorCheckbox.disabled = false;
}
customEmailMessageBlock.style.display = 'table';
} else {
if ( userExternalContractorCheckbox ) {
userExternalContractorCheckbox.disabled = true;
userExternalContractorCheckbox.checked = false;
}
customEmailMessageBlock.style.display = 'none';
}
} );
// On load, disable Send User Notification checkbox
// and show the custom email message if Invite User checkbox is checked
if ( inviteUserWpcomCheckbox.checked ) {
sendUserNotificationCheckbox.disabled = true;
sendUserNotificationCheckbox.checked = false;
customEmailMessageBlock.style.display = 'table';
}
// On load, disable External Contractor checkbox
// and hide the custom email message if Invite User checkbox is unchecked
if ( ! inviteUserWpcomCheckbox.checked ) {
if ( userExternalContractorCheckbox ) {
userExternalContractorCheckbox.disabled = true;
}
customEmailMessageBlock.style.display = 'none';
}
}
} );

View File

@ -0,0 +1,164 @@
#loginform {
/* We set !important because sometimes static is added inline */
position: relative !important;
padding-bottom: 92px;
}
.jetpack-sso-repositioned #loginform {
padding-bottom: 26px;
}
#loginform #jetpack-sso-wrap,
#loginform #jetpack-sso-wrap * {
box-sizing: border-box;
}
#jetpack-sso-wrap__action,
#jetpack-sso-wrap__user {
display: none;
}
.jetpack-sso-form-display #jetpack-sso-wrap__action,
.jetpack-sso-form-display #jetpack-sso-wrap__user {
display: block;
}
#jetpack-sso-wrap {
position: absolute;
bottom: 20px;
padding: 0 24px;
margin-left: -24px;
margin-right: -24px;
width: 100%;
}
.jetpack-sso-repositioned #jetpack-sso-wrap {
position: relative;
bottom: auto;
padding: 0;
margin-top: 16px;
margin-left: 0;
margin-right: 0;
}
.jetpack-sso-form-display #jetpack-sso-wrap {
position: relative;
bottom: auto;
padding: 0;
margin-top: 0;
margin-left: 0;
margin-right: 0;
}
#loginform #jetpack-sso-wrap p {
color: #777777;
margin-bottom: 16px;
}
#jetpack-sso-wrap a {
display: block;
width: 100%;
text-align: center;
text-decoration: none;
}
#jetpack-sso-wrap .jetpack-sso-toggle.wpcom {
display: none;
}
.jetpack-sso-form-display #jetpack-sso-wrap .jetpack-sso-toggle.wpcom {
display: block;
}
.jetpack-sso-form-display #jetpack-sso-wrap .jetpack-sso-toggle.default {
display: none;
}
.jetpack-sso-form-display #loginform>p,
.jetpack-sso-form-display #loginform>div {
display: none;
}
.jetpack-sso-form-display #loginform #jetpack-sso-wrap {
display: block;
}
.jetpack-sso-form-display #loginform {
padding: 26px 24px;
}
.jetpack-sso-or {
margin-bottom: 16px;
position: relative;
text-align: center;
}
.jetpack-sso-or:before {
background: #dcdcde;
content: '';
height: 1px;
position: absolute;
left: 0;
top: 50%;
width: 100%;
}
.jetpack-sso-or span {
background: #fff;
color: #777;
position: relative;
padding: 0 8px;
text-transform: uppercase
}
#jetpack-sso-wrap .button {
display: flex;
justify-content: center;
align-items: center;
height: 36px;
margin-bottom: 16px;
width: 100%;
}
#jetpack-sso-wrap .button .genericon-wordpress {
font-size: 24px;
margin-right: 4px;
}
#jetpack-sso-wrap__user img {
border-radius: 50%;
display: block;
margin: 0 auto 16px;
}
#jetpack-sso-wrap__user h2 {
font-size: 21px;
font-weight: 300;
margin-bottom: 16px;
text-align: center;
}
#jetpack-sso-wrap__user h2 span {
font-weight: bold;
}
.jetpack-sso-wrap__reauth {
margin-bottom: 16px;
}
.jetpack-sso-form-display #nav {
display: none;
}
.jetpack-sso-form-display #backtoblog {
margin: 24px 0 0;
}
.jetpack-sso-clear:after {
content: "";
display: table;
clear: both;
}

View File

@ -0,0 +1,27 @@
document.addEventListener( 'DOMContentLoaded', () => {
const body = document.querySelector( 'body' ),
toggleSSO = document.querySelector( '.jetpack-sso-toggle' ),
userLogin = document.getElementById( 'user_login' ),
userPassword = document.getElementById( 'user_pass' ),
ssoWrap = document.getElementById( 'jetpack-sso-wrap' ),
loginForm = document.getElementById( 'loginform' ),
overflow = document.createElement( 'div' );
overflow.className = 'jetpack-sso-clear';
loginForm.appendChild( overflow );
overflow.appendChild( document.querySelector( 'p.forgetmenot' ) );
overflow.appendChild( document.querySelector( 'p.submit' ) );
loginForm.appendChild( ssoWrap );
body.classList.add( 'jetpack-sso-repositioned' );
toggleSSO.addEventListener( 'click', e => {
e.preventDefault();
body.classList.toggle( 'jetpack-sso-form-display' );
if ( ! body.classList.contains( 'jetpack-sso-form-display' ) ) {
userLogin.focus();
userPassword.disabled = false;
}
} );
} );

View File

@ -0,0 +1,64 @@
document.addEventListener( 'DOMContentLoaded', function () {
document
.querySelectorAll( '.jetpack-sso-invitation-tooltip-icon:not(.sso-disconnected-user)' )
.forEach( function ( tooltip ) {
tooltip.innerHTML += ' [?]';
const tooltipTextbox = document.createElement( 'span' );
tooltipTextbox.classList.add( 'jetpack-sso-invitation-tooltip', 'jetpack-sso-th-tooltip' );
const tooltipString = window.Jetpack_SSOTooltip.tooltipString;
tooltipTextbox.innerHTML += tooltipString;
tooltip.addEventListener( 'mouseenter', appendTooltip );
tooltip.addEventListener( 'focus', appendTooltip );
tooltip.addEventListener( 'mouseleave', removeTooltip );
tooltip.addEventListener( 'blur', removeTooltip );
/**
* Display the tooltip textbox.
*/
function appendTooltip() {
tooltip.appendChild( tooltipTextbox );
tooltipTextbox.style.display = 'block';
}
/**
* Remove the tooltip textbox.
*/
function removeTooltip() {
// Only remove tooltip if the element isn't currently active.
if ( document.activeElement === tooltip ) {
return;
}
tooltip.removeChild( tooltipTextbox );
}
} );
document
.querySelectorAll( '.jetpack-sso-invitation-tooltip-icon:not(.jetpack-sso-status-column)' )
.forEach( function ( tooltip ) {
tooltip.addEventListener( 'mouseenter', appendSSOInvitationTooltip );
tooltip.addEventListener( 'focus', appendSSOInvitationTooltip );
tooltip.addEventListener( 'mouseleave', removeSSOInvitationTooltip );
tooltip.addEventListener( 'blur', removeSSOInvitationTooltip );
} );
/**
* Display the SSO invitation tooltip textbox.
*/
function appendSSOInvitationTooltip() {
this.querySelector( '.jetpack-sso-invitation-tooltip' ).style.display = 'block';
}
/**
* Remove the SSO invitation tooltip textbox.
*
* @param {Event} event - Triggering event.
*/
function removeSSOInvitationTooltip( event ) {
if ( document.activeElement === event.target ) {
return;
}
this.querySelector( '.jetpack-sso-invitation-tooltip' ).style.display = 'none';
}
} );

View File

@ -10,6 +10,7 @@ namespace Automattic\Jetpack\Connection\Webhooks;
use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\Constants;
use Automattic\Jetpack\Licensing;
use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\Tracking;
use GP_Locales;
use Jetpack_Network;
@ -21,14 +22,14 @@ class Authorize_Redirect {
/**
* The Connection Manager object.
*
* @var Manager
* @var \Automattic\Jetpack\Connection\Manager
*/
private $connection;
/**
* Constructs the object
*
* @param Automattic\Jetpack\Connection\Manager $connection The Connection Manager object.
* @param \Automattic\Jetpack\Connection\Manager $connection The Connection Manager object.
*/
public function __construct( $connection ) {
$this->connection = $connection;
@ -97,44 +98,57 @@ class Authorize_Redirect {
}
/**
* Create the Jetpack authorization URL. Copied from Jetpack class.
* Create the Jetpack authorization URL.
*
* @since 2.7.6 Added optional $from and $raw parameters.
*
* @param bool|string $redirect URL to redirect to.
* @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
* @param bool $raw If true, URL will not be escaped.
*
* @todo Update default value for redirect since the called function expects a string.
*
* @return mixed|void
*/
public function build_authorize_url( $redirect = false ) {
public function build_authorize_url( $redirect = false, $from = false, $raw = false ) {
add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
$url = $this->connection->get_authorization_url( wp_get_current_user(), $redirect );
$url = $this->connection->get_authorization_url( wp_get_current_user(), $redirect, $from, $raw );
remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
/** This filter is documented in plugins/jetpack/class-jetpack.php */
return apply_filters( 'jetpack_build_authorize_url', $url );
/**
* Filter the URL used when authorizing a user to a WordPress.com account.
*
* @since jetpack-8.9.0
* @since 2.7.6 Added $raw parameter.
*
* @param string $url Connection URL.
* @param bool $raw If true, URL will not be escaped.
*/
return apply_filters( 'jetpack_build_authorize_url', $url, $raw );
}
/**
* Filters the redirection URL that is used for connect requests. The redirect
* URL should return the user back to the Jetpack console.
* Copied from Jetpack class.
* URL should return the user back to the My Jetpack page.
*
* @param String $redirect the default redirect URL used by the package.
* @return String the modified URL.
* @param string $redirect the default redirect URL used by the package.
* @return string the modified URL.
*/
public static function filter_connect_redirect_url( $redirect ) {
$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=my-jetpack' ) );
$redirect = $redirect
? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
: $jetpack_admin_page;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_REQUEST['is_multisite'] ) ) {
if (
class_exists( 'Jetpack_Network' )
&& isset( $_REQUEST['is_multisite'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
) {
$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
}
@ -143,7 +157,6 @@ class Authorize_Redirect {
/**
* Filters the connection URL parameter array.
* Copied from Jetpack class.
*
* @param array $args default URL parameters used by the package.
* @return array the modified URL arguments array.
@ -170,7 +183,7 @@ class Authorize_Redirect {
)
);
$calypso_env = self::get_calypso_env();
$calypso_env = ( new Host() )->get_calypso_env();
if ( ! empty( $calypso_env ) ) {
$args['calypso_env'] = $calypso_env;
@ -184,25 +197,15 @@ class Authorize_Redirect {
* it with different Calypso enrionments, such as localhost.
* Copied from Jetpack class.
*
* @deprecated 2.7.6
*
* @since 1.37.1
*
* @return string Calypso environment
*/
public static function get_calypso_env() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['calypso_env'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
return sanitize_key( $_GET['calypso_env'] );
}
_deprecated_function( __METHOD__, '2.7.6', 'Automattic\\Jetpack\\Status\\Host::get_calypso_env' );
if ( getenv( 'CALYPSO_ENV' ) ) {
return sanitize_key( getenv( 'CALYPSO_ENV' ) );
}
if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
return sanitize_key( CALYPSO_ENV );
}
return '';
return ( new Host() )->get_calypso_env();
}
}