filename
stringlengths
11
137
content
stringlengths
6
292k
projects/plugins/jetpack/class.jetpack-network-sites-list-table.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Jetpack network sites list table. * * @package automattic/jetpack */ if ( ! class_exists( 'WP_List_Table' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; } /** * Jetpack network sites list table. */ class Jetpack_Network_Sites_List_Table extends WP_List_Table { /** * Get columns. * * @return array name => header HTML. */ public function get_columns() { // site name, status, username connected under. $columns = array( 'cb' => '<input type="checkbox" />', 'blogname' => __( 'Site Name', 'jetpack' ), 'blog_path' => __( 'Path', 'jetpack' ), 'connected' => __( 'Connected', 'jetpack' ), ); return $columns; } /** * Prepare items. */ public function prepare_items() { // Make sure Jetpack_Network is initialized. Jetpack_Network::init(); // Deal with bulk actions if any were requested by the user. $this->process_bulk_action(); $sites = get_sites( array( 'site__not_in' => array( get_current_blog_id() ), 'archived' => false, 'number' => 0, 'network_id' => get_current_network_id(), ) ); // Setup pagination. $per_page = 25; $current_page = $this->get_pagenum(); $total_items = is_countable( $sites ) ? count( $sites ) : 0; $sites = array_slice( $sites, ( ( $current_page - 1 ) * $per_page ), $per_page ); $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, ) ); $columns = $this->get_columns(); $hidden = array(); $sortable = array(); $this->_column_headers = array( $columns, $hidden, $sortable ); $this->items = $sites; } /** * Column blogname. * * @param object|array $item Item. * @return string HTML. */ public function column_blogname( $item ) { // <http://jpms/wp-admin/network/site-info.php?id=1>. switch_to_blog( $item->blog_id ); $jp_url = admin_url( 'admin.php?page=jetpack' ); restore_current_blog(); $actions = array( 'edit' => '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $item->blog_id ) ) . '">' . esc_html__( 'Edit', 'jetpack' ) . '</a>', 'dashboard' => '<a href="' . esc_url( get_admin_url( $item->blog_id, '', 'admin' ) ) . '">' . esc_html__( 'Dashboard', 'jetpack' ) . '</a>', 'view' => '<a href="' . esc_url( get_site_url( $item->blog_id, '', 'admin' ) ) . '">' . esc_html__( 'View', 'jetpack' ) . '</a>', 'jetpack-' . $item->blog_id => '<a href="' . esc_url( $jp_url ) . '">Jetpack</a>', ); return sprintf( '%1$s %2$s', '<strong>' . get_blog_option( $item->blog_id, 'blogname' ) . '</strong>', $this->row_actions( $actions ) ); } /** * Column blog path. * * @param object|array $item Item. * @return string HTML. */ public function column_blog_path( $item ) { return '<a href="' . get_site_url( $item->blog_id, '', 'admin' ) . '">' . str_replace( array( 'http://', 'https://' ), '', get_site_url( $item->blog_id, '', 'admin' ) ) . '</a>'; } /** * Column connected. * * @param object|array $item Item. * @return string HTML. */ public function column_connected( $item ) { $jpms = Jetpack_Network::init(); $jp = Jetpack::init(); switch_to_blog( $item->blog_id ); // Checks for both the stock version of Jetpack and the one managed by the Jetpack Beta Plugin. if ( ! is_plugin_active( 'jetpack/jetpack.php' ) && ! is_plugin_active( 'jetpack-dev/jetpack.php' ) && ! array_key_exists( 'jetpack.php', get_mu_plugins() ) ) { $title = __( 'Jetpack is not active on this site.', 'jetpack' ); $action = array( 'manage-plugins' => '<a href="' . get_admin_url( $item->blog_id, 'plugins.php', 'admin' ) . '">' . __( 'Manage Plugins', 'jetpack' ) . '</a>', ); restore_current_blog(); return sprintf( '%1$s %2$s', $title, $this->row_actions( $action ) ); } if ( $jp->is_connection_ready() ) { // Build url for disconnecting. $url = $jpms->get_url( array( 'name' => 'subsitedisconnect', 'site_id' => $item->blog_id, ) ); restore_current_blog(); return '<a href="' . wp_nonce_url( $url, 'jetpack-subsite-disconnect' ) . '">' . esc_html__( 'Disconnect', 'jetpack' ) . '</a>'; } restore_current_blog(); // Build URL for connecting. $url = $jpms->get_url( array( 'name' => 'subsiteregister', 'site_id' => $item->blog_id, ) ); return '<a href="' . wp_nonce_url( $url, 'jetpack-subsite-register' ) . '">' . esc_html__( 'Connect', 'jetpack' ) . '</a>'; } /** * Get bulk actions. * * @return array Code => HTML. */ public function get_bulk_actions() { $actions = array( 'connect' => esc_html__( 'Connect', 'jetpack' ), 'disconnect' => esc_html__( 'Disconnect', 'jetpack' ), ); return $actions; } /** * Column checkbox. * * @param object|array $item Item. * @return string HTML. */ public function column_cb( $item ) { return sprintf( '<input type="checkbox" name="bulk[]" value="%s" />', $item->blog_id ); } /** * Process bulk actions. */ public function process_bulk_action() { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Check if we have anything to do before checking the nonce. if ( empty( $_POST['bulk'] ) ) { return; // Thou shall not pass! There is nothing to do. } check_admin_referer( 'bulk-toplevel_page_jetpack-network' ); $jpms = Jetpack_Network::init(); $action = $this->current_action(); switch ( $action ) { case 'connect': $bulk = wp_unslash( $_POST['bulk'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized foreach ( $bulk as $site ) { $jpms->do_subsiteregister( $site ); } break; case 'disconnect': $bulk = wp_unslash( $_POST['bulk'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized foreach ( $bulk as $site ) { $jpms->do_subsitedisconnect( $site ); } break; } } } // end h
projects/plugins/jetpack/load-jetpack.php
<?php /** * Load all Jetpack files that do not get loaded via the autoloader. * * @package automattic/jetpack */ /** * Checks if the code debug mode turned on, and returns false if it is. When Jetpack is in * code debug mode, it shouldn't use minified assets. Note that this filter is not being used * in every place where assets are enqueued. The filter is added at priority 9 to be overridden * by any default priority filter that runs after it. * * @since 6.2.0 * * @return boolean * * @filter jetpack_should_use_minified_assets */ function jetpack_should_use_minified_assets() { return ! defined( 'SCRIPT_DEBUG' ) || ! SCRIPT_DEBUG; } add_filter( 'jetpack_should_use_minified_assets', 'jetpack_should_use_minified_assets', 9 ); // @todo: Abstract out the admin functions, and only include them if is_admin() require_once JETPACK__PLUGIN_DIR . 'class.jetpack.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-network.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-client-server.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-user-agent.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-post-images.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-heartbeat.php'; require_once JETPACK__PLUGIN_DIR . 'class.photon.php'; require_once JETPACK__PLUGIN_DIR . 'functions.photon.php'; require_once JETPACK__PLUGIN_DIR . 'functions.global.php'; require_once JETPACK__PLUGIN_DIR . 'functions.compat.php'; require_once JETPACK__PLUGIN_DIR . 'class-jetpack-gallery-settings.php'; require_once JETPACK__PLUGIN_DIR . 'functions.cookies.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-autoupdate.php'; require_once JETPACK__PLUGIN_DIR . 'class.frame-nonce-preview.php'; require_once JETPACK__PLUGIN_DIR . 'modules/module-headings.php'; require_once JETPACK__PLUGIN_DIR . 'class.jetpack-plan.php'; // Used by the API endpoints. require_once JETPACK__PLUGIN_DIR . 'modules/seo-tools/class-jetpack-seo-utils.php'; require_once JETPACK__PLUGIN_DIR . 'modules/seo-tools/class-jetpack-seo-titles.php'; require_once JETPACK__PLUGIN_DIR . 'modules/seo-tools/class-jetpack-seo-posts.php'; require_once JETPACK__PLUGIN_DIR . 'modules/verification-tools/verification-tools-utils.php'; require_once JETPACK__PLUGIN_DIR . 'class-jetpack-xmlrpc-methods.php'; Jetpack_XMLRPC_Methods::init(); require_once JETPACK__PLUGIN_DIR . 'class-jetpack-connection-status.php'; Jetpack_Connection_Status::init(); require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-recommendations.php'; if ( is_admin() ) { require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php'; require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger.php'; } // Play nice with https://wp-cli.org/. if ( defined( 'WP_CLI' ) && WP_CLI ) { require_once JETPACK__PLUGIN_DIR . 'class.jetpack-cli.php'; } require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.core-rest-api-endpoints.php'; require_once JETPACK__PLUGIN_DIR . '_inc/blogging-prompts.php'; add_action( 'updating_jetpack_version', array( 'Jetpack', 'do_version_bump' ), 10, 2 ); add_filter( 'is_jetpack_site', '__return_true' ); require_once JETPACK__PLUGIN_DIR . '3rd-party/3rd-party.php'; Jetpack::init();
projects/plugins/jetpack/class-jetpack-wizard-banner.php
<?php /** * Deprecated since 9.5.0 * * @deprecated * @package automattic/jetpack */ // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped _deprecated_file( basename( __FILE__ ), 'jetpack-9.5.0' );
projects/plugins/jetpack/uninstall.php
<?php /** * Functionality that is executed when Jetpack is uninstalled via built-in WordPress commands. * * @package automattic/jetpack */ use Automattic\Jetpack\Backup\V0003\Helper_Script_Manager; use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\Sync\Sender; /** * Uninstall script for Jetpack. */ function jetpack_uninstall() { if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) || ! WP_UNINSTALL_PLUGIN || dirname( WP_UNINSTALL_PLUGIN ) !== dirname( plugin_basename( __FILE__ ) ) ) { status_header( 404 ); exit; } if ( ! defined( 'JETPACK__PLUGIN_DIR' ) ) { define( 'JETPACK__PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); } require JETPACK__PLUGIN_DIR . 'vendor/autoload_packages.php'; if ( method_exists( Connection_Manager::class, 'is_ready_for_cleanup' ) && ! Connection_Manager::is_ready_for_cleanup( dirname( plugin_basename( __FILE__ ) ) ) ) { // There are other active Jetpack plugins, no need for cleanup. return; } Jetpack_Options::delete_all_known_options(); // Delete all legacy options. delete_option( 'jetpack_was_activated' ); delete_option( 'jetpack_auto_installed' ); delete_option( 'jetpack_register' ); delete_transient( 'jetpack_register' ); // Delete sync options // // Do not initialize any listeners. // Since all the files will be deleted. // No need to try to sync anything. add_filter( 'jetpack_sync_modules', '__return_empty_array', 100 ); // Jetpack Sync. Sender::get_instance()->uninstall(); // Jetpack Backup: Cleanup any leftover Helper Scripts. Helper_Script_Manager::delete_all_helper_scripts(); } jetpack_uninstall();
projects/plugins/jetpack/class.jetpack-autoupdate.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Handles items that have been selected for automatic updates. * Hooks into WP_Automatic_Updater * * @package automattic/jetpack */ /** * Handles items that have been selected for automatic updates. * Hooks into WP_Automatic_Updater */ class Jetpack_Autoupdate { /** * Results. * * @var array */ private $results = array(); /** * Expected updates. * * @var array */ private $expected = array(); /** * Successful updates. * * @var array */ private $success = array( 'plugin' => array(), 'theme' => array(), ); /** * Failed updates. * * @var array */ private $failed = array( 'plugin' => array(), 'theme' => array(), ); /** * Static instance. * * @var self */ private static $instance = null; /** * Initialize and fetch the static instance. * * @return self */ public static function init() { if ( self::$instance === null ) { self::$instance = new Jetpack_Autoupdate(); } return self::$instance; } /** Constructor. */ private function __construct() { if ( /** This filter is documented in class.jetpack-json-api-endpoint.php */ apply_filters( 'jetpack_json_manage_api_enabled', true ) ) { add_filter( 'auto_update_theme', array( $this, 'autoupdate_theme' ), 10, 2 ); add_filter( 'auto_update_core', array( $this, 'autoupdate_core' ), 10, 2 ); add_filter( 'auto_update_translation', array( $this, 'autoupdate_translation' ), 10, 2 ); add_action( 'automatic_updates_complete', array( $this, 'automatic_updates_complete' ), 999, 1 ); } } /** * Filter function for `auto_update_translation`. * * @param bool|null $update Whether to update. * @param object $item The update offer. * @return bool|null Whether to update. */ public function autoupdate_translation( $update, $item ) { // Autoupdate all translations. if ( Jetpack_Options::get_option( 'autoupdate_translations', false ) ) { return true; } // Themes. $autoupdate_themes_translations = Jetpack_Options::get_option( 'autoupdate_themes_translations', array() ); $autoupdate_theme_list = Jetpack_Options::get_option( 'autoupdate_themes', array() ); if ( ( in_array( $item->slug, $autoupdate_themes_translations, true ) || in_array( $item->slug, $autoupdate_theme_list, true ) ) && 'theme' === $item->type ) { $this->expect( $item->type . ':' . $item->slug, 'translation' ); return true; } // Plugins. $autoupdate_plugin_translations = Jetpack_Options::get_option( 'autoupdate_plugins_translations', array() ); $autoupdate_plugin_list = (array) get_site_option( 'auto_update_plugins', array() ); $plugin_files = array_unique( array_merge( $autoupdate_plugin_list, $autoupdate_plugin_translations ) ); $plugin_slugs = array_map( array( __CLASS__, 'get_plugin_slug' ), $plugin_files ); if ( in_array( $item->slug, $plugin_slugs, true ) && 'plugin' === $item->type ) { $this->expect( $item->type . ':' . $item->slug, 'translation' ); return true; } return $update; } /** * Filter function for `auto_update_theme`. * * @param bool|null $update Whether to update. * @param object $item The update offer. * @return bool|null Whether to update. */ public function autoupdate_theme( $update, $item ) { $autoupdate_theme_list = Jetpack_Options::get_option( 'autoupdate_themes', array() ); if ( in_array( $item->theme, $autoupdate_theme_list, true ) ) { $this->expect( $item->theme, 'theme' ); return true; } return $update; } /** * Filter function for `auto_update_core`. * * @param bool|null $update Whether to update. * @return bool|null Whether to update. */ public function autoupdate_core( $update ) { $autoupdate_core = Jetpack_Options::get_option( 'autoupdate_core', false ); if ( $autoupdate_core ) { return $autoupdate_core; } return $update; } /** * Stores the an item identifier to the expected array. * * @param string $item Example: 'jetpack/jetpack.php' for type 'plugin' or 'twentyfifteen' for type 'theme'. * @param string $type 'plugin' or 'theme'. */ private function expect( $item, $type ) { if ( ! isset( $this->expected[ $type ] ) ) { $this->expected[ $type ] = array(); } $this->expected[ $type ][] = $item; } /** * On completion of an automatic update, let's store the results. * * @param mixed $results - Sent by WP_Automatic_Updater after it completes an autoupdate action. Results may be empty. */ public function automatic_updates_complete( $results ) { if ( empty( $this->expected ) ) { return; } $this->results = empty( $results ) ? self::get_possible_failures() : $results; add_action( 'shutdown', array( $this, 'bump_stats' ) ); Jetpack::init(); $items_to_log = array( 'plugin', 'theme', 'translation' ); foreach ( $items_to_log as $items ) { $this->log_items( $items ); } Jetpack::log( 'autoupdates', $this->get_log() ); } /** * Get log data. * * @return array Data. */ public function get_log() { return array( 'results' => $this->results, 'failed' => $this->failed, 'success' => $this->success, ); } /** * Iterates through expected items ( plugins or themes ) and compares them to actual results. * * @param string $items 'plugin' or 'theme'. */ private function log_items( $items ) { if ( ! isset( $this->expected[ $items ] ) ) { return; } $item_results = $this->get_successful_updates( $items ); if ( is_array( $this->expected[ $items ] ) ) { foreach ( $this->expected[ $items ] as $item ) { if ( in_array( $item, $item_results, true ) ) { $this->success[ $items ][] = $item; } else { $this->failed[ $items ][] = $item; } } } } /** * Bump stats. */ public function bump_stats() { $instance = Jetpack::init(); $log = array(); // Bump numbers. if ( ! empty( $this->success['theme'] ) ) { $instance->stat( 'autoupdates/theme-success', is_countable( $this->success['theme'] ) ? count( $this->success['theme'] ) : 0 ); $log['themes_success'] = $this->success['theme']; } if ( ! empty( $this->failed['theme'] ) ) { $instance->stat( 'autoupdates/theme-fail', is_countable( $this->failed['theme'] ) ? count( $this->failed['theme'] ) : 0 ); $log['themes_failed'] = $this->failed['theme']; } $instance->do_stats( 'server_side' ); // Send a more detailed log to logstash. if ( ! empty( $log ) ) { $xml = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id(), ) ); $log['blog_id'] = Jetpack_Options::get_option( 'id' ); $xml->query( 'jetpack.debug_autoupdate', $log ); } } /** * Parses the autoupdate results generated by WP_Automatic_Updater and returns a simple array of successful items. * * @param string $type 'plugin' or 'theme'. * @return array */ private function get_successful_updates( $type ) { $successful_updates = array(); if ( ! isset( $this->results[ $type ] ) ) { return $successful_updates; } foreach ( $this->results[ $type ] as $result ) { if ( $result->result ) { switch ( $type ) { case 'theme': $successful_updates[] = $result->item->theme; break; case 'translation': $successful_updates[] = $result->item->type . ':' . $result->item->slug; break; } } } return $successful_updates; } /** * Get possible failure codes. * * @return string[] Failure codes. */ public static function get_possible_failures() { $result = array(); // Lets check some reasons why it might not be working as expected. include_once ABSPATH . '/wp-admin/includes/admin.php'; include_once ABSPATH . '/wp-admin/includes/class-wp-upgrader.php'; $upgrader = new WP_Automatic_Updater(); if ( $upgrader->is_disabled() ) { $result[] = 'autoupdates-disabled'; } if ( ! is_main_site() ) { $result[] = 'is-not-main-site'; } if ( ! is_main_network() ) { $result[] = 'is-not-main-network'; } if ( $upgrader->is_vcs_checkout( ABSPATH ) ) { $result[] = 'site-on-vcs'; } if ( $upgrader->is_vcs_checkout( WP_PLUGIN_DIR ) ) { $result[] = 'plugin-directory-on-vcs'; } if ( $upgrader->is_vcs_checkout( WP_CONTENT_DIR ) ) { $result[] = 'content-directory-on-vcs'; } $lock = get_option( 'auto_updater.lock' ); if ( $lock > ( time() - HOUR_IN_SECONDS ) ) { $result[] = 'lock-is-set'; } $skin = new Automatic_Upgrader_Skin(); include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/template.php'; if ( ! $skin->request_filesystem_credentials( false, ABSPATH, false ) ) { $result[] = 'no-system-write-access'; } if ( ! $skin->request_filesystem_credentials( false, WP_PLUGIN_DIR, false ) ) { $result[] = 'no-plugin-directory-write-access'; } if ( ! $skin->request_filesystem_credentials( false, WP_CONTENT_DIR, false ) ) { $result[] = 'no-wp-content-directory-write-access'; } return $result; } /** * Get the plugin slug. * * @param string $plugin_file Plugin file. * @return string Slug. */ public static function get_plugin_slug( $plugin_file ) { $update_plugins = get_site_transient( 'update_plugins' ); if ( isset( $update_plugins->no_update ) ) { if ( isset( $update_plugins->no_update[ $plugin_file ]->slug ) ) { $slug = $update_plugins->no_update[ $plugin_file ]->slug; } } if ( empty( $slug ) && isset( $update_plugins->response ) ) { if ( isset( $update_plugins->response[ $plugin_file ]->slug ) ) { $slug = $update_plugins->response[ $plugin_file ]->slug; } } // Try to infer from the plugin file if not cached. if ( empty( $slug ) ) { $slug = dirname( $plugin_file ); if ( '.' === $slug ) { $slug = preg_replace( '/(.+)\.php$/', '$1', $plugin_file ); } } return $slug; } } Jetpack_Autoupdate::init();
projects/plugins/jetpack/class.jetpack-affiliate.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Deprecated since 8.1.0. * Functionality moved to the automattic/jetpack-partner package. * * @package automattic/jetpack */
projects/plugins/jetpack/class.jetpack-client-server.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Client = Plugin * Client Server = API Methods the Plugin must respond to * * @package automattic/jetpack */ use Automattic\Jetpack\Connection\Webhooks; /** * Client = Plugin * Client Server = API Methods the Plugin must respond to */ class Jetpack_Client_Server { /** * Handle the client authorization error. * * @param WP_Error $error The error object. */ public static function client_authorize_error( $error ) { if ( $error instanceof WP_Error ) { Jetpack::state( 'error', $error->get_error_code() ); } } /** * The user is already authorized, we set the Jetpack state and adjust the redirect URL. * * @return string */ public static function client_authorize_already_authorized_url() { Jetpack::state( 'message', 'already_authorized' ); return Jetpack::admin_url(); } /** * The authorization processing has started. */ public static function client_authorize_processing() { Jetpack::log( 'authorize' ); } /** * The authorization has completed (successfully or not), and the redirect URL is empty. * We set the Jetpack Dashboard as the default URL. * * @return string */ public static function client_authorize_fallback_url() { return Jetpack::admin_url(); } /** * Authorization handler. * * @deprecated since Jetpack 9.5.0 * @see Webhooks::handle_authorize() */ public function client_authorize() { _deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Webhooks::handle_authorize' ); ( new Webhooks() )->handle_authorize(); } /** * Deactivate a plugin. * * @param string $probable_file Expected plugin file. * @param string $probable_title Expected plugin title. * @return int 1 if a plugin was deactivated, 0 if not. */ public static function deactivate_plugin( $probable_file, $probable_title ) { include_once ABSPATH . 'wp-admin/includes/plugin.php'; if ( is_plugin_active( $probable_file ) ) { deactivate_plugins( $probable_file ); return 1; } else { // If the plugin is not in the usual place, try looking through all active plugins. $active_plugins = Jetpack::get_active_plugins(); foreach ( $active_plugins as $plugin ) { $data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin ); if ( $data['Name'] === $probable_title ) { deactivate_plugins( $plugin ); return 1; } } } return 0; } /** * Get the Jetpack instance. * * @deprecated since Jetpack 9.5.0 * @see Jetpack::init() */ public function get_jetpack() { _deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Jetpack::init' ); return Jetpack::init(); } /** * No longer used. * * @deprecated since Jetpack 9.5.0 */ public function do_exit() { _deprecated_function( __METHOD__, 'jetpack-9.5.0' ); exit; } }
projects/plugins/jetpack/json-api-config.php
<?php /** * Config for the WP.com REST API * * @package automattic/jetpack */ define( 'WPCOM_JSON_API__CURRENT_VERSION', '1.1' ); global $wpcom_json_api_production_versions, $wpcom_json_api_dev_versions; $wpcom_json_api_production_versions = array( '1', '1.1', ); $wpcom_json_api_dev_versions = array( '1.2', '1.3', '1.4', );
projects/plugins/jetpack/class.jetpack-plan.php
<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Handles fetching of the site's plan and products from WordPress.com and caching values locally. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan instead. * * Not to be confused with the `Jetpack_Plans` class (in `_inc/lib/plans.php`), which * fetches general information about all available plans from WordPress.com, side-effect free. * * @package automattic/jetpack */ use Automattic\Jetpack\Current_Plan; /** * Provides methods methods for fetching the site's plan and products from WordPress.com. */ class Jetpack_Plan { /** * The name of the option that will store the site's plan. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::PLAN_OPTION * * @var string */ const PLAN_OPTION = Current_Plan::PLAN_OPTION; /** * The name of the option that will store the site's products. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::SITE_PRODUCTS_OPTION * * @var string */ const SITE_PRODUCTS_OPTION = Current_Plan::SITE_PRODUCTS_OPTION; /** * Array of products supported by each plan. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::PLAN_DATA * * @var array */ const PLAN_DATA = Current_Plan::PLAN_DATA; /** * Given a response to the `/sites/%d` endpoint, will parse the response and attempt to set the * site's plan and products from the response. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::update_from_sites_response instead. * * @param array $response The response from `/sites/%d`. * @return bool Was the plan successfully updated? */ public static function update_from_sites_response( $response ) { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::update_from_sites_response' ); return Current_Plan::update_from_sites_response( $response ); } /** * Make an API call to WordPress.com for plan status * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::refresh_from_wpcom instead. * * @access public * @static * * @return bool True if plan is updated, false if no update */ public static function refresh_from_wpcom() { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::refresh_from_wpcom' ); return Current_Plan::refresh_from_wpcom(); } /** * Get the plan that this Jetpack site is currently using. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::get instead. * * @access public * @static * * @return array Active Jetpack plan details */ public static function get() { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::get' ); return Current_Plan::get(); } /** * Get the site's products. * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::get_products instead. * * @access public * @static * * @return array Active Jetpack products */ public static function get_products() { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::get_products' ); return Current_Plan::get_products(); } /** * Gets the minimum plan slug that supports the given feature * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::get_minimum_plan_for_feature instead. * * @param string $feature The name of the feature. * @return string|bool The slug for the minimum plan that supports. * the feature or false if not found */ public static function get_minimum_plan_for_feature( $feature ) { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::get_minimum_plan_for_feature' ); return Current_Plan::get_minimum_plan_for_feature( $feature ); } /** * Determine whether the active plan supports a particular feature * * @deprecated 12.3 use Automattic\Jetpack\Current_Plan::supports instead. * * @access public * @static * * @param string $feature The module or feature to check. * * @return bool True if plan supports feature, false if not */ public static function supports( $feature ) { _deprecated_function( __METHOD__, '12.3', 'Automattic\Jetpack\Current_Plan::supports' ); return Current_Plan::supports( $feature ); } }
projects/plugins/jetpack/class.json-api-endpoints.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Jetpack API endpoint base class. * * @package automattic/jetpack */ use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Status; require_once __DIR__ . '/json-api-config.php'; require_once __DIR__ . '/sal/class.json-api-links.php'; require_once __DIR__ . '/sal/class.json-api-metadata.php'; require_once __DIR__ . '/sal/class.json-api-date.php'; /** * Endpoint. */ abstract class WPCOM_JSON_API_Endpoint { /** * The API Object * * @var WPCOM_JSON_API */ public $api; /** * The link-generating utility class * * @var WPCOM_JSON_API_Links */ public $links; /** * Whether to pass wpcom user details. * * @var bool */ public $pass_wpcom_user_details = false; /** * One liner. * * @var string */ public $description; /** * Object Grouping For Documentation (Users, Posts, Comments) * * @var string */ public $group; /** * Stats extra value to bump * * @var mixed */ public $stat; /** * HTTP Method * * @var string */ public $method = 'GET'; /** * Minimum version of the api for which to serve this endpoint * * @var string */ public $min_version = '0'; /** * Maximum version of the api for which to serve this endpoint * * @var string */ public $max_version = WPCOM_JSON_API__CURRENT_VERSION; /** * Forced endpoint environment when running on WPCOM * * @var string '', 'wpcom', 'secure', or 'jetpack' */ public $force = ''; /** * Whether the endpoint is deprecated * * @var bool */ public $deprecated = false; /** * Version of the endpoint this endpoint is deprecated in favor of. * * @var string */ protected $new_version = WPCOM_JSON_API__CURRENT_VERSION; /** * Whether the endpoint is only available on WordPress.com hosted blogs * * @var bool */ public $jp_disabled = false; /** * Path at which to serve this endpoint: sprintf() format. * * @var string */ public $path = ''; /** * Identifiers to fill sprintf() formatted $path * * @var array */ public $path_labels = array(); /** * Accepted query parameters * * @var array */ public $query = array( // Parameter name. 'context' => array( // Default value => description. 'display' => 'Formats the output as HTML for display. Shortcodes are parsed, paragraph tags are added, etc..', // Other possible values => description. 'edit' => 'Formats the output for editing. Shortcodes are left unparsed, significant whitespace is kept, etc..', ), 'http_envelope' => array( 'false' => '', 'true' => 'Some environments (like in-browser JavaScript or Flash) block or divert responses with a non-200 HTTP status code. Setting this parameter will force the HTTP status code to always be 200. The JSON response is wrapped in an "envelope" containing the "real" HTTP status code and headers.', ), 'pretty' => array( 'false' => '', 'true' => 'Output pretty JSON', ), 'meta' => "(string) Optional. Loads data from the endpoints found in the 'meta' part of the response. Comma-separated list. Example: meta=site,likes", 'fields' => '(string) Optional. Returns specified fields only. Comma-separated list. Example: fields=ID,title', // Parameter name => description (default value is empty). 'callback' => '(string) An optional JSONP callback function.', ); /** * Response format * * @var array */ public $response_format = array(); /** * Request format * * @var array */ public $request_format = array(); /** * Is this endpoint still in testing phase? If so, not available to the public. * * @var bool */ public $in_testing = false; /** * Is this endpoint still allowed if the site in question is flagged? * * @var bool */ public $allowed_if_flagged = false; /** * Is this endpoint allowed if the site is red flagged? * * @var bool */ public $allowed_if_red_flagged = false; /** * Is this endpoint allowed if the site is deleted? * * @var bool */ public $allowed_if_deleted = false; /** * Version of the API * * @var string */ public $version = ''; /** * Example request to make * * @var string */ public $example_request = ''; /** * Example request data (for POST methods) * * @var string */ public $example_request_data = ''; /** * Example response from $example_request * * @var string */ public $example_response = ''; /** * OAuth2 scope required when running on WPCOM * * @var string */ public $required_scope = ''; /** * Set to true if the endpoint implements its own filtering instead of the standard `fields` query method * * @var bool */ public $custom_fields_filtering = false; /** * Set to true if the endpoint accepts all cross origin requests. You probably should not set this flag. * * @var bool */ public $allow_cross_origin_request = false; /** * Set to true if the endpoint can recieve unauthorized POST requests. * * @var bool */ public $allow_unauthorized_request = false; /** * Set to true if the endpoint should accept site based (not user based) authentication. * * @var bool */ public $allow_jetpack_site_auth = false; /** * Set to true if the endpoint should accept auth from an upload token. * * @var bool */ public $allow_upload_token_auth = false; /** * Set to true if the endpoint should require auth from a Rewind auth token. * * @var bool */ public $require_rewind_auth = false; /** * Whether this endpoint allows falling back to a blog token for making requests to remote Jetpack sites. * * @var bool */ public $allow_fallback_to_jetpack_blog_token = false; /** * Constructor. * * @param string|array|object $args Args. */ public function __construct( $args ) { $defaults = array( 'in_testing' => false, 'allowed_if_flagged' => false, 'allowed_if_red_flagged' => false, 'allowed_if_deleted' => false, 'description' => '', 'group' => '', 'stat' => '', 'method' => 'GET', 'path' => '/', 'min_version' => '0', 'max_version' => WPCOM_JSON_API__CURRENT_VERSION, 'force' => '', 'deprecated' => false, 'new_version' => WPCOM_JSON_API__CURRENT_VERSION, 'jp_disabled' => false, 'path_labels' => array(), 'request_format' => array(), 'response_format' => array(), 'query_parameters' => array(), 'version' => 'v1', 'example_request' => '', 'example_request_data' => '', 'example_response' => '', 'required_scope' => '', 'pass_wpcom_user_details' => false, 'custom_fields_filtering' => false, 'allow_cross_origin_request' => false, 'allow_unauthorized_request' => false, 'allow_jetpack_site_auth' => false, 'allow_upload_token_auth' => false, 'allow_fallback_to_jetpack_blog_token' => false, ); $args = wp_parse_args( $args, $defaults ); $this->in_testing = $args['in_testing']; $this->allowed_if_flagged = $args['allowed_if_flagged']; $this->allowed_if_red_flagged = $args['allowed_if_red_flagged']; $this->allowed_if_deleted = $args['allowed_if_deleted']; $this->description = $args['description']; $this->group = $args['group']; $this->stat = $args['stat']; $this->force = $args['force']; $this->jp_disabled = $args['jp_disabled']; $this->method = $args['method']; $this->path = $args['path']; $this->path_labels = $args['path_labels']; $this->min_version = $args['min_version']; $this->max_version = $args['max_version']; $this->deprecated = $args['deprecated']; $this->new_version = $args['new_version']; // Ensure max version is not less than min version. if ( version_compare( $this->min_version, $this->max_version, '>' ) ) { $this->max_version = $this->min_version; } $this->pass_wpcom_user_details = $args['pass_wpcom_user_details']; $this->custom_fields_filtering = (bool) $args['custom_fields_filtering']; $this->allow_cross_origin_request = (bool) $args['allow_cross_origin_request']; $this->allow_unauthorized_request = (bool) $args['allow_unauthorized_request']; $this->allow_jetpack_site_auth = (bool) $args['allow_jetpack_site_auth']; $this->allow_upload_token_auth = (bool) $args['allow_upload_token_auth']; $this->allow_fallback_to_jetpack_blog_token = (bool) $args['allow_fallback_to_jetpack_blog_token']; $this->require_rewind_auth = isset( $args['require_rewind_auth'] ) ? (bool) $args['require_rewind_auth'] : false; $this->version = $args['version']; $this->required_scope = $args['required_scope']; if ( $this->request_format ) { $this->request_format = array_filter( array_merge( $this->request_format, $args['request_format'] ) ); } else { $this->request_format = $args['request_format']; } if ( $this->response_format ) { $this->response_format = array_filter( array_merge( $this->response_format, $args['response_format'] ) ); } else { $this->response_format = $args['response_format']; } if ( false === $args['query_parameters'] ) { $this->query = array(); } elseif ( is_array( $args['query_parameters'] ) ) { $this->query = array_filter( array_merge( $this->query, $args['query_parameters'] ) ); } $this->api = WPCOM_JSON_API::init(); // Auto-add to WPCOM_JSON_API. $this->links = WPCOM_JSON_API_Links::getInstance(); /** Example Request/Response */ // Examples for endpoint documentation request. $this->example_request = $args['example_request']; $this->example_request_data = $args['example_request_data']; $this->example_response = $args['example_response']; $this->api->add( $this ); } /** * Get all query args. Prefill with defaults. * * @param bool $return_default_values Whether to include default values in the response. * @param bool $cast_and_filter Whether to cast and filter input according to the documentation. * @return array */ public function query_args( $return_default_values = true, $cast_and_filter = true ) { $args = array_intersect_key( $this->api->query, $this->query ); if ( ! $cast_and_filter ) { return $args; } return $this->cast_and_filter( $args, $this->query, $return_default_values ); } /** * Get POST body data. * * @param bool $return_default_values Whether to include default values in the response. * @param bool $cast_and_filter Whether to cast and filter input according to the documentation. * @return mixed */ public function input( $return_default_values = true, $cast_and_filter = true ) { $return = null; $input = trim( (string) $this->api->post_body ); $content_type = (string) $this->api->content_type; if ( $content_type ) { list ( $content_type ) = explode( ';', $content_type ); } $content_type = trim( $content_type ); switch ( $content_type ) { case 'application/json': case 'application/x-javascript': case 'text/javascript': case 'text/x-javascript': case 'text/x-json': case 'text/json': $return = json_decode( $input, true ); if ( JSON_ERROR_NONE !== json_last_error() ) { return null; } break; case 'multipart/form-data': // phpcs:ignore WordPress.Security.NonceVerification.Missing $return = array_merge( stripslashes_deep( $_POST ), $_FILES ); break; case 'application/x-www-form-urlencoded': // attempt JSON first, since probably a curl command. $return = json_decode( $input, true ); if ( $return === null ) { wp_parse_str( $input, $return ); } break; default: wp_parse_str( $input, $return ); break; } if ( isset( $this->api->query['force'] ) && 'secure' === $this->api->query['force'] && isset( $return['secure_key'] ) ) { $this->api->post_body = $this->get_secure_body( $return['secure_key'] ); $this->api->query['force'] = false; return $this->input( $return_default_values, $cast_and_filter ); } if ( $cast_and_filter ) { $return = $this->cast_and_filter( $return, $this->request_format, $return_default_values ); } return $return; } /** * Fetch a body via secure request. * * @param string $secure_key Key for the request. * @return mixed|null API response, or null if the request failed. */ protected function get_secure_body( $secure_key ) { $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/secure-request', Jetpack_Options::get_option( 'id' ) ), '1.1', array( 'method' => 'POST' ), array( 'secure_key' => $secure_key ) ); if ( 200 !== $response['response']['code'] ) { return null; } return json_decode( $response['body'], true ); } /** * Cast and filter data. * * @param mixed $data Data to cast and filter. * @param array $documentation Documentation for keys in `$data` to keep and cast. * @param bool $return_default_values Set default values from `$documentation` to process. * @param bool $for_output See `$this->cast_and_filter_item()`. * @return mixed Filtered data. */ public function cast_and_filter( $data, $documentation, $return_default_values = false, $for_output = false ) { $return_as_object = false; if ( is_object( $data ) ) { // @todo this should probably be a deep copy if $data can ever have nested objects $data = (array) $data; $return_as_object = true; } elseif ( ! is_array( $data ) ) { return $data; } $boolean_arg = array( 'false', 'true' ); $naeloob_arg = array( 'true', 'false' ); $return = array(); foreach ( $documentation as $key => $description ) { if ( is_array( $description ) ) { // String or boolean array keys only. $whitelist = array_keys( $description ); if ( $whitelist === $boolean_arg || $whitelist === $naeloob_arg ) { // Truthiness. if ( isset( $data[ $key ] ) ) { $return[ $key ] = (bool) WPCOM_JSON_API::is_truthy( $data[ $key ] ); } elseif ( $return_default_values ) { $return[ $key ] = $whitelist === $naeloob_arg; // Default to true for naeloob_arg and false for boolean_arg. } } elseif ( isset( $data[ $key ] ) && isset( $description[ $data[ $key ] ] ) ) { // String Key. $return[ $key ] = (string) $data[ $key ]; } elseif ( $return_default_values ) { // Default value. $return[ $key ] = (string) current( $whitelist ); } continue; } $types = $this->parse_types( $description ); $type = array_shift( $types ); // Explicit default - string and int only for now. Always set these reguardless of $return_default_values. if ( isset( $type['default'] ) ) { if ( ! isset( $data[ $key ] ) ) { $data[ $key ] = $type['default']; } } if ( ! isset( $data[ $key ] ) ) { continue; } $this->cast_and_filter_item( $return, $type, $key, $data[ $key ], $types, $for_output ); } if ( $return_as_object ) { return (object) $return; } return $return; } /** * Casts $value according to $type. * Handles fallbacks for certain values of $type when $value is not that $type * Currently, only handles fallback between string <-> array (two way), from string -> false (one way), and from object -> false (one way), * and string -> object (one way) * * Handles "child types" - array:URL, object:category * array:URL means an array of URLs * object:category means a hash of categories * * Handles object typing - object>post means an object of type post * * @param array $return Array to assign the value into. * @param string|array $type Type to cast. * @param string|int $key Key in `$return` to assign the value to. * @param mixed $value Value to cast. * @param array $types Fallback types. * @param bool $for_output Appears to affect formatting of 'date' types. */ public function cast_and_filter_item( &$return, $type, $key, $value, $types = array(), $for_output = false ) { if ( is_string( $type ) ) { $type = compact( 'type' ); } switch ( $type['type'] ) { case 'false': $return[ $key ] = false; break; case 'url': if ( is_object( $value ) && isset( $value->url ) && str_contains( $value->url, 'https://videos.files.wordpress.com/' ) ) { $value = $value->url; } // Check for string since esc_url_raw() expects one. if ( ! is_string( $value ) ) { break; } $return[ $key ] = (string) esc_url_raw( $value ); break; case 'string': // Fallback string -> array, or for string -> object. if ( is_array( $value ) || is_object( $value ) ) { if ( ! empty( $types[0] ) ) { $next_type = array_shift( $types ); return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output ); } } // Fallback string -> false. if ( ! is_string( $value ) ) { if ( ! empty( $types[0] ) && 'false' === $types[0]['type'] ) { $next_type = array_shift( $types ); return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output ); } if ( is_array( $value ) ) { // Give up rather than setting the value to the string 'Array'. break; } } $return[ $key ] = (string) $value; break; case 'html': $return[ $key ] = (string) $value; break; case 'safehtml': $return[ $key ] = wp_kses( (string) $value, wp_kses_allowed_html() ); break; case 'zip': case 'media': if ( is_array( $value ) ) { if ( isset( $value['name'] ) && is_array( $value['name'] ) ) { // It's a $_FILES array // Reformat into array of $_FILES items. $files = array(); foreach ( $value['name'] as $k => $v ) { $files[ $k ] = array(); foreach ( array_keys( $value ) as $file_key ) { $files[ $k ][ $file_key ] = $value[ $file_key ][ $k ]; } } foreach ( $files as $k => $file ) { if ( ! isset( $file['tmp_name'] ) || ! is_string( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { unset( $files[ $k ] ); } } if ( $files ) { $return[ $key ] = $files; } } elseif ( isset( $value['tmp_name'] ) && is_string( $value['tmp_name'] ) && is_uploaded_file( $value['tmp_name'] ) ) { $return[ $key ] = $value; } } break; case 'array': // Fallback array -> string. if ( is_string( $value ) ) { if ( ! empty( $types[0] ) ) { $next_type = array_shift( $types ); return $this->cast_and_filter_item( $return, $next_type, $key, $value, $types, $for_output ); } } if ( isset( $type['children'] ) ) { $children = array(); foreach ( (array) $value as $k => $child ) { $this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output ); } $return[ $key ] = (array) $children; break; } $return[ $key ] = (array) $value; break; case 'iso 8601 datetime': case 'datetime': // (string)s $dates = $this->parse_date( (string) $value ); if ( $for_output ) { $return[ $key ] = $this->format_date( $dates[1], $dates[0] ); } else { list( $return[ $key ], $return[ "{$key}_gmt" ] ) = $dates; } break; case 'float': $return[ $key ] = (float) $value; break; case 'int': case 'integer': $return[ $key ] = (int) $value; break; case 'bool': case 'boolean': $return[ $key ] = (bool) WPCOM_JSON_API::is_truthy( $value ); break; case 'object': // Fallback object -> false. if ( is_scalar( $value ) || $value === null ) { if ( ! empty( $types[0] ) && 'false' === $types[0]['type'] ) { return $this->cast_and_filter_item( $return, 'false', $key, $value, $types, $for_output ); } } if ( isset( $type['children'] ) ) { $children = array(); foreach ( (array) $value as $k => $child ) { $this->cast_and_filter_item( $children, $type['children'], $k, $child, array(), $for_output ); } $return[ $key ] = (object) $children; break; } if ( isset( $type['subtype'] ) ) { return $this->cast_and_filter_item( $return, $type['subtype'], $key, $value, $types, $for_output ); } $return[ $key ] = (object) $value; break; case 'post': $return[ $key ] = (object) $this->cast_and_filter( $value, $this->post_object_format, false, $for_output ); break; case 'comment': $return[ $key ] = (object) $this->cast_and_filter( $value, $this->comment_object_format, false, $for_output ); break; case 'tag': case 'category': $docs = array( 'ID' => '(int)', 'name' => '(string)', 'slug' => '(string)', 'description' => '(HTML)', 'post_count' => '(int)', 'feed_url' => '(string)', 'meta' => '(object)', ); if ( 'category' === $type['type'] ) { $docs['parent'] = '(int)'; } $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'post_reference': case 'comment_reference': $docs = array( 'ID' => '(int)', 'type' => '(string)', 'title' => '(string)', 'link' => '(URL)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'geo': $docs = array( 'latitude' => '(float)', 'longitude' => '(float)', 'address' => '(string)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'author': $docs = array( 'ID' => '(int)', 'user_login' => '(string)', 'login' => '(string)', 'email' => '(string|false)', 'name' => '(string)', 'first_name' => '(string)', 'last_name' => '(string)', 'nice_name' => '(string)', 'URL' => '(URL)', 'avatar_URL' => '(URL)', 'profile_URL' => '(URL)', 'is_super_admin' => '(bool)', 'roles' => '(array:string)', 'ip_address' => '(string|false)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'role': $docs = array( 'name' => '(string)', 'display_name' => '(string)', 'capabilities' => '(object:boolean)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'attachment': $docs = array( 'ID' => '(int)', 'URL' => '(URL)', 'guid' => '(string)', 'mime_type' => '(string)', 'width' => '(int)', 'height' => '(int)', 'duration' => '(int)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, /** * Filter the documentation returned for a post attachment. * * @module json-api * * @since 1.9.0 * * @param array $docs Array of documentation about a post attachment. */ apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ), false, $for_output ); break; case 'metadata': $docs = array( 'id' => '(int)', 'key' => '(string)', 'value' => '(string|false|float|int|array|object)', 'previous_value' => '(string)', 'operation' => '(string)', ); $return[ $key ] = (object) $this->cast_and_filter( $value, /** This filter is documented in class.json-api-endpoints.php */ apply_filters( 'wpcom_json_api_attachment_cast_and_filter', $docs ), false, $for_output ); break; case 'plugin': $docs = array( 'id' => '(safehtml) The plugin\'s ID', 'slug' => '(safehtml) The plugin\'s Slug', 'active' => '(boolean) The plugin status.', 'update' => '(object) The plugin update info.', 'name' => '(safehtml) The name of the plugin.', 'plugin_url' => '(url) Link to the plugin\'s web site.', 'version' => '(safehtml) The plugin version number.', 'description' => '(safehtml) Description of what the plugin does and/or notes from the author', 'author' => '(safehtml) The plugin author\'s name', 'author_url' => '(url) The plugin author web site address', 'network' => '(boolean) Whether the plugin can only be activated network wide.', 'autoupdate' => '(boolean) Whether the plugin is auto updated', 'log' => '(array:safehtml) An array of update log strings.', 'action_links' => '(array) An array of action links that the plugin uses.', ); $return[ $key ] = (object) $this->cast_and_filter( $value, /** * Filter the documentation returned for a plugin. * * @module json-api * * @since 3.1.0 * * @param array $docs Array of documentation about a plugin. */ apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ), false, $for_output ); break; case 'plugin_v1_2': $docs = class_exists( 'Jetpack_JSON_API_Get_Plugins_v1_2_Endpoint' ) ? Jetpack_JSON_API_Get_Plugins_v1_2_Endpoint::$_response_format : Jetpack_JSON_API_Plugins_Endpoint::$_response_format_v1_2; $return[ $key ] = (object) $this->cast_and_filter( $value, /** * Filter the documentation returned for a plugin. * * @module json-api * * @since 3.1.0 * * @param array $docs Array of documentation about a plugin. */ apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ), false, $for_output ); break; case 'file_mod_capabilities': $docs = array( 'reasons_modify_files_unavailable' => '(array) The reasons why files can\'t be modified', 'reasons_autoupdate_unavailable' => '(array) The reasons why autoupdates aren\'t allowed', 'modify_files' => '(boolean) true if files can be modified', 'autoupdate_files' => '(boolean) true if autoupdates are allowed', ); $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'jetpackmodule': $docs = array( 'id' => '(string) The module\'s ID', 'active' => '(boolean) The module\'s status.', 'name' => '(string) The module\'s name.', 'description' => '(safehtml) The module\'s description.', 'sort' => '(int) The module\'s display order.', 'introduced' => '(string) The Jetpack version when the module was introduced.', 'changed' => '(string) The Jetpack version when the module was changed.', 'free' => '(boolean) The module\'s Free or Paid status.', 'module_tags' => '(array) The module\'s tags.', 'override' => '(string) The module\'s override. Empty if no override, otherwise \'active\' or \'inactive\'', ); $return[ $key ] = (object) $this->cast_and_filter( $value, /** This filter is documented in class.json-api-endpoints.php */ apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ), false, $for_output ); break; case 'sharing_button': $docs = array( 'ID' => '(string)', 'name' => '(string)', 'URL' => '(string)', 'icon' => '(string)', 'enabled' => '(bool)', 'visibility' => '(string)', ); $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'sharing_button_service': $docs = array( 'ID' => '(string) The service identifier', 'name' => '(string) The service name', 'class_name' => '(string) Class name for custom style sharing button elements', 'genericon' => '(string) The Genericon unicode character for the custom style sharing button icon', 'preview_smart' => '(string) An HTML snippet of a rendered sharing button smart preview', 'preview_smart_js' => '(string) An HTML snippet of the page-wide initialization scripts used for rendering the sharing button smart preview', ); $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'site_keyring': $docs = array( 'keyring_id' => '(int) Keyring ID', 'service' => '(string) The service name', 'external_user_id' => '(string) External user id for the service', ); $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'taxonomy': $docs = array( 'name' => '(string) The taxonomy slug', 'label' => '(string) The taxonomy human-readable name', 'labels' => '(object) Mapping of labels for the taxonomy', 'description' => '(string) The taxonomy description', 'hierarchical' => '(bool) Whether the taxonomy is hierarchical', 'public' => '(bool) Whether the taxonomy is public', 'capabilities' => '(object) Mapping of current user capabilities for the taxonomy', ); $return[ $key ] = (array) $this->cast_and_filter( $value, $docs, false, $for_output ); break; case 'visibility': // This is needed to fix a bug in WPAndroid where `public: "PUBLIC"` is sent in place of `public: 1`. if ( 'public' === strtolower( $value ) ) { $return[ $key ] = 1; } elseif ( 'private' === strtolower( $value ) ) { $return[ $key ] = -1; } else { $return[ $key ] = (int) $value; } break; case 'dropdown_page': $return[ $key ] = (array) $this->cast_and_filter( $value, $this->dropdown_page_object_format, false, $for_output ); break; default: $method_name = $type['type'] . '_docs'; if ( method_exists( 'WPCOM_JSON_API_Jetpack_Overrides', $method_name ) ) { $docs = WPCOM_JSON_API_Jetpack_Overrides::$method_name(); } if ( ! empty( $docs ) ) { $return[ $key ] = (object) $this->cast_and_filter( $value, /** This filter is documented in class.json-api-endpoints.php */ apply_filters( 'wpcom_json_api_plugin_cast_and_filter', $docs ), false, $for_output ); } else { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error, WordPress.Security.EscapeOutput.OutputNotEscaped trigger_error( "Unknown API casting type {$type['type']}", E_USER_WARNING ); } } } /** * Parse types from text. * * @param string $text Text. * @return array Types. */ public function parse_types( $text ) { if ( ! preg_match( '#^\(([^)]+)\)#', ltrim( $text ), $matches ) ) { return 'none'; } $types = explode( '|', strtolower( $matches[1] ) ); $return = array(); foreach ( $types as $type ) { foreach ( array( ':' => 'children', '>' => 'subtype', '=' => 'default', ) as $operator => $meaning ) { if ( str_contains( $type, $operator ) ) { $item = explode( $operator, $type, 2 ); $return[] = array( 'type' => $item[0], $meaning => $item[1], ); continue 2; } } $return[] = compact( 'type' ); } return $return; } /** * Checks if the endpoint is publicly displayable * * @return bool */ public function is_publicly_documentable() { return '__do_not_document' !== $this->group && true !== $this->in_testing; } /** * Auto generates documentation based on description, method, path, path_labels, and query parameters. * Echoes HTML. * * @param bool $show_description Whether to show the description. */ public function document( $show_description = true ) { global $wpdb; $original_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : 'unset'; unset( $GLOBALS['post'] ); $doc = $this->generate_documentation(); if ( $show_description ) : ?> <caption> <h1><?php echo wp_kses_post( $doc['method'] ); ?> <?php echo wp_kses_post( $doc['path_labeled'] ); ?></h1> <p><?php echo wp_kses_post( $doc['description'] ); ?></p> </caption> <?php endif; ?> <?php if ( true === $this->deprecated ) { ?> <p><strong>This endpoint is deprecated in favor of version <?php echo (float) $this->new_version; ?></strong></p> <?php } ?> <section class="resource-info"> <h2 id="apidoc-resource-info">Resource Information</h2> <table class="api-doc api-doc-resource-parameters api-doc-resource"> <thead> <tr> <th class="api-index-title" scope="column">&nbsp;</th> <th class="api-index-title" scope="column">&nbsp;</th> </tr> </thead> <tbody> <tr class="api-index-item"> <th scope="row" class="parameter api-index-item-title">Method</th> <td class="type api-index-item-title"><?php echo wp_kses_post( $doc['method'] ); ?></td> </tr> <tr class="api-index-item"> <th scope="row" class="parameter api-index-item-title">URL</th> <?php $version = WPCOM_JSON_API__CURRENT_VERSION; if ( ! empty( $this->max_version ) ) { $version = $this->max_version; } ?> <td class="type api-index-item-title">https://public-api.wordpress.com/rest/v<?php echo (float) $version; ?><?php echo wp_kses_post( $doc['path_labeled'] ); ?></td> </tr> <tr class="api-index-item"> <th scope="row" class="parameter api-index-item-title">Requires authentication?</th> <?php $requires_auth = $wpdb->get_row( $wpdb->prepare( 'SELECT requires_authentication FROM rest_api_documentation WHERE `version` = %s AND `path` = %s AND `method` = %s LIMIT 1', $version, untrailingslashit( $doc['path_labeled'] ), $doc['method'] ) ); ?> <td class="type api-index-item-title"><?php echo ( ! empty( $requires_auth->requires_authentication ) ? 'Yes' : 'No' ); ?></td> </tr> </tbody> </table> </section> <?php foreach ( array( 'path' => 'Method Parameters', 'query' => 'Query Parameters', 'body' => 'Request Parameters', 'response' => 'Response Parameters', ) as $doc_section_key => $label ) : $doc_section = 'response' === $doc_section_key ? $doc['response']['body'] : $doc['request'][ $doc_section_key ]; if ( ! $doc_section ) { continue; } $param_label = strtolower( str_replace( ' ', '-', $label ) ); ?> <section class="<?php echo esc_attr( $param_label ); ?>"> <h2 id="apidoc-<?php echo esc_attr( $doc_section_key ); ?>"><?php echo wp_kses_post( $label ); ?></h2> <table class="api-doc api-doc-<?php echo esc_attr( $param_label ); ?>-parameters api-doc-<?php echo esc_attr( strtolower( str_replace( ' ', '-', $doc['group'] ) ) ); ?>"> <thead> <tr> <th class="api-index-title" scope="column">Parameter</th> <th class="api-index-title" scope="column">Type</th> <th class="api-index-title" scope="column">Description</th> </tr> </thead> <tbody> <?php foreach ( $doc_section as $key => $item ) : ?> <tr class="api-index-item"> <th scope="row" class="parameter api-index-item-title"><?php echo wp_kses_post( $key ); ?></th> <td class="type api-index-item-title"><?php echo wp_kses_post( $item['type'] ); // @todo auto-link? ?></td> <td class="description api-index-item-body"> <?php $this->generate_doc_description( $item['description'] ); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> </section> <?php endforeach; ?> <?php if ( 'unset' !== $original_post ) { $GLOBALS['post'] = $original_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited } } /** * `preg_replace_callback` callback to add http_build_query to php content example. * * @todo Is this used anywhere? * * @param array $matches Matches. * @return string */ public function add_http_build_query_to_php_content_example( $matches ) { $trimmed_match = ltrim( $matches[0] ); $pad = substr( $matches[0], 0, -1 * strlen( $trimmed_match ) ); $pad = ltrim( $pad, ' ' ); $return = ' ' . str_replace( "\n", "\n ", $matches[0] ); return " http_build_query({$return}{$pad})"; } /** * Recursively generates the <dl>'s to document item descriptions. * Echoes HTML. * * @param string|array $item Post data to output, or an array of key => data mappings. */ public function generate_doc_description( $item ) { if ( is_array( $item ) ) : ?> <dl> <?php foreach ( $item as $description_key => $description_value ) : ?> <dt><?php echo wp_kses_post( $description_key . ':' ); ?></dt> <dd><?php $this->generate_doc_description( $description_value ); ?></dd> <?php endforeach; ?> </dl> <?php else : echo wp_kses_post( $item ); endif; } /** * Auto generates documentation based on description, method, path, path_labels, and query parameters. * Echoes HTML. */ public function generate_documentation() { $format = str_replace( '%d', '%s', $this->path ); $path_labeled = $format; if ( ! empty( $this->path_labels ) ) { $path_labeled = vsprintf( $format, array_keys( $this->path_labels ) ); } $boolean_arg = array( 'false', 'true' ); $naeloob_arg = array( 'true', 'false' ); $doc = array( 'description' => $this->description, 'method' => $this->method, 'path_format' => $this->path, 'path_labeled' => $path_labeled, 'group' => $this->group, 'request' => array( 'path' => array(), 'query' => array(), 'body' => array(), ), 'response' => array( 'body' => array(), ), ); foreach ( array( 'path_labels' => 'path', 'query' => 'query', 'request_format' => 'body', 'response_format' => 'body', ) as $_property => $doc_item ) { foreach ( (array) $this->$_property as $key => $description ) { if ( is_array( $description ) ) { $description_keys = array_keys( $description ); if ( $boolean_arg === $description_keys || $naeloob_arg === $description_keys ) { $type = '(bool)'; } else { $type = '(string)'; } if ( 'response_format' !== $_property ) { // hack - don't show "(default)" in response format. reset( $description ); $description_key = key( $description ); $description[ $description_key ] = "(default) {$description[$description_key]}"; } } else { $types = $this->parse_types( $description ); $type = array(); $default = ''; if ( 'none' === $types ) { $types = array(); $types[]['type'] = 'none'; } foreach ( $types as $type_array ) { $type[] = $type_array['type']; if ( isset( $type_array['default'] ) ) { $default = $type_array['default']; if ( 'string' === $type_array['type'] ) { $default = "'$default'"; } } } $type = '(' . implode( '|', $type ) . ')'; if ( str_contains( $description, ')' ) ) { list( , $description ) = explode( ')', $description, 2 ); } $description = trim( $description ); if ( $default ) { $description .= " Default: $default."; } } $item = compact( 'type', 'description' ); if ( 'response_format' === $_property ) { $doc['response'][ $doc_item ][ $key ] = $item; } else { $doc['request'][ $doc_item ][ $key ] = $item; } } } return $doc; } /** * Can the user view the post? * * @param int $post_id Post ID. * @return bool|WP_Error */ public function user_can_view_post( $post_id ) { $post = get_post( $post_id ); if ( ! $post || is_wp_error( $post ) ) { return false; } if ( 'inherit' === $post->post_status ) { $parent_post = get_post( $post->post_parent ); $post_status_obj = get_post_status_object( $parent_post->post_status ?? $post->post_status ); } else { $post_status_obj = get_post_status_object( $post->post_status ); } if ( empty( $post_status_obj->public ) ) { if ( is_user_logged_in() ) { if ( ! empty( $post_status_obj->protected ) ) { if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } } elseif ( ! empty( $post_status_obj->private ) ) { if ( ! current_user_can( 'read_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } } elseif ( in_array( $post->post_status, array( 'inherit', 'trash' ), true ) ) { if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } } elseif ( 'auto-draft' === $post->post_status ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedElseif // allow auto-drafts. } else { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } } else { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } } if ( ( new Status() )->is_private_site() && /** * Filter access to a specific post. * * @module json-api * * @since 3.4.0 * * @param bool current_user_can( 'read_post', $post->ID ) Can the current user access the post. * @param WP_Post $post Post data. */ ! apply_filters( 'wpcom_json_api_user_can_view_post', current_user_can( 'read_post', $post->ID ), $post ) ) { return new WP_Error( 'unauthorized', 'User cannot view post', array( 'status_code' => 403, 'error' => 'private_blog', ) ); } if ( strlen( $post->post_password ) && ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot view password protected post', array( 'status_code' => 403, 'error' => 'password_protected', ) ); } return true; } /** * Returns author object. * * @param object $author user ID, user row, WP_User object, comment row, post row. * @param bool $show_email_and_ip output the author's email address and IP address?. * * @return object */ public function get_author( $author, $show_email_and_ip = false ) { $is_jetpack = null; $login = null; $email = null; $name = null; $first_name = null; $last_name = null; $nice = null; $url = null; $ip_address = isset( $author->comment_author_IP ) ? $author->comment_author_IP : ''; if ( isset( $author->comment_author_email ) ) { $id = ( isset( $author->user_id ) && $author->user_id ) ? $author->user_id : 0; $login = ''; $email = $author->comment_author_email; $name = $author->comment_author; $first_name = ''; $last_name = ''; $url = $author->comment_author_url; $avatar_url = $this->api->get_avatar_url( $author ); $profile_url = 'https://gravatar.com/' . md5( strtolower( trim( $email ) ) ); $nice = ''; $site_id = -1; // Comment author URLs and Emails are sent through wp_kses() on save, which replaces "&" with "&amp;" // "&" is the only email/URL character altered by wp_kses(). foreach ( array( 'email', 'url' ) as $field ) { $$field = str_replace( '&amp;', '&', $$field ); } } else { if ( $author instanceof WP_User || isset( $author->user_email ) ) { $author = $author->ID; } elseif ( isset( $author->user_id ) && $author->user_id ) { $author = $author->user_id; } elseif ( isset( $author->post_author ) ) { // then $author is a Post Object. if ( ! $author->post_author ) { return null; } /** * Filter whether the current site is a Jetpack site. * * @module json-api * * @since 3.3.0 * * @param bool false Is the current site a Jetpack site. Default to false. * @param int get_current_blog_id() Blog ID. */ $is_jetpack = true === apply_filters( 'is_jetpack_site', false, get_current_blog_id() ); $post_id = $author->ID; if ( $is_jetpack && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) { $id = get_post_meta( $post_id, '_jetpack_post_author_external_id', true ); $email = get_post_meta( $post_id, '_jetpack_author_email', true ); $login = ''; $name = get_post_meta( $post_id, '_jetpack_author', true ); $first_name = ''; $last_name = ''; $url = ''; $nice = ''; } else { $author = $author->post_author; } } if ( ! isset( $id ) ) { $user = get_user_by( 'id', $author ); if ( ! $user || is_wp_error( $user ) ) { trigger_error( 'Unknown user', E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error return null; } $id = $user->ID; $email = $user->user_email; $login = $user->user_login; $name = $user->display_name; $first_name = $user->first_name; $last_name = $user->last_name; $url = $user->user_url; $nice = $user->user_nicename; } if ( defined( 'IS_WPCOM' ) && IS_WPCOM && ! $is_jetpack ) { $site_id = -1; /** * Allow customizing the blog ID returned with the author in WordPress.com REST API queries. * * @since 12.9 * * @module json-api * * @param bool|int $active_blog Blog ID, or false by default. * @param int $id User ID. */ $active_blog = apply_filters( 'wpcom_api_pre_get_active_blog_author', false, $id ); if ( false === $active_blog ) { $active_blog = get_active_blog_for_user( $id ); } if ( ! empty( $active_blog ) ) { $site_id = $active_blog->blog_id; } if ( $site_id > -1 ) { $site_visible = ( -1 !== (int) $active_blog->public || is_private_blog_user( $site_id, get_current_user_id() ) ); } $profile_url = "https://gravatar.com/{$login}"; } else { $profile_url = 'https://gravatar.com/' . md5( strtolower( trim( $email ) ) ); $site_id = -1; } $avatar_url = $this->api->get_avatar_url( $email ); } if ( $show_email_and_ip ) { $email = (string) $email; $ip_address = (string) $ip_address; } else { $email = false; $ip_address = false; } $author = array( 'ID' => (int) $id, 'login' => (string) $login, 'email' => $email, // string|bool. 'name' => (string) $name, 'first_name' => (string) $first_name, 'last_name' => (string) $last_name, 'nice_name' => (string) $nice, 'URL' => (string) esc_url_raw( $url ), 'avatar_URL' => (string) esc_url_raw( $avatar_url ), 'profile_URL' => (string) esc_url_raw( $profile_url ), 'ip_address' => $ip_address, // string|bool. ); if ( $site_id > -1 ) { $author['site_ID'] = (int) $site_id; $author['site_visible'] = $site_visible; } return (object) $author; } /** * Get a media item. * * @param int $media_id Media post ID. * @return object|WP_Error Media item data, or WP_Error. */ public function get_media_item( $media_id ) { $media_item = get_post( $media_id ); if ( ! $media_item || is_wp_error( $media_item ) ) { return new WP_Error( 'unknown_media', 'Unknown Media', 404 ); } $response = array( 'id' => (string) $media_item->ID, 'date' => (string) $this->format_date( $media_item->post_date_gmt, $media_item->post_date ), 'parent' => $media_item->post_parent, 'link' => wp_get_attachment_url( $media_item->ID ), 'title' => $media_item->post_title, 'caption' => $media_item->post_excerpt, 'description' => $media_item->post_content, 'metadata' => wp_get_attachment_metadata( $media_item->ID ), ); if ( defined( 'IS_WPCOM' ) && IS_WPCOM && is_array( $response['metadata'] ) && ! empty( $response['metadata']['file'] ) ) { remove_filter( '_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10 ); $response['metadata']['file'] = _wp_relative_upload_path( $response['metadata']['file'] ); add_filter( '_wp_relative_upload_path', 'wpcom_wp_relative_upload_path', 10, 2 ); } $response['meta'] = (object) array( 'links' => (object) array( 'self' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_id ), 'help' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_id, 'help' ), 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ), ), ); return (object) $response; } /** * Get a v1.1 media item. * * @param int $media_id Media post ID. * @param WP_Post|null $media_item Media item. * @param string|null $file File path. * @return object|WP_Error Media item data, or WP_Error. */ public function get_media_item_v1_1( $media_id, $media_item = null, $file = null ) { if ( ! $media_item ) { $media_item = get_post( $media_id ); } if ( ! $media_item || is_wp_error( $media_item ) ) { return new WP_Error( 'unknown_media', 'Unknown Media', 404 ); } $attachment_file = get_attached_file( $media_item->ID ); $file = basename( $attachment_file ? $attachment_file : $file ); $file_info = pathinfo( $file ); $ext = isset( $file_info['extension'] ) ? $file_info['extension'] : null; // File operations are handled differently on WordPress.com. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $attachment_metadata = wp_get_attachment_metadata( $media_item->ID ); $filesize = ! empty( $attachment_metadata['filesize'] ) ? $attachment_metadata['filesize'] : 0; } else { // For VideoPress videos, $attachment_file is the video URL. $filesize = file_exists( $attachment_file ) ? filesize( $attachment_file ) : 0; } $response = array( 'ID' => $media_item->ID, 'URL' => wp_get_attachment_url( $media_item->ID ), 'guid' => $media_item->guid, 'date' => (string) $this->format_date( $media_item->post_date_gmt, $media_item->post_date ), 'post_ID' => $media_item->post_parent, 'author_ID' => (int) $media_item->post_author, 'file' => $file, 'mime_type' => $media_item->post_mime_type, 'extension' => $ext, 'title' => $media_item->post_title, 'caption' => $media_item->post_excerpt, 'description' => $media_item->post_content, 'alt' => get_post_meta( $media_item->ID, '_wp_attachment_image_alt', true ), 'icon' => wp_mime_type_icon( $media_item->ID ), 'size' => size_format( (int) $filesize, 2 ), 'thumbnails' => array(), ); if ( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif', 'webp' ), true ) ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); if ( isset( $metadata['height'], $metadata['width'] ) ) { $response['height'] = $metadata['height']; $response['width'] = $metadata['width']; } if ( isset( $metadata['sizes'] ) ) { /** * Filter the thumbnail sizes available for each attachment ID. * * @module json-api * * @since 3.9.0 * * @param array $metadata['sizes'] Array of thumbnail sizes available for a given attachment ID. * @param string $media_id Attachment ID. */ $sizes = apply_filters( 'rest_api_thumbnail_sizes', $metadata['sizes'], $media_item->ID ); if ( is_array( $sizes ) ) { foreach ( $sizes as $size => $size_details ) { $response['thumbnails'][ $size ] = dirname( $response['URL'] ) . '/' . $size_details['file']; } /** * Filter the thumbnail URLs for attachment files. * * @module json-api * * @since 7.1.0 * * @param array $metadata['sizes'] Array with thumbnail sizes as keys and URLs as values. */ $response['thumbnails'] = apply_filters( 'rest_api_thumbnail_size_urls', $response['thumbnails'] ); } } if ( isset( $metadata['image_meta'] ) ) { $response['exif'] = $metadata['image_meta']; } } if ( in_array( $ext, array( 'mp3', 'm4a', 'wav', 'ogg' ), true ) ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); $response['length'] = $metadata['length']; $response['exif'] = $metadata; } $is_video = false; if ( in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ), true ) || 'video/videopress' === $response['mime_type'] ) { $is_video = true; } if ( $is_video ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); if ( isset( $metadata['height'], $metadata['width'] ) ) { $response['height'] = $metadata['height']; $response['width'] = $metadata['width']; } if ( isset( $metadata['length'] ) ) { $response['length'] = $metadata['length']; } if ( empty( $response['length'] ) && isset( $metadata['duration'] ) ) { $response['length'] = (int) $metadata['duration']; } if ( empty( $response['length'] ) && isset( $metadata['videopress']['duration'] ) ) { $response['length'] = ceil( $metadata['videopress']['duration'] / 1000 ); } // add VideoPress info. if ( function_exists( 'video_get_info_by_blogpostid' ) ) { $info = video_get_info_by_blogpostid( $this->api->get_blog_id_for_output(), $media_item->ID ); // If we failed to get VideoPress info, but it exists in the meta data (for some reason) // then let's use that. if ( false === $info && isset( $metadata['videopress'] ) ) { $info = (object) $metadata['videopress']; } if ( isset( $info->rating ) ) { $response['rating'] = $info->rating; } if ( isset( $info->display_embed ) ) { $response['display_embed'] = (string) (int) $info->display_embed; // If not, default to metadata (for WPCOM). } elseif ( isset( $metadata['videopress']['display_embed'] ) ) { // We convert it to int then to string so that (bool) false to become "0". $response['display_embed'] = (string) (int) $metadata['videopress']['display_embed']; } if ( isset( $info->allow_download ) ) { $response['allow_download'] = (string) (int) $info->allow_download; } elseif ( isset( $metadata['videopress']['allow_download'] ) ) { // We convert it to int then to string so that (bool) false to become "0". $response['allow_download'] = (string) (int) $metadata['videopress']['allow_download']; } if ( isset( $info->thumbnail_generating ) ) { $response['thumbnail_generating'] = (bool) intval( $info->thumbnail_generating ); } elseif ( isset( $metadata['videopress']['thumbnail_generating'] ) ) { $response['thumbnail_generating'] = (bool) intval( $metadata['videopress']['thumbnail_generating'] ); } if ( isset( $info->privacy_setting ) ) { $response['privacy_setting'] = (int) $info->privacy_setting; } elseif ( isset( $metadata['videopress']['privacy_setting'] ) ) { $response['privacy_setting'] = (int) $metadata['videopress']['privacy_setting']; } $thumbnail_query_data = array(); if ( function_exists( 'video_is_private' ) && video_is_private( $info ) ) { $thumbnail_query_data['metadata_token'] = video_generate_auth_token( $info ); } // Thumbnails. if ( function_exists( 'video_format_done' ) && function_exists( 'video_image_url_by_guid' ) ) { $response['thumbnails'] = array( 'fmt_hd' => '', 'fmt_dvd' => '', 'fmt_std' => '', ); foreach ( $response['thumbnails'] as $size => $thumbnail_url ) { if ( video_format_done( $info, $size ) ) { $response['thumbnails'][ $size ] = \add_query_arg( $thumbnail_query_data, \video_image_url_by_guid( $info->guid, $size ) ); } else { unset( $response['thumbnails'][ $size ] ); } } } if ( isset( $info->title ) ) { $response['title'] = $info->title; } // If we didn't get VideoPress information (for some reason) then let's // not try and include it in the response. if ( isset( $info->guid ) ) { $response['videopress_guid'] = $info->guid; $response['videopress_processing_done'] = true; if ( '0000-00-00 00:00:00' === $info->finish_date_gmt ) { $response['videopress_processing_done'] = false; } } } } $response['thumbnails'] = (object) $response['thumbnails']; $response['meta'] = (object) array( 'links' => (object) array( 'self' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_item->ID ), 'help' => (string) $this->links->get_media_link( $this->api->get_blog_id_for_output(), $media_item->ID, 'help' ), 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ), ), ); // add VideoPress link to the meta. if ( isset( $response['videopress_guid'] ) ) { if ( function_exists( 'video_get_info_by_blogpostid' ) ) { $response['meta']->links->videopress = (string) $this->links->get_link( '/videos/%s', $response['videopress_guid'], '' ); } } if ( $media_item->post_parent > 0 ) { $response['meta']->links->parent = (string) $this->links->get_post_link( $this->api->get_blog_id_for_output(), $media_item->post_parent ); } return (object) $response; } /** * Get a formatted taxonomy. * * @param int $taxonomy_id Taxonomy ID. * @param string $taxonomy_type Name of taxonomy. * @param string $context Context, 'edit' or 'display'. * @return object|WP_Error */ public function get_taxonomy( $taxonomy_id, $taxonomy_type, $context ) { $taxonomy = get_term_by( 'slug', $taxonomy_id, $taxonomy_type ); // keep updating this function. if ( ! $taxonomy || is_wp_error( $taxonomy ) ) { return new WP_Error( 'unknown_taxonomy', 'Unknown taxonomy', 404 ); } return $this->format_taxonomy( $taxonomy, $taxonomy_type, $context ); } /** * Format a taxonomy. * * @param WP_Term $taxonomy Taxonomy. * @param string $taxonomy_type Name of taxonomy. * @param string $context Context, 'edit' or 'display'. * @return object|WP_Error */ public function format_taxonomy( $taxonomy, $taxonomy_type, $context ) { // Permissions. switch ( $context ) { case 'edit': $tax = get_taxonomy( $taxonomy_type ); if ( ! current_user_can( $tax->cap->edit_terms ) ) { return new WP_Error( 'unauthorized', 'User cannot edit taxonomy', 403 ); } break; case 'display': if ( ( new Status() )->is_private_site() && ! current_user_can( 'read' ) ) { return new WP_Error( 'unauthorized', 'User cannot view taxonomy', 403 ); } break; default: return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 ); } $response = array(); $response['ID'] = (int) $taxonomy->term_id; $response['name'] = (string) $taxonomy->name; $response['slug'] = (string) $taxonomy->slug; $response['description'] = (string) $taxonomy->description; $response['post_count'] = (int) $taxonomy->count; $response['feed_url'] = get_term_feed_link( $taxonomy->term_id, $taxonomy_type ); if ( is_taxonomy_hierarchical( $taxonomy_type ) ) { $response['parent'] = (int) $taxonomy->parent; } $response['meta'] = (object) array( 'links' => (object) array( 'self' => (string) $this->links->get_taxonomy_link( $this->api->get_blog_id_for_output(), $taxonomy->slug, $taxonomy_type ), 'help' => (string) $this->links->get_taxonomy_link( $this->api->get_blog_id_for_output(), $taxonomy->slug, $taxonomy_type, 'help' ), 'site' => (string) $this->links->get_site_link( $this->api->get_blog_id_for_output() ), ), ); return (object) $response; } /** * Returns ISO 8601 formatted datetime: 2011-12-08T01:15:36-08:00 * * @param string $date_gmt GMT datetime string. * @param string $date Optional. Used to calculate the offset from GMT. * @return string */ public function format_date( $date_gmt, $date = null ) { return WPCOM_JSON_API_Date::format_date( $date_gmt, $date ); } /** * Parses a date string and returns the local and GMT representations * of that date & time in 'YYYY-MM-DD HH:MM:SS' format without * timezones or offsets. If the parsed datetime was not localized to a * particular timezone or offset we will assume it was given in GMT * relative to now and will convert it to local time using either the * timezone set in the options table for the blog or the GMT offset. * * @param datetime string $date_string Date to parse. * * @return array( $local_time_string, $gmt_time_string ) */ public function parse_date( $date_string ) { $date_string_info = date_parse( $date_string ); if ( is_array( $date_string_info ) && 0 === $date_string_info['error_count'] ) { // Check if it's already localized. Can't just check is_localtime because date_parse('oppossum') returns true; WTF, PHP. if ( isset( $date_string_info['zone'] ) && true === $date_string_info['is_localtime'] ) { $dt_utc = new DateTime( $date_string ); $dt_local = clone $dt_utc; $dt_utc->setTimezone( new DateTimeZone( 'UTC' ) ); return array( (string) $dt_local->format( 'Y-m-d H:i:s' ), (string) $dt_utc->format( 'Y-m-d H:i:s' ), ); } // It's parseable but no TZ info so assume UTC. $dt_utc = new DateTime( $date_string, new DateTimeZone( 'UTC' ) ); $dt_local = clone $dt_utc; } else { // Could not parse time, use now in UTC. $dt_utc = new DateTime( 'now', new DateTimeZone( 'UTC' ) ); $dt_local = clone $dt_utc; } $dt_local->setTimezone( wp_timezone() ); return array( (string) $dt_local->format( 'Y-m-d H:i:s' ), (string) $dt_utc->format( 'Y-m-d H:i:s' ), ); } /** * Load the functions.php file for the current theme to get its post formats, CPTs, etc. */ public function load_theme_functions() { if ( false === defined( 'STYLESHEETPATH' ) ) { wp_templating_constants(); } // bail if we've done this already (can happen when calling /batch endpoint). if ( defined( 'REST_API_THEME_FUNCTIONS_LOADED' ) ) { return; } // VIP context loading is handled elsewhere, so bail to prevent // duplicate loading. See `switch_to_blog_and_validate_user()`. if ( defined( 'WPCOM_IS_VIP_ENV' ) && WPCOM_IS_VIP_ENV ) { return; } $do_check_theme = defined( 'REST_API_TEST_REQUEST' ) && REST_API_TEST_REQUEST || defined( 'IS_WPCOM' ) && IS_WPCOM; if ( $do_check_theme && ! wpcom_should_load_theme_files_on_rest_api() ) { return; } define( 'REST_API_THEME_FUNCTIONS_LOADED', true ); // the theme info we care about is found either within functions.php or one of the jetpack files. $function_files = array( '/functions.php', '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php' ); $copy_dirs = array( get_template_directory() ); // Is this a child theme? Load the child theme's functions file. if ( get_stylesheet_directory() !== get_template_directory() && wpcom_is_child_theme() ) { foreach ( $function_files as $function_file ) { if ( file_exists( get_stylesheet_directory() . $function_file ) ) { require_once get_stylesheet_directory() . $function_file; } } $copy_dirs[] = get_stylesheet_directory(); } foreach ( $function_files as $function_file ) { if ( file_exists( get_template_directory() . $function_file ) ) { require_once get_template_directory() . $function_file; } } // add inc/wpcom.php and/or includes/wpcom.php. wpcom_load_theme_compat_file(); // Enable including additional directories or files in actions to be copied. $copy_dirs = apply_filters( 'restapi_theme_action_copy_dirs', $copy_dirs ); // since the stuff we care about (CPTS, post formats, are usually on setup or init hooks, we want to load those). $this->copy_hooks( 'after_setup_theme', 'restapi_theme_after_setup_theme', $copy_dirs ); /** * Fires functions hooked onto `after_setup_theme` by the theme for the purpose of the REST API. * * The REST API does not load the theme when processing requests. * To enable theme-based functionality, the API will load the '/functions.php', * '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php files * of the theme (parent and child) and copy functions hooked onto 'after_setup_theme' within those files. * * @module json-api * * @since 3.2.0 */ do_action( 'restapi_theme_after_setup_theme' ); $this->copy_hooks( 'init', 'restapi_theme_init', $copy_dirs ); /** * Fires functions hooked onto `init` by the theme for the purpose of the REST API. * * The REST API does not load the theme when processing requests. * To enable theme-based functionality, the API will load the '/functions.php', * '/inc/jetpack.compat.php', '/inc/jetpack.php', '/includes/jetpack.compat.php files * of the theme (parent and child) and copy functions hooked onto 'init' within those files. * * @module json-api * * @since 3.2.0 */ do_action( 'restapi_theme_init' ); } /** * Copy hook functions. * * @param string $from_hook Hook to copy from. * @param string $to_hook Hook to copy to. * @param array $base_paths Only copy hooks defined in the specified paths. */ public function copy_hooks( $from_hook, $to_hook, $base_paths ) { global $wp_filter; foreach ( $wp_filter as $hook => $actions ) { if ( $from_hook !== $hook ) { continue; } if ( ! has_action( $hook ) ) { continue; } foreach ( $actions as $priority => $callbacks ) { foreach ( $callbacks as $callback_data ) { $callback = $callback_data['function']; // use reflection api to determine filename where function is defined. $reflection = $this->get_reflection( $callback ); if ( false !== $reflection ) { $file_name = $reflection->getFileName(); foreach ( $base_paths as $base_path ) { // only copy hooks with functions which are part of the specified files. if ( str_starts_with( $file_name, $base_path ) ) { add_action( $to_hook, $callback_data['function'], $priority, $callback_data['accepted_args'] ); } } } } } } } /** * Get a ReflectionMethod or ReflectionFunction for the callback. * * @param callable $callback Callback. * @return ReflectionMethod|ReflectionFunction|false */ public function get_reflection( $callback ) { if ( is_array( $callback ) ) { list( $class, $method ) = $callback; return new ReflectionMethod( $class, $method ); } if ( is_string( $callback ) && strpos( $callback, '::' ) !== false ) { list( $class, $method ) = explode( '::', $callback ); return new ReflectionMethod( $class, $method ); } if ( method_exists( $callback, '__invoke' ) ) { return new ReflectionMethod( $callback, '__invoke' ); } if ( is_string( $callback ) && strpos( $callback, '::' ) === false && function_exists( $callback ) ) { return new ReflectionFunction( $callback ); } return false; } /** * Check whether a user can view or edit a post type. * * @param string $post_type post type to check. * @param string $context 'display' or 'edit'. * @return bool */ public function current_user_can_access_post_type( $post_type, $context = 'display' ) { $post_type_object = get_post_type_object( $post_type ); if ( ! $post_type_object ) { return false; } switch ( $context ) { case 'edit': return current_user_can( $post_type_object->cap->edit_posts ); case 'display': return $post_type_object->public || current_user_can( $post_type_object->cap->read_private_posts ); default: return false; } } /** * Is the post type allowed? * * @param string $post_type Post type. * @return bool */ public function is_post_type_allowed( $post_type ) { // if the post type is empty, that's fine, WordPress will default to post. if ( empty( $post_type ) ) { return true; } // allow special 'any' type. if ( 'any' === $post_type ) { return true; } // check for allowed types. if ( in_array( $post_type, $this->_get_whitelisted_post_types(), true ) ) { return true; } $post_type_object = get_post_type_object( $post_type ); if ( $post_type_object ) { if ( ! empty( $post_type_object->show_in_rest ) ) { return $post_type_object->show_in_rest; } if ( ! empty( $post_type_object->publicly_queryable ) ) { return $post_type_object->publicly_queryable; } } return ! empty( $post_type_object->public ); } /** * Gets the whitelisted post types that JP should allow access to. * * @return array Whitelisted post types. */ protected function _get_whitelisted_post_types() { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Legacy. $allowed_types = array( 'post', 'page', 'revision' ); /** * Filter the post types Jetpack has access to, and can synchronize with WordPress.com. * * @module json-api * * @since 2.2.3 * * @param array $allowed_types Array of whitelisted post types. Default to `array( 'post', 'page', 'revision' )`. */ $allowed_types = apply_filters( 'rest_api_allowed_post_types', $allowed_types ); return array_unique( $allowed_types ); } /** * Mobile apps are allowed free video uploads, but limited to 5 minutes in length. * * @param array $media_item the media item to evaluate. * * @return bool true if the media item is a video that was uploaded via the mobile * app that is longer than 5 minutes. */ public function media_item_is_free_video_mobile_upload_and_too_long( $media_item ) { if ( ! $media_item ) { return false; } // Verify file is a video. $is_video = preg_match( '@^video/@', $media_item['type'] ); if ( ! $is_video ) { return false; } // Check if the request is from a mobile app, where we allow free video uploads at limited length. if ( ! in_array( $this->api->token_details['client_id'], VIDEOPRESS_ALLOWED_REST_API_CLIENT_IDS, true ) ) { return false; } // We're only worried about free sites. require_once WP_CONTENT_DIR . '/admin-plugins/wpcom-billing.php'; $current_plan = WPCOM_Store_API::get_current_plan( get_current_blog_id() ); if ( ! $current_plan['is_free'] ) { return false; } // We don't know if this is an upload or a sideload, but in either case the tmp_name should be a path, not a URL. if ( wp_parse_url( $media_item['tmp_name'], PHP_URL_SCHEME ) !== null ) { return false; } // Check if video is longer than 5 minutes. $video_meta = wp_read_video_metadata( $media_item['tmp_name'] ); if ( false !== $video_meta && isset( $video_meta['length'] ) && 5 * MINUTE_IN_SECONDS < $video_meta['length'] ) { videopress_log( 'videopress_app_upload_length_block', 'Mobile app upload on free site blocked because length was longer than 5 minutes.', null, null, null, null, array( 'blog_id' => get_current_blog_id(), 'user_id' => get_current_user_id(), ) ); return true; } return false; } /** * Handle a v1.1 media creation. * * Only one of $media_files and $media_urls should be non-empty. * * @param array $media_files File upload data. * @param array $media_urls URLs to fetch. * @param array $media_attrs Attributes corresponding to each entry in `$media_files`/`$media_urls`. * @param int|false $force_parent_id Force the parent ID, overriding `$media_attrs[]['parent_id']`. * @return array Two items: * - media_ids: IDs created, by index in `$media_files`/`$media_urls`. * - errors: Errors encountered, by index in `$media_files`/`$media_urls`. */ public function handle_media_creation_v1_1( $media_files, $media_urls, $media_attrs = array(), $force_parent_id = false ) { add_filter( 'upload_mimes', array( $this, 'allow_video_uploads' ) ); $media_ids = array(); $errors = array(); $user_can_upload_files = current_user_can( 'upload_files' ) || $this->api->is_authorized_with_upload_token(); $media_attrs = array_values( $media_attrs ); // reset the keys. $i = 0; if ( ! empty( $media_files ) ) { $this->api->trap_wp_die( 'upload_error' ); foreach ( $media_files as $media_item ) { $_FILES['.api.media.item.'] = $media_item; if ( ! $user_can_upload_files ) { $media_id = new WP_Error( 'unauthorized', 'User cannot upload media.', 403 ); } elseif ( $this->media_item_is_free_video_mobile_upload_and_too_long( $media_item ) ) { $media_id = new WP_Error( 'upload_video_length', 'Video uploads longer than 5 minutes require a paid plan.', 400 ); } else { if ( $force_parent_id ) { $parent_id = absint( $force_parent_id ); } elseif ( ! empty( $media_attrs[ $i ] ) && ! empty( $media_attrs[ $i ]['parent_id'] ) ) { $parent_id = absint( $media_attrs[ $i ]['parent_id'] ); } else { $parent_id = 0; } $media_id = media_handle_upload( '.api.media.item.', $parent_id ); } if ( is_wp_error( $media_id ) ) { $errors[ $i ]['file'] = $media_item['name']; $errors[ $i ]['error'] = $media_id->get_error_code(); $errors[ $i ]['message'] = $media_id->get_error_message(); } else { $media_ids[ $i ] = $media_id; } ++$i; } $this->api->trap_wp_die( null ); unset( $_FILES['.api.media.item.'] ); } if ( ! empty( $media_urls ) ) { foreach ( $media_urls as $url ) { if ( ! $user_can_upload_files ) { $media_id = new WP_Error( 'unauthorized', 'User cannot upload media.', 403 ); } else { if ( $force_parent_id ) { $parent_id = absint( $force_parent_id ); } elseif ( ! empty( $media_attrs[ $i ] ) && ! empty( $media_attrs[ $i ]['parent_id'] ) ) { $parent_id = absint( $media_attrs[ $i ]['parent_id'] ); } else { $parent_id = 0; } $media_id = $this->handle_media_sideload( $url, $parent_id ); } if ( is_wp_error( $media_id ) ) { $errors[ $i ] = array( 'file' => $url, 'error' => $media_id->get_error_code(), 'message' => $media_id->get_error_message(), ); } elseif ( ! empty( $media_id ) ) { $media_ids[ $i ] = $media_id; } ++$i; } } if ( ! empty( $media_attrs ) ) { foreach ( $media_ids as $index => $media_id ) { if ( empty( $media_attrs[ $index ] ) ) { continue; } $attrs = $media_attrs[ $index ]; $insert = array(); // Attributes: Title, Caption, Description. if ( isset( $attrs['title'] ) ) { $insert['post_title'] = $attrs['title']; } if ( isset( $attrs['caption'] ) ) { $insert['post_excerpt'] = $attrs['caption']; } if ( isset( $attrs['description'] ) ) { $insert['post_content'] = $attrs['description']; } if ( ! empty( $insert ) ) { $insert['ID'] = $media_id; wp_update_post( (object) $insert ); } // Attributes: Alt. if ( isset( $attrs['alt'] ) ) { $alt = wp_strip_all_tags( $attrs['alt'], true ); update_post_meta( $media_id, '_wp_attachment_image_alt', $alt ); } // Attributes: Artist, Album. $id3_meta = array(); foreach ( array( 'artist', 'album' ) as $key ) { if ( isset( $attrs[ $key ] ) ) { $id3_meta[ $key ] = wp_strip_all_tags( $attrs[ $key ], true ); } } if ( ! empty( $id3_meta ) ) { // Before updating metadata, ensure that the item is audio. $item = $this->get_media_item_v1_1( $media_id ); if ( str_starts_with( $item->mime_type, 'audio/' ) ) { wp_update_attachment_metadata( $media_id, $id3_meta ); } } // Attributes: Meta if ( isset( $attrs['meta'] ) && isset( $attrs['meta']['vertical_id'] ) ) { update_post_meta( $media_id, 'vertical_id', $attrs['meta']['vertical_id'] ); } } } return array( 'media_ids' => $media_ids, 'errors' => $errors, ); } /** * Handle a media sideload. * * @param string $url URL. * @param int $parent_post_id Parent post ID. * @param string $type Type. * @return int|WP_Error|false Media post ID, or error, or false if nothing was sideloaded. */ public function handle_media_sideload( $url, $parent_post_id = 0, $type = 'any' ) { if ( ! function_exists( 'download_url' ) || ! function_exists( 'media_handle_sideload' ) ) { return false; } // if we didn't get a URL, let's bail. $parsed = wp_parse_url( $url ); if ( empty( $parsed ) ) { return false; } $tmp = download_url( $url ); if ( is_wp_error( $tmp ) ) { return $tmp; } // First check to see if we get a mime-type match by file, otherwise, check to // see if WordPress supports this file as an image. If neither, then it is not supported. if ( ! $this->is_file_supported_for_sideloading( $tmp ) || 'image' === $type && ! file_is_displayable_image( $tmp ) ) { @unlink( $tmp ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return new WP_Error( 'invalid_input', 'Invalid file type.', 403 ); } // emulate a $_FILES entry. $file_array = array( 'name' => basename( wp_parse_url( $url, PHP_URL_PATH ) ), 'tmp_name' => $tmp, ); $id = media_handle_sideload( $file_array, $parent_post_id ); if ( file_exists( $tmp ) ) { @unlink( $tmp ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } if ( is_wp_error( $id ) ) { return $id; } if ( ! $id || ! is_int( $id ) ) { return false; } return $id; } /** * Checks that the mime type of the specified file is among those in a filterable list of mime types. * * @param string $file Path to file to get its mime type. * * @return bool */ protected function is_file_supported_for_sideloading( $file ) { return jetpack_is_file_supported_for_sideloading( $file ); } /** * Filter for `upload_mimes`. * * @param array $mimes Allowed mime types. * @return array Allowed mime types. */ public function allow_video_uploads( $mimes ) { // if we are on Jetpack, bail - Videos are already allowed. if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) { return $mimes; } // extra check that this filter is only ever applied during REST API requests. if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) { return $mimes; } // bail early if they already have the upgrade.. if ( wpcom_site_has_videopress() ) { return $mimes; } // lets whitelist to only specific clients right now. $clients_allowed_video_uploads = array(); /** * Filter the list of whitelisted video clients. * * @module json-api * * @since 3.2.0 * * @param array $clients_allowed_video_uploads Array of whitelisted Video clients. */ $clients_allowed_video_uploads = apply_filters( 'rest_api_clients_allowed_video_uploads', $clients_allowed_video_uploads ); if ( ! in_array( $this->api->token_details['client_id'], $clients_allowed_video_uploads ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- Check what types are expected here. return $mimes; } $mime_list = wp_get_mime_types(); $video_exts = explode( ' ', get_site_option( 'video_upload_filetypes', false, false ) ); /** * Filter the video filetypes allowed on the site. * * @module json-api * * @since 3.2.0 * * @param array $video_exts Array of video filetypes allowed on the site. */ $video_exts = apply_filters( 'video_upload_filetypes', $video_exts ); $video_mimes = array(); if ( ! empty( $video_exts ) ) { foreach ( $video_exts as $ext ) { foreach ( $mime_list as $ext_pattern => $mime ) { if ( '' !== $ext && str_contains( $ext_pattern, $ext ) ) { $video_mimes[ $ext_pattern ] = $mime; } } } $mimes = array_merge( $mimes, $video_mimes ); } return $mimes; } /** * Is the current site multi-user? * * @return bool */ public function is_current_site_multi_user() { $users = wp_cache_get( 'site_user_count', 'WPCOM_JSON_API_Endpoint' ); if ( false === $users ) { $user_query = new WP_User_Query( array( 'blog_id' => get_current_blog_id(), 'fields' => 'ID', ) ); $users = (int) $user_query->get_total(); wp_cache_set( 'site_user_count', $users, 'WPCOM_JSON_API_Endpoint', DAY_IN_SECONDS ); } return $users > 1; } /** * Whether cross-origin requests are allowed. * * @return bool */ public function allows_cross_origin_requests() { return 'GET' === $this->method || $this->allow_cross_origin_request; } /** * Whether unauthorized requests are allowed. * * @param string $origin Origin. * @param string[] $complete_access_origins Access origins. * @return bool */ public function allows_unauthorized_requests( $origin, $complete_access_origins ) { return 'GET' === $this->method || ( $this->allow_unauthorized_request && in_array( $origin, $complete_access_origins, true ) ); } /** * Whether this endpoint accepts site based authentication for the current request. * * @since 9.1.0 * * @return bool true, if Jetpack blog token is used and `allow_jetpack_site_auth` is true, * false otherwise. */ public function accepts_site_based_authentication() { return $this->allow_jetpack_site_auth && $this->api->is_jetpack_authorized_for_site(); } /** * Get platform. * * @return WPORG_Platform */ public function get_platform() { return wpcom_get_sal_platform( $this->api->token_details ); } /** * Allows the endpoint to perform logic to allow it to decide whether-or-not it should force a * response from the WPCOM API, or potentially go to the Jetpack blog. * * Override this method if you want to do something different. * * @param int $blog_id Blog ID. * @return bool */ public function force_wpcom_request( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return false; } /** * Get an array of all valid AMP origins for a blog's siteurl. * * @param string $siteurl Origin url of the API request. * @return array */ public function get_amp_cache_origins( $siteurl ) { $host = wp_parse_url( $siteurl, PHP_URL_HOST ); /* * From AMP docs: * "When possible, the Google AMP Cache will create a subdomain for each AMP document's domain by first converting it * from IDN (punycode) to UTF-8. The caches replaces every - (dash) with -- (2 dashes) and replace every . (dot) with * - (dash). For example, pub.com will map to pub-com.cdn.ampproject.org." */ if ( function_exists( 'idn_to_utf8' ) ) { // The third parameter is set explicitly to prevent issues with newer PHP versions compiled with an old ICU version. // phpcs:ignore PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003Deprecated, PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003DeprecatedRemoved $host = idn_to_utf8( $host, IDNA_DEFAULT, defined( 'INTL_IDNA_VARIANT_UTS46' ) ? INTL_IDNA_VARIANT_UTS46 : INTL_IDNA_VARIANT_2003 ); } $subdomain = str_replace( array( '-', '.' ), array( '--', '-' ), $host ); return array( $siteurl, // Google AMP Cache (legacy). 'https://cdn.ampproject.org', // Google AMP Cache subdomain. sprintf( 'https://%s.cdn.ampproject.org', $subdomain ), // Cloudflare AMP Cache. sprintf( 'https://%s.amp.cloudflare.com', $subdomain ), // Bing AMP Cache. sprintf( 'https://%s.bing-amp.com', $subdomain ), ); } /** * Return endpoint response * * @param string $path ... determined by ->$path. * * @return array|WP_Error * falsy: HTTP 500, no response body * WP_Error( $error_code, $error_message, $http_status_code ): HTTP $status_code, json_encode( array( 'error' => $error_code, 'message' => $error_message ) ) response body * $data: HTTP 200, json_encode( $data ) response body */ abstract public function callback( $path = '' ); } require_once __DIR__ . '/json-endpoints.php';
projects/plugins/jetpack/jetpack.php
<?php /** * Plugin Name: Jetpack * Plugin URI: https://jetpack.com * Description: Security, performance, and marketing tools made by WordPress experts. Jetpack keeps your site protected so you can focus on more important things. * Author: Automattic * Version: 13.3-a.0 * Author URI: https://jetpack.com * License: GPL2+ * Text Domain: jetpack * Requires at least: 6.3 * Requires PHP: 7.0 * * @package automattic/jetpack */ use Automattic\Jetpack\Image_CDN\Image_CDN_Core; /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ define( 'JETPACK__MINIMUM_WP_VERSION', '6.3' ); define( 'JETPACK__MINIMUM_PHP_VERSION', '7.0' ); define( 'JETPACK__VERSION', '13.3-a.0' ); /** * Constant used to fetch the connection owner token * * @deprecated 9.0.0 * @var boolean */ define( 'JETPACK_MASTER_USER', true ); define( 'JETPACK__API_VERSION', 1 ); define( 'JETPACK__PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'JETPACK__PLUGIN_FILE', __FILE__ ); defined( 'JETPACK__RELEASE_POST_BLOG_SLUG' ) || define( 'JETPACK__RELEASE_POST_BLOG_SLUG', 'jetpackreleaseblog.wordpress.com' ); defined( 'JETPACK_CLIENT__AUTH_LOCATION' ) || define( 'JETPACK_CLIENT__AUTH_LOCATION', 'header' ); /** * WP.com API no longer supports `http://` protocol. * This means Jetpack can't function properly on servers that can't send outbound HTTPS requests. * The constant is no longer used. * * @deprecated 9.1.0 */ defined( 'JETPACK_CLIENT__HTTPS' ) || define( 'JETPACK_CLIENT__HTTPS', 'AUTO' ); defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || define( 'JETPACK__GLOTPRESS_LOCALES_PATH', JETPACK__PLUGIN_DIR . 'jetpack_vendor/automattic/jetpack-compat/lib/locales.php' ); defined( 'JETPACK__API_BASE' ) || define( 'JETPACK__API_BASE', 'https://jetpack.wordpress.com/jetpack.' ); defined( 'JETPACK_PROTECT__API_HOST' ) || define( 'JETPACK_PROTECT__API_HOST', 'https://api.bruteprotect.com/' ); defined( 'JETPACK__WPCOM_JSON_API_BASE' ) || define( 'JETPACK__WPCOM_JSON_API_BASE', 'https://public-api.wordpress.com' ); /** * WP.com API no longer supports `http://` protocol. * Use `JETPACK__WPCOM_JSON_API_BASE` instead, which has the protocol hardcoded. * * @deprecated 9.1.0 */ defined( 'JETPACK__WPCOM_JSON_API_HOST' ) || define( 'JETPACK__WPCOM_JSON_API_HOST', 'public-api.wordpress.com' ); defined( 'JETPACK__SANDBOX_DOMAIN' ) || define( 'JETPACK__SANDBOX_DOMAIN', '' ); defined( 'JETPACK__DEBUGGER_PUBLIC_KEY' ) || define( 'JETPACK__DEBUGGER_PUBLIC_KEY', "\r\n" . '-----BEGIN PUBLIC KEY-----' . "\r\n" . 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm+uLLVoxGCY71LS6KFc6' . "\r\n" . '1UnF6QGBAsi5XF8ty9kR3/voqfOkpW+gRerM2Kyjy6DPCOmzhZj7BFGtxSV2ZoMX' . "\r\n" . '9ZwWxzXhl/Q/6k8jg8BoY1QL6L2K76icXJu80b+RDIqvOfJruaAeBg1Q9NyeYqLY' . "\r\n" . 'lEVzN2vIwcFYl+MrP/g6Bc2co7Jcbli+tpNIxg4Z+Hnhbs7OJ3STQLmEryLpAxQO' . "\r\n" . 'q8cbhQkMx+FyQhxzSwtXYI/ClCUmTnzcKk7SgGvEjoKGAmngILiVuEJ4bm7Q1yok' . "\r\n" . 'xl9+wcfW6JAituNhml9dlHCWnn9D3+j8pxStHihKy2gVMwiFRjLEeD8K/7JVGkb/' . "\r\n" . 'EwIDAQAB' . "\r\n" . '-----END PUBLIC KEY-----' . "\r\n" ); /* * These constants can be set in wp-config.php to ensure sites behind proxies will still work. * Setting these constants, though, is *not* the preferred method. It's better to configure * the proxy to send the X-Forwarded-Port header. */ defined( 'JETPACK_SIGNATURE__HTTP_PORT' ) || define( 'JETPACK_SIGNATURE__HTTP_PORT', 80 ); defined( 'JETPACK_SIGNATURE__HTTPS_PORT' ) || define( 'JETPACK_SIGNATURE__HTTPS_PORT', 443 ); /** * Check if the version of WordPress in use on the site is supported by Jetpack. */ if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log sprintf( /* translators: Placeholders are numbers, versions of WordPress in use on the site, and required by WordPress. */ esc_html__( 'Your version of WordPress (%1$s) is lower than the version required by Jetpack (%2$s). Please update WordPress to continue enjoying Jetpack.', 'jetpack' ), $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION ) ); } /** * Outputs for an admin notice about running Jetpack on outdated WordPress. * * @since 7.2.0 */ function jetpack_admin_unsupported_wp_notice() { ?> <div class="notice notice-error is-dismissible"> <p><?php esc_html_e( 'Jetpack requires a more recent version of WordPress and has been paused. Please update WordPress to continue enjoying Jetpack.', 'jetpack' ); ?></p> </div> <?php } add_action( 'admin_notices', 'jetpack_admin_unsupported_wp_notice' ); return; } /** * This is where the loading of Jetpack begins. * * First, we try to load our composer autoloader. * * - If it fails, we "pause" Jetpack by ending the loading process * and displaying an admin_notice to inform the site owner. * (We want to fail gracefully if `composer install` has not been executed yet, so we are checking for the autoloader.) * - If it succeeds, we require load-jetpack.php, where all legacy files are required, * and where we add on to various hooks that we expect to always run. */ $jetpack_autoloader = JETPACK__PLUGIN_DIR . 'vendor/autoload_packages.php'; $jetpack_module_headings_file = JETPACK__PLUGIN_DIR . 'modules/module-headings.php'; // This file is loaded later in load-jetpack.php, but let's check here to pause before half-loading Jetpack. if ( is_readable( $jetpack_autoloader ) && is_readable( $jetpack_module_headings_file ) ) { require_once $jetpack_autoloader; if ( method_exists( '\Automattic\Jetpack\Assets', 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( JETPACK__PLUGIN_DIR . 'jetpack_vendor/i18n-map.php' ); } } else { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log sprintf( /* translators: Placeholder is a link to a support document. */ __( 'Your installation of Jetpack is incomplete. If you installed Jetpack from GitHub, please refer to this document to set up your development environment: %1$s', 'jetpack' ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md' ) ); } /** * Outputs an admin notice for folks running Jetpack without having run composer install. * * @since 7.4.0 */ function jetpack_admin_missing_files() { ?> <div class="notice notice-error is-dismissible"> <p> <?php printf( wp_kses( /* translators: Placeholder is a link to a support document. */ __( 'Your installation of Jetpack is incomplete. If you installed Jetpack from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. Jetpack must have Composer dependencies installed and built via the build command: <code>jetpack build plugins/jetpack --with-deps</code>', 'jetpack' ), array( 'a' => array( 'href' => array(), 'rel' => array(), 'target' => array(), ), 'code' => array(), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project' ); ?> </p> </div> <?php } add_action( 'admin_notices', 'jetpack_admin_missing_files' ); return; } register_activation_hook( __FILE__, array( 'Jetpack', 'plugin_activation' ) ); register_deactivation_hook( __FILE__, array( 'Jetpack', 'plugin_deactivation' ) ); // Load image cdn core. This should load regardless of whether the photon module is active. Image_CDN_Core::setup(); // Require everything else, that is not loaded via the autoloader. require_once JETPACK__PLUGIN_DIR . 'load-jetpack.php';
projects/plugins/jetpack/class.jetpack-user-agent.php
<?php /** * Deprecated. Use Automattic\Jetpack\Device_Detection\User_Agent_Info instead. * * @package automattic/jetpack * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * Note: we cannot get rid of the class and its methods yet as multiple plugins * still use it. See https://github.com/Automattic/jetpack/pull/16434/files#r667190852 * * @phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase * @phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase * @phpcs:disable WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase * @phpcs:disable WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid * @phpcs:disable WordPress.Files.FileName */ use Automattic\Jetpack\Device_Detection\User_Agent_Info; /** * A class providing device properties detection. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ class Jetpack_User_Agent_Info { /** * User_Agent_Info instance from the `jetpack-device-detection` package. * * @var User_Agent_Info */ private $ua_info; /** * Report deprecation if appropriate. * * Currently we don't when running on WordPress.com, as there's still a lot * there that needs cleaning up first. * * @param string $method Method. * @param string $repl Replacement method. */ private static function warn_deprecated( $method, $repl ) { if ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) { // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Strings passed are safe. _deprecated_function( $method, 'Jetpack 8.7', "\\Automattic\\Jetpack\\Device_Detection\\User_Agent_Info$repl from the `automattic/jetpack-device-detection` package" ); } } /** * The constructor. * * @param string $ua (Optional) User agent. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public function __construct( $ua = '' ) { self::warn_deprecated( __METHOD__, '' ); $this->ua_info = new User_Agent_Info( $ua ); } /** * This method detects the mobile User Agent name. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return string The matched User Agent name, false otherwise. */ public function get_mobile_user_agent_name() { self::warn_deprecated( __METHOD__, '->get_mobile_user_agent_name' ); return $this->ua_info->get_mobile_user_agent_name(); } /** * This method detects the mobile device's platform. All return strings are from the class constants. * Note that this function returns the platform name, not the UA name/type. You should use a different function * if you need to test the UA capabilites. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return string Name of the platform, false otherwise. */ public function get_platform() { self::warn_deprecated( __METHOD__, '->get_platform' ); return $this->ua_info->get_platform(); } /** * This method detects for UA which can display iPhone-optimized web content. * Includes iPhone, iPod Touch, Android, WebOS, Fennec (Firefox mobile), etc. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public function isTierIphone() { self::warn_deprecated( __METHOD__, '->isTierIphone' ); return $this->ua_info->isTierIphone(); } /** * This method detects for UA which are likely to be capable * but may not necessarily support JavaScript. * Excludes all iPhone Tier UA. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public function isTierRichCss() { self::warn_deprecated( __METHOD__, '->isTierRichCss' ); return $this->ua_info->isTierRichCss(); } /** * Detects if the user is using a tablet. * props Corey Gilmore, BGR.com * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return bool */ public static function is_tablet() { self::warn_deprecated( __METHOD__, '->is_tablet' ); return ( new User_Agent_Info() )->is_tablet(); } /** * Detects if the current UA is the default iPhone or iPod Touch Browser. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_iphoneOrIpod() { self::warn_deprecated( __METHOD__, '->is_iphone_or_ipod' ); return ( new User_Agent_Info() )->is_iphoneOrIpod(); } /** * Detects if the current UA is iPhone Mobile Safari or another iPhone or iPod Touch Browser. * * They type can check for any iPhone, an iPhone using Safari, or an iPhone using something other than Safari. * * Note: If you want to check for Opera mini, Opera mobile or Firefox mobile (or any 3rd party iPhone browser), * you should put the check condition before the check for 'iphone-any' or 'iphone-not-safari'. * Otherwise those browsers will be 'catched' by the iphone string. * * @param string $type Type of iPhone detection. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_iphone_or_ipod( $type = 'iphone-any' ) { self::warn_deprecated( __METHOD__, '::is_iphone_or_ipod' ); return User_Agent_Info::is_iphone_or_ipod( $type ); } /** * Detects if the current UA is Chrome for iOS * * The User-Agent string in Chrome for iOS is the same as the Mobile Safari User-Agent, with CriOS/<ChromeRevision> instead of Version/<VersionNum>. * - Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; en) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_chrome_for_iOS() { self::warn_deprecated( __METHOD__, '::is_chrome_for_iOS' ); return User_Agent_Info::is_chrome_for_iOS(); } /** * Detects if the current UA is Twitter for iPhone * * Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_5 like Mac OS X; nb-no) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8L1 Twitter for iPhone * Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 Twitter for iPhone * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_twitter_for_iphone() { self::warn_deprecated( __METHOD__, '::is_twitter_for_iphone' ); return User_Agent_Info::is_twitter_for_iphone(); } /** * Detects if the current UA is Twitter for iPad * * Old version 4.X - Mozilla/5.0 (iPad; U; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8L1 Twitter for iPad * Ver 5.0 or Higher - Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 Twitter for iPhone * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_twitter_for_ipad() { self::warn_deprecated( __METHOD__, '::is_twitter_for_ipad' ); return User_Agent_Info::is_twitter_for_ipad(); } /** * Detects if the current UA is Facebook for iPhone * - Facebook 4020.0 (iPhone; iPhone OS 5.0.1; fr_FR) * - Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_0 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.0.2;FBBV/4020.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.0;FBSS/2; FBCR/O2;FBID/phone;FBLC/en_US;FBSF/2.0] * - Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 [FBAN/FBIOS;FBAV/5.0;FBBV/47423;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; FBCR/3ITA;FBID/phone;FBLC/en_US] * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_facebook_for_iphone() { self::warn_deprecated( __METHOD__, '::is_facebook_for_iphone' ); return User_Agent_Info::is_facebook_for_iphone(); } /** * Detects if the current UA is Facebook for iPad * - Facebook 4020.0 (iPad; iPhone OS 5.0.1; en_US) * - Mozilla/5.0 (iPad; U; CPU iPhone OS 5_0 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.0.2;FBBV/4020.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.0;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0] * - Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10A403 [FBAN/FBIOS;FBAV/5.0;FBBV/47423;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/6.0;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US] * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_facebook_for_ipad() { self::warn_deprecated( __METHOD__, '::is_facebook_for_ipad' ); return User_Agent_Info::is_facebook_for_ipad(); } /** * Detects if the current UA is WordPress for iOS. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_wordpress_for_ios() { self::warn_deprecated( __METHOD__, '::is_wordpress_for_ios' ); return User_Agent_Info::is_wordpress_for_ios(); } /** * Detects if the current device is an iPad. * They type can check for any iPad, an iPad using Safari, or an iPad using something other than Safari. * * Note: If you want to check for Opera mini, Opera mobile or Firefox mobile (or any 3rd party iPad browser), * you should put the check condition before the check for 'iphone-any' or 'iphone-not-safari'. * Otherwise those browsers will be 'catched' by the ipad string. * * @param string $type iPad type. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_ipad( $type = 'ipad-any' ) { self::warn_deprecated( __METHOD__, '::is_ipad' ); return User_Agent_Info::is_ipad( $type ); } /** * Detects if the current browser is Firefox Mobile (Fennec) * * See http://www.useragentstring.com/pages/Fennec/ * Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.1.1) Gecko/20110415 Firefox/4.0.2pre Fennec/4.0.1 * Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1b2pre) Gecko/20081015 Fennec/1.0a1 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_firefox_mobile() { self::warn_deprecated( __METHOD__, '::is_firefox_mobile' ); return User_Agent_Info::is_firefox_mobile(); } /** * Detects if the current browser is Firefox for desktop * * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox * Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion * The platform section will include 'Mobile' for phones and 'Tablet' for tablets. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_firefox_desktop() { self::warn_deprecated( __METHOD__, '::is_firefox_desktop' ); return User_Agent_Info::is_firefox_desktop(); } /** * Detects if the current browser is FirefoxOS Native browser * * Mozilla/5.0 (Mobile; rv:14.0) Gecko/14.0 Firefox/14.0 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_firefox_os() { self::warn_deprecated( __METHOD__, '::is_firefox_os' ); return User_Agent_Info::is_firefox_os(); } /** * Detects if the current browser is Opera Mobile * * What is the difference between Opera Mobile and Opera Mini? * - Opera Mobile is a full Internet browser for mobile devices. * - Opera Mini always uses a transcoder to convert the page for a small display. * (it uses Opera advanced server compression technology to compress web content before it gets to a device. * The rendering engine is on Opera's server.) * * Opera/9.80 (Windows NT 6.1; Opera Mobi/14316; U; en) Presto/2.7.81 Version/11.00" * Opera/9.50 (Nintendo DSi; Opera/507; U; en-US) * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_opera_mobile() { self::warn_deprecated( __METHOD__, '::is_opera_mobile' ); return User_Agent_Info::is_opera_mobile(); } /** * Detects if the current browser is Opera Mini * * Opera/8.01 (J2ME/MIDP; Opera Mini/3.0.6306/1528; en; U; ssr) * Opera/9.80 (Android;Opera Mini/6.0.24212/24.746 U;en) Presto/2.5.25 Version/10.5454 * Opera/9.80 (iPhone; Opera Mini/5.0.019802/18.738; U; en) Presto/2.4.15 * Opera/9.80 (J2ME/iPhone;Opera Mini/5.0.019802/886; U; ja) Presto/2.4.15 * Opera/9.80 (J2ME/iPhone;Opera Mini/5.0.019802/886; U; ja) Presto/2.4.15 * Opera/9.80 (Series 60; Opera Mini/5.1.22783/23.334; U; en) Presto/2.5.25 Version/10.54 * Opera/9.80 (BlackBerry; Opera Mini/5.1.22303/22.387; U; en) Presto/2.5.25 Version/10.54 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_opera_mini() { self::warn_deprecated( __METHOD__, '::is_opera_mini' ); return User_Agent_Info::is_opera_mini(); } /** * Detects if the current browser is Opera Mini, but not on a smart device OS(Android, iOS, etc) * Used to send users on dumb devices to m.wor * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_opera_mini_dumb() { self::warn_deprecated( __METHOD__, '::is_opera_mini_dumb' ); return User_Agent_Info::is_opera_mini_dumb(); } /** * Detects if the current browser is Opera Mobile or Mini. * * Opera Mini 5 Beta: Opera/9.80 (J2ME/MIDP; Opera Mini/5.0.15650/756; U; en) Presto/2.2.0 * Opera Mini 8: Opera/8.01 (J2ME/MIDP; Opera Mini/3.0.6306/1528; en; U; ssr) * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_OperaMobile() { self::warn_deprecated( __METHOD__, '::is_opera_mini() or \Automattic\Jetpack\Device_Detection\User_Agent_Info::is_opera_mobile()' ); return User_Agent_Info::is_OperaMobile(); } /** * Detects if the current browser is a Windows Phone 7 device. * ex: Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; LG; GW910) * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_WindowsPhone7() { self::warn_deprecated( __METHOD__, '::is_WindowsPhone7' ); return User_Agent_Info::is_WindowsPhone7(); } /** * Detects if the current browser is a Windows Phone 8 device. * ex: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; ARM; Touch; IEMobile/10.0; <Manufacturer>; <Device> [;<Operator>]) * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_windows_phone_8() { self::warn_deprecated( __METHOD__, '::is_windows_phone_8' ); return User_Agent_Info::is_windows_phone_8(); } /** * Detects if the current browser is on a Palm device running the new WebOS. This EXCLUDES TouchPad. * * Ex1: Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1 * Ex2: Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pixi/1.1 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_PalmWebOS() { self::warn_deprecated( __METHOD__, '::is_PalmWebOS' ); return User_Agent_Info::is_PalmWebOS(); } /** * Detects if the current browser is the HP TouchPad default browser. This excludes phones wt WebOS. * * TouchPad Emulator: Mozilla/5.0 (hp-desktop; Linux; hpwOS/2.0; U; it-IT) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 Desktop/1.0 * TouchPad: Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_TouchPad() { self::warn_deprecated( __METHOD__, '::is_TouchPad' ); return User_Agent_Info::is_TouchPad(); } /** * Detects if the current browser is the Series 60 Open Source Browser. * * OSS Browser 3.2 on E75: Mozilla/5.0 (SymbianOS/9.3; U; Series60/3.2 NokiaE75-1/110.48.125 Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413 * * 7.0 Browser (Nokia 5800 XpressMusic (v21.0.025)) : Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413 * * Browser 7.1 (Nokia N97 (v12.0.024)) : Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/12.0.024; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.12344 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_S60_OSSBrowser() { self::warn_deprecated( __METHOD__, '::is_S60_OSSBrowser' ); return User_Agent_Info::is_S60_OSSBrowser(); } /** * Detects if the device platform is the Symbian Series 60. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_symbian_platform() { self::warn_deprecated( __METHOD__, '::is_symbian_platform' ); return User_Agent_Info::is_symbian_platform(); } /** * Detects if the device platform is the Symbian Series 40. * Nokia Browser for Series 40 is a proxy based browser, previously known as Ovi Browser. * This browser will report 'NokiaBrowser' in the header, however some older version will also report 'OviBrowser'. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_symbian_s40_platform() { self::warn_deprecated( __METHOD__, '::is_symbian_s40_platform' ); return User_Agent_Info::is_symbian_s40_platform(); } /** * Returns if the device belongs to J2ME capable family. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return bool */ public static function is_J2ME_platform() { self::warn_deprecated( __METHOD__, '::is_J2ME_platform' ); return User_Agent_Info::is_J2ME_platform(); } /** * Detects if the current UA is on one of the Maemo-based Nokia Internet Tablets. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_MaemoTablet() { self::warn_deprecated( __METHOD__, '::is_MaemoTablet' ); return User_Agent_Info::is_MaemoTablet(); } /** * Detects if the current UA is a MeeGo device (Nokia Smartphone). * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_MeeGo() { self::warn_deprecated( __METHOD__, '::is_MeeGo' ); return User_Agent_Info::is_MeeGo(); } /** * The is_webkit() method can be used to check the User Agent for an webkit generic browser. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_webkit() { self::warn_deprecated( __METHOD__, '::is_webkit' ); return User_Agent_Info::is_webkit(); } /** * Detects if the current browser is the Native Android browser. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean true if the browser is Android otherwise false */ public static function is_android() { self::warn_deprecated( __METHOD__, '::is_android' ); return User_Agent_Info::is_android(); } /** * Detects if the current browser is the Native Android Tablet browser. * Assumes 'Android' should be in the user agent, but not 'mobile' * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean true if the browser is Android and not 'mobile' otherwise false */ public static function is_android_tablet() { self::warn_deprecated( __METHOD__, '::is_android_tablet' ); return User_Agent_Info::is_android_tablet(); } /** * Detects if the current browser is the Kindle Fire Native browser. * * Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-84) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true * Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-84) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=false * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean true if the browser is Kindle Fire Native browser otherwise false */ public static function is_kindle_fire() { self::warn_deprecated( __METHOD__, '::is_kindle_fire' ); return User_Agent_Info::is_kindle_fire(); } /** * Detects if the current browser is the Kindle Touch Native browser * * Mozilla/5.0 (X11; U; Linux armv7l like Android; en-us) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/533.2+ Kindle/3.0+ * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean true if the browser is Kindle monochrome Native browser otherwise false */ public static function is_kindle_touch() { self::warn_deprecated( __METHOD__, '::is_kindle_touch' ); return User_Agent_Info::is_kindle_touch(); } /** * Detect if user agent is the WordPress.com Windows 8 app (used ONLY on the custom oauth stylesheet) * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_windows8_auth() { self::warn_deprecated( __METHOD__, '::is_windows8_auth' ); return User_Agent_Info::is_windows8_auth(); } /** * Detect if user agent is the WordPress.com Windows 8 app. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_wordpress_for_win8() { self::warn_deprecated( __METHOD__, '::is_wordpress_for_win8' ); return User_Agent_Info::is_wordpress_for_win8(); } /** * Detect if user agent is the WordPress.com Desktop app. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_wordpress_desktop_app() { self::warn_deprecated( __METHOD__, '::is_wordpress_desktop_app' ); return User_Agent_Info::is_wordpress_desktop_app(); } /** * The is_blackberry_tablet() method can be used to check the User Agent for a RIM blackberry tablet. * The user agent of the BlackBerry® Tablet OS follows a format similar to the following: * Mozilla/5.0 (PlayBook; U; RIM Tablet OS 1.0.0; en-US) AppleWebKit/534.8+ (KHTML, like Gecko) Version/0.0.1 Safari/534.8+ * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_blackberry_tablet() { self::warn_deprecated( __METHOD__, '::is_blackberry_tablet' ); return User_Agent_Info::is_blackberry_tablet(); } /** * The is_blackbeberry() method can be used to check the User Agent for a blackberry device. * Note that opera mini on BB matches this rule. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_blackbeberry() { self::warn_deprecated( __METHOD__, '::is_blackbeberry' ); return User_Agent_Info::is_blackbeberry(); } /** * The is_blackberry_10() method can be used to check the User Agent for a BlackBerry 10 device. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_blackberry_10() { self::warn_deprecated( __METHOD__, '::is_blackberry_10' ); return User_Agent_Info::is_blackberry_10(); } /** * Retrieve the blackberry OS version. * * Return strings are from the following list: * - blackberry-10 * - blackberry-7 * - blackberry-6 * - blackberry-torch //only the first edition. The 2nd edition has the OS7 onboard and doesn't need any special rule. * - blackberry-5 * - blackberry-4.7 * - blackberry-4.6 * - blackberry-4.5 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return string Version of the BB OS. If version is not found, get_blackbeberry_OS_version will return boolean false. */ public static function get_blackbeberry_OS_version() { self::warn_deprecated( __METHOD__, '::get_blackbeberry_OS_version' ); return User_Agent_Info::get_blackbeberry_OS_version(); } /** * Retrieve the blackberry browser version. * * Return string are from the following list: * - blackberry-10 * - blackberry-webkit * - blackberry-5 * - blackberry-4.7 * - blackberry-4.6 * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return string Type of the BB browser. If browser's version is not found, detect_blackbeberry_browser_version will return boolean false. */ public static function detect_blackberry_browser_version() { self::warn_deprecated( __METHOD__, '::detect_blackberry_browser_version' ); return User_Agent_Info::detect_blackberry_browser_version(); } /** * Checks if a visitor is coming from one of the WordPress mobile apps. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return bool */ public static function is_mobile_app() { self::warn_deprecated( __METHOD__, '::is_mobile_app' ); return User_Agent_Info::is_mobile_app(); } /** * Detects if the current browser is Nintendo 3DS handheld. * * Example: Mozilla/5.0 (Nintendo 3DS; U; ; en) Version/1.7498.US * can differ in language, version and region * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info */ public static function is_Nintendo_3DS() { self::warn_deprecated( __METHOD__, '::is_Nintendo_3DS' ); return User_Agent_Info::is_Nintendo_3DS(); } /** * Was the current request made by a known bot? * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean */ public static function is_bot() { self::warn_deprecated( __METHOD__, '::is_bot' ); return User_Agent_Info::is_bot(); } /** * Is the given user-agent a known bot? * If you want an is_bot check for the current request's UA, use is_bot() instead of passing a user-agent to this method. * * @param string $ua A user-agent string. * * @deprecated 8.7.0 Use Automattic\Jetpack\Device_Detection\User_Agent_Info * * @return boolean */ public static function is_bot_user_agent( $ua = null ) { self::warn_deprecated( __METHOD__, '::is_bot_user_agent' ); return User_Agent_Info::is_bot_user_agent( $ua ); } }
projects/plugins/jetpack/functions.photon.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Generic functions using the Photon service. * * Some are used outside of the Photon module being active, so intentionally not within the module. * As photon has been moved to the image-cdn package, the functions are now also replaced by their counterparts in Image_CDN_Core in the package. * * @package automattic/jetpack */ use Automattic\Jetpack\Image_CDN\Image_CDN; use Automattic\Jetpack\Image_CDN\Image_CDN_Core; /** * Generates a Photon URL. * * @see https://developer.wordpress.com/docs/photon/ * * @deprecated 12.2 Use Automattic\Jetpack\Image_CDN\Image_CDN_Core::cdn_url instead. * @param string $image_url URL to the publicly accessible image you want to manipulate. * @param array|string $args An array of arguments, i.e. array( 'w' => '300', 'resize' => array( 123, 456 ) ), or in string form (w=123&h=456). * @param string|null $scheme URL protocol. * @return string The raw final URL. You should run this through esc_url() before displaying it. */ function jetpack_photon_url( $image_url, $args = array(), $scheme = null ) { return Image_CDN_Core::cdn_url( $image_url, $args, $scheme ); } /** * Parses WP.com-hosted image args to replicate the crop. * * @deprecated 12.2 Use Automattic\Jetpack\Image_CDN\Image_CDN_Core::parse_wpcom_query_args instead. * @param mixed $args Args set during Photon's processing. * @param string $image_url URL of the image. * @return array|string Args for Photon to use for the URL. */ function jetpack_photon_parse_wpcom_query_args( $args, $image_url ) { return Image_CDN_Core::parse_wpcom_query_args( $args, $image_url ); } /** * Sets the scheme for a URL * * @deprecated 12.2 Use Automattic\Jetpack\Image_CDN\Image_CDN_Core::cdn_url_scheme instead. * @param string $url URL to set scheme. * @param string $scheme Scheme to use. Accepts http, https, network_path. * * @return string URL. */ function jetpack_photon_url_scheme( $url, $scheme ) { _deprecated_function( __FUNCTION__, 'jetpack-12.2', 'Automattic\Jetpack\Image_CDN\Image_CDN_Core::cdn_url_scheme' ); return Image_CDN_Core::cdn_url_scheme( $url, $scheme ); } /** * Check to skip Photon for a known domain that shouldn't be Photonized. * * @deprecated 12.2 Use Automattic\Jetpack\Image_CDN\Image_CDN_Core::banned_domains instead. * @param bool $skip If the image should be skipped by Photon. * @param string $image_url URL of the image. * * @return bool Should the image be skipped by Photon. */ function jetpack_photon_banned_domains( $skip, $image_url ) { _deprecated_function( __FUNCTION__, 'jetpack-12.2', 'Automattic\Jetpack\Image_CDN\Image_CDN_Core::banned_domains' ); return Image_CDN_Core::banned_domains( $skip, $image_url ); } /** * Jetpack Photon - Support Text Widgets. * * @deprecated 12.2 * @access public * @param string $content Content from text widget. * @return string */ function jetpack_photon_support_text_widgets( $content ) { _deprecated_function( __FUNCTION__, 'jetpack-12.2' ); return Image_CDN::filter_the_content( $content ); }
projects/plugins/jetpack/class.json-api.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Jetpack JSON API. * * @package automattic/jetpack */ use Automattic\Jetpack\Status; if ( ! defined( 'WPCOM_JSON_API__DEBUG' ) ) { define( 'WPCOM_JSON_API__DEBUG', false ); } require_once __DIR__ . '/sal/class.json-api-platform.php'; /** * Jetpack JSON API. */ class WPCOM_JSON_API { /** * Static instance. * * @todo This should be private. * @var self|null */ public static $self = null; /** * Registered endpoints. * * @var WPCOM_JSON_API_Endpoint[] */ public $endpoints = array(); /** * Endpoint being processed. * * @var WPCOM_JSON_API_Endpoint */ public $endpoint = null; /** * Token details. * * @var array */ public $token_details = array(); /** * Request HTTP method. * * @var string */ public $method = ''; /** * Request URL. * * @var string */ public $url = ''; /** * Path part of the request URL. * * @var string */ public $path = ''; /** * Version extracted from the request URL. * * @var string|null */ public $version = null; /** * Parsed query data. * * @var array */ public $query = array(); /** * Post body, if the request is a POST. * * @var string|null */ public $post_body = null; /** * Copy of `$_FILES` if the request is a POST. * * @var null|array */ public $files = null; /** * Content type of the request. * * @var string|null */ public $content_type = null; /** * Value of `$_SERVER['HTTP_ACCEPT']`, if any * * @var string */ public $accept = ''; /** * Value of `$_SERVER['HTTPS']`, or "--UNset--" if unset. * * @var string */ public $_server_https; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore /** * Whether to exit after serving a response. * * @var bool */ public $exit = true; /** * Public API scheme. * * @var string */ public $public_api_scheme = 'https'; /** * Output status code. * * @var int */ public $output_status_code = 200; /** * Trapped error. * * @var null|array */ public $trapped_error = null; /** * Whether output has been done. * * @var bool */ public $did_output = false; /** * Extra HTTP headers. * * @var string */ public $extra_headers = array(); /** * AMP source origin. * * @var string */ public $amp_source_origin = null; /** * Initialize. * * @param string|null $method As for `$this->setup_inputs()`. * @param string|null $url As for `$this->setup_inputs()`. * @param string|null $post_body As for `$this->setup_inputs()`. * @return WPCOM_JSON_API instance */ public static function init( $method = null, $url = null, $post_body = null ) { if ( ! self::$self ) { self::$self = new static( $method, $url, $post_body ); } return self::$self; } /** * Add an endpoint. * * @param WPCOM_JSON_API_Endpoint $endpoint Endpoint to add. */ public function add( WPCOM_JSON_API_Endpoint $endpoint ) { // @todo Determine if anything depends on this being serialized rather than e.g. JSON. // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Legacy, possibly depended on elsewhere. $path_versions = serialize( array( $endpoint->path, $endpoint->min_version, $endpoint->max_version, ) ); if ( ! isset( $this->endpoints[ $path_versions ] ) ) { $this->endpoints[ $path_versions ] = array(); } $this->endpoints[ $path_versions ][ $endpoint->method ] = $endpoint; } /** * Determine if a string is truthy. If it's not a string, which can happen with * not well-formed data coming from Jetpack sites, we still consider it a truthy value. * * @param mixed $value true, 1, "1", "t", and "true" (case insensitive) are truthy, everything else isn't. * @return bool */ public static function is_truthy( $value ) { if ( true === $value ) { return true; } if ( 1 === $value ) { return true; } if ( ! is_string( $value ) ) { return false; } switch ( strtolower( (string) $value ) ) { case '1': case 't': case 'true': return true; } return false; } /** * Determine if a string is falsey. * * @param mixed $value false, 0, "0", "f", and "false" (case insensitive) are falsey, everything else isn't. * @return bool */ public static function is_falsy( $value ) { if ( false === $value ) { return true; } if ( 0 === $value ) { return true; } if ( ! is_string( $value ) ) { return false; } switch ( strtolower( (string) $value ) ) { case '0': case 'f': case 'false': return true; } return false; } /** * Constructor. * * @todo This should be private. * @param string|null $method As for `$this->setup_inputs()`. * @param string|null $url As for `$this->setup_inputs()`. * @param string|null $post_body As for `$this->setup_inputs()`. */ public function __construct( $method = null, $url = null, $post_body = null ) { $this->setup_inputs( $method, $url, $post_body ); } /** * Setup inputs. * * @param string|null $method Request HTTP method. Fetched from `$_SERVER` if null. * @param string|null $url URL requested. Determined from `$_SERVER` if null. * @param string|null $post_body POST body. Read from `php://input` if null and method is POST. */ public function setup_inputs( $method = null, $url = null, $post_body = null ) { if ( $method === null ) { $this->method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( filter_var( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : ''; } else { $this->method = strtoupper( $method ); } if ( $url === null ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sniff misses the esc_url_raw. $this->url = esc_url_raw( set_url_scheme( 'http://' . ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ) ); } else { $this->url = $url; } $parsed = wp_parse_url( $this->url ); if ( ! empty( $parsed['path'] ) ) { $this->path = $parsed['path']; } if ( ! empty( $parsed['query'] ) ) { wp_parse_str( $parsed['query'], $this->query ); } if ( ! empty( $_SERVER['HTTP_ACCEPT'] ) ) { $this->accept = filter_var( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ); } if ( 'POST' === $this->method ) { if ( $post_body === null ) { $this->post_body = file_get_contents( 'php://input' ); if ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) { $this->content_type = filter_var( wp_unslash( $_SERVER['HTTP_CONTENT_TYPE'] ) ); } elseif ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) { $this->content_type = filter_var( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ); } elseif ( isset( $this->post_body[0] ) && '{' === $this->post_body[0] ) { $this->content_type = 'application/json'; } else { $this->content_type = 'application/x-www-form-urlencoded'; } if ( str_starts_with( strtolower( $this->content_type ), 'multipart/' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing $this->post_body = http_build_query( stripslashes_deep( $_POST ) ); $this->files = $_FILES; $this->content_type = 'multipart/form-data'; } } else { $this->post_body = $post_body; $this->content_type = isset( $this->post_body[0] ) && '{' === $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded'; } } else { $this->post_body = null; $this->content_type = null; } $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? filter_var( wp_unslash( $_SERVER['HTTPS'] ) ) : '--UNset--'; } /** * Initialize. * * @return null|WP_Error (although this implementation always returns null) */ public function initialize() { $this->token_details['blog_id'] = Jetpack_Options::get_option( 'id' ); return null; } /** * Checks if the current request is authorized with a blog token. * This method is overridden by a child class in WPCOM. * * @since 9.1.0 * * @param boolean|int $site_id The site id. * @return boolean */ public function is_jetpack_authorized_for_site( $site_id = false ) { if ( ! $this->token_details ) { return false; } $token_details = (object) $this->token_details; $site_in_token = (int) $token_details->blog_id; if ( $site_in_token < 1 ) { return false; } if ( $site_id && $site_in_token !== (int) $site_id ) { return false; } if ( (int) get_current_user_id() !== 0 ) { // If Jetpack blog token is used, no logged-in user should exist. return false; } return true; } /** * Serve. * * @param bool $exit Whether to exit. * @return string|null Content type (assuming it didn't exit), or null in certain error cases. */ public function serve( $exit = true ) { ini_set( 'display_errors', false ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted $this->exit = (bool) $exit; // This was causing problems with Jetpack, but is necessary for wpcom // @see https://github.com/Automattic/jetpack/pull/2603 // @see r124548-wpcom . if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { add_filter( 'home_url', array( $this, 'ensure_http_scheme_of_home_url' ), 10, 3 ); } add_filter( 'user_can_richedit', '__return_true' ); add_filter( 'comment_edit_pre', array( $this, 'comment_edit_pre' ) ); $initialization = $this->initialize(); if ( 'OPTIONS' === $this->method ) { /** * Fires before the page output. * Can be used to specify custom header options. * * @module json-api * * @since 3.1.0 */ do_action( 'wpcom_json_api_options' ); return $this->output( 200, '', 'text/plain' ); } if ( is_wp_error( $initialization ) ) { $this->output_error( $initialization ); return; } // Normalize path and extract API version. $this->path = untrailingslashit( $this->path ); if ( preg_match( '#^/rest/v(\d+(\.\d+)*)#', $this->path, $matches ) ) { $this->path = substr( $this->path, strlen( $matches[0] ) ); $this->version = $matches[1]; } $allowed_methods = array( 'GET', 'POST' ); $four_oh_five = false; $is_help = preg_match( '#/help/?$#i', $this->path ); $matching_endpoints = array(); if ( $is_help ) { $origin = get_http_origin(); if ( ! empty( $origin ) && 'GET' === $this->method ) { header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) ); } $this->path = substr( rtrim( $this->path, '/' ), 0, -5 ); // Show help for all matching endpoints regardless of method. $methods = $allowed_methods; $find_all_matching_endpoints = true; // How deep to truncate each endpoint's path to see if it matches this help request. $depth = substr_count( $this->path, '/' ) + 1; if ( false !== stripos( $this->accept, 'javascript' ) || false !== stripos( $this->accept, 'json' ) ) { $help_content_type = 'json'; } else { $help_content_type = 'html'; } } elseif ( in_array( $this->method, $allowed_methods, true ) ) { // Only serve requested method. $methods = array( $this->method ); $find_all_matching_endpoints = false; } else { // We don't allow this requested method - find matching endpoints and send 405. $methods = $allowed_methods; $find_all_matching_endpoints = true; $four_oh_five = true; } // Find which endpoint to serve. $found = false; foreach ( $this->endpoints as $endpoint_path_versions => $endpoints_by_method ) { // @todo Determine if anything depends on this being serialized rather than e.g. JSON. // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Legacy, possibly depended on elsewhere. $endpoint_path_versions = unserialize( $endpoint_path_versions ); $endpoint_path = $endpoint_path_versions[0]; $endpoint_min_version = $endpoint_path_versions[1]; $endpoint_max_version = $endpoint_path_versions[2]; // Make sure max_version is not less than min_version. if ( version_compare( $endpoint_max_version, $endpoint_min_version, '<' ) ) { $endpoint_max_version = $endpoint_min_version; } foreach ( $methods as $method ) { if ( ! isset( $endpoints_by_method[ $method ] ) ) { continue; } // Normalize. $endpoint_path = untrailingslashit( $endpoint_path ); if ( $is_help ) { // Truncate path at help depth. $endpoint_path = implode( '/', array_slice( explode( '/', $endpoint_path ), 0, $depth ) ); } // Generate regular expression from sprintf(). $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path ); if ( ! preg_match( "#^$endpoint_path_regex\$#", $this->path, $path_pieces ) ) { // This endpoint does not match the requested path. continue; } if ( version_compare( $this->version, $endpoint_min_version, '<' ) || version_compare( $this->version, $endpoint_max_version, '>' ) ) { // This endpoint does not match the requested version. continue; } $found = true; if ( $find_all_matching_endpoints ) { $matching_endpoints[] = array( $endpoints_by_method[ $method ], $path_pieces ); } else { // The method parameters are now in $path_pieces. $endpoint = $endpoints_by_method[ $method ]; break 2; } } } if ( ! $found ) { return $this->output( 404, '', 'text/plain' ); } if ( $four_oh_five ) { $allowed_methods = array(); foreach ( $matching_endpoints as $matching_endpoint ) { $allowed_methods[] = $matching_endpoint[0]->method; } header( 'Allow: ' . strtoupper( implode( ',', array_unique( $allowed_methods ) ) ) ); return $this->output( 405, array( 'error' => 'not_allowed', 'error_message' => 'Method not allowed', ) ); } if ( $is_help ) { /** * Fires before the API output. * * @since 1.9.0 * * @param string help. */ do_action( 'wpcom_json_api_output', 'help' ); $proxied = function_exists( 'wpcom_is_proxied_request' ) ? wpcom_is_proxied_request() : false; if ( 'json' === $help_content_type ) { $docs = array(); foreach ( $matching_endpoints as $matching_endpoint ) { if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) { $docs[] = call_user_func( array( $matching_endpoint[0], 'generate_documentation' ) ); } } return $this->output( 200, $docs ); } else { status_header( 200 ); foreach ( $matching_endpoints as $matching_endpoint ) { if ( $matching_endpoint[0]->is_publicly_documentable() || $proxied || WPCOM_JSON_API__DEBUG ) { call_user_func( array( $matching_endpoint[0], 'document' ) ); } } } exit; } if ( $endpoint->in_testing && ! WPCOM_JSON_API__DEBUG ) { return $this->output( 404, '', 'text/plain' ); } /** This action is documented in class.json-api.php */ do_action( 'wpcom_json_api_output', $endpoint->stat ); $response = $this->process_request( $endpoint, $path_pieces ); if ( ! $response && ! is_array( $response ) ) { return $this->output( 500, '', 'text/plain' ); } elseif ( is_wp_error( $response ) ) { return $this->output_error( $response ); } $output_status_code = $this->output_status_code; $this->set_output_status_code(); return $this->output( $output_status_code, $response, 'application/json', $this->extra_headers ); } /** * Process a request. * * @param WPCOM_JSON_API_Endpoint $endpoint Endpoint. * @param array $path_pieces Path pieces. * @return array|WP_Error Return value from the endpoint's callback. */ public function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) { $this->endpoint = $endpoint; return call_user_func_array( array( $endpoint, 'callback' ), $path_pieces ); } /** * Output a response or error without exiting. * * @param int $status_code HTTP status code. * @param mixed $response Response data. * @param string $content_type Content type of the response. */ public function output_early( $status_code, $response = null, $content_type = 'application/json' ) { $exit = $this->exit; $this->exit = false; if ( is_wp_error( $response ) ) { $this->output_error( $response ); } else { $this->output( $status_code, $response, $content_type ); } $this->exit = $exit; if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) { $this->finish_request(); } } /** * Set output status code. * * @param int $code HTTP status code. */ public function set_output_status_code( $code = 200 ) { $this->output_status_code = $code; } /** * Output a response. * * @param int $status_code HTTP status code. * @param mixed $response Response data. * @param string $content_type Content type of the response. * @param array $extra Additional HTTP headers. * @return string Content type (assuming it didn't exit). */ public function output( $status_code, $response = null, $content_type = 'application/json', $extra = array() ) { $status_code = (int) $status_code; // In case output() was called before the callback returned. if ( $this->did_output ) { if ( $this->exit ) { exit; } return $content_type; } $this->did_output = true; // 400s and 404s are allowed for all origins if ( 404 === $status_code || 400 === $status_code ) { header( 'Access-Control-Allow-Origin: *' ); } /* Add headers for form submission from <amp-form/> */ if ( $this->amp_source_origin ) { header( 'Access-Control-Allow-Origin: ' . wp_unslash( $this->amp_source_origin ) ); header( 'Access-Control-Allow-Credentials: true' ); } if ( $response === null ) { $response = new stdClass(); } if ( 'text/plain' === $content_type || 'text/html' === $content_type ) { status_header( (int) $status_code ); header( 'Content-Type: ' . $content_type ); foreach ( $extra as $key => $value ) { header( "$key: $value" ); } echo $response; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped if ( $this->exit ) { exit; } return $content_type; } $response = $this->filter_fields( $response ); if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) { $headers = array( array( 'name' => 'Content-Type', 'value' => $content_type, ), ); foreach ( $extra as $key => $value ) { $headers[] = array( 'name' => $key, 'value' => $value, ); } $response = array( 'code' => (int) $status_code, 'headers' => $headers, 'body' => $response, ); $status_code = 200; $content_type = 'application/json'; } status_header( (int) $status_code ); header( "Content-Type: $content_type" ); if ( isset( $this->query['callback'] ) && is_string( $this->query['callback'] ) ) { $callback = preg_replace( '/[^a-z0-9_.]/i', '', $this->query['callback'] ); } else { $callback = false; } if ( $callback ) { // Mitigate Rosetta Flash [1] by setting the Content-Type-Options: nosniff header // and by prepending the JSONP response with a JS comment. // [1] <https://blog.miki.it/2014/7/8/abusing-jsonp-with-rosetta-flash/index.html>. echo "/**/$callback("; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSONP output, not HTML. } echo $this->json_encode( $response ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This is JSON or JSONP output, not HTML. if ( $callback ) { echo ');'; } if ( $this->exit ) { exit; } return $content_type; } /** * Serialize an error. * * @param WP_Error $error Error. * @return array with 'status_code' and 'errors' data. */ public static function serializable_error( $error ) { $status_code = $error->get_error_data(); if ( is_array( $status_code ) && isset( $status_code['status_code'] ) ) { $status_code = $status_code['status_code']; } if ( ! $status_code ) { $status_code = 400; } $response = array( 'error' => $error->get_error_code(), 'message' => $error->get_error_message(), ); $additional_data = $error->get_error_data( 'additional_data' ); if ( $additional_data ) { $response['data'] = $additional_data; } return array( 'status_code' => $status_code, 'errors' => $response, ); } /** * Output an error. * * @param WP_Error $error Error. * @return string Content type (assuming it didn't exit). */ public function output_error( $error ) { $error_response = static::serializable_error( $error ); return $this->output( $error_response['status_code'], $error_response['errors'] ); } /** * Filter fields in a response. * * @param array|object $response Response. * @return array|object Filtered response. */ public function filter_fields( $response ) { if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) ) { return $response; } $fields = array_map( 'trim', explode( ',', $this->query['fields'] ) ); if ( is_object( $response ) ) { $response = (array) $response; } $has_filtered = false; if ( is_array( $response ) && empty( $response['ID'] ) ) { $keys_to_filter = array( 'categories', 'comments', 'connections', 'domains', 'groups', 'likes', 'media', 'notes', 'posts', 'services', 'sites', 'suggestions', 'tags', 'themes', 'topics', 'users', ); foreach ( $keys_to_filter as $key_to_filter ) { if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered ) { continue; } foreach ( $response[ $key_to_filter ] as $key => $values ) { if ( is_object( $values ) ) { if ( is_object( $response[ $key_to_filter ] ) ) { // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.Found -- False positive. $response[ $key_to_filter ]->$key = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) ); } elseif ( is_array( $response[ $key_to_filter ] ) ) { $response[ $key_to_filter ][ $key ] = (object) array_intersect_key( ( (array) $values ), array_flip( $fields ) ); } } elseif ( is_array( $values ) ) { $response[ $key_to_filter ][ $key ] = array_intersect_key( $values, array_flip( $fields ) ); } } $has_filtered = true; } } if ( ! $has_filtered ) { if ( is_object( $response ) ) { $response = (object) array_intersect_key( (array) $response, array_flip( $fields ) ); } elseif ( is_array( $response ) ) { $response = array_intersect_key( $response, array_flip( $fields ) ); } } return $response; } /** * Filter for `home_url`. * * If `$original_scheme` is null, turns an https URL to http. * * @param string $url The complete home URL including scheme and path. * @param string $path Path relative to the home URL. Blank string if no path is specified. * @param string|null $original_scheme Scheme to give the home URL context. Accepts 'http', 'https', 'relative', 'rest', or null. * @return string URL. */ public function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) { if ( $original_scheme ) { return $url; } return preg_replace( '#^https:#', 'http:', $url ); } /** * Decode HTML special characters in comment content. * * @param string $comment_content Comment content. * @return string */ public function comment_edit_pre( $comment_content ) { return htmlspecialchars_decode( $comment_content, ENT_QUOTES ); } /** * JSON encode. * * @param mixed $data Data. * @return string|false */ public function json_encode( $data ) { return wp_json_encode( $data ); } /** * Test if a string ends with a string. * * @param string $haystack String to check. * @param string $needle Suffix to check. * @return bool */ public function ends_with( $haystack, $needle ) { return substr( $haystack, -strlen( $needle ) ) === $needle; } /** * Returns the site's blog_id in the WP.com ecosystem * * @return int */ public function get_blog_id_for_output() { return $this->token_details['blog_id']; } /** * Returns the site's local blog_id. * * @param int $blog_id Blog ID. * @return int */ public function get_blog_id( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return $GLOBALS['blog_id']; } /** * Switch to blog and validate user. * * @param int $blog_id Blog ID. * @param bool $verify_token_for_blog Whether to verify the token. * @return int Blog ID. */ public function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( $this->is_restricted_blog( $blog_id ) ) { return new WP_Error( 'unauthorized', 'User cannot access this restricted blog', 403 ); } /** * If this is a private site we check for 2 things: * 1. In case of user based authentication, we need to check if the logged-in user has the 'read' capability. * 2. In case of site based authentication, make sure the endpoint accepts it. */ if ( ( new Status() )->is_private_site() && ! current_user_can( 'read' ) && ! $this->endpoint->accepts_site_based_authentication() ) { return new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 ); } return $blog_id; } /** * Returns true if the specified blog ID is a restricted blog * * @param int $blog_id Blog ID. * @return bool */ public function is_restricted_blog( $blog_id ) { /** * Filters all REST API access and return a 403 unauthorized response for all Restricted blog IDs. * * @module json-api * * @since 3.4.0 * * @param array $array Array of Blog IDs. */ $restricted_blog_ids = apply_filters( 'wpcom_json_api_restricted_blog_ids', array() ); return true === in_array( $blog_id, $restricted_blog_ids ); // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- I don't trust filters to return the right types. } /** * Post like count. * * @param int $blog_id Blog ID. * @param int $post_id Post ID. * @return int */ public function post_like_count( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return 0; } /** * Is liked? * * @param int $blog_id Blog ID. * @param int $post_id Post ID. * @return bool */ public function is_liked( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return false; } /** * Is reblogged? * * @param int $blog_id Blog ID. * @param int $post_id Post ID. * @return bool */ public function is_reblogged( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return false; } /** * Is following? * * @param int $blog_id Blog ID. * @return bool */ public function is_following( $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return false; } /** * Add global ID. * * @param int $blog_id Blog ID. * @param int $post_id Post ID. * @return string */ public function add_global_ID( $blog_id, $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable, WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid return ''; } /** * Get avatar URL. * * @param string $email Email. * @param array $avatar_size Args for `get_avatar_url()`. * @return string|false */ public function get_avatar_url( $email, $avatar_size = null ) { if ( function_exists( 'wpcom_get_avatar_url' ) ) { return null === $avatar_size ? wpcom_get_avatar_url( $email ) : wpcom_get_avatar_url( $email, $avatar_size ); } else { return null === $avatar_size ? get_avatar_url( $email ) : get_avatar_url( $email, $avatar_size ); } } /** * Counts the number of comments on a site, including certain comment types. * * @param int $post_id Post ID. * @return array Array of counts, matching the output of https://developer.wordpress.org/reference/functions/get_comment_count/. */ public function wp_count_comments( $post_id ) { global $wpdb; if ( 0 !== $post_id ) { return wp_count_comments( $post_id ); } $counts = array( 'total_comments' => 0, 'all' => 0, ); /** * Exclude certain comment types from comment counts in the REST API. * * @since 6.9.0 * @deprecated 11.1 * @module json-api * * @param array Array of comment types to exclude (default: 'order_note', 'webhook_delivery', 'review', 'action_log') */ $exclude = apply_filters_deprecated( 'jetpack_api_exclude_comment_types_count', array( 'order_note', 'webhook_delivery', 'review', 'action_log' ), 'jetpack-11.1', 'jetpack_api_include_comment_types_count' ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable /** * Include certain comment types in comment counts in the REST API. * Note: the default array of comment types includes an empty string, * to support comments posted before WP 5.5, that used an empty string as comment type. * * @since 11.1 * @module json-api * * @param array Array of comment types to include (default: 'comment', 'pingback', 'trackback') */ $include = apply_filters( 'jetpack_api_include_comment_types_count', array( 'comment', 'pingback', 'trackback', '' ) ); if ( empty( $include ) ) { return wp_count_comments( $post_id ); } array_walk( $include, 'esc_sql' ); $where = sprintf( "WHERE comment_type IN ( '%s' )", implode( "','", $include ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- `$where` is built with escaping just above. $count = $wpdb->get_results( "SELECT comment_approved, COUNT(*) AS num_comments FROM $wpdb->comments {$where} GROUP BY comment_approved " ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $approved = array( '0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed', ); // <https://developer.wordpress.org/reference/functions/get_comment_count/#source> foreach ( $count as $row ) { if ( ! in_array( $row->comment_approved, array( 'post-trashed', 'trash', 'spam' ), true ) ) { $counts['all'] += $row->num_comments; $counts['total_comments'] += $row->num_comments; } elseif ( ! in_array( $row->comment_approved, array( 'post-trashed', 'trash' ), true ) ) { $counts['total_comments'] += $row->num_comments; } if ( isset( $approved[ $row->comment_approved ] ) ) { $counts[ $approved[ $row->comment_approved ] ] = $row->num_comments; } } foreach ( $approved as $key ) { if ( empty( $counts[ $key ] ) ) { $counts[ $key ] = 0; } } $counts = (object) $counts; return $counts; } /** * Traps `wp_die()` calls and outputs a JSON response instead. * The result is always output, never returned. * * @param string|null $error_code Call with string to start the trapping. Call with null to stop. * @param int $http_status HTTP status code, 400 by default. */ public function trap_wp_die( $error_code = null, $http_status = 400 ) { // Determine the filter name; based on the conditionals inside the wp_die function. if ( wp_is_json_request() ) { $die_handler = 'wp_die_json_handler'; } elseif ( wp_is_jsonp_request() ) { $die_handler = 'wp_die_jsonp_handler'; } elseif ( wp_is_xml_request() ) { $die_handler = 'wp_die_xml_handler'; } else { $die_handler = 'wp_die_handler'; } if ( $error_code === null ) { $this->trapped_error = null; // Stop trapping. remove_filter( $die_handler, array( $this, 'wp_die_handler_callback' ) ); return; } // If API called via PHP, bail: don't do our custom wp_die(). Do the normal wp_die(). if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) { return; } } elseif ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) { return; } $this->trapped_error = array( 'status' => $http_status, 'code' => $error_code, 'message' => '', ); // Start trapping. add_filter( $die_handler, array( $this, 'wp_die_handler_callback' ) ); } /** * Filter function for `wp_die_handler` and similar filters. * * @return callable */ public function wp_die_handler_callback() { return array( $this, 'wp_die_handler' ); } /** * Handler for `wp_die` calls. * * @param string|WP_Error $message As for `wp_die()`. * @param string|int $title As for `wp_die()`. * @param string|array|int $args As for `wp_die()`. */ public function wp_die_handler( $message, $title = '', $args = array() ) { // Allow wp_die calls to override HTTP status code... $args = wp_parse_args( $args, array( 'response' => $this->trapped_error['status'], ) ); // ... unless it's 500 if ( 500 !== (int) $args['response'] ) { $this->trapped_error['status'] = $args['response']; } if ( $title ) { $message = "$title: $message"; } $this->trapped_error['message'] = wp_kses( $message, array() ); switch ( $this->trapped_error['code'] ) { case 'comment_failure': if ( did_action( 'comment_duplicate_trigger' ) ) { $this->trapped_error['code'] = 'comment_duplicate'; } elseif ( did_action( 'comment_flood_trigger' ) ) { $this->trapped_error['code'] = 'comment_flood'; } break; } // We still want to exit so that code execution stops where it should. // Attach the JSON output to the WordPress shutdown handler. add_action( 'shutdown', array( $this, 'output_trapped_error' ), 0 ); exit; } /** * Output the trapped error. */ public function output_trapped_error() { $this->exit = false; // We're already exiting once. Don't do it twice. $this->output( $this->trapped_error['status'], (object) array( 'error' => $this->trapped_error['code'], 'message' => $this->trapped_error['message'], ) ); } /** * Finish the request. */ public function finish_request() { if ( function_exists( 'fastcgi_finish_request' ) ) { return fastcgi_finish_request(); } } }
projects/plugins/jetpack/class.jetpack-admin.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Build the Jetpack admin menu as a whole. * * @package automattic/jetpack */ use Automattic\Jetpack\Admin_UI\Admin_Menu; use Automattic\Jetpack\Current_Plan as Jetpack_Plan; use Automattic\Jetpack\Partner_Coupon as Jetpack_Partner_Coupon; use Automattic\Jetpack\Status; use Automattic\Jetpack\Status\Host; /** * Build the Jetpack admin menu as a whole. */ class Jetpack_Admin { /** * Static instance. * * @var Jetpack_Admin */ private static $instance = null; /** * Initialize and fetch the static instance. * * @return self */ public static function init() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( isset( $_GET['page'] ) && 'jetpack' === $_GET['page'] ) { add_filter( 'nocache_headers', array( 'Jetpack_Admin', 'add_no_store_header' ), 100 ); } if ( self::$instance === null ) { self::$instance = new Jetpack_Admin(); } return self::$instance; } /** * Filter callback to add `no-store` to the `Cache-Control` header. * * @param array $headers Headers array. * @return array Modified headers array. */ public static function add_no_store_header( $headers ) { $headers['Cache-Control'] .= ', no-store'; return $headers; } /** Constructor. */ private function __construct() { require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php'; $jetpack_react = new Jetpack_React_Page(); require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-settings-page.php'; $fallback_page = new Jetpack_Settings_Page(); require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-about-page.php'; $jetpack_about = new Jetpack_About_Page(); add_action( 'admin_init', array( $jetpack_react, 'react_redirects' ), 0 ); add_action( 'admin_menu', array( $jetpack_react, 'add_actions' ), 998 ); add_action( 'jetpack_admin_menu', array( $jetpack_react, 'jetpack_add_dashboard_sub_nav_item' ) ); add_action( 'jetpack_admin_menu', array( $jetpack_react, 'jetpack_add_settings_sub_nav_item' ) ); add_action( 'jetpack_admin_menu', array( $this, 'admin_menu_debugger' ) ); add_action( 'jetpack_admin_menu', array( $fallback_page, 'add_actions' ) ); add_action( 'jetpack_admin_menu', array( $jetpack_about, 'add_actions' ) ); // Add redirect to current page for activation/deactivation of modules. add_action( 'jetpack_pre_activate_module', array( $this, 'fix_redirect' ), 10, 2 ); add_action( 'jetpack_pre_deactivate_module', array( $this, 'fix_redirect' ), 10, 2 ); // Add module bulk actions handler. add_action( 'jetpack_unrecognized_action', array( $this, 'handle_unrecognized_action' ) ); if ( class_exists( 'Akismet_Admin' ) ) { // If the site has Jetpack Anti-spam, change the Akismet menu label and logo accordingly. $site_products = array_column( Jetpack_Plan::get_products(), 'product_slug' ); $has_anti_spam_product = count( array_intersect( array( 'jetpack_anti_spam', 'jetpack_anti_spam_monthly' ), $site_products ) ) > 0; if ( Jetpack_Plan::supports( 'akismet' ) || Jetpack_Plan::supports( 'antispam' ) || $has_anti_spam_product ) { // Prevent Akismet from adding a menu item. add_action( 'admin_menu', function () { remove_action( 'admin_menu', array( 'Akismet_Admin', 'admin_menu' ), 5 ); }, 4 ); // Add an Anti-spam menu item for Jetpack. This is handled automatically by the Admin_Menu as long as it has been initialized. Admin_Menu::init(); add_action( 'admin_enqueue_scripts', array( $this, 'akismet_logo_replacement_styles' ) ); } } // Ensure an Additional CSS menu item is added to the Appearance menu whenever Jetpack is connected. add_action( 'admin_menu', array( $this, 'additional_css_menu' ) ); add_filter( 'jetpack_display_jitms_on_screen', array( $this, 'should_display_jitms_on_screen' ), 10, 2 ); // Register Jetpack partner coupon hooks. Jetpack_Partner_Coupon::register_coupon_admin_hooks( 'jetpack', Jetpack::admin_url() ); } /** * Generate styles to replace Akismet logo for the Jetpack Akismet Anti-spam logo. Without this, we would have to change the logo from Akismet codebase and we want to avoid that. */ public function akismet_logo_replacement_styles() { $logo_url = esc_url( plugins_url( 'images/products/logo-anti-spam.svg', JETPACK__PLUGIN_FILE ) ); $style = ".akismet-masthead__logo-container { background: url({$logo_url}) no-repeat; min-height: 42px; margin: 20px 0; padding: 0 !important; } .akismet-masthead__logo { display: none; }"; $style .= '@media screen and (max-width: 782px) { .akismet-masthead__logo-container { margin-left: 4px; } }'; wp_add_inline_style( 'admin-bar', $style ); } /** * Handle our Additional CSS menu item and legacy page declaration. * * @since 11.0 . Prior to that, this function was located in custom-css-4.7.php (now custom-css.php). */ public static function additional_css_menu() { /* * Custom CSS for the Customizer is deprecated for block themes as of WP 6.1, so we only expose it with a menu * if the site already has existing CSS code. */ if ( wp_is_block_theme() ) { $styles = wp_get_custom_css(); if ( ! $styles ) { return; } } // If the site is a WoA site and the custom-css feature is not available, return. // See https://github.com/Automattic/jetpack/pull/19965 for more on how this menu item is dealt with on WoA sites. if ( ( new Host() )->is_woa_site() && ! ( in_array( 'custom-css', Jetpack::get_available_modules(), true ) ) ) { return; } elseif ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'custom-css' ) ) { // If the Custom CSS module is enabled, add the Additional CSS menu item and link to the Customizer. // Add in our legacy page to support old bookmarks and such. add_submenu_page( '', __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss', array( __CLASS__, 'customizer_redirect' ) ); // Add in our new page slug that will redirect to the customizer. $hook = add_theme_page( __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss-customizer-redirect', array( __CLASS__, 'customizer_redirect' ) ); add_action( "load-{$hook}", array( __CLASS__, 'customizer_redirect' ) ); } elseif ( class_exists( 'Jetpack' ) && Jetpack::is_connection_ready() ) { // Link to the Jetpack Settings > Writing page, highlighting the Custom CSS setting. add_submenu_page( '', __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss', array( __CLASS__, 'theme_enhancements_redirect' ) ); $hook = add_theme_page( __( 'CSS', 'jetpack' ), __( 'Additional CSS', 'jetpack' ), 'edit_theme_options', 'editcss-theme-enhancements-redirect', array( __CLASS__, 'theme_enhancements_redirect' ) ); add_action( "load-{$hook}", array( __CLASS__, 'theme_enhancements_redirect' ) ); } } /** * Handle the redirect for the customizer. This is necessary because * we can't directly add customizer links to the admin menu. * * @since 11.0 . Prior to that, this function was located in custom-css-4.7.php (now custom-css.php). * * There is a core patch in trac that would make this unnecessary. * * @link https://core.trac.wordpress.org/ticket/39050 */ public static function customizer_redirect() { wp_safe_redirect( self::customizer_link( array( 'return_url' => wp_get_referer(), ) ) ); exit; } /** * Handle the Additional CSS redirect to the Jetpack settings Theme Enhancements section. * * @since 11.0 */ public static function theme_enhancements_redirect() { wp_safe_redirect( 'admin.php?page=jetpack#/writing?term=custom-css' ); exit; } /** * Build the URL to deep link to the Customizer. * * You can modify the return url via $args. * * @since 11.0 in this file. This method is also located in custom-css-4.7.php to cover legacy scenarios. * * @param array $args Array of parameters. * @return string */ public static function customizer_link( $args = array() ) { if ( isset( $_SERVER['REQUEST_URI'] ) ) { $args = wp_parse_args( $args, array( 'return_url' => rawurlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ) ); } return add_query_arg( array( array( 'autofocus' => array( 'section' => 'custom_css', ), ), 'return' => $args['return_url'], ), admin_url( 'customize.php' ) ); } /** * Sort callback to put modules with `requires_connection` last. * * @param array $module1 Module data. * @param array $module2 Module data. * @return int Indicating the relative ordering of module1 and module2. */ public static function sort_requires_connection_last( $module1, $module2 ) { return ( (bool) $module1['requires_connection'] ) <=> ( (bool) $module2['requires_connection'] ); } /** * Produce JS understandable objects of modules containing information for * presentation like description, name, configuration url, etc. */ public function get_modules() { include_once JETPACK__PLUGIN_DIR . 'modules/module-info.php'; $available_modules = Jetpack::get_available_modules(); $active_modules = Jetpack::get_active_modules(); $modules = array(); $jetpack_active = Jetpack::is_connection_ready() || ( new Status() )->is_offline_mode(); $overrides = Jetpack_Modules_Overrides::instance(); foreach ( $available_modules as $module ) { $module_array = Jetpack::get_module( $module ); if ( $module_array ) { /** * Filters each module's short description. * * @since 3.0.0 * * @param string $module_array['description'] Module description. * @param string $module Module slug. */ $short_desc = apply_filters( 'jetpack_short_module_description', $module_array['description'], $module ); // Fix: correct multibyte strings truncate with checking for mbstring extension. $short_desc_trunc = ( function_exists( 'mb_strlen' ) ) ? ( ( mb_strlen( $short_desc ) > 143 ) ? mb_substr( $short_desc, 0, 140 ) . '...' : $short_desc ) : ( ( strlen( $short_desc ) > 143 ) ? substr( $short_desc, 0, 140 ) . '...' : $short_desc ); $module_array['module'] = $module; $is_available = self::is_module_available( $module_array ); $module_array['activated'] = ( $jetpack_active ? in_array( $module, $active_modules, true ) : false ); $module_array['deactivate_nonce'] = wp_create_nonce( 'jetpack_deactivate-' . $module ); $module_array['activate_nonce'] = wp_create_nonce( 'jetpack_activate-' . $module ); $module_array['available'] = $is_available; $module_array['unavailable_reason'] = $is_available ? false : self::get_module_unavailable_reason( $module_array ); $module_array['short_description'] = $short_desc_trunc; $module_array['configure_url'] = Jetpack::module_configuration_url( $module ); $module_array['override'] = $overrides->get_module_override( $module ); $module_array['disabled'] = $is_available ? '' : 'disabled="disabled"'; ob_start(); /** * Allow the display of a "Learn More" button. * The dynamic part of the action, $module, is the module slug. * * @since 3.0.0 */ do_action( 'jetpack_learn_more_button_' . $module ); $module_array['learn_more_button'] = ob_get_clean(); ob_start(); /** * Allow the display of information text when Jetpack is connected to WordPress.com. * The dynamic part of the action, $module, is the module slug. * * @since 3.0.0 */ do_action( 'jetpack_module_more_info_' . $module ); /** * Filter the long description of a module. * * @since 3.5.0 * * @param string ob_get_clean() The module long description. * @param string $module The module name. */ $module_array['long_description'] = apply_filters( 'jetpack_long_module_description', ob_get_clean(), $module ); ob_start(); /** * Filter the search terms for a module * * Search terms are typically added to the module headers, under "Additional Search Queries". * * Use syntax: * function jetpack_$module_search_terms( $terms ) { * $terms = _x( 'term 1, term 2', 'search terms', 'jetpack' ); * return $terms; * } * add_filter( 'jetpack_search_terms_$module', 'jetpack_$module_search_terms' ); * * @since 3.5.0 * * @param string The search terms (comma separated). */ echo apply_filters( 'jetpack_search_terms_' . $module, $module_array['additional_search_queries'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped $module_array['search_terms'] = ob_get_clean(); $module_array['configurable'] = false; if ( current_user_can( 'manage_options' ) && /** * Allow the display of a configuration link in the Jetpack Settings screen. * * @since 3.0.0 * * @param string $module Module name. * @param bool false Should the Configure module link be displayed? Default to false. */ apply_filters( 'jetpack_module_configurable_' . $module, false ) ) { $module_array['configurable'] = sprintf( '<a href="%1$s">%2$s</a>', esc_url( $module_array['configure_url'] ), __( 'Configure', 'jetpack' ) ); } $modules[ $module ] = $module_array; } } uasort( $modules, array( 'Jetpack', 'sort_modules' ) ); if ( ! Jetpack::is_connection_ready() ) { uasort( $modules, array( __CLASS__, 'sort_requires_connection_last' ) ); } return $modules; } /** * Check if a module is available. * * @param array $module Module data. */ public static function is_module_available( $module ) { if ( ! is_array( $module ) || empty( $module ) ) { return false; } /** * We never want to show VaultPress as activatable through Jetpack. */ if ( 'vaultpress' === $module['module'] ) { return false; } /* * WooCommerce Analytics should only be available * when running WooCommerce 3+ */ if ( 'woocommerce-analytics' === $module['module'] && ( ! class_exists( 'WooCommerce' ) || version_compare( WC_VERSION, '3.0', '<' ) ) ) { return false; } /* * In Offline mode, modules that require a site or user * level connection should be unavailable. */ if ( ( new Status() )->is_offline_mode() ) { return ! ( $module['requires_connection'] || $module['requires_user_connection'] ); } /* * Jetpack not connected. */ if ( ! Jetpack::is_connection_ready() ) { return false; } /* * Jetpack connected at a site level only. Make sure to make * modules that require a user connection unavailable. */ if ( ! Jetpack::connection()->has_connected_owner() && $module['requires_user_connection'] ) { return false; } return Jetpack_Plan::supports( $module['module'] ); } /** * Returns why a module is unavailable. * * @param array $module The module. * @return string|false A string stating why the module is not available or false if the module is available. */ public static function get_module_unavailable_reason( $module ) { if ( ! is_array( $module ) || empty( $module ) ) { return false; } if ( self::is_module_available( $module ) ) { return false; } /** * We never want to show VaultPress as activatable through Jetpack so return an empty string. */ if ( 'vaultpress' === $module['module'] ) { return ''; } /* * WooCommerce Analytics should only be available * when running WooCommerce 3+ */ if ( 'woocommerce-analytics' === $module['module'] && ( ! class_exists( 'WooCommerce' ) || version_compare( WC_VERSION, '3.0', '<' ) ) ) { return __( 'Requires WooCommerce 3+ plugin', 'jetpack' ); } /* * In Offline mode, modules that require a site or user * level connection should be unavailable. */ if ( ( new Status() )->is_offline_mode() ) { if ( $module['requires_connection'] || $module['requires_user_connection'] ) { return __( 'Offline mode', 'jetpack' ); } } /* * Jetpack not connected. */ if ( ! Jetpack::is_connection_ready() ) { return __( 'Jetpack is not connected', 'jetpack' ); } /* * Jetpack connected at a site level only and module requires a user connection. */ if ( ! Jetpack::connection()->has_connected_owner() && $module['requires_user_connection'] ) { return __( 'Requires a connected WordPress.com account', 'jetpack' ); } /* * Plan restrictions. */ if ( ! Jetpack_Plan::supports( $module['module'] ) ) { return __( 'Not supported by current plan', 'jetpack' ); } return ''; } /** * Handle an unrecognized action. * * @param string $action Action. */ public function handle_unrecognized_action( $action ) { switch ( $action ) { case 'bulk-activate': check_admin_referer( 'bulk-jetpack_page_jetpack_modules' ); if ( ! current_user_can( 'jetpack_activate_modules' ) ) { break; } $modules = isset( $_GET['modules'] ) ? array_map( 'sanitize_key', wp_unslash( (array) $_GET['modules'] ) ) : array(); foreach ( $modules as $module ) { Jetpack::log( 'activate', $module ); Jetpack::activate_module( $module, false ); } // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end. wp_safe_redirect( wp_get_referer() ); exit; case 'bulk-deactivate': check_admin_referer( 'bulk-jetpack_page_jetpack_modules' ); if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) { break; } $modules = isset( $_GET['modules'] ) ? array_map( 'sanitize_key', wp_unslash( (array) $_GET['modules'] ) ) : array(); foreach ( $modules as $module ) { Jetpack::log( 'deactivate', $module ); Jetpack::deactivate_module( $module ); Jetpack::state( 'message', 'module_deactivated' ); } Jetpack::state( 'module', $modules ); wp_safe_redirect( wp_get_referer() ); exit; default: return; } } /** * Fix redirect. * * Apparently we redirect to the referrer instead of whatever WordPress * wants to redirect to when activating and deactivating modules. * * @param string $module Module slug. * @param bool $redirect Should we exit after the module has been activated. Default to true. */ public function fix_redirect( $module, $redirect = true ) { if ( ! $redirect ) { return; } if ( wp_get_referer() ) { add_filter( 'wp_redirect', 'wp_get_referer' ); } } /** * Add debugger admin menu. */ public function admin_menu_debugger() { require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger.php'; Jetpack_Debugger::disconnect_and_redirect(); $debugger_hook = add_submenu_page( '', __( 'Debugging Center', 'jetpack' ), '', 'manage_options', 'jetpack-debugger', array( $this, 'wrap_debugger_page' ) ); add_action( "admin_head-$debugger_hook", array( 'Jetpack_Debugger', 'jetpack_debug_admin_head' ) ); } /** * Wrap debugger page. */ public function wrap_debugger_page() { nocache_headers(); if ( ! current_user_can( 'manage_options' ) ) { die( '-1' ); } Jetpack_Admin_Page::wrap_ui( array( $this, 'debugger_page' ), array( 'is-wide' => true ) ); } /** * Display debugger page. */ public function debugger_page() { require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger.php'; Jetpack_Debugger::jetpack_debug_display_handler(); } /** * Determines if JITMs should display on a particular screen. * * @param bool $value The default value of the filter. * @param string $screen_id The ID of the screen being tested for JITM display. * * @return bool True if JITMs should display, false otherwise. */ public function should_display_jitms_on_screen( $value, $screen_id ) { // Disable all JITMs on these pages. if ( in_array( $screen_id, array( 'jetpack_page_akismet-key-config', 'admin_page_jetpack_modules', ), true ) ) { return false; } return $value; } } Jetpack_Admin::init();
projects/plugins/jetpack/class.frame-nonce-preview.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Allows viewing posts on the frontend when the user is not logged in. * * @package automattic/jetpack */ // phpcs:disable WordPress.Security.NonceVerification.Recommended -- This is _implementing_ cross-site nonce handling, no need for WordPress's nonces. /** * Allows viewing posts on the frontend when the user is not logged in. */ class Jetpack_Frame_Nonce_Preview { /** * Static instance. * * @todo This should be private. * @var self */ public static $instance = null; /** * Returns the single instance of the Jetpack_Frame_Nonce_Preview object * * @since 4.3.0 * * @return Jetpack_Frame_Nonce_Preview **/ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new Jetpack_Frame_Nonce_Preview(); } return self::$instance; } /** * Constructor. * * @todo This should be private. */ public function __construct() { if ( isset( $_GET['frame-nonce'] ) && ! is_admin() ) { add_filter( 'pre_get_posts', array( $this, 'maybe_display_post' ) ); } // autosave previews are validated differently. if ( isset( $_GET['frame-nonce'] ) && isset( $_GET['preview_id'] ) && isset( $_GET['preview_nonce'] ) ) { remove_action( 'init', '_show_post_preview' ); add_action( 'init', array( $this, 'handle_autosave_nonce_validation' ) ); } } /** * Verify that frame nonce exists, and if so, validate the nonce by calling WP.com. * * @since 4.3.0 * * @return bool */ public function is_frame_nonce_valid() { if ( empty( $_GET['frame-nonce'] ) ) { return false; } $xml = new Jetpack_IXR_Client(); $xml->query( 'jetpack.verifyFrameNonce', sanitize_key( $_GET['frame-nonce'] ) ); if ( $xml->isError() ) { return false; } return (bool) $xml->getResponse(); } /** * Conditionally add a hook on posts_results if this is the main query, a preview, and singular. * * @since 4.3.0 * * @param WP_Query $query Query. * @return WP_Query */ public function maybe_display_post( $query ) { if ( $query->is_main_query() && $query->is_preview() && $query->is_singular() ) { add_filter( 'posts_results', array( $this, 'set_post_to_publish' ), 10, 2 ); } return $query; } /** * Conditionally set the first post to 'publish' if the frame nonce is valid and there is a post. * * @since 4.3.0 * * @param array $posts Posts. * @return array */ public function set_post_to_publish( $posts ) { remove_filter( 'posts_results', array( $this, 'set_post_to_publish' ), 10, 2 ); if ( empty( $posts ) || is_user_logged_in() || ! $this->is_frame_nonce_valid() ) { return $posts; } $posts[0]->post_status = 'publish'; // Disable comments and pings for this post. add_filter( 'comments_open', '__return_false' ); add_filter( 'pings_open', '__return_false' ); return $posts; } /** * Handle validation for autosave preview request * * @since 4.7.0 */ public function handle_autosave_nonce_validation() { if ( ! $this->is_frame_nonce_valid() ) { wp_die( esc_html__( 'Sorry, you are not allowed to preview drafts.', 'jetpack' ) ); } add_filter( 'the_preview', '_set_preview' ); } } Jetpack_Frame_Nonce_Preview::get_instance();
projects/plugins/jetpack/class.jetpack-heartbeat.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Jetpack Heartbeat. * * @package automattic/jetpack */ use Automattic\Jetpack\Connection\Manager; use Automattic\Jetpack\Heartbeat; /** * Jetpack Heartbeat. */ class Jetpack_Heartbeat { /** * Holds the singleton instance of this class * * @since 2.3.3 * @var Jetpack_Heartbeat */ private static $instance = false; /** * Holds the singleton instance of the proxied class * * @since 8.9.0 * @var Automattic\Jetpack\Heartbeat */ private static $proxied_instance = false; /** * Singleton * * @since 2.3.3 * @static * @return Jetpack_Heartbeat */ public static function init() { if ( ! self::$instance ) { self::$instance = new Jetpack_Heartbeat(); self::$proxied_instance = Heartbeat::init(); } return self::$instance; } /** * Constructor for singleton * * @since 2.3.3 */ private function __construct() { add_filter( 'jetpack_heartbeat_stats_array', array( $this, 'add_stats_to_heartbeat' ) ); } /** * Generates heartbeat stats data. * * @param string $prefix Prefix to add before stats identifier. * * @return array The stats array. */ public static function generate_stats_array( $prefix = '' ) { $return = array(); $return[ "{$prefix}version" ] = JETPACK__VERSION; $return[ "{$prefix}wp-version" ] = get_bloginfo( 'version' ); $return[ "{$prefix}php-version" ] = PHP_VERSION; $return[ "{$prefix}branch" ] = (float) JETPACK__VERSION; $return[ "{$prefix}wp-branch" ] = (float) get_bloginfo( 'version' ); $return[ "{$prefix}php-branch" ] = (float) PHP_VERSION; $return[ "{$prefix}public" ] = Jetpack_Options::get_option( 'public' ); $return[ "{$prefix}ssl" ] = Jetpack::permit_ssl(); $return[ "{$prefix}is-https" ] = is_ssl() ? 'https' : 'http'; $return[ "{$prefix}language" ] = get_bloginfo( 'language' ); $return[ "{$prefix}charset" ] = get_bloginfo( 'charset' ); $return[ "{$prefix}is-multisite" ] = is_multisite() ? 'multisite' : 'singlesite'; $return[ "{$prefix}identitycrisis" ] = Jetpack::check_identity_crisis() ? 'yes' : 'no'; $return[ "{$prefix}plugins" ] = implode( ',', Jetpack::get_active_plugins() ); if ( function_exists( 'get_mu_plugins' ) ) { $return[ "{$prefix}mu-plugins" ] = implode( ',', array_keys( get_mu_plugins() ) ); } $return[ "{$prefix}manage-enabled" ] = true; if ( function_exists( 'get_space_used' ) ) { // Only available in multisite. $space_used = get_space_used(); } else { // This is the same as `get_space_used`, except it does not apply the short-circuit filter. $upload_dir = wp_upload_dir(); $space_used = get_dirsize( $upload_dir['basedir'] ) / MB_IN_BYTES; } $return[ "{$prefix}space-used" ] = $space_used; $xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() ); if ( $xmlrpc_errors ) { $return[ "{$prefix}xmlrpc-errors" ] = implode( ',', array_keys( $xmlrpc_errors ) ); Jetpack_Options::delete_option( 'xmlrpc_errors' ); } // Missing the connection owner? $connection_manager = new Manager(); $return[ "{$prefix}missing-owner" ] = $connection_manager->is_missing_connection_owner(); // is-multi-network can have three values, `single-site`, `single-network`, and `multi-network`. $return[ "{$prefix}is-multi-network" ] = 'single-site'; if ( is_multisite() ) { $return[ "{$prefix}is-multi-network" ] = Jetpack::is_multi_network() ? 'multi-network' : 'single-network'; } if ( ! empty( $_SERVER['SERVER_ADDR'] ) || ! empty( $_SERVER['LOCAL_ADDR'] ) ) { $ip = ! empty( $_SERVER['SERVER_ADDR'] ) ? wp_unslash( $_SERVER['SERVER_ADDR'] ) : wp_unslash( $_SERVER['LOCAL_ADDR'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized just below. $ip_arr = array_map( 'intval', explode( '.', $ip ) ); if ( 4 === count( $ip_arr ) ) { $return[ "{$prefix}ip-2-octets" ] = implode( '.', array_slice( $ip_arr, 0, 2 ) ); } } foreach ( Jetpack::get_available_modules() as $slug ) { $return[ "{$prefix}module-{$slug}" ] = Jetpack::is_module_active( $slug ) ? 'on' : 'off'; } return $return; } /** * Add Jetpack Stats array to Heartbeat if Jetpack is connected * * @since 8.9.0 * * @param array $stats Jetpack Heartbeat stats. * @return array $stats */ public function add_stats_to_heartbeat( $stats ) { if ( ! Jetpack::is_connection_ready() ) { return $stats; } $jetpack_stats = self::generate_stats_array(); return array_merge( $stats, $jetpack_stats ); } }
projects/plugins/jetpack/functions.global.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * This file is meant to be the home for any generic & reusable functions * that can be accessed anywhere within Jetpack. * * This file is loaded whether Jetpack is active. * * Please namespace with jetpack_ * * @package automattic/jetpack */ use Automattic\Jetpack\Connection\Client; use Automattic\Jetpack\Redirect; use Automattic\Jetpack\Status\Host; use Automattic\Jetpack\Sync\Functions; // Disable direct access. if ( ! defined( 'ABSPATH' ) ) { exit; } require_once __DIR__ . '/functions.is-mobile.php'; /** * Hook into Core's _deprecated_function * Add more details about when a deprecated function will be removed. * * @since 8.8.0 * * @param string $function The function that was called. * @param string $replacement Optional. The function that should have been called. Default null. * @param string $version The version of Jetpack that deprecated the function. */ function jetpack_deprecated_function( $function, $replacement, $version ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable // Bail early for non-Jetpack deprecations. if ( ! str_starts_with( $version, 'jetpack-' ) ) { return; } // Look for when a function will be removed based on when it was deprecated. $removed_version = jetpack_get_future_removed_version( $version ); // If we could find a version, let's log a message about when removal will happen. if ( ! empty( $removed_version ) && ( defined( 'WP_DEBUG' ) && WP_DEBUG ) /** This filter is documented in core/src/wp-includes/functions.php */ && apply_filters( 'deprecated_function_trigger_error', true ) ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log sprintf( /* Translators: 1. Function name. 2. Jetpack version number. */ __( 'The %1$s function will be removed from the Jetpack plugin in version %2$s.', 'jetpack' ), $function, $removed_version ) ); } } add_action( 'deprecated_function_run', 'jetpack_deprecated_function', 10, 3 ); /** * Hook into Core's _deprecated_file * Add more details about when a deprecated file will be removed. * * @since 8.8.0 * * @param string $file The file that was called. * @param string $replacement The file that should have been included based on ABSPATH. * @param string $version The version of WordPress that deprecated the file. * @param string $message A message regarding the change. */ function jetpack_deprecated_file( $file, $replacement, $version, $message ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable // Bail early for non-Jetpack deprecations. if ( ! str_starts_with( $version, 'jetpack-' ) ) { return; } // Look for when a file will be removed based on when it was deprecated. $removed_version = jetpack_get_future_removed_version( $version ); // If we could find a version, let's log a message about when removal will happen. if ( ! empty( $removed_version ) && ( defined( 'WP_DEBUG' ) && WP_DEBUG ) /** This filter is documented in core/src/wp-includes/functions.php */ && apply_filters( 'deprecated_file_trigger_error', true ) ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log sprintf( /* Translators: 1. File name. 2. Jetpack version number. */ __( 'The %1$s file will be removed from the Jetpack plugin in version %2$s.', 'jetpack' ), $file, $removed_version ) ); } } add_action( 'deprecated_file_included', 'jetpack_deprecated_file', 10, 4 ); /** * Get the major version number of Jetpack 6 months after provided version. * Useful to indicate when a deprecated function will be removed from Jetpack. * * @since 8.8.0 * * @param string $version The version of WordPress that deprecated the function. * * @return bool|float Return a Jetpack Major version number, or false. */ function jetpack_get_future_removed_version( $version ) { /* * Extract the version number from a deprecation notice. * (let's only keep the first decimal, e.g. 8.8 and not 8.8.0) */ preg_match( '#(([0-9]+\.([0-9]+))(?:\.[0-9]+)*)#', $version, $matches ); if ( isset( $matches[2] ) && isset( $matches[3] ) ) { $deprecated_version = (float) $matches[2]; $deprecated_minor = (float) $matches[3]; /* * If the detected minor version number * (e.g. "7" in "8.7") * is higher than 9, we know the version number is malformed. * Jetpack does not use semver yet. * Bail. */ if ( 10 <= $deprecated_minor ) { return false; } // We'll remove the function from the code 6 months later, thus 6 major versions later. $removed_version = $deprecated_version + 0.6; return (float) $removed_version; } return false; } /** * Determine if this site is an WoA site or not by looking for presence of the wpcomsh plugin. * * @since 4.8.1 * @deprecated 10.3.0 * * @return bool */ function jetpack_is_atomic_site() { jetpack_deprecated_function( __FUNCTION__, 'Automattic/Jetpack/Status/Host::is_woa_site', 'jetpack-10.3.0' ); return ( new Host() )->is_woa_site(); } /** * Register post type for migration. * * @since 5.2 */ function jetpack_register_migration_post_type() { register_post_type( 'jetpack_migration', array( 'supports' => array(), 'taxonomies' => array(), 'hierarchical' => false, 'public' => false, 'has_archive' => false, 'can_export' => true, ) ); } /** * Checks whether the Post DB threat currently exists on the site. * * @since 12.0 * * @param string $option_name Option name. * * @return WP_Post|bool */ function jetpack_migration_post_exists( $option_name ) { $query = new WP_Query( array( 'post_type' => 'jetpack_migration', 'title' => $option_name, 'post_status' => 'all', 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $query->post ) ) { return $query->post; } return false; } /** * Stores migration data in the database. * * @since 5.2 * * @param string $option_name Option name. * @param bool $option_value Option value. * * @return int|WP_Error */ function jetpack_store_migration_data( $option_name, $option_value ) { jetpack_register_migration_post_type(); $insert = array( 'post_title' => $option_name, 'post_content_filtered' => $option_value, 'post_type' => 'jetpack_migration', 'post_date' => gmdate( 'Y-m-d H:i:s', time() ), ); $migration_post = jetpack_migration_post_exists( $option_name ); if ( $migration_post ) { $insert['ID'] = $migration_post->ID; } return wp_insert_post( $insert, true ); } /** * Retrieves legacy image widget data. * * @since 5.2 * * @param string $option_name Option name. * * @return mixed|null */ function jetpack_get_migration_data( $option_name ) { $post = jetpack_migration_post_exists( $option_name ); return null !== $post ? maybe_unserialize( $post->post_content_filtered ) : null; } /** * Prints a TOS blurb used throughout the connection prompts. * * @since 5.3 * * @echo string */ function jetpack_render_tos_blurb() { printf( wp_kses( /* Translators: placeholders are links. */ __( 'By clicking the <strong>Set up Jetpack</strong> button, you agree to our <a href="%1$s" target="_blank" rel="noopener noreferrer">Terms of Service</a> and to <a href="%2$s" target="_blank" rel="noopener noreferrer">share details</a> with WordPress.com.', 'jetpack' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), 'strong' => true, ) ), esc_url( Redirect::get_url( 'wpcom-tos' ) ), esc_url( Redirect::get_url( 'jetpack-support-what-data-does-jetpack-sync' ) ) ); } /** * Intervene upgrade process so Jetpack themes are downloaded with credentials. * * @since 5.3 * * @param bool $preempt Whether to preempt an HTTP request's return value. Default false. * @param array $r HTTP request arguments. * @param string $url The request URL. * * @return array|bool|WP_Error */ function jetpack_theme_update( $preempt, $r, $url ) { if ( 0 === stripos( $url, JETPACK__WPCOM_JSON_API_BASE . '/rest/v1/themes/download' ) ) { $file = $r['filename']; if ( ! $file ) { return new WP_Error( 'problem_creating_theme_file', esc_html__( 'Problem creating file for theme download', 'jetpack' ) ); } $theme = pathinfo( wp_parse_url( $url, PHP_URL_PATH ), PATHINFO_FILENAME ); // Remove filter to avoid endless loop since wpcom_json_api_request_as_blog uses this too. remove_filter( 'pre_http_request', 'jetpack_theme_update' ); $result = Client::wpcom_json_api_request_as_blog( "themes/download/$theme.zip", '1.1', array( 'stream' => true, 'filename' => $file, ) ); if ( 200 !== wp_remote_retrieve_response_code( $result ) ) { return new WP_Error( 'problem_fetching_theme', esc_html__( 'Problem downloading theme', 'jetpack' ) ); } return $result; } return $preempt; } /** * Add the filter when a upgrade is going to be downloaded. * * @since 5.3 * * @param bool $reply Whether to bail without returning the package. Default false. * * @return bool */ function jetpack_upgrader_pre_download( $reply ) { add_filter( 'pre_http_request', 'jetpack_theme_update', 10, 3 ); return $reply; } add_filter( 'upgrader_pre_download', 'jetpack_upgrader_pre_download' ); /** * Wraps data in a way so that we can distinguish between objects and array and also prevent object recursion. * * @since 6.1.0 * @deprecated Automattic\Jetpack\Sync\Functions::json_wrap * * @param array|obj $any Source data to be cleaned up. * @param array $seen_nodes Built array of nodes. * * @return array */ function jetpack_json_wrap( &$any, $seen_nodes = array() ) { _deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\Jetpack\Sync\Functions' ); return Functions::json_wrap( $any, $seen_nodes ); } /** * Checks if the mime_content_type function is available and return it if so. * * The function mime_content_type is enabled by default in PHP, but can be disabled. We attempt to * enforce this via composer.json, but that won't be checked in majority of cases where * this would be happening. * * @since 7.8.0 * * @param string $file File location. * * @return string|false MIME type or false if functionality is not available. */ function jetpack_mime_content_type( $file ) { if ( function_exists( 'mime_content_type' ) ) { return mime_content_type( $file ); } return false; } /** * Checks that the mime type of the specified file is among those in a filterable list of mime types. * * @since 7.8.0 * * @param string $file Path to file to get its mime type. * * @return bool */ function jetpack_is_file_supported_for_sideloading( $file ) { $type = jetpack_mime_content_type( $file ); if ( ! $type ) { return false; } /** * Filter the list of supported mime types for media sideloading. * * @since 4.0.0 * * @module json-api * * @param array $supported_mime_types Array of the supported mime types for media sideloading. */ $supported_mime_types = apply_filters( 'jetpack_supported_media_sideload_types', array( 'image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp', 'video/quicktime', 'video/mp4', 'video/mpeg', 'video/ogg', 'video/3gpp', 'video/3gpp2', 'video/h261', 'video/h262', 'video/h264', 'video/x-msvideo', 'video/x-ms-wmv', 'video/x-ms-asf', ) ); // If the type returned was not an array as expected, then we know we don't have a match. if ( ! is_array( $supported_mime_types ) ) { return false; } return in_array( $type, $supported_mime_types, true ); } /** * Go through headers and get a list of Vary headers to add, * including a Vary Accept header if necessary. * * @since 12.2 * * @param array $headers The headers to be sent. * * @return array $vary_header_parts Vary Headers to be sent. */ function jetpack_get_vary_headers( $headers = array() ) { $vary_header_parts = array( 'accept', 'content-type' ); foreach ( $headers as $header ) { // Check for a Vary header. if ( ! str_starts_with( strtolower( $header ), 'vary:' ) ) { continue; } // If the header is a wildcard, we'll return that. if ( str_contains( $header, '*' ) ) { $vary_header_parts = array( '*' ); break; } // Remove the Vary: part of the header. $header = preg_replace( '/^vary\:\s?/i', '', $header ); // Remove spaces from the header. $header = str_replace( ' ', '', $header ); // Break the header into parts. $header_parts = explode( ',', strtolower( $header ) ); // Build an array with the Accept header and what was already there. $vary_header_parts = array_values( array_unique( array_merge( $vary_header_parts, $header_parts ) ) ); } return $vary_header_parts; } /** * Determine whether the current request is for accessing the frontend. * Also update Vary headers to indicate that the response may vary by Accept header. * * @return bool True if it's a frontend request, false otherwise. */ function jetpack_is_frontend() { $is_frontend = true; $is_varying_request = true; if ( is_admin() || wp_doing_ajax() || wp_is_jsonp_request() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST ) || ( defined( 'WP_CLI' ) && WP_CLI ) ) { $is_frontend = false; $is_varying_request = false; } elseif ( wp_is_json_request() || wp_is_xml_request() ) { $is_frontend = false; } /* * Check existing headers for the request. * If there is no existing Vary Accept header, add one. */ if ( $is_varying_request && ! headers_sent() ) { $headers = headers_list(); $vary_header_parts = jetpack_get_vary_headers( $headers ); header( 'Vary: ' . implode( ', ', $vary_header_parts ) ); } /** * Filter whether the current request is for accessing the frontend. * * @since 9.0.0 * * @param bool $is_frontend Whether the current request is for accessing the frontend. */ return (bool) apply_filters( 'jetpack_is_frontend', $is_frontend ); } /** * Build a list of Mastodon instance hosts. * That list can be extended via a filter. * * @since 11.8 * * @return array */ function jetpack_mastodon_get_instance_list() { $mastodon_instance_list = array( // Regex pattern to match any .tld for the mastodon host name. '#https?:\/\/(www\.)?mastodon\.(\w+)(\.\w+)?#', // Regex pattern to match any .tld for the mstdn host name. '#https?:\/\/(www\.)?mstdn\.(\w+)(\.\w+)?#', 'counter.social', 'fosstodon.org', 'gc2.jp', 'hachyderm.io', 'infosec.exchange', 'mas.to', 'pawoo.net', ); /** * Filter the list of Mastodon instances. * * @since 11.8 * * @module widgets, theme-tools * * @param array $mastodon_instance_list Array of Mastodon instances. */ return (array) apply_filters( 'jetpack_mastodon_instance_list', $mastodon_instance_list ); }
projects/plugins/jetpack/class.jetpack-idc.php
<?php // phpcs:disable Squiz.Commenting.FileComment.SpacingAfterComment /** * Identity Crisis handler. * * @deprecated 9.8.0. Functionality moved to the automattic/identity-crisis package. * @package automattic/jetpack */ // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped _deprecated_file( basename( __FILE__ ), 'jetpack-9.8' );
projects/plugins/jetpack/class.jetpack-post-images.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Useful for finding an image to display alongside/in representation of a specific post. * * @package automattic/jetpack */ use Automattic\Jetpack\Image_CDN\Image_CDN_Core; /** * Useful for finding an image to display alongside/in representation of a specific post. * * Includes a few different methods, all of which return a similar-format array containing * details of any images found. Everything can (should) be called statically, it's just a * function-bucket. You can also call Jetpack_PostImages::get_image() to cycle through all of the methods until * one of them finds something useful. * * This file is included verbatim in Jetpack */ class Jetpack_PostImages { /** * If a slideshow is embedded within a post, then parse out the images involved and return them * * @param int $post_id Post ID. * @param int $width Image width. * @param int $height Image height. * @return array Images. */ public static function from_slideshow( $post_id, $width = 200, $height = 200 ) { $images = array(); $post = get_post( $post_id ); if ( ! $post ) { return $images; } if ( ! empty( $post->post_password ) ) { return $images; } if ( false === has_shortcode( $post->post_content, 'slideshow' ) ) { return $images; // no slideshow - bail. } $permalink = get_permalink( $post->ID ); // Mechanic: Somebody set us up the bomb. $old_post = $GLOBALS['post']; $GLOBALS['post'] = $post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $old_shortcodes = $GLOBALS['shortcode_tags']; $GLOBALS['shortcode_tags'] = array( 'slideshow' => $old_shortcodes['slideshow'] ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited // Find all the slideshows. preg_match_all( '/' . get_shortcode_regex() . '/sx', $post->post_content, $slideshow_matches, PREG_SET_ORDER ); ob_start(); // The slideshow shortcode handler calls wp_print_scripts and wp_print_styles... not too happy about that. foreach ( $slideshow_matches as $slideshow_match ) { $slideshow = do_shortcode_tag( $slideshow_match ); $pos = stripos( $slideshow, 'jetpack-slideshow' ); if ( false === $pos ) { // must be something wrong - or we changed the output format in which case none of the following will work. continue; } $start = strpos( $slideshow, '[', $pos ); $end = strpos( $slideshow, ']', $start ); $post_images = json_decode( wp_specialchars_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ), ENT_QUOTES ) ); // parse via JSON // If the JSON didn't decode don't try and act on it. if ( is_array( $post_images ) ) { foreach ( $post_images as $post_image ) { $post_image_id = absint( $post_image->id ); if ( ! $post_image_id ) { continue; } $meta = wp_get_attachment_metadata( $post_image_id ); // Must be larger than 200x200 (or user-specified). if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) { continue; } if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) { continue; } $url = wp_get_attachment_url( $post_image_id ); $images[] = array( 'type' => 'image', 'from' => 'slideshow', 'src' => $url, 'src_width' => $meta['width'], 'src_height' => $meta['height'], 'href' => $permalink, ); } } } ob_end_clean(); // Operator: Main screen turn on. $GLOBALS['shortcode_tags'] = $old_shortcodes; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $GLOBALS['post'] = $old_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited return $images; } /** * Filtering out images with broken URL from galleries. * * @param array $galleries Galleries. * @return array $filtered_galleries */ public static function filter_gallery_urls( $galleries ) { $filtered_galleries = array(); foreach ( $galleries as $this_gallery ) { if ( ! isset( $this_gallery['src'] ) ) { continue; } $ids = isset( $this_gallery['ids'] ) ? explode( ',', $this_gallery['ids'] ) : array(); // Make sure 'src' array isn't associative and has no holes. $this_gallery['src'] = array_values( $this_gallery['src'] ); foreach ( $this_gallery['src'] as $idx => $src_url ) { if ( filter_var( $src_url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED ) === false ) { unset( $this_gallery['src'][ $idx ] ); unset( $ids[ $idx ] ); } } if ( isset( $this_gallery['ids'] ) ) { $this_gallery['ids'] = implode( ',', $ids ); } // Remove any holes we introduced. $this_gallery['src'] = array_values( $this_gallery['src'] ); $filtered_galleries[] = $this_gallery; } return $filtered_galleries; } /** * If a gallery is detected, then get all the images from it. * * @param int $post_id Post ID. * @param int $width Minimum image width to consider. * @param int $height Minimum image height to consider. * @return array Images. */ public static function from_gallery( $post_id, $width = 200, $height = 200 ) { $images = array(); $post = get_post( $post_id ); if ( ! $post ) { return $images; } if ( ! empty( $post->post_password ) ) { return $images; } add_filter( 'get_post_galleries', array( __CLASS__, 'filter_gallery_urls' ), 999999 ); $permalink = get_permalink( $post->ID ); /** * Juggle global post object because the gallery shortcode uses the * global object. * * See core ticket: * https://core.trac.wordpress.org/ticket/39304 */ // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited if ( isset( $GLOBALS['post'] ) ) { $juggle_post = $GLOBALS['post']; $GLOBALS['post'] = $post; $galleries = get_post_galleries( $post->ID, false ); $GLOBALS['post'] = $juggle_post; } else { $GLOBALS['post'] = $post; $galleries = get_post_galleries( $post->ID, false ); unset( $GLOBALS['post'] ); } // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited foreach ( $galleries as $gallery ) { if ( ! empty( $gallery['ids'] ) ) { $image_ids = explode( ',', $gallery['ids'] ); $image_size = isset( $gallery['size'] ) ? $gallery['size'] : 'thumbnail'; foreach ( $image_ids as $image_id ) { $image = wp_get_attachment_image_src( $image_id, $image_size ); $meta = wp_get_attachment_metadata( $image_id ); if ( isset( $gallery['type'] ) && 'slideshow' === $gallery['type'] ) { // Must be larger than 200x200 (or user-specified). if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) { continue; } if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) { continue; } } if ( ! empty( $image[0] ) ) { list( $raw_src ) = explode( '?', $image[0] ); // pull off any Query string (?w=250). $raw_src = wp_specialchars_decode( $raw_src ); // rawify it. $raw_src = esc_url_raw( $raw_src ); // clean it. $images[] = array( 'type' => 'image', 'from' => 'gallery', 'src' => $raw_src, 'src_width' => $meta['width'] ?? 0, 'src_height' => $meta['height'] ?? 0, 'href' => $permalink, 'alt_text' => self::get_alt_text( $image_id ), ); } } } elseif ( ! empty( $gallery['src'] ) ) { foreach ( $gallery['src'] as $src ) { list( $raw_src ) = explode( '?', $src ); // pull off any Query string (?w=250). $raw_src = wp_specialchars_decode( $raw_src ); // rawify it. $raw_src = esc_url_raw( $raw_src ); // clean it. $images[] = array( 'type' => 'image', 'from' => 'gallery', 'src' => $raw_src, 'href' => $permalink, ); } } } return $images; } /** * Get attachment images for a specified post and return them. Also make sure * their dimensions are at or above a required minimum. * * @param int $post_id The post ID to check. * @param int $width Image width. * @param int $height Image height. * @return array Containing details of the image, or empty array if none. */ public static function from_attachment( $post_id, $width = 200, $height = 200 ) { $images = array(); $post = get_post( $post_id ); if ( ! empty( $post->post_password ) ) { return $images; } $post_images = get_posts( array( 'post_parent' => $post_id, // Must be children of post. 'numberposts' => 5, // No more than 5. 'post_type' => 'attachment', // Must be attachments. 'post_mime_type' => 'image', // Must be images. 'suppress_filters' => false, ) ); if ( ! $post_images ) { return $images; } $permalink = get_permalink( $post_id ); foreach ( $post_images as $post_image ) { $current_image = self::get_attachment_data( $post_image->ID, $permalink, $width, $height ); if ( false !== $current_image ) { $images[] = $current_image; } } /* * We only want to pass back attached images that were actually inserted. * We can load up all the images found in the HTML source and then * compare URLs to see if an image is attached AND inserted. */ $html_images = self::from_html( $post_id ); $inserted_images = array(); foreach ( $html_images as $html_image ) { $src = wp_parse_url( $html_image['src'] ); if ( ! $src ) { continue; } // strip off any query strings from src. if ( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) { $inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path']; } elseif ( ! empty( $src['host'] ) ) { $inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] ); } else { $inserted_images[] = site_url( '/' ) . $src['path']; } } foreach ( $images as $i => $image ) { if ( ! in_array( $image['src'], $inserted_images, true ) ) { unset( $images[ $i ] ); } } return $images; } /** * Check if a Featured Image is set for this post, and return it in a similar * format to the other images?_from_*() methods. * * @param int $post_id The post ID to check. * @param int $width Image width. * @param int $height Image height. * @return array containing details of the Featured Image, or empty array if none. */ public static function from_thumbnail( $post_id, $width = 200, $height = 200 ) { $images = array(); $post = get_post( $post_id ); if ( ! empty( $post->post_password ) ) { return $images; } if ( 'attachment' === get_post_type( $post ) && wp_attachment_is_image( $post ) ) { $thumb = $post_id; } else { $thumb = get_post_thumbnail_id( $post ); } if ( $thumb ) { $meta = wp_get_attachment_metadata( $thumb ); // Must be larger than requested minimums. if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) { return $images; } if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) { return $images; } $too_big = ( ( ! empty( $meta['width'] ) && $meta['width'] > 1200 ) || ( ! empty( $meta['height'] ) && $meta['height'] > 1200 ) ); if ( $too_big && ( ( method_exists( 'Jetpack', 'is_module_active' ) && Jetpack::is_module_active( 'photon' ) ) || ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) ) { $img_src = wp_get_attachment_image_src( $thumb, array( 1200, 1200 ) ); } else { $img_src = wp_get_attachment_image_src( $thumb, 'full' ); } if ( ! is_array( $img_src ) ) { // If wp_get_attachment_image_src returns false but we know that there should be an image that could be used. // we try a bit harder and user the data that we have. $thumb_post_data = get_post( $thumb ); $img_src = array( $thumb_post_data->guid ?? null, $meta['width'], $meta['height'] ); } // Let's try to use the postmeta if we can, since it seems to be // more reliable if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $featured_image = get_post_meta( $post->ID, '_jetpack_featured_image' ); if ( $featured_image ) { $url = $featured_image[0]; } else { $url = $img_src[0]; } } else { $url = $img_src[0]; } $images = array( array( // Other methods below all return an array of arrays. 'type' => 'image', 'from' => 'thumbnail', 'src' => $url, 'src_width' => $img_src[1], 'src_height' => $img_src[2], 'href' => get_permalink( $thumb ), 'alt_text' => self::get_alt_text( $thumb ), ), ); } if ( empty( $images ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) { $meta_thumbnail = get_post_meta( $post_id, '_jetpack_post_thumbnail', true ); if ( ! empty( $meta_thumbnail ) ) { if ( ! isset( $meta_thumbnail['width'] ) || $meta_thumbnail['width'] < $width ) { return $images; } if ( ! isset( $meta_thumbnail['height'] ) || $meta_thumbnail['height'] < $height ) { return $images; } $images = array( array( // Other methods below all return an array of arrays. 'type' => 'image', 'from' => 'thumbnail', 'src' => $meta_thumbnail['URL'], 'src_width' => $meta_thumbnail['width'], 'src_height' => $meta_thumbnail['height'], 'href' => $meta_thumbnail['URL'], 'alt_text' => self::get_alt_text( $thumb ), ), ); } } return $images; } /** * Get images from Gutenberg Image blocks. * * @since 6.9.0 * * @param mixed $html_or_id The HTML string to parse for images, or a post id. * @param int $width Minimum Image width. * @param int $height Minimum Image height. */ public static function from_blocks( $html_or_id, $width = 200, $height = 200 ) { $images = array(); $html_info = self::get_post_html( $html_or_id ); if ( empty( $html_info['html'] ) ) { return $images; } // Look for block information in the HTML. $blocks = parse_blocks( $html_info['html'] ); if ( empty( $blocks ) ) { return $images; } /* * Let's loop through our blocks. * Some blocks may include some other blocks. Let's go 2 levels deep to look for blocks * that we support and that may include images (see get_images_from_block) * * @to-do: instead of looping manually (that's a lot of if and loops), search recursively instead. */ foreach ( $blocks as $block ) { if ( ! self::is_nested_block( $block ) || 'core/media-text' === $block['blockName'] ) { $images = self::get_images_from_block( $images, $block, $html_info, $width, $height ); } else { foreach ( $block['innerBlocks'] as $inner_block ) { if ( ! self::is_nested_block( $inner_block ) ) { $images = self::get_images_from_block( $images, $inner_block, $html_info, $width, $height ); } else { foreach ( $inner_block['innerBlocks'] as $inner_inner_block ) { $images = self::get_images_from_block( $images, $inner_inner_block, $html_info, $width, $height ); } } } } } /** * Returning a filtered array because get_attachment_data returns false * for unsuccessful attempts. */ return array_filter( $images ); } /** * Very raw -- just parse the HTML and pull out any/all img tags and return their src * * @param mixed $html_or_id The HTML string to parse for images, or a post id. * @param int $width Minimum Image width. * @param int $height Minimum Image height. * * @uses DOMDocument * * @return array containing images */ public static function from_html( $html_or_id, $width = 200, $height = 200 ) { $images = array(); $html_info = self::get_post_html( $html_or_id ); if ( empty( $html_info['html'] ) ) { return $images; } // Do not go any further if DOMDocument is disabled on the server. if ( ! class_exists( 'DOMDocument' ) ) { return $images; } // Let's grab all image tags from the HTML. $dom_doc = new DOMDocument(); // The @ is not enough to suppress errors when dealing with libxml, // we have to tell it directly how we want to handle errors. libxml_use_internal_errors( true ); @$dom_doc->loadHTML( $html_info['html'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged libxml_use_internal_errors( false ); $image_tags = $dom_doc->getElementsByTagName( 'img' ); // For each image Tag, make sure it can be added to the $images array, and add it. foreach ( $image_tags as $image_tag ) { $img_src = $image_tag->getAttribute( 'src' ); if ( empty( $img_src ) ) { continue; } // Do not grab smiley images that were automatically created by WP when entering text smilies. if ( stripos( $img_src, '/smilies/' ) ) { continue; } // First try to get the width and height from the img attributes, but if they are not set, check to see if they are specified in the url. WordPress automatically names files like foo-1024x768.jpg during the upload process $width = (int) $image_tag->getAttribute( 'width' ); $height = (int) $image_tag->getAttribute( 'height' ); if ( 0 === $width && 0 === $height ) { preg_match( '/-([0-9]{1,5})x([0-9]{1,5})\.(?:jpg|jpeg|png|gif|webp)$/i', $img_src, $matches ); if ( ! empty( $matches[1] ) ) { $width = (int) $matches[1]; } if ( ! empty( $matches[2] ) ) { $height = (int) $matches[2]; } } // If width and height are still 0, try to get the id of the image from the class, e.g. wp-image-1234 if ( 0 === $width && 0 === $height ) { preg_match( '/wp-image-([0-9]+)/', $image_tag->getAttribute( 'class' ), $matches ); if ( ! empty( $matches[1] ) ) { $attachment_id = $matches[1]; $meta = wp_get_attachment_metadata( $attachment_id ); $height = $meta['height'] ?? 0; $width = $meta['width'] ?? 0; } } $meta = array( 'width' => $width, 'height' => $height, 'alt_text' => $image_tag->getAttribute( 'alt' ), ); /** * Filters the switch to ignore minimum image size requirements. Can be used * to add custom logic to image dimensions, like only enforcing one of the dimensions, * or disabling it entirely. * * @since 6.4.0 * * @param bool $ignore Should the image dimensions be ignored? * @param array $meta Array containing image dimensions parsed from the markup. */ $ignore_dimensions = apply_filters( 'jetpack_postimages_ignore_minimum_dimensions', false, $meta ); // Must be larger than 200x200 (or user-specified). if ( ! $ignore_dimensions && ( empty( $meta['width'] ) || empty( $meta['height'] ) || $meta['width'] < $width || $meta['height'] < $height ) ) { continue; } $image = array( 'type' => 'image', 'from' => 'html', 'src' => $img_src, 'src_width' => $meta['width'], 'src_height' => $meta['height'], 'href' => $html_info['post_url'], ); if ( ! empty( $meta['alt_text'] ) ) { $image['alt_text'] = $meta['alt_text']; } $images[] = $image; } return $images; } /** * Data from blavatar. * * @param int $post_id The post ID to check. * @param int $size Size. * @return array containing details of the image, or empty array if none. */ public static function from_blavatar( $post_id, $size = 96 ) { $permalink = get_permalink( $post_id ); if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) { $domain = blavatar_domain( $permalink ); if ( ! blavatar_exists( $domain ) ) { return array(); } $url = blavatar_url( $domain, 'img', $size ); } else { $url = get_site_icon_url( $size ); if ( ! $url ) { return array(); } } return array( array( 'type' => 'image', 'from' => 'blavatar', 'src' => $url, 'src_width' => $size, 'src_height' => $size, 'href' => $permalink, 'alt_text' => '', ), ); } /** * Gets a post image from the author avatar. * * @param int $post_id The post ID to check. * @param int $size The size of the avatar to get. * @param string $default The default image to use. * @return array containing details of the image, or empty array if none. */ public static function from_gravatar( $post_id, $size = 96, $default = false ) { $post = get_post( $post_id ); $permalink = get_permalink( $post_id ); if ( ! $post instanceof WP_Post ) { return array(); } if ( function_exists( 'wpcom_get_avatar_url' ) ) { $url = wpcom_get_avatar_url( $post->post_author, $size, $default, true ); if ( $url && is_array( $url ) ) { $url = $url[0]; } } else { $url = get_avatar_url( $post->post_author, array( 'size' => $size, 'default' => $default, ) ); } return array( array( 'type' => 'image', 'from' => 'gravatar', 'src' => $url, 'src_width' => $size, 'src_height' => $size, 'href' => $permalink, 'alt_text' => '', ), ); } /** * Run through the different methods that we have available to try to find a single good * display image for this post. * * @param int $post_id Post ID. * @param array $args Other arguments (currently width and height required for images where possible to determine). * @return array|null containing details of the best image to be used, or null if no image is found. */ public static function get_image( $post_id, $args = array() ) { $image = null; /** * Fires before we find a single good image for a specific post. * * @since 2.2.0 * * @param int $post_id Post ID. */ do_action( 'jetpack_postimages_pre_get_image', $post_id ); $media = self::get_images( $post_id, $args ); if ( is_array( $media ) ) { foreach ( $media as $item ) { if ( 'image' === $item['type'] ) { $image = $item; break; } } } /** * Fires after we find a single good image for a specific post. * * @since 2.2.0 * * @param int $post_id Post ID. */ do_action( 'jetpack_postimages_post_get_image', $post_id ); return $image; } /** * Get an array containing a collection of possible images for this post, stopping once we hit a method * that returns something useful. * * @param int $post_id Post ID. * @param array $args Optional args, see defaults list for details. * @return array containing images that would be good for representing this post */ public static function get_images( $post_id, $args = array() ) { // Figure out which image to attach to this post. $media = array(); /** * Filters the array of images that would be good for a specific post. * This filter is applied before options ($args) filter the original array. * * @since 2.0.0 * * @param array $media Array of images that would be good for a specific post. * @param int $post_id Post ID. * @param array $args Array of options to get images. */ $media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args ); if ( $media ) { return $media; } $defaults = array( 'width' => 200, // Required minimum width (if possible to determine). 'height' => 200, // Required minimum height (if possible to determine). 'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack. 'avatar_size' => 96, // Used for both Grav and Blav. 'gravatar_default' => false, // Default image to use if we end up with no Gravatar. 'from_thumbnail' => true, // Use these flags to specify which methods to use to find an image. 'from_slideshow' => true, 'from_gallery' => true, 'from_attachment' => true, 'from_blocks' => true, 'from_html' => true, 'html_content' => '', // HTML string to pass to from_html(). ); $args = wp_parse_args( $args, $defaults ); $media = array(); if ( $args['from_thumbnail'] ) { $media = self::from_thumbnail( $post_id, $args['width'], $args['height'] ); } if ( ! $media && $args['from_slideshow'] ) { $media = self::from_slideshow( $post_id, $args['width'], $args['height'] ); } if ( ! $media && $args['from_gallery'] ) { $media = self::from_gallery( $post_id ); } if ( ! $media && $args['from_attachment'] ) { $media = self::from_attachment( $post_id, $args['width'], $args['height'] ); } if ( ! $media && $args['from_blocks'] ) { if ( empty( $args['html_content'] ) ) { $media = self::from_blocks( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content. } else { $media = self::from_blocks( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that. } } if ( ! $media && $args['from_html'] ) { if ( empty( $args['html_content'] ) ) { $media = self::from_html( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content. } else { $media = self::from_html( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that. } } if ( ! $media && $args['fallback_to_avatars'] ) { $media = self::from_blavatar( $post_id, $args['avatar_size'] ); if ( ! $media ) { $media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] ); } } /** * Filters the array of images that would be good for a specific post. * This filter is applied after options ($args) filter the original array. * * @since 2.0.0 * * @param array $media Array of images that would be good for a specific post. * @param int $post_id Post ID. * @param array $args Array of options to get images. */ return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args ); } /** * Takes an image and base pixel dimensions and returns a srcset for the * resized and cropped images, based on a fixed set of multipliers. * * @param array $image Array containing details of the image. * @param int $base_width Base image width (i.e., the width at 1x). * @param int $base_height Base image height (i.e., the height at 1x). * @param bool $use_widths Whether to generate the srcset with widths instead of multipliers. * @return string The srcset for the image. */ public static function generate_cropped_srcset( $image, $base_width, $base_height, $use_widths = false ) { $srcset = ''; if ( ! is_array( $image ) || empty( $image['src'] ) || empty( $image['src_width'] ) ) { return $srcset; } $multipliers = array( 1, 1.5, 2, 3, 4 ); $srcset_values = array(); foreach ( $multipliers as $multiplier ) { $srcset_width = (int) ( $base_width * $multiplier ); $srcset_height = (int) ( $base_height * $multiplier ); if ( $srcset_width < 1 || $srcset_width > $image['src_width'] ) { break; } $srcset_url = self::fit_image_url( $image['src'], $srcset_width, $srcset_height ); if ( $use_widths ) { $srcset_values[] = "{$srcset_url} {$srcset_width}w"; } else { $srcset_values[] = "{$srcset_url} {$multiplier}x"; } } if ( count( $srcset_values ) > 1 ) { $srcset = implode( ', ', $srcset_values ); } return $srcset; } /** * Takes an image URL and pixel dimensions then returns a URL for the * resized and cropped image. * * @param string $src Image URL. * @param int $width Image width. * @param int $height Image height. * @return string Transformed image URL */ public static function fit_image_url( $src, $width, $height ) { $width = (int) $width; $height = (int) $height; if ( $width < 1 || $height < 1 ) { return $src; } // See if we should bypass WordPress.com SaaS resizing. if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) { /** * Filters the image URL used after dimensions are set by Photon. * * @since 3.3.0 * * @param string $src Image URL. * @param int $width Image width. * @param int $width Image height. */ return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height ); } // If WPCOM hosted image use native transformations. $img_host = wp_parse_url( $src, PHP_URL_HOST ); if ( str_ends_with( $img_host, '.files.wordpress.com' ) ) { return add_query_arg( array( 'w' => $width, 'h' => $height, 'crop' => 1, ), set_url_scheme( $src ) ); } // Use image cdn magic. if ( class_exists( Image_CDN_Core::class ) && method_exists( Image_CDN_Core::class, 'cdn_url' ) ) { return Image_CDN_Core::cdn_url( $src, array( 'resize' => "$width,$height" ) ); } // Arg... no way to resize image using WordPress.com infrastructure! return $src; } /** * Get HTML from given post content. * * @since 6.9.0 * * @param mixed $html_or_id The HTML string to parse for images, or a post id. * * @return array $html_info { * @type string $html Post content. * @type string $post_url Post URL. * } */ public static function get_post_html( $html_or_id ) { if ( is_numeric( $html_or_id ) ) { $post = get_post( $html_or_id ); if ( empty( $post ) || ! empty( $post->post_password ) ) { return ''; } $html_info = array( 'html' => $post->post_content, // DO NOT apply the_content filters here, it will cause loops. 'post_url' => get_permalink( $post->ID ), ); } else { $html_info = array( 'html' => $html_or_id, 'post_url' => '', ); } return $html_info; } /** * Get info about a WordPress attachment. * * @since 6.9.0 * * @param int $attachment_id Attachment ID. * @param string $post_url URL of the post, if we have one. * @param int $width Minimum Image width. * @param int $height Minimum Image height. * @return array|bool Image data or false if unavailable. */ public static function get_attachment_data( $attachment_id, $post_url, $width, $height ) { if ( empty( $attachment_id ) ) { return false; } $meta = wp_get_attachment_metadata( $attachment_id ); if ( empty( $meta ) ) { return false; } if ( ! empty( $meta['videopress'] ) ) { // Use poster image for VideoPress videos. $url = $meta['videopress']['poster']; $meta_width = $meta['videopress']['width']; $meta_height = $meta['videopress']['height']; } elseif ( ! empty( $meta['thumb'] ) ) { // On WordPress.com, VideoPress videos have a 'thumb' property with the // poster image filename instead. $media_url = wp_get_attachment_url( $attachment_id ); $url = str_replace( wp_basename( $media_url ), $meta['thumb'], $media_url ); $meta_width = $meta['width']; $meta_height = $meta['height']; } elseif ( wp_attachment_is( 'video', $attachment_id ) ) { // We don't have thumbnail images for non-VideoPress videos - skip them. return false; } else { if ( ! isset( $meta['width'] ) || ! isset( $meta['height'] ) ) { return false; } $url = wp_get_attachment_url( $attachment_id ); $meta_width = $meta['width']; $meta_height = $meta['height']; } if ( $meta_width < $width || $meta_height < $height ) { return false; } return array( 'type' => 'image', 'from' => 'attachment', 'src' => $url, 'src_width' => $meta_width, 'src_height' => $meta_height, 'href' => $post_url, 'alt_text' => self::get_alt_text( $attachment_id ), ); } /** * Get the alt text for an image or other media from the Media Library. * * @since 7.1 * * @param int $attachment_id The Post ID of the media. * @return string The alt text value or an empty string. */ public static function get_alt_text( $attachment_id ) { return (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); } /** * Get an image from a block. * * @since 7.8.0 * * @param array $images Images found. * @param array $block Block and its attributes. * @param array $html_info Info about the post where the block is found. * @param int $width Desired image width. * @param int $height Desired image height. * * @return array Array of images found. */ private static function get_images_from_block( $images, $block, $html_info, $width, $height ) { /** * Parse content from Core Image blocks. * If it is an image block for an image hosted on our site, it will have an ID. * If it does not have an ID, let `from_html` parse that content later, * and extract an image if it has size parameters. */ if ( 'core/image' === $block['blockName'] && ! empty( $block['attrs']['id'] ) ) { $images[] = self::get_attachment_data( $block['attrs']['id'], $html_info['post_url'], $width, $height ); } elseif ( 'core/media-text' === $block['blockName'] && ! empty( $block['attrs']['mediaId'] ) ) { $images[] = self::get_attachment_data( $block['attrs']['mediaId'], $html_info['post_url'], $width, $height ); } elseif ( /** * Parse content from Core Gallery blocks as well from Jetpack's Tiled Gallery and Slideshow blocks. * Gallery blocks include the ID of each one of the images in the gallery. */ in_array( $block['blockName'], array( 'core/gallery', 'jetpack/tiled-gallery', 'jetpack/slideshow' ), true ) && ! empty( $block['attrs']['ids'] ) ) { foreach ( $block['attrs']['ids'] as $img_id ) { $images[] = self::get_attachment_data( $img_id, $html_info['post_url'], $width, $height ); } } elseif ( /** * Parse content from Jetpack's Story block. */ 'jetpack/story' === $block['blockName'] && ! empty( $block['attrs']['mediaFiles'] ) ) { foreach ( $block['attrs']['mediaFiles'] as $media_file ) { if ( ! empty( $media_file['id'] ) ) { $images[] = self::get_attachment_data( $media_file['id'], $html_info['post_url'], $width, $height ); } } } return $images; } /** * Check if a block has inner blocks. * * @since 7.8.0 * * @param array $block Block and its attributes. * * @return bool */ private static function is_nested_block( $block ) { if ( ! empty( $block['innerBlocks'] ) ) { return true; } return false; } }
projects/plugins/jetpack/class.jetpack-twitter-cards.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Jetpack Twitter Card handling. * * @package automattic/jetpack */ /** * Twitter Cards * * Hooks onto the Open Graph protocol and extends it by adding only the tags * we need for twitter cards. * * @see /wp-content/blog-plugins/open-graph.php * @see https://dev.twitter.com/cards/overview */ class Jetpack_Twitter_Cards { /** * Adds Twitter Card tags. * * @param array $og_tags Existing OG tags. * * @return array OG tags inclusive of Twitter Card output. */ public static function twitter_cards_tags( $og_tags ) { global $post; $post_id = ( $post instanceof WP_Post ) ? $post->ID : null; /** * Maximum alt text length. * * @see https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary-card-with-large-image.html */ $alt_length = 420; if ( post_password_required() ) { return $og_tags; } /** This action is documented in class.jetpack.php */ if ( apply_filters( 'jetpack_disable_twitter_cards', false ) ) { return $og_tags; } /* * These tags apply to any page (home, archives, etc). */ // If we have information on the author/creator, then include that as well. if ( ! empty( $post ) && ! empty( $post->post_author ) ) { /** This action is documented in modules/sharedaddy/sharing-sources.php */ $handle = apply_filters( 'jetpack_sharing_twitter_via', '', $post_id ); if ( ! empty( $handle ) && ! self::is_default_site_tag( $handle ) ) { $og_tags['twitter:creator'] = self::sanitize_twitter_user( $handle ); } } $site_tag = self::site_tag(); /** This action is documented in modules/sharedaddy/sharing-sources.php */ $site_tag = apply_filters( 'jetpack_sharing_twitter_via', $site_tag, ( is_singular() ? $post_id : null ) ); /** This action is documented in modules/sharedaddy/sharing-sources.php */ $site_tag = apply_filters( 'jetpack_twitter_cards_site_tag', $site_tag, $og_tags ); if ( ! empty( $site_tag ) ) { $og_tags['twitter:site'] = self::sanitize_twitter_user( $site_tag ); } if ( ! is_singular() || ! empty( $og_tags['twitter:card'] ) ) { /** * Filter the default Twitter card image, used when no image can be found in a post. * * @module sharedaddy * * @since 5.9.0 * * @param string $str Default image URL. */ $image = apply_filters( 'jetpack_twitter_cards_image_default', '' ); if ( ! empty( $image ) ) { $og_tags['twitter:image'] = $image; } return $og_tags; } $the_title = get_the_title(); if ( ! $the_title ) { $the_title = get_bloginfo( 'name' ); } $og_tags['twitter:text:title'] = $the_title; /* * The following tags only apply to single pages. */ $card_type = 'summary'; // Try to give priority to featured images. if ( class_exists( 'Jetpack_PostImages' ) && ! empty( $post_id ) ) { $post_image = Jetpack_PostImages::get_image( $post_id, array( 'width' => 144, 'height' => 144, ) ); if ( ! empty( $post_image ) && is_array( $post_image ) ) { // 4096 is the maximum size for an image per https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary . if ( isset( $post_image['src_width'] ) && isset( $post_image['src_height'] ) && (int) $post_image['src_width'] <= 4096 && (int) $post_image['src_height'] <= 4096 ) { // 300x157 is the minimum size for a summary_large_image per https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary-card-with-large-image . if ( (int) $post_image['src_width'] >= 300 && (int) $post_image['src_height'] >= 157 ) { $card_type = 'summary_large_image'; $og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 640, $post_image['src'] ) ); } else { $og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 144, $post_image['src'] ) ); } // Add the alt tag if we have one. if ( ! empty( $post_image['alt_text'] ) ) { // Shorten it if it is too long. if ( strlen( $post_image['alt_text'] ) > $alt_length ) { $og_tags['twitter:image:alt'] = esc_attr( mb_substr( $post_image['alt_text'], 0, $alt_length ) . '…' ); } else { $og_tags['twitter:image:alt'] = esc_attr( $post_image['alt_text'] ); } } } } } // Only proceed with media analysis if a featured image has not superseded it already. if ( empty( $og_tags['twitter:image'] ) && empty( $og_tags['twitter:image:src'] ) ) { if ( ! class_exists( 'Jetpack_Media_Summary' ) ) { require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media-summary.php'; } // Test again, class should already be auto-loaded in Jetpack. // If not, skip extra media analysis and stick with a summary card. if ( class_exists( 'Jetpack_Media_Summary' ) && ! empty( $post_id ) ) { $extract = Jetpack_Media_Summary::get( $post_id ); if ( 'gallery' === $extract['type'] ) { list( $og_tags, $card_type ) = self::twitter_cards_define_type_based_on_image_count( $og_tags, $extract ); } elseif ( 'video' === $extract['type'] ) { // Leave as summary, but with large pict of poster frame (we know those comply to Twitter's size requirements). $card_type = 'summary_large_image'; $og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 640, $extract['image'] ) ); } else { list( $og_tags, $card_type ) = self::twitter_cards_define_type_based_on_image_count( $og_tags, $extract ); } } } $og_tags['twitter:card'] = $card_type; // Make sure we have a description for Twitter, their validator isn't happy without some content (single space not valid). if ( ! isset( $og_tags['og:description'] ) || '' === trim( $og_tags['og:description'] ) || __( 'Visit the post for more.', 'jetpack' ) === $og_tags['og:description'] ) { // empty( trim( $og_tags['og:description'] ) ) isn't valid php. $has_creator = ( ! empty( $og_tags['twitter:creator'] ) && '@wordpressdotcom' !== $og_tags['twitter:creator'] ) ? true : false; if ( ! empty( $extract ) && 'video' === $extract['type'] ) { // use $extract['type'] since $card_type is 'summary' for video posts. /* translators: %s is the post author */ $og_tags['twitter:description'] = ( $has_creator ) ? sprintf( __( 'Video post by %s.', 'jetpack' ), $og_tags['twitter:creator'] ) : __( 'Video post.', 'jetpack' ); } else { /* translators: %s is the post author */ $og_tags['twitter:description'] = ( $has_creator ) ? sprintf( __( 'Post by %s.', 'jetpack' ), $og_tags['twitter:creator'] ) : __( 'Visit the post for more.', 'jetpack' ); } } if ( empty( $og_tags['twitter:image'] ) && empty( $og_tags['twitter:image:src'] ) ) { /** This action is documented in class.jetpack-twitter-cards.php */ $image = apply_filters( 'jetpack_twitter_cards_image_default', '' ); if ( ! empty( $image ) ) { $og_tags['twitter:image'] = $image; } } return $og_tags; } /** * Sanitize the Twitter user by normalizing the @. * * @param string $str Twitter user value. * * @return string Twitter user value. */ public static function sanitize_twitter_user( $str ) { return '@' . preg_replace( '/^@/', '', $str ); } /** * Determines if a site tag is one of the default WP.com/Jetpack ones. * * @param string $site_tag Site tag. * * @return bool True if the default site tag is being used. */ public static function is_default_site_tag( $site_tag ) { return in_array( $site_tag, array( '@wordpressdotcom', '@jetpack', 'wordpressdotcom', 'jetpack' ), true ); } /** * Give priority to the creator tag if using the default site tag. * * @param string $site_tag Site tag. * @param array $og_tags OG tags. * * @return string Site tag. */ public static function prioritize_creator_over_default_site( $site_tag, $og_tags = array() ) { if ( ! empty( $og_tags['twitter:creator'] ) && self::is_default_site_tag( $site_tag ) ) { return $og_tags['twitter:creator']; } return $site_tag; } /** * Define the Twitter Card type based on image count. * * @param array $og_tags Existing OG tags. * @param array $extract Result of the Image Extractor class. * * @return array */ public static function twitter_cards_define_type_based_on_image_count( $og_tags, $extract ) { $card_type = 'summary'; $img_count = $extract['count']['image']; if ( empty( $img_count ) ) { // No images, use Blavatar as a thumbnail for the summary type. if ( function_exists( 'blavatar_domain' ) ) { $blavatar_domain = blavatar_domain( site_url() ); if ( blavatar_exists( $blavatar_domain ) ) { $og_tags['twitter:image'] = blavatar_url( $blavatar_domain, 'img', 240 ); } } // Second fall back, Site Logo. if ( empty( $og_tags['twitter:image'] ) && ( function_exists( 'jetpack_has_site_logo' ) && jetpack_has_site_logo() ) ) { $og_tags['twitter:image'] = jetpack_get_site_logo( 'url' ); } // Third fall back, Site Icon. if ( empty( $og_tags['twitter:image'] ) && has_site_icon() ) { $og_tags['twitter:image'] = get_site_icon_url( '240' ); } // Not falling back on Gravatar, because there's no way to know if we end up with an auto-generated one. } elseif ( $img_count && ( 'image' === $extract['type'] || 'gallery' === $extract['type'] ) ) { // Test for $extract['type'] to limit to image and gallery, so we don't send a potential fallback image like a Gravatar as a photo post. $card_type = 'summary_large_image'; $og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 1400, ( empty( $extract['images'] ) ) ? $extract['image'] : $extract['images'][0]['url'] ) ); } return array( $og_tags, $card_type ); } /** * Updates the Twitter Card output. * * @param string $og_tag A single OG tag. * * @return string Result of the OG tag. */ public static function twitter_cards_output( $og_tag ) { return ( str_contains( $og_tag, 'twitter:' ) ) ? preg_replace( '/property="([^"]+)"/', 'name="\1"', $og_tag ) : $og_tag; } /** * Adds settings section and field. */ public static function settings_init() { add_settings_section( 'jetpack-twitter-cards-settings', 'Twitter Cards', '__return_false', 'sharing' ); add_settings_field( 'jetpack-twitter-cards-site-tag', __( 'Twitter Site Tag', 'jetpack' ), array( __CLASS__, 'settings_field' ), 'sharing', 'jetpack-twitter-cards-settings', array( 'label_for' => 'jetpack-twitter-cards-site-tag', ) ); } /** * Add global sharing options. */ public static function sharing_global_options() { do_settings_fields( 'sharing', 'jetpack-twitter-cards-settings' ); } /** * Get the Twitter Via tag. * * @return string Twitter via tag. */ public static function site_tag() { $site_tag = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? trim( get_option( 'twitter_via' ) ) : Jetpack_Options::get_option_and_ensure_autoload( 'jetpack-twitter-cards-site-tag', '' ); if ( empty( $site_tag ) ) { /** This action is documented in modules/sharedaddy/sharing-sources.php */ return apply_filters( 'jetpack_sharing_twitter_via', '', null ); } return $site_tag; } /** * Output the settings field. */ public static function settings_field() { wp_nonce_field( 'jetpack-twitter-cards-settings', 'jetpack_twitter_cards_nonce', false ); ?> <input type="text" id="jetpack-twitter-cards-site-tag" class="regular-text" name="jetpack-twitter-cards-site-tag" value="<?php echo esc_attr( get_option( 'jetpack-twitter-cards-site-tag' ) ); ?>" /> <p class="description" style="width: auto;"><?php esc_html_e( 'The Twitter username of the owner of this site\'s domain.', 'jetpack' ); ?></p> <?php } /** * Validate the settings submission. */ public static function settings_validate() { if ( isset( $_POST['jetpack_twitter_cards_nonce'] ) && wp_verify_nonce( $_POST['jetpack_twitter_cards_nonce'], 'jetpack-twitter-cards-settings' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized update_option( 'jetpack-twitter-cards-site-tag', isset( $_POST['jetpack-twitter-cards-site-tag'] ) ? trim( ltrim( wp_strip_all_tags( filter_var( wp_unslash( $_POST['jetpack-twitter-cards-site-tag'] ) ) ), '@' ) ) : '' ); } } /** * Initiates the class. */ public static function init() { add_filter( 'jetpack_open_graph_tags', array( __CLASS__, 'twitter_cards_tags' ), 11 ); // $priority=11: this should hook into jetpack_open_graph_tags after 'class.jetpack-seo.php' has done so. add_filter( 'jetpack_open_graph_output', array( __CLASS__, 'twitter_cards_output' ) ); add_filter( 'jetpack_twitter_cards_site_tag', array( __CLASS__, 'site_tag' ), -99 ); add_filter( 'jetpack_twitter_cards_site_tag', array( __CLASS__, 'prioritize_creator_over_default_site' ), 99, 2 ); add_action( 'admin_init', array( __CLASS__, 'settings_init' ) ); add_action( 'sharing_global_options', array( __CLASS__, 'sharing_global_options' ) ); add_action( 'sharing_admin_update', array( __CLASS__, 'settings_validate' ) ); } } Jetpack_Twitter_Cards::init();
projects/plugins/jetpack/functions.opengraph.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Open Graph Tags * * Add Open Graph tags so that Facebook (and any other service that supports them) * can crawl the site better and we provide a better sharing experience. * * @link https://ogp.me/ * @link https://developers.facebook.com/docs/opengraph/ * * @package automattic/jetpack */ add_action( 'wp_head', 'jetpack_og_tags' ); add_action( 'web_stories_story_head', 'jetpack_og_tags' ); /** * Outputs Open Graph tags generated by Jetpack. */ function jetpack_og_tags() { global $post; $data = $post; // so that we don't accidentally explode the global. $is_amp_response = ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ); // Disable the widont filter on WP.com to avoid stray &nbsps. $disable_widont = remove_filter( 'the_title', 'widont' ); $og_output = "\n"; if ( ! $is_amp_response ) { // Because AMP optimizes the order or the nodes in the head. $og_output .= "<!-- Jetpack Open Graph Tags -->\n"; } $tags = array(); /** * Filter the minimum width of the images used in Jetpack Open Graph Meta Tags. * * @module sharedaddy, publicize * * @since 2.0.0 * * @param int 200 Minimum image width used in Jetpack Open Graph Meta Tags. */ $image_width = absint( apply_filters( 'jetpack_open_graph_image_width', 200 ) ); /** * Filter the minimum height of the images used in Jetpack Open Graph Meta Tags. * * @module sharedaddy, publicize * * @since 2.0.0 * * @param int 200 Minimum image height used in Jetpack Open Graph Meta Tags. */ $image_height = absint( apply_filters( 'jetpack_open_graph_image_height', 200 ) ); $description_length = 197; if ( is_home() || is_front_page() ) { $site_type = Jetpack_Options::get_option_and_ensure_autoload( 'open_graph_protocol_site_type', '' ); $tags['og:type'] = ! empty( $site_type ) ? $site_type : 'website'; $tags['og:title'] = get_bloginfo( 'name' ); $tags['og:description'] = get_bloginfo( 'description' ); $front_page_id = get_option( 'page_for_posts' ); if ( 'page' === get_option( 'show_on_front' ) && $front_page_id && is_home() ) { $tags['og:url'] = get_permalink( $front_page_id ); } else { $tags['og:url'] = home_url( '/' ); } // Associate a blog's root path with one or more Facebook accounts. $facebook_admins = Jetpack_Options::get_option_and_ensure_autoload( 'facebook_admins', array() ); if ( ! empty( $facebook_admins ) ) { $tags['fb:admins'] = $facebook_admins; } } elseif ( is_author() ) { $tags['og:type'] = 'profile'; $author = get_queried_object(); if ( is_a( $author, 'WP_User' ) ) { $tags['og:title'] = $author->display_name; if ( ! empty( $author->user_url ) ) { $tags['og:url'] = $author->user_url; } else { $tags['og:url'] = get_author_posts_url( $author->ID ); } $tags['og:description'] = $author->description; $tags['profile:first_name'] = get_the_author_meta( 'first_name', $author->ID ); $tags['profile:last_name'] = get_the_author_meta( 'last_name', $author->ID ); } } elseif ( is_archive() ) { $tags['og:type'] = 'website'; $tags['og:title'] = wp_get_document_title(); $archive = get_queried_object(); if ( ! empty( $archive ) ) { if ( is_category() || is_tag() || is_tax() ) { $tags['og:url'] = get_term_link( $archive->term_id, $archive->taxonomy ); $tags['og:description'] = $archive->description; } elseif ( is_post_type_archive() ) { $tags['og:url'] = get_post_type_archive_link( $archive->name ); $tags['og:description'] = $archive->description; } } } elseif ( is_singular() && is_a( $data, 'WP_Post' ) ) { $tags['og:type'] = 'article'; if ( empty( $data->post_title ) ) { $tags['og:title'] = ' '; } else { /** This filter is documented in core/src/wp-includes/post-template.php */ $tags['og:title'] = wp_kses( apply_filters( 'the_title', $data->post_title, $data->ID ), array() ); } $tags['og:url'] = get_permalink( $data->ID ); if ( ! post_password_required() ) { /* * If the post author set an excerpt, use that. * Otherwise, pick the post content that comes before the More tag if there is one. * Do not use the post content if it contains premium content. */ if ( ! empty( $data->post_excerpt ) ) { $tags['og:description'] = jetpack_og_get_description( $data->post_excerpt ); } elseif ( ! has_block( 'premium-content/container', $data->post_content ) ) { $excerpt = explode( '<!--more-->', $data->post_content )[0]; $tags['og:description'] = jetpack_og_get_description( $excerpt ); } } $tags['article:published_time'] = gmdate( 'c', strtotime( $data->post_date_gmt ) ); $tags['article:modified_time'] = gmdate( 'c', strtotime( $data->post_modified_gmt ) ); if ( post_type_supports( get_post_type( $data ), 'author' ) && isset( $data->post_author ) ) { $publicize_facebook_user = get_post_meta( $data->ID, '_publicize_facebook_user', true ); if ( ! empty( $publicize_facebook_user ) ) { $tags['article:author'] = esc_url( $publicize_facebook_user ); } } } elseif ( is_search() ) { if ( '' !== get_query_var( 's', '' ) ) { $tags['og:title'] = wp_get_document_title(); } } /** * Allow plugins to inject additional template-specific Open Graph tags. * * @module sharedaddy, publicize * * @since 3.0.0 * * @param array $tags Array of Open Graph Meta tags. * @param array $args Array of image size parameters. */ $tags = apply_filters( 'jetpack_open_graph_base_tags', $tags, compact( 'image_width', 'image_height' ) ); // Re-enable widont if we had disabled it. if ( $disable_widont ) { add_filter( 'the_title', 'widont' ); } /** * Do not return any Open Graph Meta tags if we don't have any info about a post. * * @module sharedaddy, publicize * * @since 3.0.0 * * @param bool true Do not return any Open Graph Meta tags if we don't have any info about a post. */ if ( empty( $tags ) && apply_filters( 'jetpack_open_graph_return_if_empty', true ) ) { return; } $tags['og:site_name'] = get_bloginfo( 'name' ); // Get image info and build tags. if ( ! post_password_required() ) { $image_info = jetpack_og_get_image( $image_width, $image_height ); $tags['og:image'] = $image_info['src']; if ( ! empty( $image_info['width'] ) ) { $tags['og:image:width'] = (int) $image_info['width']; } if ( ! empty( $image_info['height'] ) ) { $tags['og:image:height'] = (int) $image_info['height']; } // If we have an image, add the alt text even if it's empty. if ( ! empty( $image_info['src'] ) && isset( $image_info['alt_text'] ) ) { $tags['og:image:alt'] = esc_attr( $image_info['alt_text'] ); } } // Facebook whines if you give it an empty title. if ( empty( $tags['og:title'] ) ) { $tags['og:title'] = __( '(no title)', 'jetpack' ); } // Shorten the description if it's too long. if ( isset( $tags['og:description'] ) ) { $tags['og:description'] = strlen( $tags['og:description'] ) > $description_length ? mb_substr( $tags['og:description'], 0, $description_length ) . '…' : $tags['og:description']; } // Try to add OG locale tag if the WP->FB data mapping exists. if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) { require_once JETPACK__GLOTPRESS_LOCALES_PATH; $_locale = get_locale(); // We have to account for w.org vs WP.com locale divergence. if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $gp_locale = GP_Locales::by_field( 'slug', $_locale ); } else { $gp_locale = GP_Locales::by_field( 'wp_locale', $_locale ); } } if ( isset( $gp_locale->facebook_locale ) && ! empty( $gp_locale->facebook_locale ) ) { $tags['og:locale'] = $gp_locale->facebook_locale; } /** * Allow the addition of additional Open Graph Meta tags, or modify the existing tags. * * @module sharedaddy, publicize * * @since 2.0.0 * * @param array $tags Array of Open Graph Meta tags. * @param array $args Array of image size parameters. */ $tags = apply_filters( 'jetpack_open_graph_tags', $tags, compact( 'image_width', 'image_height' ) ); // secure_urls need to go right after each og:image to work properly so we will abstract them here. $tags['og:image:secure_url'] = ( empty( $tags['og:image:secure_url'] ) ) ? '' : $tags['og:image:secure_url']; $secure = $tags['og:image:secure_url']; unset( $tags['og:image:secure_url'] ); $secure_image_num = 0; $allowed_empty_tags = array( 'og:image:alt', ); foreach ( (array) $tags as $tag_property => $tag_content ) { // to accommodate multiple images. $tag_content = (array) $tag_content; $tag_content = array_unique( $tag_content ); foreach ( $tag_content as $tag_content_single ) { if ( empty( $tag_content_single ) && ! in_array( $tag_property, $allowed_empty_tags, true ) ) { continue; // Only allow certain empty tags. } switch ( $tag_property ) { case 'og:url': case 'og:image': case 'og:image:url': case 'og:image:secure_url': case 'og:audio': case 'og:audio:url': case 'og:audio:secure_url': case 'og:video': case 'og:video:url': case 'og:video:secure_url': $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_url( $tag_content_single ) ); break; default: $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_attr( $tag_content_single ) ); } /** * Filter the HTML Output of each Open Graph Meta tag. * * @module sharedaddy, publicize * * @since 2.0.0 * * @param string $og_tag HTML HTML Output of each Open Graph Meta tag. */ $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag ); $og_output .= "\n"; if ( 'og:image' === $tag_property ) { if ( is_array( $secure ) && ! empty( $secure[ $secure_image_num ] ) ) { $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure[ $secure_image_num ] ) ); /** This filter is documented in functions.opengraph.php */ $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag ); $og_output .= "\n"; } elseif ( ! is_array( $secure ) && ! empty( $secure ) ) { $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure ) ); /** This filter is documented in functions.opengraph.php */ $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag ); $og_output .= "\n"; } ++$secure_image_num; } } } if ( ! $is_amp_response ) { // Because AMP optimizes the order or the nodes in the head. $og_output .= "\n<!-- End Jetpack Open Graph Tags -->"; } $og_output .= "\n"; // This is trusted output or added by a filter. echo $og_output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } /** * Returns an image used in social shares. * * @since 2.0.0 * * @param int $width Minimum width for the image. Default is 200 based on Facebook's requirement. * @param int $height Minimum height for the image. Default is 200 based on Facebook's requirement. * @param null $deprecated Deprecated. * * @return array The source ('src'), 'width', and 'height' of the image. */ function jetpack_og_get_image( $width = 200, $height = 200, $deprecated = null ) { if ( ! empty( $deprecated ) ) { _deprecated_argument( __FUNCTION__, 'jetpack-6.6.0' ); } $image = array(); if ( is_singular() && ! is_home() ) { // Grab obvious image if post is an attachment page for an image. if ( is_attachment( get_the_ID() ) && str_starts_with( get_post_mime_type(), 'image' ) ) { $image['src'] = wp_get_attachment_url( get_the_ID() ); $image['alt_text'] = Jetpack_PostImages::get_alt_text( get_the_ID() ); } // Attempt to find something good for this post using our generalized PostImages code. if ( empty( $image ) && class_exists( 'Jetpack_PostImages' ) ) { $post_image = Jetpack_PostImages::get_image( get_the_ID(), array( 'width' => $width, 'height' => $height, ) ); if ( ! empty( $post_image ) && is_array( $post_image ) ) { $image['src'] = $post_image['src']; if ( isset( $post_image['src_width'] ) && isset( $post_image['src_height'] ) ) { $image['width'] = $post_image['src_width']; $image['height'] = $post_image['src_height']; } if ( ! empty( $post_image['alt_text'] ) ) { $image['alt_text'] = $post_image['alt_text']; } } } } elseif ( is_author() ) { $author = get_queried_object(); if ( is_a( $author, 'WP_User' ) ) { $image['src'] = get_avatar_url( $author->user_email, array( 'size' => $width, ) ); $image['alt_text'] = $author->display_name; } } // First fall back, blavatar. if ( empty( $image ) && function_exists( 'blavatar_domain' ) ) { $blavatar_domain = blavatar_domain( site_url() ); if ( blavatar_exists( $blavatar_domain ) ) { $image['src'] = blavatar_url( $blavatar_domain, 'img', $width, false, true ); $image['width'] = $width; $image['height'] = $height; } } // Second fall back, Site Logo. if ( empty( $image ) && ( function_exists( 'jetpack_has_site_logo' ) && jetpack_has_site_logo() ) ) { $image_id = jetpack_get_site_logo( 'id' ); $logo = wp_get_attachment_image_src( $image_id, 'full' ); if ( isset( $logo[0] ) && isset( $logo[1] ) && isset( $logo[2] ) && ( _jetpack_og_get_image_validate_size( $logo[1], $logo[2], $width, $height ) ) ) { $image['src'] = $logo[0]; $image['width'] = $logo[1]; $image['height'] = $logo[2]; $image['alt_text'] = Jetpack_PostImages::get_alt_text( $image_id ); } } // Third fall back, Core Site Icon, if valid in size. if ( empty( $image ) && has_site_icon() ) { $image_id = get_option( 'site_icon' ); $icon = wp_get_attachment_image_src( $image_id, 'full' ); if ( isset( $icon[0] ) && isset( $icon[1] ) && isset( $icon[2] ) && ( _jetpack_og_get_image_validate_size( $icon[1], $icon[2], $width, $height ) ) ) { $image['src'] = $icon[0]; $image['width'] = $icon[1]; $image['height'] = $icon[2]; $image['alt_text'] = Jetpack_PostImages::get_alt_text( $image_id ); } } // Final fall back, blank image. if ( empty( $image ) ) { /** * Filter the default Open Graph Image tag, used when no Image can be found in a post. * * @since 3.0.0 * * @param string $str Default Image URL. */ $image['src'] = apply_filters( 'jetpack_open_graph_image_default', 'https://s0.wp.com/i/blank.jpg' ); } // If we didn't get an explicit alt tag from the image, set a default. if ( empty( $image['alt_text'] ) ) { /** * Filter the default Open Graph image alt text, used when the Open Graph image from the post does not have an alt text. * * @since 10.4 * * @param string $str Default Open Graph image alt text. */ $image['alt_text'] = apply_filters( 'jetpack_open_graph_image_default_alt_text', '' ); } return $image; } /** * Validate the width and height against required width and height * * @param int $width Width of the image. * @param int $height Height of the image. * @param int $req_width Required width to pass validation. * @param int $req_height Required height to pass validation. * * @return bool - True if the image passed the required size validation */ function _jetpack_og_get_image_validate_size( $width, $height, $req_width, $req_height ) { if ( ! $width || ! $height ) { return false; } $valid_width = ( $width >= $req_width ); $valid_height = ( $height >= $req_height ); $is_image_acceptable = $valid_width && $valid_height; return $is_image_acceptable; } /** * Gets a gravatar URL of the specified size. * * @param string $email E-mail address to get gravatar for. * @param int $width Size of returned gravatar. * @return array|bool|mixed|string */ function jetpack_og_get_image_gravatar( $email, $width ) { return get_avatar_url( $email, array( 'size' => $width, ) ); } /** * Clean up text meant to be used as Description Open Graph tag. * * There should be: * - no links * - no shortcodes * - no html tags or their contents * - not too many words. * * @param string $description Text coming from WordPress (autogenerated or manually generated by author). * @param WP_Post|null $data Information about our post. * * @return string $description Cleaned up description string. */ function jetpack_og_get_description( $description = '', $data = null ) { // Remove tags such as <style or <script. $description = wp_strip_all_tags( $description ); /* * Clean up any plain text entities left into formatted entities. * Intentionally not using a filter to prevent pollution. * @see https://github.com/Automattic/jetpack/pull/2899#issuecomment-151957382 */ $description = wp_kses( trim( convert_chars( wptexturize( $description ) ) ), array() ); // Remove shortcodes. $description = strip_shortcodes( $description ); // Remove links. $description = preg_replace( '@https?://[\S]+@', '', $description ); /* * Limit things to a small text blurb. * There isn't a hard limit set by Facebook, so let's rely on WP's own limit. * (55 words or the localized equivalent). * This limit can be customized with the wp_trim_words filter. */ $description = wp_trim_words( $description ); // Let's set a default if we have no text by now. if ( empty( $description ) ) { /** * Filter the fallback `og:description` used when no excerpt information is provided. * * @module sharedaddy, publicize * * @since 3.9.0 * * @param string $var Fallback og:description. Default is translated `Visit the post for more'. * @param object $data Post object for the current post. */ $description = apply_filters( 'jetpack_open_graph_fallback_description', __( 'Visit the post for more.', 'jetpack' ), $data ); } return $description; }
projects/plugins/jetpack/class.jetpack-data.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Deprecated since 9.5. * * @deprecated * @package automattic/jetpack */ // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped _deprecated_file( basename( __FILE__ ), 'jetpack-9.5' );
projects/plugins/jetpack/tools/check-block-assets.php
#!/usr/bin/env php <?php /** * Script to check blocks' view.asset.php for unexpected dependencies. * * @package automattic/jetpack */ // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- This is not WordPress code. /** * Non-WP dependencies to check for. * * @var string[] */ $bad_deps = array( 'jquery', 'lodash', 'lodash-es', 'moment', 'react', 'react-dom', ); /** * WP dependencies to allow. * * @var string[] */ $ok_wp_deps = array( 'wp-a11y', 'wp-api-fetch', 'wp-autop', 'wp-blob', 'wp-block-serialization-default-parser', 'wp-block-serialization-spec-parser', 'wp-deprecated', 'wp-dom', 'wp-dom-ready', 'wp-escape-html', 'wp-experiments', 'wp-hooks', 'wp-html-entities', 'wp-i18n', 'wp-is-shallow-equal', 'wp-polyfill', 'wp-preferences-persistence', 'wp-priority-queue', 'wp-redux-routine', 'wp-shortcode', 'wp-token-list', 'wp-url', 'wp-warning', ); /** * Blocks allowed to have extra dependencies. * * @var string[][] Keys are block names, value is an array of dependencies to not complain about. */ $allowed = array( 'ai-chat' => array( 'react', 'react-dom', 'wp-components', 'wp-compose', 'wp-element', ), 'podcast-player' => array( 'lodash', 'react', 'react-dom', 'wp-compose', 'wp-data', 'wp-element', 'wp-primitives', ), 'story' => array( 'lodash', 'react', 'react-dom', 'wp-compose', 'wp-data', 'wp-element', 'wp-keycodes', 'wp-plugins', 'wp-primitives', ), ); chdir( dirname( __DIR__ ) ); $base = 'projects/plugins/jetpack/'; $script = 'projects/plugins/jetpack/tools/check-block-assets.php'; $issues = array( $script => array() ); $tmp = $bad_deps; sort( $bad_deps ); if ( $tmp !== $bad_deps ) { $issues[ $script ][] = 'The `$bad_deps` array is not sorted. Please sort it.'; } $tmp = $ok_wp_deps; sort( $ok_wp_deps ); if ( $tmp !== $ok_wp_deps ) { $issues[ $script ][] = 'The `$ok_wp_deps` array is not sorted. Please sort it.'; } $tmp = array_keys( $allowed ); ksort( $allowed ); if ( $tmp !== array_keys( $allowed ) ) { $issues[ $script ][] = 'The `$allowed` array is not sorted. Please sort it.'; } foreach ( $allowed as $k => $v ) { $tmp = $v; sort( $v ); if ( $tmp !== $v ) { $issues[ $script ][] = "The `\$allowed['$k']` array is not sorted. Please sort it."; } } $bad_deps = array_fill_keys( $bad_deps, true ); $ok_wp_deps = array_fill_keys( $ok_wp_deps, true ); $iter = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( '_inc/blocks/', FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_PATHNAME ) ); foreach ( $iter as $file ) { if ( ! str_ends_with( $file, '/view.asset.php' ) ) { continue; } $block = substr( $file, 12, -15 ); $data = require $file; $allow = isset( $allowed[ $block ] ) ? array_fill_keys( $allowed[ $block ], true ) : array(); unset( $allowed[ $block ] ); foreach ( $data['dependencies'] as $dep ) { if ( isset( $bad_deps[ $dep ] ) || str_starts_with( $dep, 'wp-' ) && ! isset( $ok_wp_deps[ $dep ] ) ) { if ( isset( $allow[ $dep ] ) ) { unset( $allow[ $dep ] ); } else { $issues[ $base . $file ][] = "Dependency `$dep` should not be used by the $block block's view.js."; } } } if ( ! empty( $allow ) ) { $issues[ $script ][] = sprintf( 'Allowlist data for the %s block lists unneeded dependencies: %s.', $block, implode( ', ', array_keys( $allow ) ) ); } } if ( ! empty( $allowed ) ) { foreach ( $allowed as $block => $dummy ) { $issues[ $script ][] = "A block \"$block\" has allowlist data, but no view script for the block was found."; } } if ( empty( $issues[ $script ] ) ) { unset( $issues[ $script ] ); } if ( ! empty( $issues ) ) { echo "\n\n\e[1mBlock view script dependency check detected issues!\e[0m\n"; foreach ( $issues as $file => $msgs ) { echo "\n\e[1mIn $file\e[0m\n" . implode( "\n", $msgs ) . "\n"; } echo "\n\e[32mDependencies allowed may be adjusted by editing the arrays at the top of $script.\e[0m\n\n"; exit( 1 ); }
projects/plugins/jetpack/tools/build-asset-cdn-json.php
<?php /** * Script to build modules/photon-cdn/jetpack-manifest.php * * @package automattic/jetpack */ // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.system_calls_proc_open, WordPress.WP.AlternativeFunctions // The repo root path. $jetpack_path = dirname( __DIR__ ) . '/'; // Build an iterator over all files in the repo that match the regex in the RegexIterator. $directory = new RecursiveDirectoryIterator( $jetpack_path ); $iterator = new RecursiveIteratorIterator( $directory ); $regex = new RegexIterator( $iterator, '/^.+\.(css|js)$/i', RecursiveRegexIterator::GET_MATCH ); $ignore_paths = array( '_inc/client/', 'extensions/', 'jetpack_vendor/', 'logs/', 'node_modules/', 'tests/', 'tools/', 'vendor/', ); $manifest = array(); foreach ( $regex as $path_to_file => $value ) { $path_from_repo_root = str_replace( $jetpack_path, '', $path_to_file ); // Ignore top-level files. if ( ! str_contains( $path_from_repo_root, '/' ) ) { continue; } // Ignore explicit ignore list. foreach ( $ignore_paths as $ignore_path ) { if ( str_starts_with( $path_from_repo_root, $ignore_path ) ) { continue 2; } } $manifest[] = $path_from_repo_root; } /** * Wrapper for proc_open. * * @param array|string $cmd Command. * @param array $pipes Output variable for pipes. * @return resource From `proc_open`. */ function do_proc_open( $cmd, &$pipes ) { global $jetpack_path; if ( is_array( $cmd ) && version_compare( PHP_VERSION, '7.4.0', '<' ) ) { // PHP <7.4 doesn't support an array, so convert it to a string. $cmd = implode( ' ', array_map( 'escapeshellarg', $cmd ) ); } return proc_open( $cmd, array( array( 'pipe', 'r' ), array( 'pipe', 'w' ), STDERR ), $pipes, $jetpack_path ); } // Make phpcs happy. These get set by the `do_proc_open` call. $ignore_pipes = null; $include_pipes = null; $exclude_pipes = null; // Use .gitignore and .gitattributes to select files to include. $ignore = do_proc_open( array( 'git', 'check-ignore', '--stdin', '-v', '-n' ), $ignore_pipes ); $include = do_proc_open( array( 'git', 'check-attr', '--stdin', 'production-include' ), $include_pipes ); $exclude = do_proc_open( array( 'git', 'check-attr', '--stdin', 'production-exclude' ), $exclude_pipes ); foreach ( $manifest as $i => $file ) { fwrite( $ignore_pipes[0], "$file\n" ); $res = array_map( 'trim', explode( ':', fgets( $ignore_pipes[1] ) ) ); if ( '' !== $res[0] ) { // File is ignored. Check if it's included anyway. fwrite( $include_pipes[0], "$file\n" ); $res = array_map( 'trim', explode( ':', fgets( $include_pipes[1] ) ) ); if ( 'production-include' === $res[1] && ( 'unspecified' === $res[2] || 'unset' === $res[2] ) ) { // File is not included. Skip it. unset( $manifest[ $i ] ); continue; } } fwrite( $exclude_pipes[0], "$file\n" ); $res = array_map( 'trim', explode( ':', fgets( $exclude_pipes[1] ) ) ); if ( 'production-exclude' === $res[1] && 'unspecified' !== $res[2] && 'unset' !== $res[2] ) { // File is excluded. Skip it. unset( $manifest[ $i ] ); } } fclose( $ignore_pipes[0] ); fclose( $ignore_pipes[1] ); fclose( $include_pipes[0] ); fclose( $include_pipes[1] ); fclose( $exclude_pipes[0] ); fclose( $exclude_pipes[1] ); proc_close( $ignore ); proc_close( $include ); proc_close( $exclude ); sort( $manifest ); $export = var_export( $manifest, true ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export file_put_contents( $jetpack_path . 'modules/photon-cdn/jetpack-manifest.php', "<?php // This file is autogenerated by bin/build-asset-cdn-json.php \$assets = $export;\n" );
projects/plugins/jetpack/tools/build-module-headings-translations.php
<?php /** * Creates the module-headings.php file. * * @package jetpack */ // phpcs:disable WordPress.WP.AlternativeFunctions, WordPress.PHP.DevelopmentFunctions.error_log_var_export $all_module_headers = array( 'name' => 'Module Name', 'description' => 'Module Description', 'sort' => 'Sort Order', 'recommendation_order' => 'Recommendation Order', 'introduced' => 'First Introduced', 'changed' => 'Major Changes In', 'deactivate' => 'Deactivate', 'free' => 'Free', 'requires_connection' => 'Requires Connection', 'requires_user_connection' => 'Requires User Connection', 'auto_activate' => 'Auto Activate', 'module_tags' => 'Module Tags', 'feature' => 'Feature', 'additional_search_queries' => 'Additional Search Queries', 'plan_classes' => 'Plans', ); // Contains all of the module info in an associative array with module slugs as keys. $all_modules = array(); // Slugs for module files that do not have module info. $no_info_slugs = array(); $jp_dir = dirname( __DIR__ ) . '/'; $files = glob( "{$jp_dir}modules/*.php" ); $tags = array( 'Other' => array(), ); foreach ( $files as $file ) { $absolute_path = $file; $relative_path = str_replace( $jp_dir, '', $file ); $_file_contents = ''; $file = fopen( $absolute_path, 'r' ); $file_data = fread( $file, 8192 ); fclose( $file ); $module_slug = str_replace( '.php', '', basename( $absolute_path ) ); // Make sure we catch CR-only line endings. $file_data = str_replace( "\r", "\n", $file_data ); $all_modules[ $module_slug ] = array_fill_keys( array_keys( $all_module_headers ), '' ); foreach ( $all_module_headers as $field => $regex ) { if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) { $string = trim( preg_replace( '/\s*(?:\*\/|\?>).*/', '', $match[1] ) ); if ( 'Module Tags' === $regex ) { $module_tags = array_map( 'trim', explode( ',', $string ) ); foreach ( $module_tags as $module_tag ) { $tags[ $module_tag ][] = $relative_path; } } $all_modules[ $module_slug ][ $field ] = $string; } } if ( '' === $all_modules[ $module_slug ]['name'] ) { // If the module info doesn't have a name, add the slug to the no info slugs list instead. unset( $all_modules[ $module_slug ] ); $no_info_slugs[] = $module_slug; } } /* * Create the jetpack_get_module_i18n function. */ $file_contents = "<?php /** * Do not edit this file. It's generated by `jetpack/tools/build-module-headings-translations.php`. * * @package automattic/jetpack */ /** * For a given module, return an array with translated name and description. * * @param string \$key Module file name without `.php`. * * @return array */ function jetpack_get_module_i18n( \$key ) { \tstatic \$modules; \tif ( ! isset( \$modules ) ) { \t\t\$modules = array("; $i18n_headers = array( 'name' => 'Module Name', 'description' => 'Module Description', 'tags' => 'Module Tags', ); foreach ( $all_modules as $module_key => $module_info ) { $_file_contents = ''; foreach ( $i18n_headers as $field => $description ) { if ( ! empty( $module_info[ $field ] ) ) { $_file_contents .= sprintf( "\t\t\t\t%s => _x( %s, %s, 'jetpack' ),\n", var_export( $field, true ), var_export( $module_info[ $field ], true ), var_export( $description, true ) ); } } if ( $_file_contents ) { $file_contents .= sprintf( "\n\t\t\t%s => array(\n%s\t\t\t),\n", var_export( $module_key, true ), $_file_contents ); } } $file_contents .= "\t\t); \t}"; $file_contents .= "\n\treturn isset( \$modules[ \$key ] ) ? \$modules[ \$key ] : null; }"; /* * Create the jetpack_get_module_i18n_tag function. */ $file_contents .= ' /** * For a given module tag, return its translated version. * * @param string $key Module tag as is in each module heading. * * @return string */'; $file_contents .= "\nfunction jetpack_get_module_i18n_tag( \$key ) { \tstatic \$module_tags; \tif ( ! isset( \$module_tags ) ) {"; $file_contents .= "\n\t\t\$module_tags = array("; foreach ( $tags as $tag_name => $tag_files ) { $file_contents .= "\n\t\t\t// Modules with `{$tag_name}` tag:\n"; foreach ( $tag_files as $file ) { $file_contents .= "\t\t\t// - {$file}\n"; } $file_contents .= sprintf( "\t\t\t%s => _x( %s, 'Module Tag', 'jetpack' ),\n", var_export( $tag_name, true ), var_export( $tag_name, true ) ); } $file_contents .= "\t\t); \t}"; $file_contents .= "\n\treturn ! empty( \$module_tags[ \$key ] ) ? \$module_tags[ \$key ] : ''; }\n"; /* * Create the jetpack_get_module_info function. */ $file_contents .= " /** * For a given module, return an array with the module info. * * @param string \$key Module file name without `.php`. * * return array|string An array containing the module info or an empty string if the given module isn't known. */ function jetpack_get_module_info( \$key ) { \tstatic \$module_info = " . str_replace( "\n", "\n\t", var_export( $all_modules, true ) ) . "; \treturn isset( \$module_info[ \$key ] ) ? \$module_info[ \$key ] : null; }\n"; /* * Create the jetpack_get_all_module_header_names function. */ $file_contents .= " /** * Return an array containing all module header names. * * @return array */ function jetpack_get_all_module_header_names() { \treturn " . str_replace( "\n", "\n\t", var_export( $all_module_headers, true ) ) . "; }\n"; /* * Create the jetpack_has_no_module_info function. */ $file_contents .= " /** * Returns whether the file associated with the given slug has no module info. * * @param string \$slug The slug name. * * @return bool Whether the file has no module info. */ function jetpack_has_no_module_info( \$slug ) { \t\$no_info_slugs = " . str_replace( "\n", "\n\t", var_export( $no_info_slugs, true ) ) . "; \treturn in_array( \$slug, \$no_info_slugs, true ); }\n"; file_put_contents( "{$jp_dir}modules/module-headings.php", $file_contents );
projects/plugins/jetpack/sal/class.json-api-date.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * WPCOM_JSON_API_Date class. * * @package automattic/jetpack */ /** * Base class for WPCOM_JSON_API_Date. */ class WPCOM_JSON_API_Date { /** * Returns ISO 8601 formatted datetime: 2011-12-08T01:15:36-08:00 * * @param string $date_gmt GMT datetime string. * @param string $date Optional. Used to calculate the offset from GMT. * * @return string */ public static function format_date( $date_gmt, $date = null ) { $offset = null; $timestamp_gmt = strtotime( "$date_gmt+0000" ); if ( null === $date ) { $timestamp = $timestamp_gmt; $west = 0; $minutes = 0; $hours = 0; } else { $date_time = date_create( "$date+0000" ); if ( $date_time ) { $timestamp = date_format( $date_time, 'U' ); } else { $timestamp = 0; } // "0000-00-00 00:00:00" == -62169984000 if ( -62169984000 === $timestamp_gmt ) { // WordPress sets post_date=now, post_date_gmt="0000-00-00 00:00:00" for all drafts // WordPress sets post_modified=now, post_modified_gmt="0000-00-00 00:00:00" for new drafts. // Try to guess the correct offset from the blog's options. $timezone_string = get_option( 'timezone_string' ); if ( $timezone_string && $date_time ) { $timezone = timezone_open( $timezone_string ); if ( $timezone ) { $offset = $timezone->getOffset( $date_time ); } } else { $offset = 3600 * get_option( 'gmt_offset' ); } } else { $offset = $timestamp - $timestamp_gmt; } $west = $offset < 0; $offset = abs( $offset ); $hours = (int) floor( $offset / 3600 ); $offset -= $hours * 3600; $minutes = (int) floor( $offset / 60 ); } return (string) gmdate( 'Y-m-d\\TH:i:s', $timestamp ) . sprintf( '%s%02d:%02d', $west ? '-' : '+', $hours, $minutes ); } /** * Returns ISO 8601 formatted duration interval: P0DT1H10M0S * * @param string $time Duration in minutes or hours. * * @return null|string */ public static function format_duration( $time ) { $timestamp = strtotime( $time, 0 ); // Bail early if we don't recognize a date. if ( empty( $timestamp ) ) { return; } $days = floor( $timestamp / 86400 ); $timestamp = $timestamp % 86400; $hours = floor( $timestamp / 3600 ); $timestamp = $timestamp % 3600; $minutes = floor( $timestamp / 60 ); $timestamp = $timestamp % 60; return (string) sprintf( 'P%dDT%dH%dM%dS', $days, $hours, $minutes, $timestamp ); } }
projects/plugins/jetpack/sal/class.json-api-links.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * WPCOM_JSON_API_Links class. * * @package automattic/jetpack */ require_once __DIR__ . '/../class.json-api.php'; /** * Base class for WPCOM_JSON_API_Links. */ class WPCOM_JSON_API_Links { /** * An instance of the WPCOM_JSON_API. * * @var WPCOM_JSON_API */ private $api; /** * A WPCOM_JSON_API_Links instance. * * @var WPCOM_JSON_API_Links */ private static $instance; /** * An array of the closest supported version of an endpoint to the current endpoint. * * @var array */ private $closest_endpoint_cache_by_version = array(); /** * An array including the current api endpoint as well as the max versions found if that endpoint doesn't exist. * * @var array */ private $matches_by_version = array(); /** * An array including the cached endpoint path versions. * * @var array */ private $cache_result = null; /** * Creates a new instance of the WPCOM_JSON_API_Links class. * * @return WPCOM_JSON_API_Links */ public static function getInstance() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * WPCOM_JSON_API_Links constructor. * * Method protected for singleton. */ protected function __construct() { $this->api = WPCOM_JSON_API::init(); } /** * An empty, private __clone method to prohibit cloning of this instance. */ private function __clone() { } /** * Overriding PHP's default __wakeup method to prvent unserializing of the instance, and return an error message. */ public function __wakeup() { die( "Please don't __wakeup WPCOM_JSON_API_Links" ); } /** * Generate a URL to an endpoint * * Used to construct meta links in API responses * * @param mixed ...$args Optional arguments to be appended to URL. * @return string Endpoint URL **/ public function get_link( ...$args ) { $format = array_shift( $args ); $base = WPCOM_JSON_API__BASE; $path = array_pop( $args ); if ( $path ) { $path = '/' . ltrim( $path, '/' ); // tack the path onto the end of the format string. // have to escape %'s in the path as %% because // we're about to pass it through sprintf and we don't // want it to see the % as a placeholder. $format .= str_replace( '%', '%%', $path ); } // Escape any % in args before using sprintf. $escaped_args = array(); foreach ( $args as $arg_key => $arg_value ) { $escaped_args[ $arg_key ] = str_replace( '%', '%%', $arg_value ); } $relative_path = vsprintf( $format, $escaped_args ); if ( ! wp_startswith( $relative_path, '.' ) ) { // Generic version. Match the requested version as best we can. $api_version = $this->get_closest_version_of_endpoint( $format, $relative_path ); $base = substr( $base, 0, - 1 ) . $api_version; } // escape any % in the relative path before running it through sprintf again. $relative_path = str_replace( '%', '%%', $relative_path ); // http, WPCOM_JSON_API__BASE, ... , path. // %s , %s , $format, %s. return esc_url_raw( sprintf( "https://%s$relative_path", $base ) ); } /** * Generate the /me prefixed endpoint URL * * Used to construct meta links in API responses, specific to WordPress.com user account pages. * * @param string $path Optional path to be appended to the URL. * @return string /me endpoint URL **/ public function get_me_link( $path = '' ) { return $this->get_link( '/me', $path ); } /** * Generate the endpoint URL for taxonomies * * Used to construct meta links in API responses, specific to taxonomies. * * @param int $blog_id The site's Jetpack blog ID. * @param int $taxonomy_id The taxonomy ID (for example of the category, tag). * @param string $taxonomy_type The taxonomy type (for example category, tag). * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including taxonomy information. **/ public function get_taxonomy_link( $blog_id, $taxonomy_id, $taxonomy_type, $path = '' ) { switch ( $taxonomy_type ) { case 'category': return $this->get_link( '/sites/%d/categories/slug:%s', $blog_id, $taxonomy_id, $path ); case 'post_tag': return $this->get_link( '/sites/%d/tags/slug:%s', $blog_id, $taxonomy_id, $path ); default: return $this->get_link( '/sites/%d/taxonomies/%s/terms/slug:%s', $blog_id, $taxonomy_type, $taxonomy_id, $path ); } } /** * Generate the endpoint URL for media links * * Used to construct meta links in API responses, specific to media links. * * @param int $blog_id The site's Jetpack blog ID. * @param int $media_id The media item ID. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including media information. **/ public function get_media_link( $blog_id, $media_id, $path = '' ) { return $this->get_link( '/sites/%d/media/%d', $blog_id, $media_id, $path ); } /** * Generate the site link endpoint URL * * Used to construct meta links in API responses, specific to /site links. * * @param int $blog_id The site's Jetpack blog ID. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including site information. **/ public function get_site_link( $blog_id, $path = '' ) { return $this->get_link( '/sites/%d', $blog_id, $path ); } /** * Generate the posts endpoint URL * * Used to construct meta links in API responses, specific to posts links. * * @param int $blog_id The site's Jetpack blog ID. * @param int $post_id The post ID. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including post information. **/ public function get_post_link( $blog_id, $post_id, $path = '' ) { return $this->get_link( '/sites/%d/posts/%d', $blog_id, $post_id, $path ); } /** * Generate the comments endpoint URL * * Used to construct meta links in API responses, specific to comments links. * * @param int $blog_id The site's Jetpack blog ID. * @param int $comment_id The comment ID. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including comment information. **/ public function get_comment_link( $blog_id, $comment_id, $path = '' ) { return $this->get_link( '/sites/%d/comments/%d', $blog_id, $comment_id, $path ); } /** * Generate the endpoint URL for Publicize connections * * Used to construct meta links in API responses, specific to Publicize connections. * * @param int $blog_id The site's Jetpack blog ID. * @param int $publicize_connection_id The ID of the Publicize connection. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including Publicize connection information. **/ public function get_publicize_connection_link( $blog_id, $publicize_connection_id, $path = '' ) { return $this->get_link( '.1/sites/%d/publicize-connections/%d', $blog_id, $publicize_connection_id, $path ); } /** * Generate the endpoint URL for a single Publicize connection including a Keyring connection * * Used to construct meta links in API responses, specific to a single Publicize and Keyring connection. * * @param int $keyring_token_id The ID of the Keyring connection. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including specific Keyring connection information for a specific Publicize connection. **/ public function get_publicize_connections_link( $keyring_token_id, $path = '' ) { return $this->get_link( '.1/me/publicize-connections/?keyring_connection_ID=%d', $keyring_token_id, $path ); } /** * Generate the endpoint URL for a single Keyring connection * * Used to construct meta links in API responses, specific to a Keyring connections. * * @param int $keyring_token_id The ID of the Keyring connection. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including specific Keyring connection. **/ public function get_keyring_connection_link( $keyring_token_id, $path = '' ) { return $this->get_link( '.1/me/keyring-connections/%d', $keyring_token_id, $path ); } /** * Generate the endpoint URL for an external service that can be integrated with via Keyring * * Used to construct meta links in API responses, specific to an external service. * * @param int $external_service The ID of the external service. * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including information about an external service that WordPress.com or Jetpack sites can integrate with via keyring. **/ public function get_external_service_link( $external_service, $path = '' ) { return $this->get_link( '.1/meta/external-services/%s', $external_service, $path ); } /** * Try to find the closest supported version of an endpoint to the current endpoint * * For example, if we were looking at the path /animals/panda: * - if the current endpoint is v1.3 and there is a v1.3 of /animals/%s available, we return 1.3 * - if the current endpoint is v1.3 and there is no v1.3 of /animals/%s known, we fall back to the * maximum available version of /animals/%s, e.g. 1.1 * * This method is used in get_link() to construct meta links for API responses. * * @param string $template_path The generic endpoint path, e.g. /sites/%s . * @param string $path The current endpoint path, relative to the version, e.g. /sites/12345 . * @param string $request_method Request method used to access the endpoint path . * @return string The current version, or otherwise the maximum version available */ public function get_closest_version_of_endpoint( $template_path, $path, $request_method = 'GET' ) { $closest_endpoint_cache_by_version = & $this->closest_endpoint_cache_by_version; $closest_endpoint_cache = & $closest_endpoint_cache_by_version[ $this->api->version ]; if ( ! $closest_endpoint_cache ) { $closest_endpoint_cache_by_version[ $this->api->version ] = array(); $closest_endpoint_cache = & $closest_endpoint_cache_by_version[ $this->api->version ]; } if ( ! isset( $closest_endpoint_cache[ $template_path ] ) ) { $closest_endpoint_cache[ $template_path ] = array(); } elseif ( isset( $closest_endpoint_cache[ $template_path ][ $request_method ] ) ) { return $closest_endpoint_cache[ $template_path ][ $request_method ]; } $path = untrailingslashit( $path ); // /help is a special case - always use the current request version if ( wp_endswith( $path, '/help' ) ) { $closest_endpoint_cache[ $template_path ][ $request_method ] = $this->api->version; return $this->api->version; } $matches_by_version = & $this->matches_by_version; // try to match out of saved matches. if ( ! isset( $matches_by_version[ $this->api->version ] ) ) { $matches_by_version[ $this->api->version ] = array(); } foreach ( $matches_by_version[ $this->api->version ] as $match ) { $regex = $match->regex; if ( preg_match( "#^$regex\$#", $path ) ) { $closest_endpoint_cache[ $template_path ][ $request_method ] = $match->version; return $match->version; } } $endpoint_path_versions = $this->get_endpoint_path_versions(); $last_path_segment = $this->get_last_segment_of_relative_path( $path ); $max_version_found = null; foreach ( $endpoint_path_versions as $endpoint_last_path_segment => $endpoints ) { // Does the last part of the path match the path key? (e.g. 'posts') // If the last part contains a placeholder (e.g. %s), we want to carry on. // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual if ( $last_path_segment != $endpoint_last_path_segment && ! strstr( $endpoint_last_path_segment, '%' ) ) { continue; } foreach ( $endpoints as $endpoint ) { // Does the request method match? if ( ! in_array( $request_method, $endpoint['request_methods'], true ) ) { continue; } $endpoint_path = untrailingslashit( $endpoint['path'] ); $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path ); if ( ! preg_match( "#^$endpoint_path_regex\$#", $path ) ) { continue; } // Make sure the endpoint exists at the same version. if ( null !== $this->api->version && version_compare( $this->api->version, $endpoint['min_version'], '>=' ) && version_compare( $this->api->version, $endpoint['max_version'], '<=' ) ) { array_push( $matches_by_version[ $this->api->version ], (object) array( 'version' => $this->api->version, 'regex' => $endpoint_path_regex, ) ); $closest_endpoint_cache[ $template_path ][ $request_method ] = $this->api->version; return $this->api->version; } // If the endpoint doesn't exist at the same version, record the max version we found. if ( empty( $max_version_found ) || version_compare( $max_version_found['version'], $endpoint['max_version'], '<' ) ) { $max_version_found = array( 'version' => $endpoint['max_version'], 'regex' => $endpoint_path_regex, ); } } } // If the endpoint version is less than the requested endpoint version, return the max version found. if ( ! empty( $max_version_found ) ) { array_push( $matches_by_version[ $this->api->version ], (object) $max_version_found ); $closest_endpoint_cache[ $template_path ][ $request_method ] = $max_version_found['version']; return $max_version_found['version']; } // Otherwise, use the API version of the current request. return $this->api->version; } /** * Get an array of endpoint paths with their associated versions * * @return array Array of endpoint paths, min_versions and max_versions, keyed by last segment of path **/ protected function get_endpoint_path_versions() { if ( ! empty( $this->cache_result ) ) { return $this->cache_result; } /* * Create a map of endpoints and their min/max versions keyed by the last segment of the path (e.g. 'posts') * This reduces the search space when finding endpoint matches in get_closest_version_of_endpoint() */ $endpoint_path_versions = array(); foreach ( $this->api->endpoints as $key => $endpoint_objects ) { // @todo As with the todo in class.json-api.php, we need to determine if anything depends on this being serialized and hence unserialized, rather than e.g. JSON. // The key contains a serialized path, min_version and max_version. list( $path, $min_version, $max_version ) = unserialize( $key ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Legacy, see serialization at class.json-api.php. // Grab the last component of the relative path to use as the top-level key. $last_path_segment = $this->get_last_segment_of_relative_path( $path ); $endpoint_path_versions[ $last_path_segment ][] = array( 'path' => $path, 'min_version' => $min_version, 'max_version' => $max_version, 'request_methods' => array_keys( $endpoint_objects ), ); } $this->cache_result = $endpoint_path_versions; return $endpoint_path_versions; } /** * Grab the last segment of a relative path * * @param string $path Path. * @return string Last path segment */ protected function get_last_segment_of_relative_path( $path ) { $path_parts = array_filter( explode( '/', $path ) ); if ( empty( $path_parts ) ) { return null; } return end( $path_parts ); } }
projects/plugins/jetpack/sal/class.json-api-site-jetpack-base.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * This class extends the SAL_Site class, providing the implementation for * functions that were declared in that SAL_Site class as well as defining * base functions to be implemented in class Jetpack_Site. * * @see class.json-api-site-jetpack.php for more context on * the functions extended here. * * @package automattic/jetpack */ require_once __DIR__ . '/class.json-api-site-base.php'; /** * Base class for Abstract_Jetpack_Site. */ abstract class Abstract_Jetpack_Site extends SAL_Site { /** * Defining a base get_constant() function to be extended in the Jetpack_Site class. * * If a Jetpack constant name has been defined, this will return the value of the constant. * * @param string $name the name of the Jetpack constant to check. */ abstract protected function get_constant( $name ); /** * Defining a base current_theme_supports() function to be extended in the Jetpack_Site class. * * Returns true if the current theme supports the $feature_name, false otherwise. * * @param string $feature_name the name of the Jetpack feature. */ abstract protected function current_theme_supports( $feature_name ); /** * Defining a base get_theme_support() function to be extended in the Jetpack_Site class. * * Gets theme support arguments to be checked against the specific Jetpack feature. * * @param string $feature_name the name of the Jetpack feature to check against. */ abstract protected function get_theme_support( $feature_name ); /** * Defining a base get_mock_option() function to be extended in the Jetpack_Site class. * * Retrieves a Jetpack option's value, given the option name. * * @param string $name the name of the Jetpack option, without the 'jetpack' prefix (eg. 'log' for 'jetpack_log'). */ abstract protected function get_mock_option( $name ); /** * Defining a base get_jetpack_version() function to be extended in the Jetpack_Site class. * * Returns the current Jetpack version number. */ abstract public function get_jetpack_version(); /** * Defining a base get_updates() function to be extended in the Jetpack_Site class. * * Gets updates and then stores them in the jetpack_updates option, returning an array with the option schema. */ abstract public function get_updates(); /** * Defining a base main_network_site() function to be extended in the Jetpack_Site class. * * Returns the site URL for the current network. */ abstract protected function main_network_site(); /** * Defining a base wp_version() function to be extended in the Jetpack_Site class. * * Returns the WordPress version for the current site. */ abstract protected function wp_version(); /** * Defining a base max_upload_size() function to be extended in the Jetpack_Site class. * * Returns the maximum upload size allowed in php.ini. */ abstract protected function max_upload_size(); /** * Defining a base is_main_network() function to be extended in the Jetpack_Site class. * * Returns true if the site is within a system with a multiple networks, false otherwise. * * @see /projects/packages/status/src/class-status.php. */ abstract protected function is_main_network(); /** * Defining a base is_version_controlled() function to be extended in the Jetpack_Site class. * * Returns true if is_vcs_checkout discovers a version control checkout, false otherwise. * * @see projects/packages/sync/src/class-functions.php. */ abstract protected function is_version_controlled(); /** * Defining a base file_system_write_access() function to be extended in the Jetpack_Site class. * * Returns true if the site has file write access false otherwise. * * @see projects/packages/sync/src/class-functions.php. */ abstract protected function file_system_write_access(); /** * Fetch a list of active plugins that are using Jetpack Connection. */ abstract protected function get_connection_active_plugins(); /** * This function is implemented on WPCom sites, where a filter is removed which forces the URL to http. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. */ public function before_render() { } /** * This function returns the value of the 'WP_MEMORY_LIMIT' constant. * * @return int|string */ protected function wp_memory_limit() { return $this->get_constant( 'WP_MEMORY_LIMIT' ); } /** * This function returns the value of the 'WP_MAX_MEMORY_LIMIT' constant. * * @return int|string */ protected function wp_max_memory_limit() { return $this->get_constant( 'WP_MAX_MEMORY_LIMIT' ); } /** * If a user has manage options permissions and the site is the main site of the network, make updates visible. * * Called after response_keys have been rendered, which itself is used to return all the necessary information for a site’s response. * * @param array $response an array of the response keys. */ public function after_render( &$response ) { if ( current_user_can( 'manage_options' ) && $this->is_main_site( $response ) ) { $jetpack_update = $this->get_updates(); if ( ! empty( $jetpack_update ) ) { // In previous version of Jetpack 3.4, 3.5, 3.6 we synced the wp_version into to jetpack_updates. unset( $jetpack_update['wp_version'] ); // In previous version of Jetpack 3.4, 3.5, 3.6 we synced the site_is_version_controlled into to jetpack_updates. unset( $jetpack_update['site_is_version_controlled'] ); $response['updates'] = $jetpack_update; } } } /** * Extends the Jetpack options array with details including site constraints, WordPress and Jetpack versions, and plugins using the Jetpack connection. * * @param array $options an array of the Jetpack options. */ public function after_render_options( &$options ) { $options['jetpack_version'] = $this->get_jetpack_version(); $main_network_site = $this->main_network_site(); if ( $main_network_site ) { $options['main_network_site'] = (string) rtrim( $main_network_site, '/' ); } $active_modules = Jetpack_Options::get_option( 'active_modules' ); if ( is_array( $active_modules ) ) { $options['active_modules'] = (array) array_values( $active_modules ); } $options['software_version'] = (string) $this->wp_version(); $options['max_upload_size'] = $this->max_upload_size(); $options['wp_memory_limit'] = $this->wp_memory_limit(); $options['wp_max_memory_limit'] = $this->wp_max_memory_limit(); // Sites have to prove that they are not main_network site. // If the sync happends right then we should be able to see that we are not dealing with a network site. $options['is_multi_network'] = (bool) $this->is_main_network(); $options['is_multi_site'] = (bool) $this->is_multisite(); $file_mod_disabled_reasons = array_keys( array_filter( array( 'automatic_updater_disabled' => (bool) $this->get_constant( 'AUTOMATIC_UPDATER_DISABLED' ), // WP AUTO UPDATE CORE defaults to minor, '1' if true and '0' if set to false. 'wp_auto_update_core_disabled' => ! ( (bool) $this->get_constant( 'WP_AUTO_UPDATE_CORE' ) ), 'is_version_controlled' => (bool) $this->is_version_controlled(), // By default we assume that site does have system write access if the value is not set yet. 'has_no_file_system_write_access' => ! (bool) $this->file_system_write_access(), 'disallow_file_mods' => (bool) $this->get_constant( 'DISALLOW_FILE_MODS' ), ) ) ); $options['file_mod_disabled'] = empty( $file_mod_disabled_reasons ) ? false : $file_mod_disabled_reasons; $options['jetpack_connection_active_plugins'] = $this->get_connection_active_plugins(); } /** * This function returns the values of any active Jetpack modules. * * @return array */ public function get_jetpack_modules() { return array_values( Jetpack_Options::get_option( 'active_modules', array() ) ); } /** * This function returns true if a specified Jetpack module is active, false otherwise. * * @param string $module The Jetpack module name to check. * * @return bool */ public function is_module_active( $module ) { return in_array( $module, Jetpack_Options::get_option( 'active_modules', array() ), true ); } /** * This function returns false for a check as to whether a site is a VIP site or not. * * @return bool Always returns false. */ public function is_vip() { return false; // this may change for VIP Go sites, which sync using Jetpack. } /** * If the site's current theme supports post thumbnails, return true (otherwise return false). * * @return bool */ public function featured_images_enabled() { return $this->current_theme_supports( 'post-thumbnails' ); } /** * Returns an array of supported post formats. * * @return array */ public function get_post_formats() { // deprecated - see separate endpoint. get a list of supported post formats. $all_formats = get_post_format_strings(); $supported = $this->get_theme_support( 'post-formats' ); $supported_formats = array(); if ( isset( $supported[0] ) ) { foreach ( $supported[0] as $format ) { $supported_formats[ $format ] = $all_formats[ $format ]; } } return $supported_formats; } /** * Returns an array with site icon details. * * @return array */ public function get_icon() { $icon_id = get_option( 'site_icon' ); if ( empty( $icon_id ) ) { $icon_id = Jetpack_Options::get_option( 'site_icon_id' ); } if ( empty( $icon_id ) ) { return null; } $icon = array_filter( array( 'img' => wp_get_attachment_image_url( $icon_id, 'full' ), 'ico' => wp_get_attachment_image_url( $icon_id, array( 16, 16 ) ), ) ); if ( empty( $icon ) ) { return null; } if ( current_user_can( 'edit_posts', $icon_id ) ) { $icon['media_id'] = (int) $icon_id; } return $icon; } /** * Private methods **/ /** * This function returns true if the current site is the main network site, false otherwise. * * @param array $response The array of Jetpack response keys. * * @return bool */ private function is_main_site( $response ) { if ( isset( $response['options']->main_network_site ) && isset( $response['options']->unmapped_url ) ) { $main_network_site_url = set_url_scheme( $response['options']->main_network_site, 'http' ); $unmapped_url = set_url_scheme( $response['options']->unmapped_url, 'http' ); if ( $unmapped_url === $main_network_site_url ) { return true; } } return false; } /** * For Jetpack sites this will always return false. * * This is extended for WordPress.com sites in wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @param int $post_id The post id. * * @return bool */ protected function is_a8c_publication( $post_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Extended and used in WordPress.com. return false; } }
projects/plugins/jetpack/sal/class.json-api-site-jetpack.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * This class extends the Abstract_Jetpack_Site class, which includes providing * the implementation for functions that were declared in that class. * * @see class.json-api-site-jetpack-base.php for more context on some of * the functions extended here. * * @package automattic/jetpack */ use Automattic\Jetpack\Status\Host; use Automattic\Jetpack\Sync\Functions; require_once __DIR__ . '/class.json-api-site-jetpack-base.php'; require_once __DIR__ . '/class.json-api-post-jetpack.php'; /** * Base class for Jetpack_Site. This code runs on Jetpack (.org) sites. */ class Jetpack_Site extends Abstract_Jetpack_Site { /** * Retrieves a Jetpack option's value, given the option name. * * @param string $name the name of the Jetpack option, without the 'jetpack' prefix (eg. 'log' for 'jetpack_log'). * * @return mixed */ protected function get_mock_option( $name ) { return get_option( 'jetpack_' . $name ); } /** * If a Jetpack constant name has been defined, this will return the value of the constant. * * @param string $name the name of the Jetpack constant to check. * * @return mixed */ protected function get_constant( $name ) { if ( defined( $name ) ) { return constant( $name ); } return null; } /** * Returns the site URL for the current network. * * @return string */ protected function main_network_site() { return network_site_url(); } /** * Returns the WordPress version for the current site. * * @return string */ protected function wp_version() { global $wp_version; return $wp_version; } /** * Returns the maximum upload size allowed in php.ini. * * @return int */ protected function max_upload_size() { return wp_max_upload_size(); } /** * This function returns the value of the 'WP_MEMORY_LIMIT' constant converted to an integer byte value. * * @return int */ protected function wp_memory_limit() { return wp_convert_hr_to_bytes( WP_MEMORY_LIMIT ); } /** * This function returns the value of the 'WP_MAX_MEMORY_LIMIT' constant converted to an integer byte value. * * @return int */ protected function wp_max_memory_limit() { return wp_convert_hr_to_bytes( WP_MAX_MEMORY_LIMIT ); } /** * Returns true if the site is within a system with a multiple networks, false otherwise. * * @see /projects/packages/status/src/class-status.php * * @return bool */ protected function is_main_network() { return Jetpack::is_multi_network(); } /** * Returns true if Multisite is enabled, false otherwise. * * @return bool */ public function is_multisite() { return (bool) is_multisite(); } /** * Returns true if the current site is a single user site, false otherwise. * * @return bool */ public function is_single_user_site() { return (bool) Jetpack::is_single_user_site(); } /** * Returns true if is_vcs_checkout discovers a version control checkout, false otherwise. * * @see projects/packages/sync/src/class-functions.php. * * @return bool */ protected function is_version_controlled() { return Functions::is_version_controlled(); } /** * Returns true if the site has file write access, false otherwise. * * @see projects/packages/sync/src/class-functions.php. * * @return bool */ protected function file_system_write_access() { return Functions::file_system_write_access(); } /** * Returns true if the current theme supports the $feature_name, false otherwise. * * @param string $feature_name the name of the Jetpack feature. * * @return bool */ protected function current_theme_supports( $feature_name ) { return current_theme_supports( $feature_name ); } /** * Gets theme support arguments to be checked against the specific Jetpack feature. * * @param string $feature_name the name of the Jetpack feature to check against. * * @return array */ protected function get_theme_support( $feature_name ) { return get_theme_support( $feature_name ); } /** * Fetch a list of active plugins that are using Jetpack Connection. * * @return array An array of active plugins (by slug) that are using Jetpack Connection. */ protected function get_connection_active_plugins() { $plugins = $this->get_mock_option( 'connection_active_plugins' ); return is_array( $plugins ) ? array_keys( $plugins ) : array(); } /** * Gets updates and then stores them in the jetpack_updates option, returning an array with the option schema. * * @return array */ public function get_updates() { return (array) Jetpack::get_updates(); } /** * Returns the Jetpack blog ID for a site. * * @return int */ public function get_id() { return $this->platform->token->blog_id; } /** * Returns true if a site has the 'videopress' option enabled, false otherwise. * * @return bool */ public function has_videopress() { // TODO - this only works on wporg site - need to detect videopress option for remote Jetpack site on WPCOM. $videopress = Jetpack_Options::get_option( 'videopress', array() ); if ( isset( $videopress['blog_id'] ) && $videopress['blog_id'] > 0 ) { return true; } return false; } /** * Returns VideoPress storage used, in MB. * * @see class.json-api-site-jetpack-shadow.php on WordPress.com for implementation. Only applicable on WordPress.com. * * @return float */ public function get_videopress_storage_used() { return 0; } /** * Sets the upgraded_filetypes_enabled Jetpack option to true as a default. * * Only relevant for WordPress.com sites: * See wpcom_site_has_upgraded_upload_filetypes at /wpcom/wp-content/mu-plugins/misc.php. * * @return bool */ public function upgraded_filetypes_enabled() { return true; } /** * Sets the is_mapped_domain Jetpack option to true as a default. * * Primarily used in WordPress.com to confirm the current blog's domain does or doesn't match the primary redirect. * * @see /wpcom/wp-content/mu-plugins/insecure-content-helpers.php within WordPress.com. * * @return bool */ public function is_mapped_domain() { return true; } /** * Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain. * * @return string */ public function get_unmapped_url() { // Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain. return $this->get_url(); } /** * Whether the domain is a site redirect or not. Defaults to false on a Jetpack site. * * Primarily used in WordPress.com where it is determined if a HTTP status check is a redirect or not and whether an exception should be thrown. * * @see /wpcom/wp-includes/Requests/Response.php within WordPress.com. * * @return bool */ public function is_redirect() { return false; } /** * Whether or not the current user is following this blog. Defaults to false. * * @return bool */ public function is_following() { return false; } /** * Points to the user ID of the site owner * * @return null for Jetpack sites */ public function get_site_owner() { return null; } /** * Whether or not the Jetpack 'wordads' module is active on the site. * * @return bool */ public function has_wordads() { return Jetpack::is_module_active( 'wordads' ); } /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites. This nonce is used for previews on Jetpack sites. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool */ public function get_frame_nonce() { return false; } /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites, * where it creates a nonce to be used with iframed block editor requests to a Jetpack site. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool */ public function get_jetpack_frame_nonce() { return false; } /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites, where it returns true if the headstart-fresh blog sticker is present. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return bool */ public function is_headstart_fresh() { return false; } /** * Returns the allowed mime types and file extensions for a site. * * @return array */ public function allowed_file_types() { $allowed_file_types = array(); // https://codex.wordpress.org/Uploading_Files. $mime_types = get_allowed_mime_types(); foreach ( $mime_types as $type => $mime_type ) { $extras = explode( '|', $type ); foreach ( $extras as $extra ) { $allowed_file_types[] = $extra; } } return $allowed_file_types; } /** * Return site's privacy status. * * @return bool Is site private? */ public function is_private() { return (int) $this->get_atomic_cloud_site_option( 'blog_public' ) === -1; } /** * Return site's coming soon status. * * @return bool Is site "Coming soon"? */ public function is_coming_soon() { return $this->is_private() && (int) $this->get_atomic_cloud_site_option( 'wpcom_coming_soon' ) === 1; } /** * Return site's launch status. * * @return string|bool Launch status ('launched', 'unlaunched', or false). */ public function get_launch_status() { return $this->get_atomic_cloud_site_option( 'launch-status' ); } /** * Given an option name, returns false if the site isn't WoA or doesn't have the ability to retrieve cloud site options. * Otherwise, if the option name exists amongst Jetpack options, the option value is returned. * * @param string $option The option name to check. * * @return string|bool */ public function get_atomic_cloud_site_option( $option ) { if ( ! ( new Host() )->is_woa_site() ) { return false; } $jetpack = Jetpack::init(); if ( ! method_exists( $jetpack, 'get_cloud_site_options' ) ) { return false; } $result = $jetpack->get_cloud_site_options( array( $option ) ); if ( ! array_key_exists( $option, $result ) ) { return false; } return $result[ $option ]; } /** * Defaults to false instead of returning the current site plan. * * @see /modules/masterbar/admin-menu/class-dashboard-switcher-tracking.php. * * @return bool */ public function get_plan() { return false; } /** * Defaults to 0 for the number of WordPress.com subscribers - this is filled in on the WordPress.com side. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return int */ public function get_subscribers_count() { return 0; } /** * Defaults to false - this is filled on the WordPress.com side in multiple locations. * * @return bool */ public function get_capabilities() { return false; } /** * Returns the language code for the current site. * * @return string */ public function get_locale() { return get_bloginfo( 'language' ); } /** * The flag indicates that the site has Jetpack installed. * * @return bool */ public function is_jetpack() { return true; } /** * The flag indicates that the site is connected to WP.com via Jetpack Connection. * * @return bool */ public function is_jetpack_connection() { return true; } /** * Returns the current site's Jetpack version. * * @return string */ public function get_jetpack_version() { return JETPACK__VERSION; } /** * Empty function declaration - this function is filled out on the WordPress.com side, returning true if the site has an AK / VP bundle. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. */ public function get_ak_vp_bundle_enabled() {} /** * Returns the front page meta description for current site. * * @see /modules/seo-tools/class-jetpack-seo-utils.php. * * @return string */ public function get_jetpack_seo_front_page_description() { return Jetpack_SEO_Utils::get_front_page_meta_description(); } /** * Returns custom title formats from site option. * * @see /modules/seo-tools/class-jetpack-seo-titles.php. * * @return array */ public function get_jetpack_seo_title_formats() { return Jetpack_SEO_Titles::get_custom_title_formats(); } /** * Returns website verification codes. Allowed keys include: google, pinterest, bing, yandex, facebook. * * @see /modules/verification-tools/blog-verification-tools.php. * * @return array */ public function get_verification_services_codes() { return get_option( 'verification_services_codes', null ); } /** * Returns null for Jetpack sites. For WordPress.com sites this returns the value of the 'podcasting_archive' option. * * @see /wpcom/public.api/rest/sal/class.json-api-site-wpcom.php. * * @return null */ public function get_podcasting_archive() { return null; } /** * Defaulting to true, this function is expanded out on the WordPress.com side, returning an error if the site is not connected or not communicating to us. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool */ public function is_connected_site() { return true; } /** * Defaulting to false and not relevant for Jetpack sites, this is expanded on the WordPress.com side for a specific wp.com/start 'WP for teams' flow. * * @see /wpcom/public.api/rest/sal/class.json-api-site-wpcom.php. * * @return bool */ public function is_wpforteams_site() { return false; } /** * Returns true if a user has got the capability that is being checked, false otherwise. * * @param string $role The capability to check. * * @return bool */ public function current_user_can( $role ) { return current_user_can( $role ); } /** * Check if full site editing should be considered as currently active. Full site editing * requires the FSE plugin to be installed and activated, as well the current * theme to be FSE compatible. The plugin can also be explicitly disabled via the * a8c_disable_full_site_editing filter. * * @since 7.7.0 * * @return bool true if full site editing is currently active. */ public function is_fse_active() { if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) { return false; } return function_exists( '\A8C\FSE\is_full_site_editing_active' ) && \A8C\FSE\is_full_site_editing_active(); } /** * Check if site should be considered as eligible for full site editing. Full site editing * requires the FSE plugin to be installed and activated. For this method to return true * the current theme does not need to be FSE compatible. The plugin can also be explicitly * disabled via the a8c_disable_full_site_editing filter. * * @since 8.1.0 * * @return bool true if site is eligible for full site editing */ public function is_fse_eligible() { if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) { return false; } return function_exists( '\A8C\FSE\is_site_eligible_for_full_site_editing' ) && \A8C\FSE\is_site_eligible_for_full_site_editing(); } /** * Check if site should be considered as eligible for use of the core Site Editor. * The Site Editor requires a block based theme to be active. * * @since 12.2 Uses wp_is_block_theme() to determine if site is eligible instead of gutenberg_is_fse_theme(). * @return bool true if site is eligible for the Site Editor */ public function is_core_site_editor_enabled() { return wp_is_block_theme(); } /** * Return the last engine used for an import on the site. Not used in Jetpack. * * @see /wpcom/public.api/rest/sal/class.json-api-site-wpcom.php. * * @return null */ public function get_import_engine() { return null; } /** * Post functions */ /** * Wrap a WP_Post object with SAL methods, returning a Jetpack_Post object. * * @param WP_Post $post A WP_Post object. * @param string $context The post request context (for example 'edit' or 'display'). * * @return Jetpack_Post */ public function wrap_post( $post, $context ) { return new Jetpack_Post( $this, $post, $context ); } /** * Get the option storing the Anchor podcast ID that identifies a site as a podcasting site. * * @return string */ public function get_anchor_podcast() { return $this->get_atomic_cloud_site_option( 'anchor_podcast' ); } /** * Get user interactions with a site. Not used in Jetpack. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return null */ public function get_user_interactions() { return null; } /** * Detect whether a site is WordPress.com Staging Site. Not used in Jetpack. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return false */ public function is_wpcom_staging_site() { return false; } /** * Get site option for the production blog id (if is a WP.com Staging Site). Not used in Jetpack. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return null */ public function get_wpcom_production_blog_id() { return null; } /** * Get site option for the staging blog ids (if it has them). Not used in Jetpack. * * @see /wpcom/public.api/rest/sal/trait.json-api-site-wpcom.php. * * @return null */ public function get_wpcom_staging_blog_ids() { return null; } /** * Get site option for the admin interface on WordPress.com Atomic sites. Not used in Jetpack. * * @return null */ public function get_wpcom_admin_interface() { return null; } }
projects/plugins/jetpack/sal/class.json-api-site-base.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * This file defines the base class for the Site Abstraction Layer (SAL). * Note that this is the site "as seen by user $user_id with token $token", which * is why we pass the token to the platform; these site instances are value objects * to be used in the context of a single request for a single user. * Also note that at present this class _assumes_ you've "switched to" * the site in question, and functions like `get_bloginfo( 'name' )` will * therefore return the correct value. * * @package automattic/jetpack **/ use Automattic\Jetpack\Blaze; use Automattic\Jetpack\Status; use Automattic\Jetpack\Status\Host; require_once __DIR__ . '/class.json-api-date.php'; require_once __DIR__ . '/class.json-api-post-base.php'; /** * Base class for SAL_Site. * The abstract functions here are extended by Abstract_Jetpack_Site in class.json-api-site-jetpack-base.php. */ abstract class SAL_Site { /** * The Jetpack blog ID for the site. * * @var int */ public $blog_id; /** * A new WPORG_Platform instance. * * @see class.json-api-platform-jetpack.php. * * @var WPORG_Platform */ public $platform; /** * Contructs the SAL_Site instance. * * @param int $blog_id The Jetpack blog ID for the site. * @param WPORG_Platform $platform A new WPORG_Platform instance. */ public function __construct( $blog_id, $platform ) { $this->blog_id = $blog_id; $this->platform = $platform; } /** * Get the blog_id property. * * @return int */ public function get_id() { return $this->blog_id; } /** * Returns the site name. * * @return string */ public function get_name() { return (string) htmlspecialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); } /** * Returns the site description. * * @return string */ public function get_description() { return (string) htmlspecialchars_decode( get_bloginfo( 'description' ), ENT_QUOTES ); } /** * Returns the URL for the current site. * * @return string */ public function get_url() { return (string) home_url(); } /** * Returns the number of published posts with the 'post' post-type. * * @return int */ public function get_post_count() { return (int) wp_count_posts( 'post' )->publish; } /** * A prototype function for get_quota - currently returns null. * * @return null */ public function get_quota() { return null; } /** * Returns an array of blogging prompt settings. Only applicable on WordPress.com. * * Data comes from .com since the fearture requires a .com connection to work. * * @param int $user_id the current user_id. * @param int $blog_id the blog id in this context. */ public function get_blogging_prompts_settings( $user_id, $blog_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return false; } /** * Returns true if a site has the 'videopress' option enabled, false otherwise. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function has_videopress(); /** * Returns VideoPress storage used, in MB. * * @see class.json-api-site-jetpack-shadow.php on WordPress.com for implementation. Only applicable on WordPress.com. */ abstract public function get_videopress_storage_used(); /** * Sets the upgraded_filetypes_enabled Jetpack option to true as a default. Only relevant for WordPress.com sites. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function upgraded_filetypes_enabled(); /** * Sets the is_mapped_domain Jetpack option to true as a default. * * Primarily used in WordPress.com to confirm the current blog's domain does or doesn't match the primary redirect. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_mapped_domain(); /** * Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_unmapped_url(); /** * Whether the domain is a site redirect or not. Defaults to false on a Jetpack site. * * Primarily used in WordPress.com where it is determined if a HTTP status check is a redirect or not and whether an exception should be thrown. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_redirect(); /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites, where it returns true if the headstart-fresh blog sticker is present. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_headstart_fresh(); /** * If the site's current theme supports post thumbnails, return true (otherwise return false). * * @see class.json-api-site-jetpack-base.php for implementation. */ abstract public function featured_images_enabled(); /** * Whether or not the Jetpack 'wordads' module is active on the site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function has_wordads(); /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites. This nonce is used for previews on Jetpack sites. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_frame_nonce(); /** * Defaults to false on Jetpack sites, however is used on WordPress.com sites where * it creates a nonce to be used with iframed block editor requests to a Jetpack site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_jetpack_frame_nonce(); /** * Returns the allowed mime types and file extensions for a site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function allowed_file_types(); /** * Returns an array of supported post formats. * * @see class.json-api-site-jetpack-base.php for implementation. */ abstract public function get_post_formats(); /** * Return site's privacy status. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_private(); /** * Return site's coming soon status. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_coming_soon(); /** * Whether or not the current user is following this blog. Defaults to false. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_following(); /** * Defaults to 0 for the number of WordPress.com subscribers - this is filled in on the WordPress.com side. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_subscribers_count(); /** * Returns the language code for the current site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_locale(); /** * The flag indicates that the site has Jetpack installed. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_jetpack(); /** * The flag indicates that the site is connected to WP.com via Jetpack Connection. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_jetpack_connection(); /** * This function returns the values of any active Jetpack modules. * * @see class.json-api-site-jetpack-base.php for implementation. */ abstract public function get_jetpack_modules(); /** * This function returns true if a specified Jetpack module is active, false otherwise. * * @see class.json-api-site-jetpack-base.php for implementation. * * @param string $module The Jetpack module name to check. */ abstract public function is_module_active( $module ); /** * This function returns false for a check as to whether a site is a VIP site or not. * * @see class.json-api-site-jetpack-base.php for implementation. */ abstract public function is_vip(); /** * Returns true if Multisite is enabled, false otherwise. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_multisite(); /** * Points to the user ID of the site owner * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_site_owner(); /** * Returns true if the current site is a single user site, false otherwise. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_single_user_site(); /** * Defaults to false instead of returning the current site plan. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_plan(); /** * Empty function declaration - this function is filled out on the WordPress.com side, returning true if the site has an AK / VP bundle. * * @see class.json-api-site-jetpack.php and /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. */ abstract public function get_ak_vp_bundle_enabled(); /** * Returns null for Jetpack sites. For WordPress.com sites this returns the value of the 'podcasting_archive' option. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_podcasting_archive(); /** * Return the last engine used for an import on the site. Not used in Jetpack. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_import_engine(); /** * Returns the front page meta description for current site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_jetpack_seo_front_page_description(); /** * Returns custom title formats from site option. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_jetpack_seo_title_formats(); /** * Returns website verification codes. Allowed keys include: google, pinterest, bing, yandex, facebook. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_verification_services_codes(); /** * This function is implemented on WPCom sites, where a filter is removed which forces the URL to http. * * @see class.json-api-site-jetpack-base.php and /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. */ abstract public function before_render(); /** * If a user has manage options permissions and the site is the main site of the network, make updates visible. * * Called after response_keys have been rendered, which itself is used to return all the necessary information for a site’s response. * * @see class.json-api-site-jetpack-base.php for implementation. * * @param array $response an array of the response keys. */ abstract public function after_render( &$response ); /** * Extends the Jetpack options array with details including site constraints, WordPress and Jetpack versions, and plugins using the Jetpack connection. * * @see class.json-api-site-jetpack-base.php for implementation. * @todo factor this out? Seems an odd thing to have on a site * * @param array $options an array of the Jetpack options. */ abstract public function after_render_options( &$options ); /** * Wrap a WP_Post object with SAL methods, returning a Jetpack_Post object. * * @see class.json-api-site-jetpack.php for implementation. * * @param WP_Post $post A WP_Post object. * @param string $context The post request context (for example 'edit' or 'display'). */ abstract public function wrap_post( $post, $context ); /** * For Jetpack sites this will always return false. * * @see class.json-api-site-jetpack-base.php for implementation. * * @param int $post_id The post id. */ abstract protected function is_a8c_publication( $post_id ); /** * Return the user interactions with a site. Not used in Jetpack. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_user_interactions(); /** * Defines a filter to set whether a site is an automated_transfer site or not. * * Default is false. * * @return bool */ public function is_automated_transfer() { /** * Filter if a site is an automated-transfer site. * * @module json-api * * @since 6.4.0 * * @param bool is_automated_transfer( $this->blog_id ) * @param int $blog_id Blog identifier. */ return apply_filters( 'jetpack_site_automated_transfer', false, $this->blog_id ); } /** * Defaulting to false and not relevant for Jetpack sites, this is expanded on the WordPress.com side for a specific wp.com/start 'WP for teams' flow. * * @see class.json-api-site-jetpack.php for implementation. */ abstract protected function is_wpforteams_site(); /** * Get hub blog id for P2 sites. * * @return null */ public function get_p2_hub_blog_id() { return null; } /** * Getter for the p2 organization ID. * * @return int */ public function get_p2_organization_id() { return 0; // WPForTeams\Constants\NO_ORG_ID not loaded. } /** * Get details used to render a thumbnail of the site. P2020 themed sites only. * * @return ?array */ public function get_p2_thumbnail_elements() { return null; } /** * Detect whether a site is a WordPress.com on Atomic site. * * @return bool */ public function is_wpcom_atomic() { return ( new Host() )->is_woa_site(); } /** * Detect whether a site is an automated transfer site and WooCommerce is active. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool - False for Jetpack-connected sites. */ public function is_wpcom_store() { return false; } /** * Indicate whether this site was ever a specific trial. * * @param string $trial The trial type to check for. * * @return bool */ public function was_trial( $trial ) { if ( function_exists( 'has_blog_sticker' ) ) { return has_blog_sticker( "had-{$trial}-trial" ); } return false; } /** * Indicate whether this site was upgraded from a trial plan at some point. * * @return bool */ public function was_upgraded_from_trial() { if ( function_exists( 'has_blog_sticker' ) ) { return has_blog_sticker( 'has-upgraded-from-ecommerce-trial' ); } return false; } /** * Detect whether a site has the WooCommerce plugin active. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool - Default false for Jetpack-connected sites. */ public function woocommerce_is_active() { return false; } /** * Whether the Editing Toolkit plugin is active (relevant only on WordPress.com). * * @return true */ public function editing_toolkit_is_active() { return true; } /** * Detect whether a site has access to the Jetpack cloud. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool - Default false for Jetpack-connected sites. */ public function is_cloud_eligible() { return false; } /** * Returns an array of WPCOM_Store products. * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php. * * @return bool - Default empty array for Jetpack-connected sites. */ public function get_products() { return array(); } /** * Get post by ID * * @param int $post_id The ID of the post. * @param string $context The context by which the post data is required (display or edit). * * @return Jetpack_Post Post object on success, WP_Error object on failure **/ public function get_post_by_id( $post_id, $context ) { $post = get_post( $post_id, OBJECT, $context ); if ( ! $post ) { return new WP_Error( 'unknown_post', 'Unknown post', 404 ); } $wrapped_post = $this->wrap_post( $post, $context ); // validate access return $this->validate_access( $wrapped_post ); } /** * Validate current user can access the post * * @param Jetpack_Post $post Post object. * * @return WP_Error|Jetpack_Post */ private function validate_access( $post ) { $context = $post->context; if ( ! $this->is_post_type_allowed( $post->post_type ) && ! $this->is_a8c_publication( $post->ID ) ) { return new WP_Error( 'unknown_post', 'Unknown post', 404 ); } switch ( $context ) { case 'edit': if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot edit post', 403 ); } break; case 'display': $can_view = $this->user_can_view_post( $post ); if ( is_wp_error( $can_view ) ) { return $can_view; } break; default: return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 ); } return $post; } /** * Validate whether the current user can access the specified post type. * * @param string $post_type The post type to check. * @param string $context The context by which the post data is required (display or edit). * * @return bool */ public function current_user_can_access_post_type( $post_type, $context ) { $post_type_object = $this->get_post_type_object( $post_type ); if ( ! $post_type_object ) { return false; } switch ( $context ) { case 'edit': return current_user_can( $post_type_object->cap->edit_posts ); case 'display': return $post_type_object->public || current_user_can( $post_type_object->cap->read_private_posts ); default: return false; } } /** * Retrieves a post type object by name. * * @param string $post_type The post type to check. * * @return WP_Post_Type|null */ protected function get_post_type_object( $post_type ) { return get_post_type_object( $post_type ); } /** * Is the post type allowed? * * Function copied from class.json-api-endpoints.php. * * @param string $post_type Post type. * * @return bool */ public function is_post_type_allowed( $post_type ) { // if the post type is empty, that's fine, WordPress will default to post if ( empty( $post_type ) ) { return true; } // allow special 'any' type if ( 'any' === $post_type ) { return true; } // check for allowed types if ( in_array( $post_type, $this->get_whitelisted_post_types(), true ) ) { return true; } $post_type_object = get_post_type_object( $post_type ); if ( $post_type_object ) { if ( ! empty( $post_type_object->show_in_rest ) ) { return $post_type_object->show_in_rest; } if ( ! empty( $post_type_object->publicly_queryable ) ) { return $post_type_object->publicly_queryable; } } return ! empty( $post_type_object->public ); } /** * Gets the whitelisted post types that JP should allow access to. * * Function copied from class.json-api-endpoints.php. * * @return array Whitelisted post types. */ public function get_whitelisted_post_types() { $allowed_types = array( 'post', 'page', 'revision' ); /** * Filter the post types Jetpack has access to, and can synchronize with WordPress.com. * * @module json-api * * @since 2.2.3 * * @param array $allowed_types Array of whitelisted post types. Default to `array( 'post', 'page', 'revision' )`. */ $allowed_types = apply_filters( 'rest_api_allowed_post_types', $allowed_types ); return array_unique( $allowed_types ); } /** * Can the user view the post? * * Function copied from class.json-api-endpoints.php and modified. * * @param Jetpack_Post $post Post object. * @return bool|WP_Error */ private function user_can_view_post( $post ) { if ( ! $post || is_wp_error( $post ) ) { return false; } if ( 'inherit' === $post->post_status ) { $parent_post = get_post( $post->post_parent ); $post_status_obj = get_post_status_object( $parent_post->post_status ); } else { $post_status_obj = get_post_status_object( $post->post_status ); } $authorized = ( $post_status_obj->public || ( is_user_logged_in() && ( ( $post_status_obj->protected && current_user_can( 'edit_post', $post->ID ) ) || ( $post_status_obj->private && current_user_can( 'read_post', $post->ID ) ) || ( 'trash' === $post->post_status && current_user_can( 'edit_post', $post->ID ) ) || 'auto-draft' === $post->post_status ) ) ); if ( ! $authorized ) { return new WP_Error( 'unauthorized', 'User cannot view post', 403 ); } if ( ( new Status() )->is_private_site() && /** * Filter access to a specific post. * * @module json-api * * @since 3.4.0 * * @param bool current_user_can( 'read_post', $post->ID ) Can the current user access the post. * @param WP_Post $post Post data. */ ! apply_filters( 'wpcom_json_api_user_can_view_post', current_user_can( 'read_post', $post->ID ), $post ) ) { return new WP_Error( 'unauthorized', 'User cannot view post', array( 'status_code' => 403, 'error' => 'private_blog', ) ); } if ( strlen( $post->post_password ) && ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'unauthorized', 'User cannot view password protected post', array( 'status_code' => 403, 'error' => 'password_protected', ) ); } return true; } /** * Get post ID by name * * Attempts to match name on post title and page path * * @param string $name The post name. * * @return int|WP_Error Post ID on success, WP_Error object on failure */ public function get_post_id_by_name( $name ) { $name = sanitize_title( $name ); if ( ! $name ) { return new WP_Error( 'invalid_post', 'Invalid post', 400 ); } $posts = get_posts( array( 'name' => $name, 'numberposts' => 1, 'post_type' => $this->get_whitelisted_post_types(), ) ); if ( ! $posts || ! isset( $posts[0]->ID ) || ! $posts[0]->ID ) { $page = get_page_by_path( $name ); if ( ! $page ) { return new WP_Error( 'unknown_post', 'Unknown post', 404 ); } return $page->ID; } return (int) $posts[0]->ID; } /** * Get post by name * * Attempts to match name on post title and page path * * @param string $name The post name. * @param string $context (display or edit). * * @return Jetpack_Post|WP_Error Post object on success, WP_Error object on failure **/ public function get_post_by_name( $name, $context ) { $post_id = $this->get_post_id_by_name( $name ); if ( is_wp_error( $post_id ) ) { return $post_id; } return $this->get_post_by_id( $post_id, $context ); } /** * Whether or not the current user is an admin (has option management capabilities). * * @return bool **/ public function user_can_manage() { return current_user_can( 'manage_options' ); } /** * Returns the XMLRPC URL - the site URL including the URL scheme that is used when querying your site's REST API endpoint. * * @return string **/ public function get_xmlrpc_url() { $xmlrpc_scheme = apply_filters( 'wpcom_json_api_xmlrpc_scheme', wp_parse_url( get_option( 'home' ), PHP_URL_SCHEME ) ); return site_url( 'xmlrpc.php', $xmlrpc_scheme ); } /** * Returns a date/time string with the date the site was registered, or a default date/time string otherwise. * * @return string **/ public function get_registered_date() { if ( function_exists( 'get_blog_details' ) ) { $blog_details = get_blog_details(); if ( ! empty( $blog_details->registered ) ) { return WPCOM_JSON_API_Date::format_date( $blog_details->registered ); } } return '0000-00-00T00:00:00+00:00'; } /** * Returns a date/time string with the date the site was last updated, or a default date/time string otherwise. * * @return string **/ public function get_last_update_date() { if ( function_exists( 'get_blog_details' ) ) { $blog_details = get_blog_details(); if ( ! empty( $blog_details->last_updated ) ) { return WPCOM_JSON_API_Date::format_date( $blog_details->last_updated ); } } return '0000-00-00T00:00:00+00:00'; } /** * Returns an array including the current users relevant capabilities. * * @return array **/ public function get_capabilities() { $is_wpcom_blog_owner = wpcom_get_blog_owner() === (int) get_current_user_id(); return array( 'edit_pages' => current_user_can( 'edit_pages' ), 'edit_posts' => current_user_can( 'edit_posts' ), 'edit_others_posts' => current_user_can( 'edit_others_posts' ), 'edit_others_pages' => current_user_can( 'edit_others_pages' ), 'delete_posts' => current_user_can( 'delete_posts' ), 'delete_others_posts' => current_user_can( 'delete_others_posts' ), 'edit_theme_options' => current_user_can( 'edit_theme_options' ), 'edit_users' => current_user_can( 'edit_users' ), 'list_users' => current_user_can( 'list_users' ), 'manage_categories' => current_user_can( 'manage_categories' ), 'manage_options' => current_user_can( 'manage_options' ), 'moderate_comments' => current_user_can( 'moderate_comments' ), 'activate_wordads' => $is_wpcom_blog_owner, 'promote_users' => current_user_can( 'promote_users' ), 'publish_posts' => current_user_can( 'publish_posts' ), 'upload_files' => current_user_can( 'upload_files' ), 'delete_users' => current_user_can( 'delete_users' ), 'remove_users' => current_user_can( 'remove_users' ), 'own_site' => $is_wpcom_blog_owner, /** * Filter whether the Hosting section in Calypso should be available for site. * * @module json-api * * @since 8.2.0 * * @param bool $view_hosting Can site access Hosting section. Default to false. */ 'view_hosting' => apply_filters( 'jetpack_json_api_site_can_view_hosting', false ), 'view_stats' => stats_is_blog_user( $this->blog_id ), 'activate_plugins' => current_user_can( 'activate_plugins' ), ); } /** * Whether or not a site is public. * * @return bool **/ public function is_visible() { if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $visible = (array) get_user_meta( $current_user->ID, 'blog_visibility', true ); $is_visible = true; if ( isset( $visible[ $this->blog_id ] ) ) { $is_visible = (bool) $visible[ $this->blog_id ]; } // null and true are visible return $is_visible; } return null; } /** * Creates and returns an array with logo settings. * * @return array **/ public function get_logo() { // Set an empty response array. $logo_setting = array( 'id' => (int) 0, 'sizes' => array(), 'url' => '', ); // Get current site logo values. $logo_id = get_option( 'site_logo' ); // Update the response array if there's a site logo currenty active. if ( $logo_id ) { $logo_setting['id'] = $logo_id; $logo_setting['url'] = wp_get_attachment_url( $logo_id ); } return $logo_setting; } /** * Returns the timezone string from the site's settings (eg. 'Europe/London'). * * @return string **/ public function get_timezone() { return (string) get_option( 'timezone_string' ); } /** * Returns the GMT offset from the site's settings (eg. 5.5). * * @return float **/ public function get_gmt_offset() { return (float) get_option( 'gmt_offset' ); } /** * Returns the site's login URL. * * @return string **/ public function get_login_url() { return wp_login_url(); } /** * Returns the URL for a site's admin area. * * @return string **/ public function get_admin_url() { return get_admin_url(); } /** * Returns the theme's slug (eg. 'twentytwentytwo') * * @return string **/ public function get_theme_slug() { return get_option( 'stylesheet' ); } /** * Gets the header image data. * * @return bool|object **/ public function get_header_image() { return get_theme_mod( 'header_image_data' ); } /** * Gets the theme background color. * * @return bool|string **/ public function get_background_color() { return get_theme_mod( 'background_color' ); } /** * Get the image default link type. * * @return string **/ public function get_image_default_link_type() { return get_option( 'image_default_link_type' ); } /** * Gets the image thumbnails width. * * @return int **/ public function get_image_thumbnail_width() { return (int) get_option( 'thumbnail_size_w' ); } /** * Gets the image thumbnails height. * * @return int **/ public function get_image_thumbnail_height() { return (int) get_option( 'thumbnail_size_h' ); } /** * Whether cropping is enabled for thumbnails. * * @return string **/ public function get_image_thumbnail_crop() { return get_option( 'thumbnail_crop' ); } /** * Gets the medium sized image setting's width. * * @return int **/ public function get_image_medium_width() { return (int) get_option( 'medium_size_w' ); } /** * Gets the medium sized image setting's height. * * @return int **/ public function get_image_medium_height() { return (int) get_option( 'medium_size_h' ); } /** * Gets the large sized image setting's width. * * @return int **/ public function get_image_large_width() { return (int) get_option( 'large_size_w' ); } /** * Gets the large sized image setting's height. * * @return int **/ public function get_image_large_height() { return (int) get_option( 'large_size_h' ); } /** * Gets the permalink structure as defined in the site's settings. * * @return string **/ public function get_permalink_structure() { return get_option( 'permalink_structure' ); } /** * Gets the default post format * * @return string **/ public function get_default_post_format() { return get_option( 'default_post_format' ); } /** * Gets the default post category * * @return int **/ public function get_default_category() { return (int) get_option( 'default_category' ); } /** * Returns what should be shown on the front page (eg. page or posts) * * @return string **/ public function get_show_on_front() { return get_option( 'show_on_front' ); } /** * Whether or not the front page is set as 'page' to allow a custom front page * * @return bool **/ public function is_custom_front_page() { return ( 'page' === $this->get_show_on_front() ); } /** * Whether or not likes have been enabled on all site posts * * @return bool **/ public function get_default_likes_enabled() { return (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) ); } /** * If sharing has been enabled and there are visible blog services (eg. 'facebook', 'twitter'), returns true. * * @return bool **/ public function get_default_sharing_status() { $default_sharing_status = false; if ( class_exists( 'Sharing_Service' ) ) { $ss = new Sharing_Service(); $blog_services = $ss->get_blog_services(); $default_sharing_status = ! empty( $blog_services['visible'] ); } return (bool) $default_sharing_status; } /** * Displays the current comment status * * @return bool False if closed, true for all other comment statuses. **/ public function get_default_comment_status() { return 'closed' !== get_option( 'default_comment_status' ); } /** * Displays the current site-wide post ping status (for pingbacks and trackbacks) * * @return bool False if closed, true for all other ping statuses. **/ public function default_ping_status() { return 'closed' !== get_option( 'default_ping_status' ); } /** * Whether or not Publicize has been permanently disabled on the site * * @see wpcom/wp-content/admin-plugins/publicize/publicize-wpcom.php * * @return bool Default false. **/ public function is_publicize_permanently_disabled() { $publicize_permanently_disabled = false; if ( function_exists( 'is_publicize_permanently_disabled' ) ) { $publicize_permanently_disabled = is_publicize_permanently_disabled( $this->blog_id ); } return $publicize_permanently_disabled; } /** * Returns the post ID of the static front page. * * @return int **/ public function get_page_on_front() { return (int) get_option( 'page_on_front' ); } /** * Returns the post ID of the page designated as the posts page. * * @return int **/ public function get_page_for_posts() { return (int) get_option( 'page_for_posts' ); } /** * Whether or not headstart is enabled for the site * * @return bool **/ public function is_headstart() { return get_option( 'headstart' ); } /** * The WordPress version on the site. * * @return string **/ public function get_wordpress_version() { global $wp_version; return $wp_version; } /** * Whether or not this is a domain-only site (only relevant on WordPress.com simple sites - false otherwise) * * @return bool **/ public function is_domain_only() { $options = get_option( 'options' ); return ! empty( $options['is_domain_only'] ) ? (bool) $options['is_domain_only'] : false; } /** * Whether or not the blog is set to public (not hidden from search engines) * * @return int 1 for true, 0 for false. **/ public function get_blog_public() { return (int) get_option( 'blog_public' ); } /** * Whether or not the site is in a 'pending automated transfer' state. * * @return bool **/ public function has_pending_automated_transfer() { /** * Filter if a site is in pending automated transfer state. * * @module json-api * * @since 6.4.0 * * @param bool has_site_pending_automated_transfer( $this->blog_id ) * @param int $blog_id Blog identifier. */ return apply_filters( 'jetpack_site_pending_automated_transfer', false, $this->blog_id ); } /** * Whether or not the site has a 'designType' option set as 'store' * * @return bool **/ public function signup_is_store() { return $this->get_design_type() === 'store'; } /** * Return a new WP_Roles instance, which implements a user roles API * * @return WP_Roles **/ public function get_roles() { return new WP_Roles(); } /** * Returns the 'designType' option if set (the site design type), null otherwise. * * @return string|null **/ public function get_design_type() { $options = get_option( 'options' ); return empty( $options['designType'] ) ? null : $options['designType']; } /** * Returns the 'siteGoals' option if set (eg. share, promote, educate, sell, showcase), null otherwise. * * @return string|null **/ public function get_site_goals() { $options = get_option( 'options' ); return empty( $options['siteGoals'] ) ? null : $options['siteGoals']; } /** * Return site's launch status. Expanded in class.json-api-site-jetpack.php. * * @return bool False in this case. */ public function get_launch_status() { return false; } /** * Whether a site has any migration meta details - only applicable on WordPress.com * * @see /wpcom/public.api/rest/sal/class.json-api-site-jetpack-shadow.php * * @return null */ public function get_migration_meta() { return null; } /** * Whether a site has a site segment - only applicable on WordPress.com * * @see /wpcom/public.api/rest/sal/class.json-api-site-wpcom.php * * @return false */ public function get_site_segment() { return false; } /** * Whether a site has Vertical ID (used for Starter Templates) - default to only applicable on WordPress.com * * @see /wpcom/public.api/rest/sal/class.json-api-site-wpcom.php * * @return false */ public function get_site_vertical_id() { return false; } /** * Whether a site has a 'site_creation_flow' option set (eg gutenboarding, mobile) - only applicable on WordPress.com * * @see /wpcom-json-endpoints/class.wpcom-json-api-new-site-endpoint.php for more on the option. * * @return bool */ public function get_site_creation_flow() { return get_option( 'site_creation_flow' ); } /** * Whether a site has a 'site_source_slug' option set - only applicable on WordPress.com * * @see /wpcom-json-endpoints/class.wpcom-json-api-new-site-endpoint.php for more on the option. * * @return bool */ public function get_site_source_slug() { return get_option( 'site_source_slug' ); } /** * Return any selected features (used to help recommend plans) * * @return string */ public function get_selected_features() { return get_option( 'selected_features' ); } /** * Return true if the site design was created with a Blank Canvas (empty homepage template), false otherwise. * * @return bool */ public function was_created_with_blank_canvas_design() { return (bool) get_option( 'was_created_with_blank_canvas_design' ); } /** * Get the option storing the Anchor podcast ID that identifies a site as a podcasting site. * * @return string */ public function get_anchor_podcast() { return get_option( 'anchor_podcast' ); } /** * Check if the site is currently being built by the DIFM Lite team. * * @return bool */ public function is_difm_lite_in_progress() { if ( function_exists( 'has_blog_sticker' ) ) { return has_blog_sticker( 'difm-lite-in-progress' ); } elseif ( function_exists( 'wpcomsh_is_site_sticker_active' ) ) { // For atomic sites return wpcomsh_is_site_sticker_active( 'difm-lite-in-progress' ); } return false; } /** * The site options for DIFM lite in the design picker step * * @return string */ public function get_difm_lite_site_options() { return get_option( 'difm_lite_site_options' ); } /** * Get the option of site intent which value is coming from the Hero Flow * * @return string */ public function get_site_intent() { return get_option( 'site_intent', '' ); } /** * Get site option to determine if and how to display launchpad onboarding * * @return string */ public function get_launchpad_screen() { return get_option( 'launchpad_screen' ); } /** * Get site option for completed launchpad checklist tasks * * @return string */ public function get_launchpad_checklist_tasks_statuses() { $launchpad_checklist_tasks_statuses_option = get_option( 'launchpad_checklist_tasks_statuses' ); if ( is_array( $launchpad_checklist_tasks_statuses_option ) ) { return $launchpad_checklist_tasks_statuses_option; } return array(); } /** * Detect whether a site is WordPress.com Staging Site. * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function is_wpcom_staging_site(); /** * Get site option for the production blog id (if is a WP.com Staging Site). * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_wpcom_production_blog_id(); /** * Get site option for the staging blog ids (if it has them) * * @see class.json-api-site-jetpack.php for implementation. */ abstract public function get_wpcom_staging_blog_ids(); /** * Get the site's Blaze eligibility status. * * @return bool */ public function can_blaze() { return (bool) Blaze::site_supports_blaze( $this->blog_id ); } /** * Return site's setup identifier. * * @return string */ public function get_wpcom_site_setup() { return get_option( 'wpcom_site_setup' ); } /** * Returns whether the site is commercial. * * @return mixed * * - `true`: the site is commercial * - `false`: the site is not commercial * - `null`: the commercial status is not yet determined */ public function is_commercial() { // Override if blog has the commercial stickers. if ( function_exists( 'has_blog_sticker' ) ) { $has_not_commercial_sticker = has_blog_sticker( 'jetpack-site-is-not-commercial-override', $this->blog_id ); if ( $has_not_commercial_sticker ) { return false; } $has_commercial_sticker = has_blog_sticker( 'jetpack-site-is-commercial-override', $this->blog_id ); if ( $has_commercial_sticker ) { return true; } } $is_commercial = get_option( '_jetpack_site_is_commercial', null ); return $is_commercial === null ? null : (bool) $is_commercial; } /** * Returns an array of reasons why the site is considered commercial. * * @return array|null */ public function get_is_commercial_reasons() { $reasons = get_option( '_jetpack_site_is_commercial_reason', array() ); // Add override as reason if blog has the commercial stickers. if ( empty( $reasons ) && $this->is_commercial() ) { return array( 'manual-override' ); } elseif ( ! is_array( $reasons ) ) { return array(); } return $reasons; } /** * Returns the site's interface selection e.g. calypso vs. wp-admin * * @return string **/ public function get_wpcom_admin_interface() { return (string) get_option( 'wpcom_admin_interface' ); } /** * Returns whether the site is part of the classic view early release. * * @return bool **/ public function get_wpcom_classic_early_release() { return ! empty( get_option( 'wpcom_classic_early_release' ) ); } }
projects/plugins/jetpack/sal/class.json-api-post-base.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * This class wraps a WP_Post and proxies any undefined attributes * and methods to the wrapped class. We need to do this because at present * the WP_Post class is marked as final (in 4.5 this will change, though it's * not clear if there will be a mechanism to retrieve from the DB into the over- * ridden class dynamically). * * @package automattic/jetpack */ use Automattic\Jetpack\Status; require_once __DIR__ . '/class.json-api-metadata.php'; require_once __DIR__ . '/class.json-api-date.php'; require_once ABSPATH . 'wp-admin/includes/post.php'; require_once ABSPATH . 'wp-includes/post.php'; /** * Base class for SAL_Post. */ abstract class SAL_Post { /** * A WP_Post instance. * * @var WP_Post */ public $post; /** * The post request context (for example 'edit' or 'display') * * @var string */ public $context; /** * A Jetpack_Site instance. * * @var Jetpack_Site */ public $site; /** * Constructor function * * @param Jetpack_Site $site A Jetpack_Site instance. * @param WP_Post $post A WP_Post instance. * @param string $context The post request context (for example 'edit' or 'display'). */ public function __construct( $site, $post, $context ) { $this->post = $post; $this->context = $context; $this->site = $site; } /** * Setting this WP_Post instance's key value * * @param string $key The post key to set. * @param string $value The value to set the post key to (for example filter, ID, post_status). */ public function __set( $key, $value ) { $this->post->{ $key } = $value; } /** * Returning a WPCOM_JSON_API_Links instance if the post key is set to 'links', or the post key value. * * @param string $key The post key value. * * @return WPCOM_JSON_API_Links|string */ public function __get( $key ) { if ( 'links' === $key ) { require_once __DIR__ . '/class.json-api-links.php'; return WPCOM_JSON_API_Links::getInstance(); } return $this->post->{ $key }; } /** * A function to either call a given function, or return an error if it doesn't exist. * * @param string $name A function name to be called. * @param mixed $arguments Arguments to be passed into the given function. * * @return mixed|bool */ public function __call( $name, $arguments ) { if ( is_callable( array( $this->post, $name ) ) ) { return call_user_func_array( array( $this->post, $name ), $arguments ); } else { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error trigger_error( esc_html( sprintf( /* translators: %s is the method name that has been called */ __( 'Call to undefined method %s', 'jetpack' ), $name ) ) ); } } /** * Checking to see if a given property is set. * * @param string $name Property to check if set. * * @return bool */ public function __isset( $name ) { return isset( $this->post->{ $name } ); } /** * Defining a base get_like_count() function to be extended in the Jetpack_Post class. * * This will define a default value for the like counts on a post, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function get_like_count(); /** * Defining a base is_liked() function to be extended in the Jetpack_Post class. * * This will define a default value for whether or not the current user likes this post, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function is_liked(); /** * Defining a base is_reblogged() function to be extended in the Jetpack_Post class. * * This will define a default value for whether or not the current user reblogged this post, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function is_reblogged(); /** * Defining a base is_following() function to be extended in the Jetpack_Post class. * * This will define a default value for whether or not the current user is following this blog, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function is_following(); /** * Defining a base get_global_id() function to be extended in the Jetpack_Post class. * * This will define the unique WordPress.com-wide representation of a post, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function get_global_id(); /** * Defining a base get_geo() function to be extended in the Jetpack_Post class. * * This will define a default value for whether or not there is gelocation data for this post, if this hasn't been defined yet. * * @see class.json-api-post-jetpack.php */ abstract public function get_geo(); /** * Returns an int which helps define the menu order for the post. * * @return int */ public function get_menu_order() { return (int) $this->post->menu_order; } /** * Returns a string which represents the post's GUID. * * @return string */ public function get_guid() { return (string) $this->post->guid; } /** * Returns a string which represents the post type. * * @return string */ public function get_type() { return (string) $this->post->post_type; } /** * Returns an object which holds the terms associated with that post object. * * @return object */ public function get_terms() { $taxonomies = get_object_taxonomies( $this->post, 'objects' ); $terms = array(); foreach ( $taxonomies as $taxonomy ) { if ( ! $taxonomy->public && ! current_user_can( $taxonomy->cap->assign_terms ) ) { continue; } $terms[ $taxonomy->name ] = array(); $taxonomy_terms = wp_get_object_terms( $this->post->ID, $taxonomy->name, array( 'fields' => 'all' ) ); foreach ( $taxonomy_terms as $term ) { $formatted_term = $this->format_taxonomy( $term, $taxonomy->name, 'display' ); $terms[ $taxonomy->name ][ $term->name ] = $formatted_term; } $terms[ $taxonomy->name ] = (object) $terms[ $taxonomy->name ]; } return (object) $terms; } /** * Returns an object which holds the posts tag details * * @return object */ public function get_tags() { $tags = array(); $terms = wp_get_post_tags( $this->post->ID ); foreach ( $terms as $term ) { if ( ! empty( $term->name ) ) { $tags[ $term->name ] = $this->format_taxonomy( $term, 'post_tag', 'display' ); } } return (object) $tags; } /** * Returns an object which holds the posts category details * * @return object */ public function get_categories() { $categories = array(); $terms = wp_get_object_terms( $this->post->ID, 'category', array( 'fields' => 'all' ) ); foreach ( $terms as $term ) { if ( ! empty( $term->name ) ) { $categories[ $term->name ] = $this->format_taxonomy( $term, 'category', 'display' ); } } return (object) $categories; } /** * Returns an array of objects which hold the posts attachment information and numbers representing how many associated posts are found. * * @return array */ public function get_attachments_and_count() { $attachments = array(); $_attachments = new WP_Query( array( 'post_parent' => $this->post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'posts_per_page' => '20', ) ); foreach ( $_attachments->posts as $attachment ) { $attachments[ $attachment->ID ] = $this->get_media_item_v1_1( $attachment->ID ); } return array( (object) $attachments, (int) $_attachments->found_posts ); } /** * Returns an array with a posts metadata information. * * @return array */ public function get_metadata() { $metadata = array(); foreach ( (array) has_meta( $this->post->ID ) as $meta ) { // Don't expose protected fields. $meta_key = $meta['meta_key']; $show = ! ( WPCOM_JSON_API_Metadata::is_internal_only( $meta_key ) ) && ( WPCOM_JSON_API_Metadata::is_public( $meta_key ) || current_user_can( 'edit_post_meta', $this->post->ID, $meta_key ) ); if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY === $meta_key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) { $show = false; } if ( $show ) { $metadata[] = array( 'id' => $meta['meta_id'], 'key' => $meta['meta_key'], 'value' => $this->safe_maybe_unserialize( $meta['meta_value'] ), ); } } return $metadata; } /** * Returns an object with a posts link meta details. * * @return object */ public function get_meta() { $meta = (object) array( 'links' => (object) array( 'self' => (string) $this->get_post_link(), 'help' => (string) $this->get_post_link( 'help' ), 'site' => (string) $this->get_site_link(), 'replies' => (string) $this->get_post_link( 'replies/' ), 'likes' => (string) $this->get_post_link( 'likes/' ), ), ); $amp_permalink = get_post_meta( $this->post->ID, '_jetpack_amp_permalink', true ); if ( ! empty( $amp_permalink ) ) { $meta->links->amp = (string) $amp_permalink; } // add autosave link if a more recent autosave exists. if ( 'edit' === $this->context ) { $autosave = wp_get_post_autosave( $this->post->ID ); if ( $autosave && $autosave->post_modified > $this->post->post_modified ) { $meta->links->autosave = (string) $this->get_post_link() . '/autosave'; } } return $meta; } /** * Returns an array with the current user's publish, deletion and edit capabilities. * * @return array */ public function get_current_user_capabilities() { return array( 'publish_post' => current_user_can( 'publish_post', $this->post->ID ), 'delete_post' => current_user_can( 'delete_post', $this->post->ID ), 'edit_post' => current_user_can( 'edit_post', $this->post->ID ), ); } /** * Returns an array with details of the posts revisions, or false if 'edit' isn't the current post request context. * * @return bool|array */ public function get_revisions() { if ( 'edit' !== $this->context ) { return false; } $revisions = array(); $post_revisions = wp_get_post_revisions( $this->post->ID ); foreach ( $post_revisions as $_post ) { $revisions[] = $_post->ID; } return $revisions; } /** * Returns an object with extra post permalink suggestions. * * @return object */ public function get_other_urls() { $other_urls = array(); if ( 'publish' !== $this->post->post_status ) { $other_urls = $this->get_permalink_suggestions( $this->post->post_title ); } return (object) $other_urls; } /** * Calls the WPCOM_JSON_API_Links get_site_link() function to generate a site link endpoint URL. * * @return string Endpoint URL including site information. */ protected function get_site_link() { return $this->links->get_site_link( $this->site->get_id() ); } /** * Calls the WPCOM_JSON_API_Links get_post_link() function to generate a posts endpoint URL. * * @param string $path Optional path to be appended to the URL. * @return string Endpoint URL including post information. */ protected function get_post_link( $path = null ) { return $this->links->get_post_link( $this->site->get_id(), $this->post->ID, $path ); } /** * Returns an array of user and post specific social media post URLs. * * @return array */ public function get_publicize_urls() { $publicize_urls = array(); $publicize = get_post_meta( $this->post->ID, 'publicize_results', true ); if ( $publicize ) { foreach ( $publicize as $service => $data ) { switch ( $service ) { // @todo explore removing once Twitter is removed from Publicize. case 'twitter': foreach ( $data as $datum ) { $publicize_urls[] = esc_url_raw( "https://twitter.com/{$datum['user_id']}/status/{$datum['post_id']}" ); } break; case 'fb': foreach ( $data as $datum ) { $publicize_urls[] = esc_url_raw( "https://www.facebook.com/permalink.php?story_fbid={$datum['post_id']}&id={$datum['user_id']}" ); } break; } } } return (array) $publicize_urls; } /** * Returns a string with the page's custom template metadata. * * @return string */ public function get_page_template() { return (string) get_post_meta( $this->post->ID, '_wp_page_template', true ); } /** * Returns a string representing the source URL of a post's featured image (or an empty string otherwise). * * Note - this is overridden in jetpack-shadow * * @return string */ public function get_featured_image() { $image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $this->post->ID ), 'full' ); if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) { return (string) $image_attributes[0]; } else { return ''; } } /** * Returns an object representing a post's featured image thumbnail image. * * @return object */ public function get_post_thumbnail() { $thumb = null; $thumb_id = get_post_thumbnail_id( $this->post->ID ); if ( ! empty( $thumb_id ) ) { $attachment = get_post( $thumb_id ); if ( ! empty( $attachment ) ) { $featured_image_object = $this->get_attachment( $attachment ); } if ( ! empty( $featured_image_object ) ) { $thumb = (object) $featured_image_object; } } return $thumb; } /** * Returns the format slug for a post (for example 'link', 'image' - the default being 'standard'). * * @return string */ public function get_format() { $format = (string) get_post_format( $this->post->ID ); if ( ! $format ) { $format = 'standard'; } return $format; } /** * Returns an object with the post's attachment details. * * @param WP_POST $attachment The post's attachment details in the form of a WP_POST object. * * @return object */ private function get_attachment( $attachment ) { $metadata = wp_get_attachment_metadata( $attachment->ID ); $result = array( 'ID' => (int) $attachment->ID, 'URL' => (string) wp_get_attachment_url( $attachment->ID ), 'guid' => (string) $attachment->guid, 'mime_type' => (string) $attachment->post_mime_type, 'width' => (int) isset( $metadata['width'] ) ? $metadata['width'] : 0, 'height' => (int) isset( $metadata['height'] ) ? $metadata['height'] : 0, ); if ( isset( $metadata['duration'] ) ) { $result['duration'] = (int) $metadata['duration']; } /** This filter is documented in class.jetpack-sync.php */ return (object) apply_filters( 'get_attachment', $result ); } /** * Returns an ISO 8601 formatted datetime string representing the date of post creation. * * @return string */ public function get_date() { return (string) WPCOM_JSON_API_Date::format_date( $this->post->post_date_gmt, $this->post->post_date ); } /** * Returns an ISO 8601 formatted datetime string representing the date the post was last modified. * * @return string */ public function get_modified_date() { return (string) WPCOM_JSON_API_Date::format_date( $this->post->post_modified_gmt, $this->post->post_modified ); } /** * Returns the post's title. * * @return string */ public function get_title() { if ( 'display' === $this->context ) { return (string) get_the_title( $this->post->ID ); } else { return (string) htmlspecialchars_decode( $this->post->post_title, ENT_QUOTES ); } } /** * Returns the permalink for the post (or the post parent if the post type is a revision). * * @return string */ public function get_url() { if ( 'revision' === $this->post->post_type ) { return (string) esc_url_raw( get_permalink( $this->post->post_parent ) ); } else { return (string) esc_url_raw( get_permalink( $this->post->ID ) ); } } /** * Returns the shortlink for the post. * * @return string */ public function get_shortlink() { return (string) esc_url_raw( wp_get_shortlink( $this->post->ID ) ); } /** * Returns the post content, or a string saying 'This post is password protected' if that is the case. * * @return string */ public function get_content() { if ( 'display' === $this->context ) { // @todo: move this WPCOM-specific hack add_filter( 'the_password_form', array( $this, 'the_password_form' ) ); $content = (string) $this->get_the_post_content_for_display(); remove_filter( 'the_password_form', array( $this, 'the_password_form' ) ); return $content; } else { return (string) $this->post->post_content; } } /** * Returns the post excerpt, or a string saying 'This post is password protected' if that is the case. * * @return string */ public function get_excerpt() { if ( 'display' === $this->context ) { add_filter( 'the_password_form', array( $this, 'the_password_form' ) ); ob_start(); the_excerpt(); $response = (string) ob_get_clean(); remove_filter( 'the_password_form', array( $this, 'the_password_form' ) ); } else { $response = htmlspecialchars_decode( (string) $this->post->post_excerpt, ENT_QUOTES ); } return $response; } /** * Returns the current post status (publish, future, draft, pending, private). * * @return string */ public function get_status() { return (string) get_post_status( $this->post->ID ); } /** * Returns true if the post is a sticky post, false otherwise. * * @return bool */ public function is_sticky() { return (bool) is_sticky( $this->post->ID ); } /** * Returns the post's slug. * * @return string */ public function get_slug() { return (string) $this->post->post_name; } /** * Returns the post's password, if password protected. * * @return string */ public function get_password() { $password = (string) $this->post->post_password; if ( 'edit' === $this->context ) { $password = htmlspecialchars_decode( (string) $password, ENT_QUOTES ); } return $password; } /** * Returns an object representing a post's parent, and false if it doesn't have one. * * @return object|bool */ public function get_parent() { if ( $this->post->post_parent ) { $parent = get_post( $this->post->post_parent ); if ( 'display' === $this->context ) { $parent_title = (string) get_the_title( $parent->ID ); } else { $parent_title = (string) htmlspecialchars_decode( $this->post->post_title, ENT_QUOTES ); } return (object) array( 'ID' => (int) $parent->ID, 'type' => (string) $parent->post_type, 'link' => (string) $this->links->get_post_link( $this->site->get_id(), $parent->ID ), 'title' => $parent_title, ); } else { return false; } } /** * Returns a string saying 'This post is password protected' (to be later used within the_password_form filter). * * @return string */ public function the_password_form() { return __( 'This post is password protected.', 'jetpack' ); } /** * Returns an array with information related to the comment and ping status of a post. * * @return array */ public function get_discussion() { return array( 'comments_open' => (bool) comments_open( $this->post->ID ), 'comment_status' => (string) $this->post->comment_status, 'pings_open' => (bool) pings_open( $this->post->ID ), 'ping_status' => (string) $this->post->ping_status, 'comment_count' => (int) $this->post->comment_count, ); } /** * Returns true if likes are enabled - either for the post, or site-wide. * * @return bool */ public function is_likes_enabled() { /** This filter is documented in modules/likes.php */ $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) ); $post_likes_switched = get_post_meta( $this->post->ID, 'switch_like_status', true ); return $post_likes_switched || ( $sitewide_likes_enabled && '0' !== $post_likes_switched ); } /** * Returns true if sharing is enabled, false otherwise. * * @return bool */ public function is_sharing_enabled() { $show = true; /** This filter is documented in modules/sharedaddy/sharing-service.php */ $show = apply_filters( 'sharing_show', $show, $this->post ); $switched_status = get_post_meta( $this->post->ID, 'sharing_disabled', false ); if ( ! empty( $switched_status ) ) { $show = false; } return (bool) $show; } /** * Returns the post content in the form of a string, ready for displaying. * * Note: No Blog ID parameter. No Post ID parameter. Depends on globals. * Expects setup_postdata() to already have been run * * @return string */ public function get_the_post_content_for_display() { global $pages, $page; $old_pages = $pages; $old_page = $page; $content = implode( "\n\n", $pages ); $content = preg_replace( '/<!--more(.*?)?-->/', '', $content ); // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited -- Assignment to globals is intentional $pages = array( $content ); $page = 1; ob_start(); the_content(); $return = ob_get_clean(); $pages = $old_pages; $page = $old_page; // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited return $return; } /** * Returns an object containing the post author's information (eg. ID, display name, email if the user has post editing capabilities). * * @return object */ public function get_author() { if ( 0 == $this->post->post_author ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- numbers could be numeric strings. return null; } $show_email = 'edit' === $this->context && current_user_can( 'edit_post', $this->post->ID ); $user = get_user_by( 'id', $this->post->post_author ); if ( ! $user || is_wp_error( $user ) ) { return null; } // @todo: factor this out // phpcs:disable WordPress.NamingConventions.ValidVariableName if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $active_blog = get_active_blog_for_user( $user->ID ); $site_id = $active_blog->blog_id; $profile_URL = "https://gravatar.com/{$user->user_login}"; } else { $profile_URL = 'https://gravatar.com/' . md5( strtolower( trim( $user->user_email ) ) ); $site_id = -1; } $author = array( 'ID' => (int) $user->ID, 'login' => (string) $user->user_login, 'email' => $show_email ? (string) $user->user_email : false, 'name' => (string) $user->display_name, 'first_name' => (string) $user->first_name, 'last_name' => (string) $user->last_name, 'nice_name' => (string) $user->user_nicename, 'URL' => (string) esc_url_raw( $user->user_url ), 'avatar_URL' => (string) esc_url_raw( $this->get_avatar_url( $user->user_email ) ), 'profile_URL' => (string) esc_url_raw( $profile_URL ), ); // phpcs:enable WordPress.NamingConventions.ValidVariableName if ( $site_id > -1 ) { $author['site_ID'] = (int) $site_id; } return (object) $author; } /** * Returns the avatar URL for a user, or an empty string if there isn't a valid avatar. * * @param string $email The user's email. * @param int $avatar_size The size of the avatar in pixels. * * @todo Provide a non-WP.com option. * * @return string */ protected function get_avatar_url( $email, $avatar_size = 96 ) { $avatar_url = function_exists( 'wpcom_get_avatar_url' ) ? wpcom_get_avatar_url( $email, $avatar_size ) : ''; if ( ! $avatar_url || is_wp_error( $avatar_url ) ) { return ''; } return esc_url_raw( htmlspecialchars_decode( $avatar_url[0], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ) ); } /** * Return extra post permalink suggestions in an array including the 'permalink_URL' and the 'suggested_slug'. * * @param string $title The current post title. * * @return array */ public function get_permalink_suggestions( $title ) { $suggestions = array(); list( $suggestions['permalink_URL'], $suggestions['suggested_slug'] ) = get_sample_permalink( $this->post->ID, $title ); return $suggestions; } /** * Returns an object with formatted taxonomy information such as slug and meta information. * * Otherwise, returns an error if the edit or display permissions aren't correct. * * @param WP_Term $taxonomy The current taxonomy. * @param string $taxonomy_type The current taxonomy type, for example 'category'. * @param string $context The current context, for example 'edit' or 'display'. * * @return object */ private function format_taxonomy( $taxonomy, $taxonomy_type, $context ) { // Permissions. switch ( $context ) { case 'edit': $tax = get_taxonomy( $taxonomy_type ); if ( ! current_user_can( $tax->cap->edit_terms ) ) { return new WP_Error( 'unauthorized', 'User cannot edit taxonomy', 403 ); } break; case 'display': if ( ( new Status() )->is_private_site() && ! current_user_can( 'read' ) ) { return new WP_Error( 'unauthorized', 'User cannot view taxonomy', 403 ); } break; default: return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 ); } $response = array(); $response['ID'] = (int) $taxonomy->term_id; $response['name'] = (string) $taxonomy->name; $response['slug'] = (string) $taxonomy->slug; $response['description'] = (string) $taxonomy->description; $response['post_count'] = (int) $taxonomy->count; if ( is_taxonomy_hierarchical( $taxonomy_type ) ) { $response['parent'] = (int) $taxonomy->parent; } $response['meta'] = (object) array( 'links' => (object) array( 'self' => (string) $this->links->get_taxonomy_link( $this->site->get_id(), $taxonomy->slug, $taxonomy_type ), 'help' => (string) $this->links->get_taxonomy_link( $this->site->get_id(), $taxonomy->slug, $taxonomy_type, 'help' ), 'site' => (string) $this->links->get_site_link( $this->site->get_id() ), ), ); return (object) $response; } /** * Builds and returns the media item's details. * * @param int $media_id The media item ID. * @todo: factor this out into site. * * @return object */ private function get_media_item_v1_1( $media_id ) { $media_item = get_post( $media_id ); if ( ! $media_item || is_wp_error( $media_item ) ) { return new WP_Error( 'unknown_media', 'Unknown Media', 404 ); } $file = basename( wp_get_attachment_url( $media_item->ID ) ); $file_info = pathinfo( $file ); $ext = isset( $file_info['extension'] ) ? $file_info['extension'] : ''; $response = array( 'ID' => $media_item->ID, 'URL' => wp_get_attachment_url( $media_item->ID ), 'guid' => $media_item->guid, 'date' => (string) WPCOM_JSON_API_Date::format_date( $media_item->post_date_gmt, $media_item->post_date ), 'post_ID' => $media_item->post_parent, 'author_ID' => (int) $media_item->post_author, 'file' => $file, 'mime_type' => $media_item->post_mime_type, 'extension' => $ext, 'title' => $media_item->post_title, 'caption' => $media_item->post_excerpt, 'description' => $media_item->post_content, 'alt' => get_post_meta( $media_item->ID, '_wp_attachment_image_alt', true ), 'thumbnails' => array(), ); if ( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif', 'webp' ), true ) ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); if ( isset( $metadata['height'] ) && isset( $metadata['width'] ) ) { $response['height'] = $metadata['height']; $response['width'] = $metadata['width']; } if ( isset( $metadata['sizes'] ) ) { /** * Filter the thumbnail sizes available for each attachment ID. * * @module json-api * * @since 3.9.0 * * @param array $metadata['sizes'] Array of thumbnail sizes available for a given attachment ID. * @param int $media_id The media item ID. */ $sizes = apply_filters( 'rest_api_thumbnail_sizes', $metadata['sizes'], $media_id ); if ( is_array( $sizes ) ) { foreach ( $sizes as $size => $size_details ) { $response['thumbnails'][ $size ] = dirname( $response['URL'] ) . '/' . $size_details['file']; } } } if ( isset( $metadata['image_meta'] ) ) { $response['exif'] = $metadata['image_meta']; } } if ( in_array( $ext, array( 'mp3', 'm4a', 'wav', 'ogg' ), true ) ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); if ( isset( $metadata['length'] ) ) { $response['length'] = $metadata['length']; } $response['exif'] = $metadata; } if ( in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ), true ) ) { $metadata = wp_get_attachment_metadata( $media_item->ID ); if ( isset( $metadata['height'] ) && isset( $metadata['width'] ) ) { $response['height'] = $metadata['height']; $response['width'] = $metadata['width']; } if ( isset( $metadata['length'] ) ) { $response['length'] = $metadata['length']; } if ( empty( $response['length'] ) && isset( $metadata['duration'] ) ) { $response['length'] = (int) $metadata['duration']; } if ( empty( $response['length'] ) && isset( $metadata['videopress']['duration'] ) ) { $response['length'] = ceil( $metadata['videopress']['duration'] / 1000 ); } // add VideoPress info. if ( function_exists( 'video_get_info_by_blogpostid' ) ) { $info = video_get_info_by_blogpostid( $this->site->get_id(), $media_id ); // Thumbnails. if ( function_exists( 'video_format_done' ) && function_exists( 'video_image_url_by_guid' ) ) { $response['thumbnails'] = array( 'fmt_hd' => '', 'fmt_dvd' => '', 'fmt_std' => '', ); foreach ( $response['thumbnails'] as $size => $thumbnail_url ) { if ( video_format_done( $info, $size ) ) { $response['thumbnails'][ $size ] = video_image_url_by_guid( $info->guid, $size ); } else { unset( $response['thumbnails'][ $size ] ); } } } $response['videopress_guid'] = $info->guid; $response['videopress_processing_done'] = true; if ( '0000-00-00 00:00:00' === $info->finish_date_gmt ) { $response['videopress_processing_done'] = false; } } } $response['thumbnails'] = (object) $response['thumbnails']; $response['meta'] = (object) array( 'links' => (object) array( 'self' => (string) $this->links->get_media_link( $this->site->get_id(), $media_id ), 'help' => (string) $this->links->get_media_link( $this->site->get_id(), $media_id, 'help' ), 'site' => (string) $this->links->get_site_link( $this->site->get_id() ), ), ); // add VideoPress link to the meta. if ( in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ), true ) ) { if ( function_exists( 'video_get_info_by_blogpostid' ) ) { $response['meta']->links->videopress = (string) $this->links->get_link( '/videos/%s', $response['videopress_guid'], '' ); } } if ( $media_item->post_parent > 0 ) { $response['meta']->links->parent = (string) $this->links->get_post_link( $this->site->get_id(), $media_item->post_parent ); } return (object) $response; } /** * Temporary wrapper around maybe_unserialize() to catch exceptions thrown by unserialize(). * * Can be removed after https://core.trac.wordpress.org/ticket/45895 lands in Core. * * @param string $original Serialized string. * * @return string Unserialized string or original string if an exception was raised. **/ protected function safe_maybe_unserialize( $original ) { try { return maybe_unserialize( $original ); } catch ( Exception $e ) { return $original; } } }
projects/plugins/jetpack/sal/class.json-api-metadata.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * WPCOM_JSON_API_Metadata class - Utility classes that don't necessarily have a home yet. * * @package automattic/jetpack */ /** * Base class for WPCOM_JSON_API_Metadata */ class WPCOM_JSON_API_Metadata { /** * Checks to see if a meta key is in the array of allowed public (and whitelisted) meta data. * * Additionally, if the key begins with 'geo_' or '_wpas_', true will also be returned. * * @param string $key A post metadata key value to check. * @return bool True or false depending on whether the key meets the defined criteria. **/ public static function is_public( $key ) { if ( empty( $key ) ) { return false; } // Default whitelisted meta keys. $whitelisted_meta = array( '_thumbnail_id' ); // whitelist of metadata that can be accessed. /** This filter is documented in json-endpoints/class.wpcom-json-api-post-endpoint.php */ if ( in_array( $key, apply_filters( 'rest_api_allowed_public_metadata', $whitelisted_meta ), true ) ) { return true; } if ( str_starts_with( $key, 'geo_' ) ) { return true; } if ( str_starts_with( $key, '_wpas_' ) ) { return true; } return false; } /** * Checks to see if a meta key should be used internally only. * * @param string $key A post metadata key value to check. * @return bool True or false depending on whether the key meets the defined criteria. **/ public static function is_internal_only( $key ) { // We want to always return the `_jetpack_blogging_prompt_key` key in post responses if it is available. if ( $key === '_jetpack_blogging_prompt_key' ) { return false; } // We want to always return the `_jetpack_newsletter_access` key to // display the correct newsletter access in Calypso. $whitelist = array( '_jetpack_newsletter_access', '_jetpack_newsletter_tier_id', ); if ( in_array( $key, $whitelist, true ) ) { return false; } if ( str_starts_with( $key, '_jetpack_' ) ) { return true; } if ( str_starts_with( $key, '_elasticsearch_' ) ) { return true; } return false; } }
projects/plugins/jetpack/sal/class.json-api-token.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * SAL_Token class * * @package automattic/jetpack */ /** * Base class for Jetpack_Site, so that we have a real class instead of just passing around an array. */ class SAL_Token { /** * The Jetpack blog ID for the site. * * @var int */ public $blog_id; /** * The Jetpack user's user ID. * * @var int */ public $user_id; /** * The scope for the token, for example global or auth. * * @var string */ public $scope; /** * The Client ID (or WordPress.com Blog ID of this site. * * @var int */ public $client_id; /** * The user ID on the local site. * * @var int */ public $external_user_id; /** * Used for tokens created by Oauth clients. * * @var string */ public $external_user_code; /** * The type of authorization based on where the Jetpack connection is made - eg 'calypso', 'jetpack', 'client'. * * @var string */ public $auth_type; /** * Contructs the SAL_Token instance. * * @param int $blog_id The Jetpack blog ID for the site. * @param int $user_id The Jetpack user's user ID. * @param string $scope The scope for the token, for example global or auth. * @param int $client_id The Client ID (or WordPress.com Blog ID of this site. * @param int $external_user_id The user ID on the local site. * @param string $external_user_code Used for tokens created by Oauth clients. * @param string $auth_type The type of authorization based on where the Jetpack connection is made (eg. calypso). */ public function __construct( $blog_id, $user_id, $scope, $client_id, $external_user_id, $external_user_code, $auth_type ) { $this->blog_id = $blog_id; // if blog_id is set and scope is not global, limit to that blog. $this->user_id = $user_id; $this->client_id = $client_id; $this->scope = $scope; $this->external_user_id = $external_user_id; $this->external_user_code = $external_user_code; $this->auth_type = $auth_type; } /** * Set's the scope variable to 'global'. * * @return string */ public function is_global() { return $scope === 'global'; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable } /** * This function is used to create a SAL_Token instance with only a user id, if a token doesn't already exist. * * @return SAL_Token */ public static function for_anonymous_user() { return new SAL_Token( null, get_current_user_id(), null, // there's only ever one scope in our current API implementation, auth or global. null, null, null, null ); } /** * If a user token exists, the information is used to construct a SAL_Token with the correct parameters. * * @param array $token An array of details relevant to the connected user (may be empty). * * @return SAL_Token */ public static function from_rest_token( $token ) { $user_id = isset( $token['user_id'] ) ? $token['user_id'] : get_current_user_id(); $scope = isset( $token['scope'][0] ) ? $token['scope'][0] : null; $client_id = isset( $token['client_id'] ) ? $token['client_id'] : null; $external_user_id = isset( $token['external_user_id'] ) ? $token['external_user_id'] : null; $external_user_code = isset( $token['external_user_code'] ) ? $token['external_user_code'] : null; $auth = isset( $token['auth'] ) ? $token['auth'] : null; $blog_id = isset( $token['blog_id'] ) ? $token['blog_id'] : null; return new SAL_Token( $blog_id, $user_id, $scope, // there's only ever one scope in our current API implementation, auth or global. $client_id, $external_user_id, $external_user_code, $auth ); } }
projects/plugins/jetpack/sal/class.json-api-platform.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * SAL_Platform class which defines a token to later be associated with a Jetpack site * * @package automattic/jetpack */ require_once __DIR__ . '/class.json-api-token.php'; /** * Base class for SAL_Platform */ abstract class SAL_Platform { /** * A token that will represent a SAL_Token instance, default is empty. * * @var SAL_Token */ public $token; /** * Contructs the SAL_Platform instance * * @param SAL_Token $token The variable which will store the SAL_Token instance. */ public function __construct( $token ) { if ( is_array( $token ) ) { $token = SAL_Token::from_rest_token( $token ); } else { $token = SAL_Token::for_anonymous_user(); } $this->token = $token; } /** * This is the get_site function declaration, initially not implemented. * * @param int $blog_id The sites Jetpack blog ID. * @see class.json-api-platform-jetpack.php for the implementation of this function. */ abstract public function get_site( $blog_id ); } if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { require_once dirname( WP_CONTENT_DIR ) . '/public.api/rest/sal/class.json-api-platform-wpcom.php'; } else { require_once __DIR__ . '/class.json-api-platform-jetpack.php'; }
projects/plugins/jetpack/sal/class.json-api-platform-jetpack.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * WPORG_Platform class that extends SAL_Platform, returning a Jetpack_Site with a $blog_id and $token * * @package automattic/jetpack */ require_once __DIR__ . '/class.json-api-platform.php'; /** * Base class for WPORG_Platform, which extends SAL_Platform */ class WPORG_Platform extends SAL_Platform { /** * Given a Jetpack blog ID, this function returns a Jetpack_Site instance * * @param int $blog_id A Jetpack blog ID. * @return Jetpack_Site A Jetpack_Site instance including all relevant details needed to define a Jetpack site. **/ public function get_site( $blog_id ) { require_once __DIR__ . '/class.json-api-site-jetpack.php'; return new Jetpack_Site( $blog_id, $this ); } } // phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move these functions to some other file. /** * Given a token instance (with blog and user id related information), this function returns a new WPORG_Platform instance * * @param SAL_Token $token A token instance. * @see class.json-api-token.php * @return WPORG_Platform A WPORG_Platform instance including all relevant details needed to define a Jetpack site, as well as a token instance. **/ function wpcom_get_sal_platform( $token ) { return new WPORG_Platform( $token ); }
projects/plugins/jetpack/sal/class.json-api-post-jetpack.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * This class extends the SAL_Post class, providing the implementation for * functions that were declared in that SAL_Post class. * * @see WPCOM_JSON_API_Post_v1_1_Endpoint in class.wpcom-json-api-post-v1-1-endpoint.php for more context on * the functions implemented here. * * @package automattic/jetpack */ /** * Base class for Jetpack_Post. */ class Jetpack_Post extends SAL_Post { /** * Defines a default value for the like counts on a post, if this hasn't been defined yet. * * @return int Returns 0. **/ public function get_like_count() { return 0; } /** * Defines a default value for whether or not the current user likes this post, if this hasn't been defined yet. * * @return bool Returns false **/ public function is_liked() { return false; } /** * Defines a default value for whether or not the current user reblogged this post, if this hasn't been defined yet. * * @return bool Returns false **/ public function is_reblogged() { return false; } /** * Defines a default value for whether or not the current user is following this blog, if this hasn't been defined yet. * * @return bool Returns false **/ public function is_following() { return false; } /** * Defines the unique WordPress.com-wide representation of a post, if this hasn't been defined yet. * * @return string Returns an empty string **/ public function get_global_id() { return ''; } /** * Defines a default value for whether or not there is gelocation data for this post, if this hasn't been defined yet. * * @return bool Returns false **/ public function get_geo() { return false; } /** * Returns the avatar URL for a user, or an empty string if there isn't a valid avatar. * * @param string $email The user's email. * @param int $avatar_size The size of the avatar in pixels. * * @return string */ protected function get_avatar_url( $email, $avatar_size = 96 ) { $avatar_url = get_avatar_url( $email, array( 'size' => $avatar_size, ) ); if ( ! $avatar_url || is_wp_error( $avatar_url ) ) { return ''; } return $avatar_url; } }
projects/plugins/jetpack/3rd-party/qtranslate-x.php
<?php /** * 3rd party integration for qTranslate. * * @package automattic/jetpack */ /** * Prevent qTranslate X from redirecting REST calls. * * @since 5.3 * * @param string $url_lang Language URL to redirect to. * @param string $url_orig Original URL. * @param array $url_info Pieces of original URL. * * @return bool */ function jetpack_no_qtranslate_rest_url_redirect( $url_lang, $url_orig, $url_info ) { if ( str_contains( $url_info['wp-path'], 'wp-json/jetpack' ) ) { return false; } return $url_lang; } add_filter( 'qtranslate_language_detect_redirect', 'jetpack_no_qtranslate_rest_url_redirect', 10, 3 );
projects/plugins/jetpack/3rd-party/debug-bar.php
<?php /** * 3rd Party integration for Debug Bar. * * @package automattic/jetpack */ /** * Checks if the search module is active, and if so, will initialize the singleton instance * of Jetpack_Search_Debug_Bar and add it to the array of debug bar panels. * * @param array $panels The array of debug bar panels. * @return array $panel The array of debug bar panels with our added panel. */ function init_jetpack_search_debug_bar( $panels ) { if ( ! Jetpack::is_module_active( 'search' ) ) { return $panels; } require_once __DIR__ . '/debug-bar/class-jetpack-search-debug-bar.php'; $panels[] = Jetpack_Search_Debug_Bar::instance(); return $panels; } add_filter( 'debug_bar_panels', 'init_jetpack_search_debug_bar' );
projects/plugins/jetpack/3rd-party/web-stories.php
<?php /** * Compatibility functions for the Web Stories plugin. * https://wordpress.org/plugins/web-stories/ * * @since 9.2.0 * * @package automattic/jetpack */ namespace Automattic\Jetpack\Web_Stories; if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Filter to enable web stories built in open graph data from being output. * If Jetpack is already handling Open Graph Meta Tags, the Web Stories plugin will not output any. * * @param bool $enabled If web stories open graph data is enabled. * * @return bool */ function maybe_disable_open_graph( $enabled ) { /** This filter is documented in class.jetpack.php */ $jetpack_enabled = apply_filters( 'jetpack_enable_open_graph', false ); if ( $jetpack_enabled ) { $enabled = false; } return $enabled; } add_filter( 'web_stories_enable_open_graph_metadata', __NAMESPACE__ . '\maybe_disable_open_graph' ); add_filter( 'web_stories_enable_twitter_metadata', __NAMESPACE__ . '\maybe_disable_open_graph' );
projects/plugins/jetpack/3rd-party/creative-mail.php
<?php /** * Compatibility functions for the Creative Mail plugin. * https://wordpress.org/plugins/creative-mail-by-constant-contact/ * * @since 8.9.0 * * @package automattic/jetpack */ namespace Automattic\Jetpack\Creative_Mail; use Automattic\Jetpack\Plugins_Installer; if ( ! defined( 'ABSPATH' ) ) { exit; } const PLUGIN_SLUG = 'creative-mail-by-constant-contact'; const PLUGIN_FILE = 'creative-mail-by-constant-contact/creative-mail-plugin.php'; add_action( 'jetpack_activated_plugin', __NAMESPACE__ . '\configure_plugin', 10, 2 ); // Check for the JITM action. if ( isset( $_GET['creative-mail-action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_init', __NAMESPACE__ . '\try_install' ); } if ( ! empty( $_GET['creative-mail-install-error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_notices', __NAMESPACE__ . '\error_notice' ); } /** * Verify the intent to install Creative Mail, and kick off installation. * * This works in tandem with a JITM set up in the JITM package. */ function try_install() { check_admin_referer( 'creative-mail-install' ); $result = false; $redirect = admin_url( 'edit.php?post_type=feedback' ); // Attempt to install and activate the plugin. if ( current_user_can( 'activate_plugins' ) ) { switch ( $_GET['creative-mail-action'] ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Function only hooked if set. case 'install': $result = install_and_activate(); break; case 'activate': $result = activate(); break; } } if ( $result ) { /** This action is already documented in _inc/lib/class.core-rest-api-endpoints.php */ do_action( 'jetpack_activated_plugin', PLUGIN_FILE, 'jitm' ); $redirect = admin_url( 'admin.php?page=creativemail' ); } else { $redirect = add_query_arg( 'creative-mail-install-error', true, $redirect ); } wp_safe_redirect( $redirect ); exit; } /** * Install and activate the Creative Mail plugin. * * @return bool result of installation */ function install_and_activate() { $result = Plugins_Installer::install_and_activate_plugin( PLUGIN_SLUG ); if ( is_wp_error( $result ) ) { return false; } else { return true; } } /** * Activate the Creative Mail plugin. * * @return bool result of activation */ function activate() { $result = activate_plugin( PLUGIN_FILE ); // Activate_plugin() returns null on success. return $result === null; } /** * Notify the user that the installation of Creative Mail failed. */ function error_notice() { ?> <div class="notice notice-error is-dismissible"> <p><?php esc_html_e( 'There was an error installing Creative Mail.', 'jetpack' ); ?></p> </div> <?php } /** * Set some options when first activating the plugin via Jetpack. * * @since 8.9.0 * * @param string $plugin_file Plugin file. * @param string $source Where did the plugin installation originate. */ function configure_plugin( $plugin_file, $source ) { if ( PLUGIN_FILE !== $plugin_file ) { return; } $plugin_info = array( 'plugin' => 'jetpack', 'version' => JETPACK__VERSION, 'time' => time(), 'source' => esc_attr( $source ), ); update_option( 'ce4wp_referred_by', $plugin_info ); }
projects/plugins/jetpack/3rd-party/woocommerce.php
<?php /** * This file contains compatibility functions for WooCommerce to improve Jetpack feature support. * * @package automattic/jetpack */ add_action( 'woocommerce_init', 'jetpack_woocommerce_integration' ); /** * Loads JP+WC integration. * * Fires on `woocommerce_init` hook */ function jetpack_woocommerce_integration() { /** * Double check WooCommerce exists - unlikely to fail due to the hook being used but better safe than sorry. */ if ( ! class_exists( 'WooCommerce' ) ) { return; } add_action( 'woocommerce_share', 'jetpack_woocommerce_social_share_icons', 10 ); /** * Add product post type to Jetpack sitemap while skipping hidden products. */ add_filter( 'jetpack_sitemap_post_types', 'jetpack_woocommerce_add_to_sitemap' ); add_filter( 'jetpack_sitemap_skip_post', 'jetpack_woocommerce_skip_hidden_products_in_sitemap', 10, 2 ); /** * Wrap in function exists check since this requires WooCommerce 3.3+. */ if ( function_exists( 'wc_get_default_products_per_row' ) ) { add_filter( 'infinite_scroll_render_callbacks', 'jetpack_woocommerce_infinite_scroll_render_callback', 10 ); add_action( 'wp_enqueue_scripts', 'jetpack_woocommerce_infinite_scroll_style', 10 ); } } /** * Add product post type to sitemap if Woocommerce is present. * * @param array $post_types Array of post types included in sitemap. */ function jetpack_woocommerce_add_to_sitemap( $post_types ) { $post_types[] = 'product'; return $post_types; } /** * Skip hidden products when generating the sitemap. * * @param bool $skip Whether to skip the post. * @param WP_Post $post The post object. */ function jetpack_woocommerce_skip_hidden_products_in_sitemap( $skip, $post ) { if ( $post !== null && $post->post_type === 'product' ) { $product = wc_get_product( $post->ID ); if ( $product ) { $skip = ! $product->is_visible(); } } return $skip; } /** * Make sure the social sharing icons show up under the product's short description */ function jetpack_woocommerce_social_share_icons() { if ( function_exists( 'sharing_display' ) ) { remove_filter( 'the_content', 'sharing_display', 19 ); remove_filter( 'the_excerpt', 'sharing_display', 19 ); sharing_display( '', true ); } } /** * Remove sharing display from account, cart, and checkout pages in WooCommerce. */ function jetpack_woocommerce_remove_share() { /** * Double check WooCommerce exists - unlikely to fail due to the hook being used but better safe than sorry. */ if ( ! class_exists( 'WooCommerce' ) ) { return; } if ( is_cart() || is_checkout() || is_account_page() ) { remove_filter( 'the_content', 'sharing_display', 19 ); if ( class_exists( 'Jetpack_Likes' ) ) { remove_filter( 'the_content', array( Jetpack_Likes::init(), 'post_likes' ), 30, 1 ); } } } add_action( 'loop_start', 'jetpack_woocommerce_remove_share' ); /** * Add a callback for WooCommerce product rendering in infinite scroll. * * @param array $callbacks Array of render callpacks for IS. * @return array */ function jetpack_woocommerce_infinite_scroll_render_callback( $callbacks ) { $callbacks[] = 'jetpack_woocommerce_infinite_scroll_render'; return $callbacks; } /** * Add a default renderer for WooCommerce products within infinite scroll. */ function jetpack_woocommerce_infinite_scroll_render() { if ( ! is_shop() && ! is_product_taxonomy() && ! is_product_category() && ! is_product_tag() ) { return; } woocommerce_product_loop_start(); while ( have_posts() ) { the_post(); wc_get_template_part( 'content', 'product' ); } woocommerce_product_loop_end(); } /** * Basic styling when infinite scroll is active only. */ function jetpack_woocommerce_infinite_scroll_style() { $custom_css = ' .infinite-scroll .woocommerce-pagination { display: none; }'; wp_add_inline_style( 'woocommerce-layout', $custom_css ); }
projects/plugins/jetpack/3rd-party/wpml.php
<?php /** * Only load these if WPML plugin is installed and active. * * @package automattic/jetpack */ /** * Load routines only if WPML is loaded. * * @since 4.4.0 */ function wpml_jetpack_init() { add_action( 'jetpack_widget_get_top_posts', 'wpml_jetpack_widget_get_top_posts', 10, 3 ); add_filter( 'grunion_contact_form_field_html', 'grunion_contact_form_field_html_filter', 10, 3 ); } add_action( 'wpml_loaded', 'wpml_jetpack_init' ); /** * Filter the Top Posts and Pages by language. * * @param array $posts Array of the most popular posts. * * @return array */ function wpml_jetpack_widget_get_top_posts( $posts ) { global $sitepress; foreach ( $posts as $k => $post ) { $lang_information = wpml_get_language_information( $post['post_id'] ); if ( ! is_wp_error( $lang_information ) ) { $post_language = substr( $lang_information['locale'], 0, 2 ); if ( $post_language !== $sitepress->get_current_language() ) { unset( $posts[ $k ] ); } } } return $posts; } /** * Filter the HTML of the Contact Form and output the one requested by language. * * @param string $r Contact Form HTML output. * @param string $field_label Field label. * * @return string */ function grunion_contact_form_field_html_filter( $r, $field_label ) { global $sitepress; if ( function_exists( 'icl_translate' ) ) { if ( $sitepress->get_current_language() !== $sitepress->get_default_language() ) { $label_translation = icl_translate( 'jetpack ', $field_label . '_label', $field_label ); $r = str_replace( $field_label, $label_translation, $r ); } } return $r; }
projects/plugins/jetpack/3rd-party/class-salesforce-lead-form.php
<?php /** * Salesforce Lead Form using Jetpack Contact Forms. * * @package automattic/jetpack */ namespace Automattic\Jetpack; /** * Class Salesforce_Lead_Form * * Hooks on Jetpack's Contact form to send form data to Salesforce. */ class Salesforce_Lead_Form { /** * Salesforce_Contact_Form constructor. * Hooks on `grunion_after_feedback_post_inserted` action to send form data to Salesforce. */ public static function initialize() { add_action( 'grunion_after_feedback_post_inserted', array( __CLASS__, 'process_salesforce_form' ), 10, 4 ); } /** * Process Salesforce Lead forms * * @param int $post_id - the post_id for the CPT that is created. * @param array $fields - Grunion_Contact_Form_Field array. * @param bool $is_spam - marked as spam by Akismet(?). * @param array $entry_values - extra fields added to from the contact form. * * @return null|void */ public static function process_salesforce_form( $post_id, $fields, $is_spam, $entry_values ) { if ( ! is_array( $fields ) ) { // nothing to do, also prevent hook from processing actions triggered with different args return; } // if spam (hinted by akismet?), don't process if ( $is_spam ) { return; } $blocks = parse_blocks( get_the_content() ); $filtered_blocks = self::get_salesforce_contact_form_blocks( $blocks ); // no contact-form blocks with salesforceData and organizationId, move on if ( empty( $filtered_blocks ) ) { return; } // more than one form on post, skipping process if ( count( $filtered_blocks ) > 1 ) { return; } $attrs = $filtered_blocks[0]['attrs']['salesforceData']; $organization_id = $attrs['organizationId']; // Double sanity check: no organization ID? Abort. if ( empty( $organization_id ) ) { return; } $keyed_fields = array_map( function ( $field ) { return $field->value; }, $fields ); // this is yet TBD, campaign IDs are hard to get from SF app/UI, but if // the user filled it, then send as API field Campaign_ID if ( ! empty( $attrs['campaignId'] ) ) { $keyed_fields['Campaign_ID'] = $attrs['campaignId']; } // add post/page URL as lead_source $keyed_fields['lead_source'] = $entry_values['entry_permalink']; $keyed_fields['oid'] = $organization_id; // we got this far, try and send it. Need to check for errors on submit try { self::send_to_salesforce( $keyed_fields ); } catch ( \Exception $e ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error trigger_error( sprintf( 'Jetpack Form: Sending lead to Salesforce failed: %s', esc_html( $e->getMessage() ) ) ); } } /** * POST to Salesforce WebToLead servlet * * @param array $data The data key/value pairs to send in POST. * @param array $options Options for POST. * * @return array|WP_Error The result value from wp_remote_post */ public static function send_to_salesforce( $data, $options = array() ) { global $wp_version; $user_agent = "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' ) . '; ' . get_bloginfo( 'url' ); $url = 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8'; $args = array( 'body' => $data, 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded', 'user-agent' => $user_agent, ), 'sslverify' => empty( $options['sslverify'] ) ? false : $options['sslverify'], ); $args = apply_filters( 'jetpack_contactform_salesforce_request_args', $args ); return wp_remote_post( $url, $args ); } /** * Extracts any jetpack/contact-form found on post. * * @param array $block_array - Array of blocks. * * @return array Array of jetpack/contact-form blocks found. */ public static function get_salesforce_contact_form_blocks( $block_array ) { $jetpack_form_blocks = array(); foreach ( $block_array as $block ) { if ( $block['blockName'] === 'jetpack/contact-form' && isset( $block['attrs']['salesforceData'] ) && $block['attrs']['salesforceData'] && isset( $block['attrs']['salesforceData']['sendToSalesforce'] ) && $block['attrs']['salesforceData']['sendToSalesforce'] && isset( $block['attrs']['salesforceData']['organizationId'] ) && $block['attrs']['salesforceData']['organizationId'] ) { $jetpack_form_blocks[] = $block; } elseif ( isset( $block['innerBlocks'] ) ) { $jetpack_form_blocks = array_merge( $jetpack_form_blocks, self::get_salesforce_contact_form_blocks( $block['innerBlocks'] ) ); } } return $jetpack_form_blocks; } } Salesforce_Lead_Form::initialize();
projects/plugins/jetpack/3rd-party/beaverbuilder.php
<?php /** * Beaverbuilder Compatibility. * * @package automattic/jetpack */ namespace Automattic\Jetpack\Third_Party; add_action( 'init', __NAMESPACE__ . '\beaverbuilder_refresh' ); /** * If masterbar module is active force BeaverBuilder to refresh when publishing a layout. */ function beaverbuilder_refresh() { if ( \Jetpack::is_module_active( 'masterbar' ) ) { add_filter( 'fl_builder_should_refresh_on_publish', '__return_true' ); } }
projects/plugins/jetpack/3rd-party/woocommerce-services.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName use Automattic\Jetpack\Plugins_Installer; if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Installs and activates the WooCommerce Services plugin. */ class WC_Services_Installer { /** * The instance of the Jetpack class. * * @var Jetpack */ private $jetpack; /** * The singleton instance of this class. * * @var WC_Services_Installer */ private static $instance = null; /** * Returns the singleton instance of this class. * * @return object The WC_Services_Installer object. */ public static function init() { if ( self::$instance === null ) { self::$instance = new WC_Services_Installer(); } return self::$instance; } /** * Constructor */ public function __construct() { add_action( 'jetpack_loaded', array( $this, 'on_jetpack_loaded' ) ); if ( ! empty( $_GET['wc-services-install-error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_notices', array( $this, 'error_notice' ) ); } if ( isset( $_GET['wc-services-action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_init', array( $this, 'try_install' ) ); } } /** * Runs on Jetpack being ready to load its packages. * * @param Jetpack $jetpack object. */ public function on_jetpack_loaded( $jetpack ) { $this->jetpack = $jetpack; } /** * Verify the intent to install WooCommerce Services, and kick off installation. */ public function try_install() { if ( ! isset( $_GET['wc-services-action'] ) ) { return; } check_admin_referer( 'wc-services-install' ); $result = false; switch ( $_GET['wc-services-action'] ) { case 'install': if ( current_user_can( 'install_plugins' ) ) { $this->jetpack->stat( 'jitm', 'wooservices-install-' . JETPACK__VERSION ); $result = $this->install(); if ( $result ) { $result = $this->activate(); } } break; case 'activate': if ( current_user_can( 'activate_plugins' ) ) { $this->jetpack->stat( 'jitm', 'wooservices-activate-' . JETPACK__VERSION ); $result = $this->activate(); } break; } if ( isset( $_GET['redirect'] ) ) { $redirect = home_url( esc_url_raw( wp_unslash( $_GET['redirect'] ) ) ); } else { $redirect = admin_url(); } if ( $result ) { $this->jetpack->stat( 'jitm', 'wooservices-activated-' . JETPACK__VERSION ); } else { $redirect = add_query_arg( 'wc-services-install-error', true, $redirect ); } wp_safe_redirect( $redirect ); exit; } /** * Notify the user that the installation of WooCommerce Services failed. */ public function error_notice() { ?> <div class="notice notice-error is-dismissible"> <p><?php esc_html_e( 'There was an error installing WooCommerce Services.', 'jetpack' ); ?></p> </div> <?php } /** * Download and install the WooCommerce Services plugin. * * @return bool result of installation */ private function install() { $result = Plugins_Installer::install_plugin( 'woocommerce-services' ); if ( is_wp_error( $result ) ) { return false; } else { return true; } } /** * Activate the WooCommerce Services plugin. * * @return bool result of activation */ private function activate() { $result = activate_plugin( 'woocommerce-services/woocommerce-services.php' ); // Activate_plugin() returns null on success. return $result === null; } } WC_Services_Installer::init();
projects/plugins/jetpack/3rd-party/atomic.php
<?php /** * Helper functions for the Atomic platform. * * @package automattic/jetpack */ namespace Automattic\Jetpack\Third_Party; use Automattic\Jetpack\Constants; use Automattic\Jetpack\Status\Host; /** * Handles suppressing development version notices on Atomic-hosted sites. * * @param bool $development_version Filterable value if this is a development version of Jetpack. * * @return bool */ function atomic_weekly_override( $development_version ) { if ( ( new Host() )->is_atomic_platform() ) { $haystack = Constants::get_constant( 'JETPACK__PLUGIN_DIR' ); $needle = '/jetpack-dev/'; if ( str_ends_with( $haystack, $needle ) ) { return $development_version; // Returns the default response if the active Jetpack version is from the beta plugin. } $development_version = false; // Returns false for regular installs on Atomic. } return $development_version; // Return default if not on Atomic. } add_filter( 'jetpack_development_version', __NAMESPACE__ . '\atomic_weekly_override' );
projects/plugins/jetpack/3rd-party/vaultpress.php
<?php /** * Handles VaultPress->Rewind transition by deactivating VaultPress when needed. * * @package automattic/jetpack */ use Automattic\Jetpack\Redirect; /** * Notify user that VaultPress has been disabled. Hide VaultPress notice that requested attention. * * @since 5.8 */ function jetpack_vaultpress_rewind_enabled_notice() { // The deactivation is performed here because there may be pages that admin_init runs on, // such as admin_ajax, that could deactivate the plugin without showing this notification. deactivate_plugins( 'vaultpress/vaultpress.php' ); // Remove WP core notice that says that the plugin was activated. unset( $_GET['activate'] ); // phpcs:ignore WordPress.Security.NonceVerification ?> <div class="notice notice-success is-dismissible vp-deactivated"> <p style="margin-bottom: 0.25em;"><strong><?php esc_html_e( 'Jetpack is now handling your backups.', 'jetpack' ); ?></strong></p> <p> <?php esc_html_e( 'VaultPress is no longer needed and has been deactivated.', 'jetpack' ); ?> <?php printf( wp_kses( /* Translators: first variable is the full URL to the new dashboard */ __( 'You can access your backups at <a href="%s" target="_blank" rel="noopener noreferrer">this dashboard</a>.', 'jetpack' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), esc_url( Redirect::get_url( 'calypso-backups' ) ) ); ?> </p> </div> <style>#vp-notice{display:none;}</style> <?php } /** * If Backup & Scan is enabled, remove its entry in sidebar, deactivate VaultPress, and show a notification. * * @since 5.8 */ function jetpack_vaultpress_rewind_check() { if ( Jetpack::is_connection_ready() && Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) && Jetpack::is_rewind_enabled() ) { remove_submenu_page( 'jetpack', 'vaultpress' ); add_action( 'admin_notices', 'jetpack_vaultpress_rewind_enabled_notice' ); } } add_action( 'admin_init', 'jetpack_vaultpress_rewind_check', 11 );
projects/plugins/jetpack/3rd-party/amp.php
<?php /** * This file contains compatibility features for AMP to improve Jetpack feature support. * * @package automattic/jetpack */ namespace Automattic\Jetpack; /** * Load Jetpack_AMP_Support. */ function load_3rd_party_amp_support() { // Only load the support class when AMP actually initializes. // This avoids calls to some slow functions if the plugin is loaded but // 'amp_is_enabled' is used to prevent it from initializing. require_once JETPACK__PLUGIN_DIR . '/3rd-party/class.jetpack-amp-support.php'; add_action( 'init', array( 'Jetpack_AMP_Support', 'init' ), 1 ); add_action( 'admin_init', array( 'Jetpack_AMP_Support', 'admin_init' ), 1 ); } add_action( 'amp_init', __NAMESPACE__ . '\load_3rd_party_amp_support' );
projects/plugins/jetpack/3rd-party/bitly.php
<?php /** * Fixes issues with the Official Bitly for WordPress * https://wordpress.org/plugins/bitly/ * * @package automattic/jetpack */ if ( isset( $GLOBALS['bitly'] ) ) { if ( method_exists( $GLOBALS['bitly'], 'og_tags' ) ) { remove_action( 'wp_head', array( $GLOBALS['bitly'], 'og_tags' ) ); } add_action( 'wp_head', 'jetpack_bitly_og_tag', 100 ); } /** * Adds bitly OG tags. */ function jetpack_bitly_og_tag() { if ( has_filter( 'wp_head', 'jetpack_og_tags' ) === false ) { // Add the bitly part again back if we don't have any jetpack_og_tags added. if ( method_exists( $GLOBALS['bitly'], 'og_tags' ) ) { $GLOBALS['bitly']->og_tags(); } } elseif ( isset( $GLOBALS['posts'] ) && $GLOBALS['posts'][0]->ID > 0 && method_exists( $GLOBALS['bitly'], 'get_bitly_link_for_post_id' ) ) { printf( "<meta property=\"bitly:url\" content=\"%s\" /> \n", esc_attr( $GLOBALS['bitly']->get_bitly_link_for_post_id( $GLOBALS['posts'][0]->ID ) ) ); } }
projects/plugins/jetpack/3rd-party/crowdsignal.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Fallback for the Crowdsignal Plugin. * * The PollDaddy/Crowdsignal prior to v. 2.033 called Jetpack_Sync as long as the Jetpack class was present. This stub is provided to prevent any fatals for older versions of the plugin. * This was resolved in 2016, but need to do just a little research before ripping it out. * * @see https://github.com/Automattic/crowdsignal-plugin/commit/941fc5758152ebf860a14d1cd0058245e8aed86b * * @package automattic/jetpack */ /** * Stub of Jetpack_Sync for Crowdsignal. */ class Jetpack_Sync { /** * Stub of sync_options to prevent fatals for Crowdsignal. */ public static function sync_options() { _deprecated_function( __METHOD__, 'jetpack-4.2', 'jetpack_options_whitelist filter' ); } }
projects/plugins/jetpack/3rd-party/class-domain-mapping.php
<?php /** * Domain Mapping 3rd Party * * @package automattic/jetpack */ namespace Automattic\Jetpack\Third_Party; use Automattic\Jetpack\Constants; /** * Class Automattic\Jetpack\Third_Party\Domain_Mapping. * * This class contains methods that are used to provide compatibility between Jetpack sync and domain mapping plugins. */ class Domain_Mapping { /** * Singleton holder. * * @var Domain_Mapping **/ private static $instance = null; /** * An array of methods that are used to hook the Jetpack sync filters for home_url and site_url to a mapping plugin. * * @var array */ public static $test_methods = array( 'hook_wordpress_mu_domain_mapping', 'hook_wpmu_dev_domain_mapping', ); /** * Singleton constructor. * * @return Domain_Mapping|null */ public static function init() { if ( self::$instance === null ) { self::$instance = new Domain_Mapping(); } return self::$instance; } /** * Class Automattic\Jetpack\Third_Party\Domain_Mapping constructor. */ private function __construct() { add_action( 'plugins_loaded', array( $this, 'attempt_to_hook_domain_mapping_plugins' ) ); } /** * This function is called on the plugins_loaded action and will loop through the $test_methods * to try and hook a domain mapping plugin to the Jetpack sync filters for the home_url and site_url callables. */ public function attempt_to_hook_domain_mapping_plugins() { if ( ! Constants::is_defined( 'SUNRISE' ) ) { return; } $hooked = false; $count = count( self::$test_methods ); for ( $i = 0; $i < $count && ! $hooked; $i++ ) { $hooked = call_user_func( array( $this, self::$test_methods[ $i ] ) ); } } /** * This method will test for a constant and function that are known to be used with Donncha's WordPress MU * Domain Mapping plugin. If conditions are met, we hook the domain_mapping_siteurl() function to Jetpack sync * filters for home_url and site_url callables. * * @return bool */ public function hook_wordpress_mu_domain_mapping() { if ( ! Constants::is_defined( 'SUNRISE_LOADED' ) || ! $this->function_exists( 'domain_mapping_siteurl' ) ) { return false; } add_filter( 'jetpack_sync_home_url', 'domain_mapping_siteurl' ); add_filter( 'jetpack_sync_site_url', 'domain_mapping_siteurl' ); return true; } /** * This method will test for a class and method known to be used in WPMU Dev's domain mapping plugin. If the * method exists, then we'll hook the swap_to_mapped_url() to our Jetpack sync filters for home_url and site_url. * * @return bool */ public function hook_wpmu_dev_domain_mapping() { if ( ! $this->class_exists( 'domain_map' ) || ! $this->method_exists( 'domain_map', 'utils' ) ) { return false; } $utils = $this->get_domain_mapping_utils_instance(); add_filter( 'jetpack_sync_home_url', array( $utils, 'swap_to_mapped_url' ) ); add_filter( 'jetpack_sync_site_url', array( $utils, 'swap_to_mapped_url' ) ); return true; } /* * Utility Methods * * These methods are very minimal, and in most cases, simply pass on arguments. Why create them you ask? * So that we can test. */ /** * Checks if a method exists. * * @param string $class Class name. * @param string $method Method name. * * @return bool Returns function_exists() without modification. */ public function method_exists( $class, $method ) { return method_exists( $class, $method ); } /** * Checks if a class exists. * * @param string $class Class name. * * @return bool Returns class_exists() without modification. */ public function class_exists( $class ) { return class_exists( $class ); } /** * Checks if a function exists. * * @param string $function Function name. * * @return bool Returns function_exists() without modification. */ public function function_exists( $function ) { return function_exists( $function ); } /** * Returns the Domain_Map::utils() instance. * * @see https://github.com/wpmudev/domain-mapping/blob/master/classes/Domainmap/Utils.php * @return Domainmap_Utils */ public function get_domain_mapping_utils_instance() { return \domain_map::utils(); } } Domain_Mapping::init();
projects/plugins/jetpack/3rd-party/3rd-party.php
<?php /** * Compatibility files for third-party plugins. * This is used to improve compatibility of specific Jetpack features with third-party plugins. * * @package automattic/jetpack */ namespace Automattic\Jetpack; use Automattic\Jetpack\Status\Host; add_action( 'plugins_loaded', __NAMESPACE__ . '\load_3rd_party_compat_filters', 11 ); /** * Loads the individual 3rd-party compat functions. * * This is a refactor of load_3rd_party() to load the individual compat files only when needed instead of universally. */ function load_3rd_party_compat_filters() { // SalesForce // @todo This one probably makes more sense to move to the Forms package (and the module until it is fully deprecated). require_once JETPACK__PLUGIN_DIR . '/3rd-party/class-salesforce-lead-form.php'; // not a module but the handler for Salesforce forms // bbPress if ( function_exists( 'bbpress' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/bbpress.php'; } // Beaver Builder if ( class_exists( 'FLBuilder' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/beaverbuilder.php'; } // Bitly if ( class_exists( 'Bitly' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/bitly.php'; } // BuddyPress if ( class_exists( 'BuddyPress' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/buddypress.php'; } // AMP. AMP__DIR__ is defined in the AMP plugin since the very first version. if ( Constants::is_defined( 'AMP__DIR__' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/amp.php'; } // Domain Mapping. All assume multisite, so it's an easy check. if ( Constants::is_defined( 'SUNRISE' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/class-domain-mapping.php'; } // Debug Bar if ( class_exists( 'Debug_Bar' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/debug-bar.php'; } // Letting these always load since it handles somethings upon plugin activation. require_once JETPACK__PLUGIN_DIR . '/3rd-party/creative-mail.php'; require_once JETPACK__PLUGIN_DIR . '/3rd-party/jetpack-backup.php'; require_once JETPACK__PLUGIN_DIR . '/3rd-party/jetpack-boost.php'; require_once JETPACK__PLUGIN_DIR . '/3rd-party/woocommerce-services.php'; // Crowdsignal. @todo Review the usage of modern Jetpack with outdated Crowdsignal. require_once JETPACK__PLUGIN_DIR . '/3rd-party/crowdsignal.php'; // qTranslate. Plugin closed in 2021, but leaving support for now to allow sites to drop it. if ( Constants::is_defined( 'QTX_VERSION' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/qtranslate-x.php'; } // VaultPress. if ( Constants::is_defined( 'VAULTPRESS__VERSION' ) || class_exists( 'VaultPress' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/vaultpress.php'; } // Web Stories if ( Constants::is_defined( 'WEBSTORIES_VERSION' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/web-stories.php'; } // WooCommerce if ( class_exists( 'WooCommerce' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/woocommerce.php'; } // Atomic Weekly if ( ( new Host() )->is_atomic_platform() ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/atomic.php'; } // WPML if ( defined( 'ICL_SITEPRESS_VERSION' ) ) { require_once JETPACK__PLUGIN_DIR . '/3rd-party/wpml.php'; } }
projects/plugins/jetpack/3rd-party/bbpress.php
<?php /** * Compatibility functions for bbpress. * * Only added if bbpress is active via function_exists( 'bbpress' ) in 3rd-party.php. * * @package automattic/jetpack */ use Automattic\Jetpack\Image_CDN\Image_CDN; // Priority 11 needed to ensure sharing_display is loaded. add_action( 'init', 'jetpack_bbpress_compat', 11 ); /** * Adds Jetpack + bbPress Compatibility filters. * * @author Brandon Kraft * @since 3.7.1 */ function jetpack_bbpress_compat() { /** * Add compatibility layer for REST API. * * @since 8.5.0 Moved from root-level file and check_rest_api_compat() */ require_once __DIR__ . '/class-jetpack-bbpress-rest-api.php'; Jetpack_BbPress_REST_API::instance(); // Adds sharing buttons to bbPress items. if ( function_exists( 'sharing_display' ) ) { add_filter( 'bbp_get_topic_content', 'sharing_display', 19 ); add_action( 'bbp_template_after_single_forum', 'jetpack_sharing_bbpress' ); add_action( 'bbp_template_after_single_topic', 'jetpack_sharing_bbpress' ); } /** * Enable Markdown support for bbpress post types. * * @author Brandon Kraft * @since 6.0.0 */ if ( function_exists( 'bbp_get_topic_post_type' ) ) { add_post_type_support( bbp_get_topic_post_type(), 'wpcom-markdown' ); add_post_type_support( bbp_get_reply_post_type(), 'wpcom-markdown' ); add_post_type_support( bbp_get_forum_post_type(), 'wpcom-markdown' ); } /** * Use Photon for all images in Topics and replies. * * @since 4.9.0 */ if ( class_exists( Image_CDN::class ) && Image_CDN::is_enabled() ) { add_filter( 'bbp_get_topic_content', array( Image_CDN::class, 'filter_the_content' ), 999999 ); add_filter( 'bbp_get_reply_content', array( Image_CDN::class, 'filter_the_content' ), 999999 ); } } /** * Display Jetpack "Sharing" buttons on bbPress 2.x forums/ topics/ lead topics/ replies. * * Determination if the sharing buttons should display on the post type is handled within sharing_display(). * * @author David Decker * @since 3.7.0 */ function jetpack_sharing_bbpress() { sharing_display( null, true ); }
projects/plugins/jetpack/3rd-party/jetpack-backup.php
<?php /** * Compatibility functions for the Jetpack Backup plugin. * https://wordpress.org/plugins/jetpack-backup/ * * @since 10.4 * * @package automattic/jetpack */ namespace Automattic\Jetpack\Jetpack_Backup; use Automattic\Jetpack\Plugins_Installer; if ( ! defined( 'ABSPATH' ) ) { exit; } const PLUGIN_SLUG = 'jetpack-backup'; const PLUGIN_FILE = 'jetpack-backup/jetpack-backup.php'; if ( isset( $_GET['jetpack-backup-install-error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_notices', __NAMESPACE__ . '\error_notice' ); } if ( isset( $_GET['jetpack-backup-action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_init', __NAMESPACE__ . '\try_install' ); } /** * Verify the intent to install Jetpack Backup, and kick off installation. * * This works in tandem with a JITM set up in the JITM package. */ function try_install() { check_admin_referer( 'jetpack-backup-install' ); $result = false; // If the plugin install fails, redirect to plugin install page pre-populated with jetpack-backup search term. $redirect_on_error = admin_url( 'plugin-install.php?s=jetpack-backup&tab=search&type=term' ); // Attempt to install and activate the plugin. if ( current_user_can( 'activate_plugins' ) ) { switch ( $_GET['jetpack-backup-action'] ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Function only hooked if set. case 'install': $result = install_and_activate(); break; case 'activate': $result = activate(); break; } } if ( $result ) { /** This action is already documented in _inc/lib/class.core-rest-api-endpoints.php */ do_action( 'jetpack_activated_plugin', PLUGIN_FILE, 'jitm' ); $redirect = admin_url( 'admin.php?page=jetpack-backup' ); } else { $redirect = add_query_arg( 'jetpack-backup-install-error', true, $redirect_on_error ); } wp_safe_redirect( $redirect ); exit; } /** * Install and activate the Jetpack Backup plugin. * * @return bool result of installation */ function install_and_activate() { $result = Plugins_Installer::install_and_activate_plugin( PLUGIN_SLUG ); if ( is_wp_error( $result ) ) { return false; } else { return true; } } /** * Activate the Jetpack Backup plugin. * * @return bool result of activation */ function activate() { $result = activate_plugin( PLUGIN_FILE ); // Activate_plugin() returns null on success. return $result === null; } /** * Notify the user that the installation of Jetpack Backup failed. */ function error_notice() { ?> <div class="notice notice-error is-dismissible"> <p><?php esc_html_e( 'There was an error installing Jetpack Backup. Please try again.', 'jetpack' ); ?></p> </div> <?php }
projects/plugins/jetpack/3rd-party/buddypress.php
<?php /** * 3rd Party Integration for BuddyPress. * * @package automattic/jetpack. */ namespace Automattic\Jetpack\Third_Party; add_filter( 'bp_core_pre_avatar_handle_upload', __NAMESPACE__ . '\blobphoto' ); /** * Adds filters for skipping photon during pre_avatar_handle_upload. * * @param bool $bool Passthrough of filter's original content. No changes made. * * @return bool */ function blobphoto( $bool ) { add_filter( 'jetpack_photon_skip_image', '__return_true' ); return $bool; }
projects/plugins/jetpack/3rd-party/jetpack-boost.php
<?php /** * Compatibility functions for the Jetpack Boost plugin. * https://wordpress.org/plugins/jetpack-boost/ * * @since 10.4 * * @package automattic/jetpack */ namespace Automattic\Jetpack\Jetpack_Boost; use Automattic\Jetpack\Plugins_Installer; if ( ! defined( 'ABSPATH' ) ) { exit; } const PLUGIN_SLUG = 'jetpack-boost'; const PLUGIN_FILE = 'jetpack-boost/jetpack-boost.php'; if ( isset( $_GET['jetpack-boost-install-error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_notices', __NAMESPACE__ . '\error_notice' ); } if ( isset( $_GET['jetpack-boost-action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended add_action( 'admin_init', __NAMESPACE__ . '\try_install' ); } /** * Verify the intent to install Jetpack Boost, and kick off installation. * * This works in tandem with a JITM set up in the JITM package. */ function try_install() { if ( ! isset( $_GET['jetpack-boost-action'] ) ) { return; } check_admin_referer( 'jetpack-boost-install' ); $result = false; // If the plugin install fails, redirect to plugin install page pre-populated with jetpack-boost search term. $redirect_on_error = admin_url( 'plugin-install.php?s=jetpack-boost&tab=search&type=term' ); // Attempt to install and activate the plugin. if ( current_user_can( 'activate_plugins' ) ) { switch ( $_GET['jetpack-boost-action'] ) { case 'install': $result = install_and_activate(); break; case 'activate': $result = activate(); break; } } if ( $result ) { /** This action is already documented in _inc/lib/class.core-rest-api-endpoints.php */ do_action( 'jetpack_activated_plugin', PLUGIN_FILE, 'jitm' ); $redirect = admin_url( 'admin.php?page=jetpack-boost' ); } else { $redirect = add_query_arg( 'jetpack-boost-install-error', true, $redirect_on_error ); } wp_safe_redirect( $redirect ); exit; } /** * Install and activate the Jetpack Boost plugin. * * @return bool result of installation */ function install_and_activate() { $result = Plugins_Installer::install_and_activate_plugin( PLUGIN_SLUG ); if ( is_wp_error( $result ) ) { return false; } else { return true; } } /** * Activate the Jetpack Boost plugin. * * @return bool result of activation */ function activate() { $result = activate_plugin( PLUGIN_FILE ); // Activate_plugin() returns null on success. return $result === null; } /** * Notify the user that the installation of Jetpack Boost failed. */ function error_notice() { if ( empty( $_GET['jetpack-boost-install-error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } ?> <div class="notice notice-error is-dismissible"> <p><?php esc_html_e( 'There was an error installing Jetpack Boost. Please try again.', 'jetpack' ); ?></p> </div> <?php }
projects/plugins/jetpack/3rd-party/class-jetpack-bbpress-rest-api.php
<?php /** * REST API Compatibility: bbPress & Jetpack * Enables bbPress to work with the Jetpack REST API * * @package automattic/jetpack */ /** * REST API Compatibility: bbPress. */ class Jetpack_BbPress_REST_API { /** * Singleton * * @var Jetpack_BbPress_REST_API. */ private static $instance; /** * Returns or creates the singleton. * * @return Jetpack_BbPress_REST_API */ public static function instance() { if ( isset( self::$instance ) ) { return self::$instance; } self::$instance = new self(); } /** * Jetpack_BbPress_REST_API constructor. */ private function __construct() { add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_bbpress_post_types' ) ); add_filter( 'bbp_map_meta_caps', array( $this, 'adjust_meta_caps' ), 10, 4 ); add_filter( 'rest_api_allowed_public_metadata', array( $this, 'allow_bbpress_public_metadata' ) ); } /** * Adds the bbPress post types to the rest_api_allowed_post_types filter. * * @param array $allowed_post_types Allowed post types. * * @return array */ public function allow_bbpress_post_types( $allowed_post_types ) { $allowed_post_types[] = 'forum'; $allowed_post_types[] = 'topic'; $allowed_post_types[] = 'reply'; return $allowed_post_types; } /** * Adds the bbpress meta keys to the rest_api_allowed_public_metadata filter. * * @param array $allowed_meta_keys Allowed meta keys. * * @return array */ public function allow_bbpress_public_metadata( $allowed_meta_keys ) { $allowed_meta_keys[] = '_bbp_forum_id'; $allowed_meta_keys[] = '_bbp_topic_id'; $allowed_meta_keys[] = '_bbp_status'; $allowed_meta_keys[] = '_bbp_forum_type'; $allowed_meta_keys[] = '_bbp_forum_subforum_count'; $allowed_meta_keys[] = '_bbp_reply_count'; $allowed_meta_keys[] = '_bbp_total_reply_count'; $allowed_meta_keys[] = '_bbp_topic_count'; $allowed_meta_keys[] = '_bbp_total_topic_count'; $allowed_meta_keys[] = '_bbp_topic_count_hidden'; $allowed_meta_keys[] = '_bbp_last_topic_id'; $allowed_meta_keys[] = '_bbp_last_reply_id'; $allowed_meta_keys[] = '_bbp_last_active_time'; $allowed_meta_keys[] = '_bbp_last_active_id'; $allowed_meta_keys[] = '_bbp_sticky_topics'; $allowed_meta_keys[] = '_bbp_voice_count'; $allowed_meta_keys[] = '_bbp_reply_count_hidden'; $allowed_meta_keys[] = '_bbp_anonymous_reply_count'; return $allowed_meta_keys; } /** * Adds the needed caps to the bbp_map_meta_caps filter. * * @param array $caps Capabilities for meta capability. * @param string $cap Capability name. * @param int $user_id User id. * @param array $args Arguments. * * @return array */ public function adjust_meta_caps( $caps, $cap, $user_id, $args ) { // Return early if not a REST request or if not meta bbPress caps. if ( $this->should_adjust_meta_caps_return_early( $caps, $cap, $user_id, $args ) ) { return $caps; } // $args[0] could be a post ID or a post_type string. if ( is_int( $args[0] ) ) { $_post = get_post( $args[0] ); if ( ! empty( $_post ) ) { $post_type = get_post_type_object( $_post->post_type ); } } elseif ( is_string( $args[0] ) ) { $post_type = get_post_type_object( $args[0] ); } // no post type found, bail. if ( empty( $post_type ) ) { return $caps; } // reset the needed caps. $caps = array(); // Add 'do_not_allow' cap if user is spam or deleted. if ( bbp_is_user_inactive( $user_id ) ) { $caps[] = 'do_not_allow'; // Moderators can always edit meta. } elseif ( user_can( $user_id, 'moderate' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown $caps[] = 'moderate'; // Unknown so map to edit_posts. } else { $caps[] = $post_type->cap->edit_posts; } return $caps; } /** * Should adjust_meta_caps return early? * * @param array $caps Capabilities for meta capability. * @param string $cap Capability name. * @param int $user_id User id. * @param array $args Arguments. * * @return bool */ private function should_adjust_meta_caps_return_early( $caps, $cap, $user_id, $args ) { // only run for REST API requests. if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) { return true; } // only modify caps for meta caps and for bbPress meta keys. if ( ! in_array( $cap, array( 'edit_post_meta', 'delete_post_meta', 'add_post_meta' ), true ) || empty( $args[1] ) || ! str_contains( $args[1], '_bbp_' ) ) { return true; } return false; } }
projects/plugins/jetpack/3rd-party/class.jetpack-amp-support.php
<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName use Automattic\Jetpack\Assets; use Automattic\Jetpack\Stats\Tracking_Pixel as Stats_Tracking_Pixel; use Automattic\Jetpack\Sync\Functions; /** * Manages compatibility with the amp-wp plugin * * @see https://github.com/Automattic/amp-wp */ class Jetpack_AMP_Support { /** * Apply custom AMP changes on the front-end. */ public static function init() { // Add Stats tracking pixel on Jetpack sites when the Stats module is active. if ( Jetpack::is_module_active( 'stats' ) && ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) { add_action( 'amp_post_template_footer', array( 'Jetpack_AMP_Support', 'add_stats_pixel' ) ); } /** * Remove this during the init hook in case users have enabled it during * the after_setup_theme hook, which triggers before init. */ remove_theme_support( 'jetpack-devicepx' ); // Sharing. add_filter( 'jetpack_sharing_display_markup', array( 'Jetpack_AMP_Support', 'render_sharing_html' ), 10, 2 ); add_filter( 'sharing_enqueue_scripts', array( 'Jetpack_AMP_Support', 'amp_disable_sharedaddy_css' ) ); add_action( 'wp_enqueue_scripts', array( 'Jetpack_AMP_Support', 'amp_enqueue_sharing_css' ) ); // Sharing for Reader mode. if ( function_exists( 'jetpack_social_menu_include_svg_icons' ) ) { add_action( 'amp_post_template_footer', 'jetpack_social_menu_include_svg_icons' ); } add_action( 'amp_post_template_css', array( 'Jetpack_AMP_Support', 'amp_reader_sharing_css' ), 10, 0 ); // enforce freedom mode for videopress. add_filter( 'videopress_shortcode_options', array( 'Jetpack_AMP_Support', 'videopress_enable_freedom_mode' ) ); // include Jetpack og tags when rendering native AMP head. add_action( 'amp_post_template_head', array( 'Jetpack_AMP_Support', 'amp_post_jetpack_og_tags' ) ); // Post rendering changes for legacy AMP. add_action( 'pre_amp_render_post', array( 'Jetpack_AMP_Support', 'amp_disable_the_content_filters' ) ); // Disable Comment Likes. add_filter( 'jetpack_comment_likes_enabled', array( 'Jetpack_AMP_Support', 'comment_likes_enabled' ) ); // Transitional mode AMP should not have comment likes. add_filter( 'the_content', array( 'Jetpack_AMP_Support', 'disable_comment_likes_before_the_content' ) ); // Remove the Likes button from the admin bar. add_filter( 'jetpack_admin_bar_likes_enabled', array( 'Jetpack_AMP_Support', 'disable_likes_admin_bar' ) ); // Add post template metadata for legacy AMP. add_filter( 'amp_post_template_metadata', array( 'Jetpack_AMP_Support', 'amp_post_template_metadata' ), 10, 2 ); // Filter photon image args for AMP Stories. add_filter( 'jetpack_photon_post_image_args', array( 'Jetpack_AMP_Support', 'filter_photon_post_image_args_for_stories' ), 10, 2 ); // Sync the amp-options. add_filter( 'jetpack_options_whitelist', array( 'Jetpack_AMP_Support', 'filter_jetpack_options_safelist' ) ); } /** * Disable the Comment Likes feature on AMP views. * * @param bool $enabled Should comment likes be enabled. */ public static function comment_likes_enabled( $enabled ) { return $enabled && ! self::is_amp_request(); } /** * Apply custom AMP changes in wp-admin. */ public static function admin_init() { // disable Likes metabox for post editor if AMP canonical disabled. add_filter( 'post_flair_disable', array( 'Jetpack_AMP_Support', 'is_amp_canonical' ), 99 ); } /** * Is the page in AMP 'canonical mode'. * Used when themes register support for AMP with `add_theme_support( 'amp' )`. * * @return bool is_amp_canonical */ public static function is_amp_canonical() { return function_exists( 'amp_is_canonical' ) && amp_is_canonical(); } /** * Is AMP available for this request * This returns false for admin, CLI requests etc. * * @return bool is_amp_available */ public static function is_amp_available() { return ( function_exists( 'amp_is_available' ) && amp_is_available() ); } /** * Does the page return AMP content. * * @return bool $is_amp_request Are we on am AMP view. */ public static function is_amp_request() { $is_amp_request = ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ); /** * Returns true if the current request should return valid AMP content. * * @since 6.2.0 * * @param boolean $is_amp_request Is this request supposed to return valid AMP content? */ return apply_filters( 'jetpack_is_amp_request', $is_amp_request ); } /** * Determines whether the legacy AMP post templates are being used. * * @since 10.6.0 * * @return bool */ public static function is_amp_legacy() { return ( function_exists( 'amp_is_legacy' ) && amp_is_legacy() ); } /** * Remove content filters added by Jetpack. */ public static function amp_disable_the_content_filters() { if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { add_filter( 'protected_embeds_use_form_post', '__return_false' ); remove_filter( 'the_title', 'widont' ); } remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'filter' ), 11 ); remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'maybe_create_links' ), 100 ); } /** * Do not add comment likes on AMP requests. * * @param string $content Post content. */ public static function disable_comment_likes_before_the_content( $content ) { if ( self::is_amp_request() ) { remove_filter( 'comment_text', 'comment_like_button', 12, 2 ); } return $content; } /** * Do not display the Likes' Admin bar on AMP requests. * * @param bool $is_admin_bar_button_visible Should the Like button be visible in the Admin bar. Default to true. */ public static function disable_likes_admin_bar( $is_admin_bar_button_visible ) { if ( self::is_amp_request() ) { return false; } return $is_admin_bar_button_visible; } /** * Add Jetpack stats pixel. * * @since 6.2.1 */ public static function add_stats_pixel() { if ( ! has_action( 'wp_footer', array( Stats_Tracking_Pixel::class, 'add_amp_pixel' ) ) ) { return; } $stats_data = Stats_Tracking_Pixel::build_view_data(); Stats_Tracking_Pixel::render_amp_footer( $stats_data ); } /** * Add publisher and image metadata to legacy AMP post. * * @since 6.2.0 * * @param array $metadata Metadata array. * @param WP_Post $post Post. * @return array Modified metadata array. */ public static function amp_post_template_metadata( $metadata, $post ) { if ( isset( $metadata['publisher'] ) && ! isset( $metadata['publisher']['logo'] ) ) { $metadata = self::add_site_icon_to_metadata( $metadata ); } if ( ! isset( $metadata['image'] ) && ! empty( $post ) ) { $metadata = self::add_image_to_metadata( $metadata, $post ); } return $metadata; } /** * Add blavatar to legacy AMP post metadata. * * @since 6.2.0 * * @param array $metadata Metadata. * * @return array Metadata. */ private static function add_site_icon_to_metadata( $metadata ) { $size = 60; $site_icon_url = class_exists( 'Automattic\\Jetpack\\Sync\\Functions' ) ? Functions::site_icon_url( $size ) : ''; if ( function_exists( 'blavatar_domain' ) ) { $metadata['publisher']['logo'] = array( '@type' => 'ImageObject', 'url' => blavatar_url( blavatar_domain( site_url() ), 'img', $size, self::staticize_subdomain( 'https://wordpress.com/i/favicons/apple-touch-icon-60x60.png' ) ), 'width' => $size, 'height' => $size, ); } elseif ( $site_icon_url ) { $metadata['publisher']['logo'] = array( '@type' => 'ImageObject', 'url' => $site_icon_url, 'width' => $size, 'height' => $size, ); } return $metadata; } /** * Add image to legacy AMP post metadata. * * @since 6.2.0 * * @param array $metadata Metadata. * @param WP_Post $post Post. * @return array Metadata. */ private static function add_image_to_metadata( $metadata, $post ) { $image = Jetpack_PostImages::get_image( $post->ID, array( 'fallback_to_avatars' => true, 'avatar_size' => 200, // AMP already attempts these. 'from_thumbnail' => false, 'from_attachment' => false, ) ); if ( empty( $image ) ) { return self::add_fallback_image_to_metadata( $metadata ); } if ( ! isset( $image['src_width'] ) ) { $dimensions = self::extract_image_dimensions_from_getimagesize( array( $image['src'] => false, ) ); if ( false !== $dimensions[ $image['src'] ] ) { $image['src_width'] = $dimensions['width']; $image['src_height'] = $dimensions['height']; } } $metadata['image'] = array( '@type' => 'ImageObject', 'url' => $image['src'], ); if ( isset( $image['src_width'] ) ) { $metadata['image']['width'] = $image['src_width']; } if ( isset( $image['src_width'] ) ) { $metadata['image']['height'] = $image['src_height']; } return $metadata; } /** * Add fallback image to legacy AMP post metadata. * * @since 6.2.0 * * @param array $metadata Metadata. * @return array Metadata. */ private static function add_fallback_image_to_metadata( $metadata ) { /** This filter is documented in functions.opengraph.php */ $default_image = apply_filters( 'jetpack_open_graph_image_default', 'https://wordpress.com/i/blank.jpg' ); $metadata['image'] = array( '@type' => 'ImageObject', 'url' => self::staticize_subdomain( $default_image ), 'width' => 200, 'height' => 200, ); return $metadata; } /** * Return static WordPress.com domain to use to load resources from WordPress.com. * * @param string $domain Asset URL. */ private static function staticize_subdomain( $domain ) { // deal with WPCOM vs Jetpack. if ( function_exists( 'staticize_subdomain' ) ) { return staticize_subdomain( $domain ); } else { return Assets::staticize_subdomain( $domain ); } } /** * Extract image dimensions via wpcom/imagesize, only on WPCOM * * @since 6.2.0 * * @param array $dimensions Dimensions. * @return array Dimensions. */ private static function extract_image_dimensions_from_getimagesize( $dimensions ) { if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'require_lib' ) ) ) { return $dimensions; } require_lib( 'wpcom/imagesize' ); foreach ( $dimensions as $url => $value ) { if ( is_array( $value ) ) { continue; } $result = wpcom_getimagesize( $url ); if ( is_array( $result ) ) { $dimensions[ $url ] = array( 'width' => $result[0], 'height' => $result[1], ); } } return $dimensions; } /** * Display Open Graph Meta tags in AMP views. */ public static function amp_post_jetpack_og_tags() { if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) { Jetpack::init()->check_open_graph(); } if ( function_exists( 'jetpack_og_tags' ) ) { jetpack_og_tags(); } } /** * Force Freedom mode in VideoPress. * * @param array $options Array of VideoPress shortcode options. */ public static function videopress_enable_freedom_mode( $options ) { if ( self::is_amp_request() ) { $options['freedom'] = true; } return $options; } /** * Display custom markup for the sharing buttons when in an AMP view. * * @param string $markup Content markup of the Jetpack sharing links. * @param array $sharing_enabled Array of Sharing Services currently enabled. */ public static function render_sharing_html( $markup, $sharing_enabled ) { global $post; if ( empty( $post ) ) { return ''; } if ( ! self::is_amp_request() ) { return $markup; } remove_action( 'wp_footer', 'sharing_add_footer' ); if ( empty( $sharing_enabled ) ) { return $markup; } $sharing_links = array(); foreach ( $sharing_enabled['visible'] as $service ) { $sharing_link = $service->get_amp_display( $post ); if ( ! empty( $sharing_link ) ) { $sharing_links[] = $sharing_link; } } // Replace the existing unordered list with AMP sharing buttons. $markup = preg_replace( '#<ul>(.+)</ul>#', implode( '', $sharing_links ), $markup ); // Remove any lingering share-end list items. $markup = str_replace( '<li class="share-end"></li>', '', $markup ); return $markup; } /** * Tells Jetpack not to enqueue CSS for share buttons. * * @param bool $enqueue Whether or not to enqueue. * @return bool Whether or not to enqueue. */ public static function amp_disable_sharedaddy_css( $enqueue ) { if ( self::is_amp_request() ) { $enqueue = false; } return $enqueue; } /** * Enqueues the AMP specific sharing styles for the sharing icons. */ public static function amp_enqueue_sharing_css() { if ( Jetpack::is_module_active( 'sharedaddy' ) && self::is_amp_request() && ! self::is_amp_legacy() ) { wp_enqueue_style( 'sharedaddy-amp', plugin_dir_url( __DIR__ ) . 'modules/sharedaddy/amp-sharing.css', array( 'social-logos' ), JETPACK__VERSION ); } } /** * For the AMP Reader mode template, include styles that we need. */ public static function amp_reader_sharing_css() { // If sharing is not enabled, we should not proceed to render the CSS. if ( ! defined( 'JETPACK_SOCIAL_LOGOS_DIR' ) || ! defined( 'JETPACK_SOCIAL_LOGOS_URL' ) || ! defined( 'WP_SHARING_PLUGIN_DIR' ) ) { return; } /* * We'll need to output the full contents of the 2 files * in the head on AMP views. We can't rely on regular enqueues here. * @todo As of AMP plugin v1.5, you can actually rely on regular enqueues thanks to https://github.com/ampproject/amp-wp/pull/4299. Once WPCOM upgrades AMP, then this method can be eliminated. * * phpcs:disable WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents * phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped */ $css = file_get_contents( JETPACK_SOCIAL_LOGOS_DIR . 'social-logos.css' ); $css = preg_replace( '#(?<=url\(")(?=social-logos\.)#', JETPACK_SOCIAL_LOGOS_URL, $css ); // Make sure font files get their absolute paths. echo $css; echo file_get_contents( WP_SHARING_PLUGIN_DIR . 'amp-sharing.css' ); /* * phpcs:enable WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents * phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped */ } /** * Ensure proper Photon image dimensions for AMP Stories. * * @param array $args Array of Photon Arguments. * @param array $details { * Array of image details. * * @type string $tag Image tag (Image HTML output). * @type string $src Image URL. * @type string $src_orig Original Image URL. * @type int|false $width Image width. * @type int|false $height Image height. * @type int|false $width_orig Original image width before constrained by content_width. * @type int|false $height_orig Original Image height before constrained by content_width. * @type string $transform_orig Original transform before constrained by content_width. * } * @return array Args. */ public static function filter_photon_post_image_args_for_stories( $args, $details ) { if ( ! is_singular( 'amp_story' ) ) { return $args; } // Percentage-based dimensions are not allowed in AMP, so this shouldn't happen, but short-circuit just in case. if ( str_contains( $details['width_orig'], '%' ) || str_contains( $details['height_orig'], '%' ) ) { return $args; } $max_height = 1280; // See image size with the slug \AMP_Story_Post_Type::MAX_IMAGE_SIZE_SLUG. $transform = $details['transform_orig']; $width = $details['width_orig']; $height = $details['height_orig']; // If height is available, constrain to $max_height. if ( false !== $height ) { if ( $height > $max_height && false !== $height ) { $width = ( $max_height * $width ) / $height; $height = $max_height; } elseif ( $height > $max_height ) { $height = $max_height; } } /* * Set a height if none is found. * If height is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing. */ if ( false === $height ) { $height = $max_height; if ( false !== $width ) { $transform = 'fit'; } } // Build array of Photon args and expose to filter before passing to Photon URL function. $args = array(); if ( false !== $width && false !== $height ) { $args[ $transform ] = $width . ',' . $height; } elseif ( false !== $width ) { $args['w'] = $width; } elseif ( false !== $height ) { $args['h'] = $height; } return $args; } /** * Adds amp-options to the list of options to sync, if AMP is available * * @param array $options_safelist Safelist of options to sync. * * @return array Updated options safelist */ public static function filter_jetpack_options_safelist( $options_safelist ) { if ( function_exists( 'is_amp_endpoint' ) ) { $options_safelist[] = 'amp-options'; } return $options_safelist; } }
projects/plugins/jetpack/3rd-party/debug-bar/class-jetpack-search-debug-bar.php
<?php /** * Adds a Jetpack Search debug panel to Debug Bar. * * @package automattic/jetpack */ use Automattic\Jetpack\Search as Jetpack_Search; /** * Singleton class instantiated by Jetpack_Searc_Debug_Bar::instance() that handles * rendering the Jetpack Search debug bar menu item and panel. */ class Jetpack_Search_Debug_Bar extends Debug_Bar_Panel { /** * Holds singleton instance * * @var Jetpack_Search_Debug_Bar */ protected static $instance = null; /** * The title to use in the debug bar navigation * * @var string */ public $title; /** * Constructor */ public function __construct() { $this->title( esc_html__( 'Jetpack Search', 'jetpack' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'login_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'enqueue_embed_scripts', array( $this, 'enqueue_scripts' ) ); } /** * Returns the singleton instance of Jetpack_Search_Debug_Bar * * @return Jetpack_Search_Debug_Bar */ public static function instance() { if ( self::$instance === null ) { self::$instance = new Jetpack_Search_Debug_Bar(); } return self::$instance; } /** * Enqueues styles for our panel in the debug bar * * @return void */ public function enqueue_scripts() { // Do not enqueue scripts if we haven't already enqueued Debug Bar or Query Monitor styles. if ( ! wp_style_is( 'debug-bar' ) && ! wp_style_is( 'query-monitor' ) ) { return; } wp_enqueue_style( 'jetpack-search-debug-bar', plugins_url( '3rd-party/debug-bar/debug-bar.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION ); wp_enqueue_script( 'jetpack-search-debug-bar', plugins_url( '3rd-party/debug-bar/debug-bar.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION, true ); } /** * Should the Jetpack Search Debug Bar show? * * Since we've previously done a check for the search module being activated, let's just return true. * Later on, we can update this to only show when `is_search()` is true. * * @return boolean */ public function is_visible() { return true; } /** * Renders the panel content * * @return void */ public function render() { $jetpack_search = ( Jetpack_Search\Options::is_instant_enabled() ? Jetpack_Search\Instant_Search::instance() : Jetpack_Search\Classic_Search::instance() ); // Search hasn't been initialized. Exit early and do not display the debug bar. if ( ! method_exists( $jetpack_search, 'get_last_query_info' ) ) { return; } $last_query_info = $jetpack_search->get_last_query_info(); // If not empty, let's reshuffle the order of some things. if ( ! empty( $last_query_info ) ) { $args = $last_query_info['args']; $response = $last_query_info['response']; $response_code = $last_query_info['response_code']; unset( $last_query_info['args'] ); unset( $last_query_info['response'] ); unset( $last_query_info['response_code'] ); if ( $last_query_info['es_time'] === null ) { $last_query_info['es_time'] = esc_html_x( 'cache hit', 'displayed in search results when results are cached', 'jetpack' ); } $temp = array_merge( array( 'response_code' => $response_code ), array( 'args' => $args ), $last_query_info, array( 'response' => $response ) ); $last_query_info = $temp; } ?> <div class="jetpack-search-debug-bar"> <h2><?php esc_html_e( 'Last query information:', 'jetpack' ); ?></h2> <?php if ( empty( $last_query_info ) ) : ?> <?php echo esc_html_x( 'None', 'Text displayed when there is no information', 'jetpack' ); ?> <?php else : foreach ( $last_query_info as $key => $info ) : ?> <h3><?php echo esc_html( $key ); ?></h3> <?php if ( 'response' !== $key && 'args' !== $key ) : ?> <pre><?php print_r( esc_html( $info ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions ?></pre> <?php else : $this->render_json_toggle( $info ); endif; ?> <?php endforeach; endif; ?> </div><!-- Closes .jetpack-search-debug-bar --> <?php } /** * Responsible for rendering the HTML necessary for the JSON toggle * * @param array $value The resonse from the API as an array. * @return void */ public function render_json_toggle( $value ) { ?> <div class="json-toggle-wrap"> <pre class="json"> <?php // esc_html() will not double-encode entities (&amp; -> &amp;amp;). // If any entities are part of the JSON blob, we want to re-encoode them // (double-encode them) so that they are displayed correctly in the debug // bar. // Use _wp_specialchars() "manually" to ensure entities are encoded correctly. echo _wp_specialchars( // phpcs:ignore WordPress.Security.EscapeOutput wp_json_encode( $value ), ENT_NOQUOTES, // Don't need to encode quotes (output is for a text node). 'UTF-8', // wp_json_encode() outputs UTF-8 (really just ASCII), not the blog's charset. true // Do "double-encode" existing HTML entities. ); ?> </pre> <span class="pretty toggle"><?php echo esc_html_x( 'Pretty', 'label for formatting JSON', 'jetpack' ); ?></span> <span class="ugly toggle"><?php echo esc_html_x( 'Minify', 'label for formatting JSON', 'jetpack' ); ?></span> </div> <?php } }
projects/plugins/jetpack/tests/php/test_deprecation.php
<?php class WP_Test_Jetpack_Deprecation extends WP_UnitTestCase { /** * @dataProvider provider_deprecated_file_paths */ public function test_deprecated_file_paths( $file_path, $replacement_path ) { $this->setExpectedDeprecated( $file_path ); $mock = $this->getMockBuilder( stdClass::class ) ->setMethods( array( 'action' ) ) ->getMock(); $mock->expects( $this->once() )->method( 'action' )->with( $file_path, $replacement_path ); add_action( 'deprecated_file_included', array( $mock, 'action' ), 10, 2 ); add_filter( 'deprecated_file_trigger_error', '__return_false' ); require_once JETPACK__PLUGIN_DIR . $file_path; } /** * @dataProvider provider_deprecated_method_stubs */ public function test_deprecated_method_stubs( $class_name, $method_name ) { $this->assertTrue( method_exists( $class_name, $method_name ) ); } public function provider_deprecated_method_stubs() { return array( array( 'JetpackTracking', 'record_user_event', array( 'Bogus' ) ), array( 'Jetpack_Client', '_wp_remote_request', array( 'Bogus', 'Bogus' ) ), array( 'Jetpack_Client', 'remote_request', array( 'Bogus' ) ), array( 'Jetpack_Client', 'wpcom_json_api_request_as_blog', array( 'Bogus' ) ), array( 'Jetpack_Options', 'get_option', array( 'Bogus' ), false ), array( 'Jetpack_Options', 'get_option_and_ensure_autoload', array( 'Bogus', 'Bogus' ), false ), array( 'Jetpack_Options', 'update_option', array( 'Bogus', 'Bogus' ), false ), array( 'Jetpack_Sync_Actions', 'initialize_listener', array() ), array( 'Jetpack_Sync_Actions', 'initialize_sender', array() ), array( 'Jetpack_Sync_Actions', 'sync_via_cron_allowed', array() ), array( 'Jetpack_Sync_Modules', 'get_module', array( 'Bogus' ) ), array( 'Jetpack_Sync_Settings', 'is_syncing', array() ), array( 'Jetpack_Sync_Settings', 'reset_data', array() ), array( 'Jetpack_Sync_Settings', 'update_settings', array( array( 'Bogus' => 1 ) ) ), array( 'Jetpack_Tracks_Client', 'get_connected_user_tracks_identity', array(), false ), array( 'Jetpack_Sync_Settings', 'is_syncing', array() ), ); } /** * @dataProvider provider_deprecated_defined_functions */ public function test_deprecated_defined_functions( $function ) { $this->assertTrue( function_exists( $function ) ); } /** * @dataProvider provider_deprecated_method_stubs */ public function test_deprecated_method_smoke_test( $class, $method, $arguments, $expect_notice = true ) { if ( $expect_notice ) { $this->setExpectedDeprecated( "$class::$method" ); } $class = new ReflectionClass( $class ); $method = $class->getMethod( $method ); set_error_handler( '__return_null' ); try { $method->invokeArgs( null, $arguments ); $this->assertTrue( true ); } catch ( Error $e ) { $this->fail( "{$class->getName()}::{$method->getName()} is throwing fatal errors.\n$e" ); } finally { restore_error_handler(); } } public function provider_deprecated_defined_functions() { return array( array( 'jetpack_tracks_get_identity' ), array( 'jetpack_tracks_record_event' ), ); } public function test_jetpack_sync_action_sender_exists() { $this->assertTrue( property_exists( 'Jetpack_Sync_Actions', 'sender' ) ); } /** * Provides deprecated files and expected replacements. * * @return array */ public function provider_deprecated_file_paths() { return array(); } }
projects/plugins/jetpack/tests/php/trait-woo-tests.php
<?php /** * Adds WooCommerce phpunit dependencies once, before all tests of the class * using this trait are run. */ trait WooCommerceTestTrait { /** * Is Woo Enabled * * @var bool */ protected static $woo_enabled = false; /** * @beforeClass **/ public static function set_up_woo_before_class() { if ( '1' !== getenv( 'JETPACK_TEST_WOOCOMMERCE' ) ) { return; } self::$woo_enabled = true; $woo_tests_dir = JETPACK_WOOCOMMERCE_INSTALL_DIR . '/tests'; if ( ! file_exists( $woo_tests_dir ) ) { error_log( 'PLEASE RUN THE GIT VERSION OF WooCommerce that has the tests folder. Found at github.com/WooCommerce/woocommerce' ); self::$woo_enabled = false; } // This is taken from WooCommerce's bootstrap.php file // framework require_once $woo_tests_dir . '/legacy/framework/class-wc-unit-test-factory.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-mock-session-handler.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-mock-wc-data.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-mock-wc-object-query.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-mock-payment-gateway.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-mock-enhanced-payment-gateway.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-payment-token-stub.php'; // commenting this out for now. require_once( $woo_tests_dir . '/framework/vendor/class-wp-test-spy-rest-server.php' ); // test cases require_once $woo_tests_dir . '/legacy/includes/wp-http-testcase.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-unit-test-case.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-api-unit-test-case.php'; require_once $woo_tests_dir . '/legacy/framework/class-wc-rest-unit-test-case.php'; // Helpers require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-product.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-coupon.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-fee.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-shipping.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-customer.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-order.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-shipping-zones.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-payment-token.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-settings.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-reports.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-admin-notes.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-test-action-queue.php'; require_once $woo_tests_dir . '/legacy/framework/helpers/class-wc-helper-queue.php'; // Traits. require_once $woo_tests_dir . '/legacy/framework/traits/trait-wc-rest-api-complex-meta.php'; require_once $woo_tests_dir . '/php/helpers/HPOSToggleTrait.php'; // Action Scheduler. $as_file = dirname( $woo_tests_dir ) . '/packages/action-scheduler/action-scheduler.php'; require_once dirname( $woo_tests_dir ) . '/packages/action-scheduler/classes/abstracts/ActionScheduler.php'; ActionScheduler::init( $as_file ); } }
projects/plugins/jetpack/tests/php/redefine-exit.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Use Patchwork to redefine `exit()` and `die()`. * * This should be loaded as early as possible, as it will only take effect * for files loaded after this one. * * @package automattic/jetpack */ /** * Exception to represent the calling of `exit()` or `die()`. */ class ExitException extends Exception { } // If we're running under `jetpack docker phpunit --php`, Patchwork is located in DOCKER_PHPUNIT_BASE_DIR. if ( getenv( 'DOCKER_PHPUNIT_BASE_DIR' ) ) { require_once getenv( 'DOCKER_PHPUNIT_BASE_DIR' ) . '/vendor/antecedent/patchwork/Patchwork.php'; } else { require_once __DIR__ . '/../../vendor/antecedent/patchwork/Patchwork.php'; } $exitfunc = function ( $arg = null ) { // While Patchwork does have a way to exclude files from replacement, // it requires non-wildcarded paths in the patchwork.json. Easier to just // check here for calls from within PHPUnit itself. $bt = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); $func = \Patchwork\getFunction(); foreach ( $bt as $i => $data ) { if ( $data['function'] === $func ) { if ( isset( $bt[ $i + 1 ]['class'] ) && str_starts_with( $bt[ $i + 1 ]['class'], 'PHPUnit' ) ) { return \Patchwork\relay(); } break; } } if ( is_int( $arg ) ) { throw new ExitException( "Exit called with code $arg", $arg ); } elseif ( is_string( $arg ) ) { if ( '' === $arg ) { throw new ExitException( 'Exit called with an empty string' ); } throw new ExitException( "Exit called: $arg" ); } elseif ( null === $arg ) { throw new ExitException( 'Exit called (with no argument)' ); } throw new ExitException( 'Exit called with argument ' . var_export( $arg, true ) ); }; foreach ( array( 'exit', 'die' ) as $func ) { $handle = \Patchwork\redefine( $func, $exitfunc ); $handle->addExpirationHandler( function () use ( $func ) { // Allow removing the handler when called from Patchwork's own __destruct. // Otherwise complain and exit. $bt = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); foreach ( $bt as $data ) { if ( isset( $data['class'] ) && $data['class'] === \Patchwork\CallRerouting\Handle::class && $data['function'] === '__destruct' ) { return; } } fprintf( STDERR, "The Patchwork handler for %s was removed. This breaks tests, don't do it.\nStack trace:\n%s\n", $func, ( new \Exception() )->getTraceAsString() ); exit( 1 ); } ); $handle->unsilence(); } unset( $exitfunc, $func, $handle );
projects/plugins/jetpack/tests/php/bootstrap.php
<?php /** * Bootstrap the plugin unit testing environment. * * @package automattic/jetpack */ // Catch `exit()` and `die()` so they won't make PHPUnit exit. require __DIR__ . '/redefine-exit.php'; /* * For tests that should be skipped in Jetpack but run in WPCOM (or vice versa), test against this constant. * * if ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) { * self::markTestSkipped( 'This test only runs on WPCOM' ); * } */ define( 'TESTING_IN_JETPACK', true ); // Support for: // 1. `WP_DEVELOP_DIR` environment variable. // 2. Plugin installed inside of WordPress.org developer checkout. // 3. Tests checked out to /tmp. if ( false !== getenv( 'WP_DEVELOP_DIR' ) ) { // Defined on command line. $test_root = getenv( 'WP_DEVELOP_DIR' ); if ( file_exists( "$test_root/tests/phpunit/" ) ) { $test_root .= '/tests/phpunit/'; } } elseif ( file_exists( '../../../../tests/phpunit/includes/bootstrap.php' ) ) { // Installed inside wordpress-develop. $test_root = '../../../../tests/phpunit'; } elseif ( file_exists( '/vagrant/www/wordpress-develop/public_html/tests/phpunit/includes/bootstrap.php' ) ) { // VVV. $test_root = '/vagrant/www/wordpress-develop/public_html/tests/phpunit'; } elseif ( file_exists( '/srv/www/wordpress-trunk/public_html/tests/phpunit/includes/bootstrap.php' ) ) { // VVV 3.0. $test_root = '/srv/www/wordpress-trunk/public_html/tests/phpunit'; } elseif ( file_exists( '/tmp/wordpress-develop/tests/phpunit/includes/bootstrap.php' ) ) { // Manual checkout & Jetpack's docker environment. $test_root = '/tmp/wordpress-develop/tests/phpunit'; } elseif ( file_exists( '/tmp/wordpress-tests-lib/includes/bootstrap.php' ) ) { // Legacy tests. $test_root = '/tmp/wordpress-tests-lib'; } if ( ! isset( $test_root ) || ! file_exists( $test_root . '/includes/bootstrap.php' ) ) { fprintf( STDERR, <<<'EOF' Failed to automatically locate WordPress or wordpress-develop to run tests. Set the WP_DEVELOP_DIR environment variable to point to a copy of WordPress or wordpress-develop. EOF ); exit( 1 ); } echo "Using test root $test_root\n"; $jp_autoloader = __DIR__ . '/../../vendor/autoload.php'; if ( ! is_readable( $jp_autoloader ) || ! is_readable( __DIR__ . '/../../modules/module-headings.php' ) ) { echo 'Jetpack is not ready for testing.' . PHP_EOL; echo PHP_EOL; echo 'Jetpack must have Composer dependencies installed and be built.' . PHP_EOL; echo 'If developing in the Jetpack monorepo, try running: jetpack build plugins/jetpack' . PHP_EOL; exit( 1 ); } // If we're running under `jetpack docker phpunit --php`, load the autoloader for that. if ( getenv( 'DOCKER_PHPUNIT_BASE_DIR' ) ) { require getenv( 'DOCKER_PHPUNIT_BASE_DIR' ) . '/vendor/autoload.php'; } require $jp_autoloader; if ( '1' !== getenv( 'WP_MULTISITE' ) && ( ! defined( 'WP_TESTS_MULTISITE' ) || ! WP_TESTS_MULTISITE ) ) { echo 'To run Jetpack multisite, use -c tests/php.multisite.xml' . PHP_EOL; echo "Disregard Core's -c tests/phpunit/multisite.xml notice below." . PHP_EOL; } if ( '1' !== getenv( 'JETPACK_TEST_WOOCOMMERCE' ) ) { echo 'To run Jetpack woocommerce tests, prefix phpunit with JETPACK_TEST_WOOCOMMERCE=1' . PHP_EOL; } else { define( 'JETPACK_WOOCOMMERCE_INSTALL_DIR', __DIR__ . '/../../../woocommerce' ); } require __DIR__ . '/lib/mock-functions.php'; require $test_root . '/includes/functions.php'; // Activates this plugin in WordPress so it can be tested. function _manually_load_plugin() { if ( '1' === getenv( 'JETPACK_TEST_WOOCOMMERCE' ) ) { require JETPACK_WOOCOMMERCE_INSTALL_DIR . '/woocommerce.php'; } require __DIR__ . '/../../jetpack.php'; $jetpack = Jetpack::init(); $jetpack->configure(); } function _manually_install_woocommerce() { // clean existing install first define( 'WP_UNINSTALL_PLUGIN', true ); define( 'WC_REMOVE_ALL_DATA', true ); require JETPACK_WOOCOMMERCE_INSTALL_DIR . '/uninstall.php'; WC_Install::install(); // reload capabilities after install, see https://core.trac.wordpress.org/ticket/28374 $GLOBALS['wp_roles'] = new WP_Roles(); echo 'Installing WooCommerce...' . PHP_EOL; } // If we are running the uninstall tests don't load jetpack. if ( ! ( in_running_uninstall_group() ) ) { tests_add_filter( 'plugins_loaded', '_manually_load_plugin', 1 ); if ( '1' === getenv( 'JETPACK_TEST_WOOCOMMERCE' ) ) { tests_add_filter( 'setup_theme', '_manually_install_woocommerce' ); } } /** * As of Jetpack 8.2, we are using Full_Sync_Immediately as the default full sync module. * Some unit tests will need to revert to the now legacy Full_Sync module. The unit tests * will look for a LEGACY_FULL_SYNC flag to run tests on the legacy module. * * @param array $modules Sync Modules. * * @return array */ function jetpack_full_sync_immediately_off( $modules ) { foreach ( $modules as $key => $module ) { if ( in_array( $module, array( 'Automattic\\Jetpack\\Sync\\Modules\\Full_Sync_Immediately' ), true ) ) { $modules[ $key ] = 'Automattic\\Jetpack\\Sync\\Modules\\Full_Sync'; } } return $modules; } if ( '1' === getenv( 'LEGACY_FULL_SYNC' ) ) { tests_add_filter( 'jetpack_sync_modules', 'jetpack_full_sync_immediately_off' ); } require $test_root . '/includes/bootstrap.php'; // Load the shortcodes module to test properly. if ( ! function_exists( 'shortcode_new_to_old_params' ) && ! in_running_uninstall_group() ) { require __DIR__ . '/../../modules/shortcodes.php'; } // Load attachment helper methods. require __DIR__ . '/attachment_test_case.php'; // Load WPCOM-shared helper functions. require __DIR__ . '/lib/class-wpcom-features.php'; function in_running_uninstall_group() { global $argv; return is_array( $argv ) && in_array( '--group=uninstall', $argv, true ); }
projects/plugins/jetpack/tests/php/attachment_test_case.php
<?php // phpcs:ignore WordPress.Files.FileName /** * Class with methods common to tests involving attachments. * * @since 3.9.2 */ class Jetpack_Attachment_Test_Case extends WP_UnitTestCase { /** * A helper to create an upload object. This method was copied verbatim from WP Core's * WP_UnitTest_Factory_For_Attachment class. When Jetpack is no longer tested on Core * versions older than 4.4, it can be removed and replaced with the following call: * * $factory->attachment->create_upload_object( $filename ); * * The $factory here is an instance of WP_UnitTest_Factory and is passed as an argument * to wpSetUpBeforeClass method. * * @param String $file file path. * @param Integer $parent the ID of the parent object. * @return Integer $id */ protected static function create_upload_object( $file, $parent = 0, $generate_meta = false ) { $contents = file_get_contents( $file ); $upload = wp_upload_bits( basename( $file ), null, $contents ); $type = ''; if ( ! empty( $upload['type'] ) ) { $type = $upload['type']; } else { $mime = wp_check_filetype( $upload['file'] ); if ( $mime ) { $type = $mime['type']; } } $attachment = array( 'post_title' => basename( $upload['file'] ), 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $parent, 'post_mime_type' => $type, 'guid' => $upload['url'], ); // Save the data $id = wp_insert_attachment( $attachment, $upload['file'], $parent ); $meta = $generate_meta ? wp_generate_attachment_metadata( $id, $upload['file'] ) : false; wp_update_attachment_metadata( $id, $meta ); return $id; } }
projects/plugins/jetpack/tests/php/test-get-modules.php
<?php /** * Test module related methods in Jetpack and Jetpack_Admin class. * * @package jetpack */ use Automattic\Jetpack\Status\Cache as StatusCache; /** * Test module related methods in Jetpack and Jetpack_Admin class. */ class WP_Test_Get_Modules extends WP_UnitTestCase { /** * Store all available modules. * * @var array */ public static $all_modules; /** * This is an expensive operation so let's make it only once */ public static function set_up_before_class() { parent::set_up_before_class(); self::$all_modules = Jetpack::get_available_modules(); } /** * Make sure all our modules are being found. */ public function test_get_available_modules() { $expected_modules = array( 'comment-likes', 'comments', 'contact-form', 'copy-post', 'custom-content-types', 'custom-css', 'enhanced-distribution', 'google-analytics', 'gravatar-hovercards', 'infinite-scroll', 'json-api', 'latex', 'likes', 'markdown', 'masterbar', 'monitor', 'notes', 'photon-cdn', 'photon', 'post-by-email', 'protect', 'publicize', 'related-posts', 'search', 'seo-tools', 'sharedaddy', 'shortcodes', 'shortlinks', 'sitemaps', 'sso', 'stats', 'subscriptions', 'tiled-gallery', 'vaultpress', 'verification-tools', 'videopress', 'widget-visibility', 'widgets', 'woocommerce-analytics', 'wordads', ); $this->assertSame( asort( $expected_modules ), asort( self::$all_modules ) ); } /** * Test * * @dataProvider get_test_connection_filters_data * @param null|bool $value_requires_connection Value to be used in the requires_connection filter. * @param null|bool $value_requires_user_connection Value to be used in the requires_user_connection filter. * @return void */ public function test_filter_by_require_connection( $value_requires_connection, $value_requires_user_connection ) { $modules = Jetpack::get_available_modules( false, false, $value_requires_connection, $value_requires_user_connection ); $found = array(); foreach ( $modules as $module ) { $found[] = $module; $details = Jetpack::get_module( $module ); if ( is_bool( $value_requires_connection ) ) { $this->assertSame( $value_requires_connection, $details['requires_connection'] ); } if ( is_bool( $value_requires_user_connection ) ) { $this->assertSame( $value_requires_user_connection, $details['requires_user_connection'] ); } } // Make sure no one was left behind. $max_matches = 0; if ( is_bool( $value_requires_connection ) ) { ++$max_matches; } if ( is_bool( $value_requires_user_connection ) ) { ++$max_matches; } foreach ( self::$all_modules as $module ) { if ( in_array( $module, $found, true ) ) { continue; } $matches = 0; $details = Jetpack::get_module( $module ); if ( is_bool( $value_requires_connection ) && $details['requires_connection'] === $value_requires_connection ) { ++$matches; } if ( is_bool( $value_requires_user_connection ) && $details['requires_user_connection'] === $value_requires_user_connection ) { ++$matches; } $this->assertGreaterThan( $matches, $max_matches, $module . ' module should be returned by get_available_modules but was not.' ); } } /** * Send all the possible combinations to test_filter_by_require_connection * * @return array */ public function get_test_connection_filters_data() { return array( array( true, true, ), array( true, false, ), array( false, true, ), array( false, false, ), array( null, true, ), array( null, false, ), array( false, null, ), array( true, null, ), ); } /** * Test_get_module_unavailable_reason * * @covers Jetpack_Admin::get_module_unavailable_reason() */ public function test_get_module_unavailable_reason() { require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php'; // Inalid input. $this->assertFalse( Jetpack_Admin::get_module_unavailable_reason( array() ) ); $dummy_module = array( 'module' => 'dummy', 'requires_connection' => true, 'requires_user_connection' => true, ); $this->assertSame( 'Jetpack is not connected', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); // Mock site connection. Jetpack_Options::update_option( 'blog_token', 'dummy.blogtoken' ); Jetpack_Options::update_option( 'id', '123' ); add_filter( 'jetpack_no_user_testing_mode', '__return_true' ); $this->assertSame( 'Requires a connected WordPress.com account', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); remove_filter( 'jetpack_no_user_testing_mode', '__return_true' ); // Mock a user connection. $user = self::factory()->user->create_and_get( array( 'role' => 'administrator', ) ); Jetpack_Options::update_option( 'master_user', $user->ID ); Jetpack_Options::update_option( 'user_tokens', array( $user->ID => "dummy.usertoken.$user->ID" ) ); $this->assertSame( 'Not supported by current plan', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); StatusCache::clear(); add_filter( 'jetpack_offline_mode', '__return_true' ); $this->assertSame( 'Offline mode', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); remove_filter( 'jetpack_offline_mode', '__return_true' ); StatusCache::clear(); $dummy_module['module'] = 'woocommerce-analytics'; $this->assertSame( 'Requires WooCommerce 3+ plugin', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); $dummy_module['module'] = 'vaultpress'; $this->assertSame( '', Jetpack_Admin::get_module_unavailable_reason( $dummy_module ) ); } /** * Test get_module with a valid module name that has module info. */ public function test_get_module_valid_module() { $module_info = array( 'name' => 'Secure Sign On', 'description' => 'Allow users to log in to this site using WordPress.com accounts', 'sort' => 30, 'recommendation_order' => 5, 'introduced' => '2.6', 'changed' => '', 'deactivate' => true, 'free' => true, 'requires_connection' => true, 'requires_user_connection' => true, 'auto_activate' => 'No', 'module_tags' => array( 'Developers' ), 'feature' => array( 'Security' ), 'additional_search_queries' => 'sso, single sign on, login, log in, 2fa, two-factor', 'plan_classes' => array( 'free' ), ); $this->assertSame( $module_info, Jetpack::get_module( 'sso' ) ); } /** * Test get_module with a module slug that doesn't have module info. */ public function test_get_module_module_no_info() { $this->assertFalse( Jetpack::get_module( 'module-extras' ) ); } }
projects/plugins/jetpack/tests/php/test_class.functions.opengraph.php
<?php /** * Class with PHPUnit tests for Open Graph functions. * * @since 3.9.2 */ class WP_Test_Functions_OpenGraph extends Jetpack_Attachment_Test_Case { private $icon_id; /** * Include Open Graph functions before each test. * * @since 3.9.2 */ public function set_up() { parent::set_up(); $this->icon_id = self::create_upload_object( __DIR__ . '/jetpack-icon.jpg', 0, true ); // 500 x 500 require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php'; } /** * Include Open Graph functions after each test. */ public function tear_down() { parent::tear_down(); // Restoring global variables. global $wp_the_query; $wp_the_query = new WP_Query(); wp_delete_attachment( $this->icon_id ); } /** * @author automattic * @covers ::jetpack_og_get_image * @since 3.9.2 */ public function test_jetpack_og_get_image_default() { $image_url = jetpack_og_get_image(); $this->assertEquals( is_array( $image_url ), true ); } /** * @author automattic * @covers ::jetpack_og_get_image * @since 3.9.2 */ public function test_jetpack_og_get_site_icon_and_logo_url() { $default_url = jetpack_og_get_image(); // Test Jetpack's Site Logo update_option( 'site_logo', $this->icon_id ); require_once JETPACK__PLUGIN_DIR . 'modules/theme-tools/site-logo/inc/functions.php'; require_once JETPACK__PLUGIN_DIR . 'modules/theme-tools/site-logo/inc/class-site-logo.php'; // Test Smaller/Invalid Jetpack's Site Logo $image_url = jetpack_og_get_image( 512, 512 ); $this->assertNotEquals( jetpack_get_site_logo( 'url' ), $image_url['src'] ); $this->assertEquals( $default_url['src'], $image_url['src'] ); // Test Valid-sized Jetpack's Site Logo $image_url = jetpack_og_get_image( 200, 200 ); $image_id = jetpack_get_site_logo( 'id' ); $logo = wp_get_attachment_image_src( $image_id, 'full' ); $this->assertEquals( $logo[0], $image_url['src'] ); delete_option( 'site_logo' ); update_option( 'site_icon', $this->icon_id ); // Test Valid-sized core's Site Icon $image_url = jetpack_og_get_image( 200, 200 ); $image_id = get_option( 'site_icon' ); $icon = wp_get_attachment_image_src( $image_id, 'full' ); $this->assertEquals( $icon[0], $image_url['src'] ); delete_option( 'site_icon' ); } /** * Test potential descriptions given to OG description. * * @dataProvider jetpack_og_get_description_data_provider * * @param string $description Post description. * @param string $cleaned_description Description cleaned up and ready to be used. */ public function test_jetpack_og_get_description_default( $description, $cleaned_description ) { // A test shortcode that should be removed from descriptions. add_shortcode( 'foo', function () { return 'bar'; } ); $processed_description = jetpack_og_get_description( $description ); $this->assertEquals( $cleaned_description, $processed_description ); } /** * Potential descriptions given to OG description. */ public function jetpack_og_get_description_data_provider() { return array( 'empty' => array( '', 'Visit the post for more.', ), 'no_entities' => array( "OpenGraph's test", 'OpenGraph&#8217;s test', ), 'too_many_words' => array( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam consectetur quam eget finibus consectetur. Donec sollicitudin finibus massa, ut cursus elit. Mauris dictum quam eu ullamcorper feugiat. Proin id ante purus. Aliquam lorem libero, tempus id dictum non, feugiat vel eros. Sed sed viverra libero. Praesent eu lacinia felis, et tempus turpis. Proin bibendum, ligula. These last sentence should be removed.', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam consectetur quam eget finibus consectetur. Donec sollicitudin finibus massa, ut cursus elit. Mauris dictum quam eu ullamcorper feugiat. Proin id ante purus. Aliquam lorem libero, tempus id dictum non, feugiat vel eros. Sed sed viverra libero. Praesent eu lacinia felis, et tempus turpis. Proin bibendum, ligula.&hellip;', ), 'no_tags' => array( 'A post description<script>alert("hello");</script>', 'A post description', ), 'no_shortcodes' => array( '[foo test="true"]A post description', 'A post description', ), 'no_links' => array( 'A post description https://jetpack.com', 'A post description', ), 'no_html' => array( '<strong>A post description</strong>', 'A post description', ), 'image_then_text' => array( '<img src="https://example.org/jetpack-icon.jpg" />A post description', 'A post description', ), 'linked_image_then_text' => array( '<a href="https://jetpack.com"><img src="https://example.org/jetpack-icon.jpg" /></a>A post description', 'A post description', ), ); } /** * Create a post containing a few images attached to another post. * * @since 9.2.0 * * @param int $number_of_images The number of image blocks to add to the post. * * @return array $post_info { * An array of information about our post. * @type int $post_id Post ID. * @type array $img_urls Image URLs we'll look to extract. * } */ protected function create_post_with_image_blocks( $number_of_images = 1 ) { $img_dimensions = array( 'width' => 250, 'height' => 250, ); $post_id = self::factory()->post->create(); $image_urls = array(); for ( $i = 1; $i <= $number_of_images; $i++ ) { $attachment_id = self::factory()->attachment->create_object( 'image' . $i . '.jpg', $post_id, array( 'post_mime_type' => 'image/jpeg', 'post_type' => 'attachment', ) ); wp_update_attachment_metadata( $attachment_id, $img_dimensions ); $image_urls[ $attachment_id ] = wp_get_attachment_url( $attachment_id ); } // Create another post with those images. $post_html = ''; foreach ( $image_urls as $attachment_id => $image_url ) { $post_html .= sprintf( '<!-- wp:image {"id":%2$d} --><div class="wp-block-image"><figure class="wp-block-image"><img src="%1$s" alt="" class="wp-image-%2$d"/></figure></div><!-- /wp:image -->', $image_url, $attachment_id ); } $second_post_id = self::factory()->post->create( array( 'post_content' => $post_html ) ); return array( 'post_id' => $second_post_id, 'img_urls' => array_values( $image_urls ), ); } /** * Test if jetpack_og_get_image returns the correct image for a post with image blocks. * * @author automattic * @covers ::jetpack_og_get_image * @since 9.2.0 */ public function test_jetpack_og_get_image_from_post_order() { // Create a post containing two image blocks. $post_info = $this->create_post_with_image_blocks( 2 ); $this->go_to( get_permalink( $post_info['post_id'] ) ); // Extract an image from the current post. $chosen_image = jetpack_og_get_image(); $this->assertTrue( is_array( $chosen_image ) ); // We expect jetpack_og_get_image to return the first of the images in the post. $first_image_url = $post_info['img_urls'][0]; $this->assertEquals( $first_image_url, $chosen_image['src'] ); } /** * Helper function to get default alt text. * * @return string */ public function get_default_alt_text() { return 'Default alt text'; } /** * Test if jetpack_og_get_image returns the correct default alt text. * * @author automattic * @covers ::jetpack_og_get_image * @since 10.4 */ public function test_jetpack_og_get_image_alt_text_default() { $this->go_to( get_permalink( $this->icon_id ) ); $image = jetpack_og_get_image(); $this->assertEquals( $image['alt_text'], '' ); } /** * Test if jetpack_og_get_image returns the correct filtered alt text. * * @author automattic * @covers ::jetpack_og_get_image * @since 10.4 */ public function test_jetpack_og_get_image_alt_text_filter() { $this->go_to( get_permalink( $this->icon_id ) ); add_filter( 'jetpack_open_graph_image_default_alt_text', array( $this, 'get_default_alt_text' ) ); $image = jetpack_og_get_image(); remove_filter( 'jetpack_open_graph_image_default_alt_text', array( $this, 'get_default_alt_text' ) ); $this->assertEquals( $image['alt_text'], $this->get_default_alt_text() ); } /** * Test if jetpack_og_get_image returns the correct alt text when set. * * @author automattic * @covers ::jetpack_og_get_image * @since 10.4 */ public function test_jetpack_og_get_image_alt_text_when_set() { $this->go_to( get_permalink( $this->icon_id ) ); $alt_text = 'Example Alt Text'; update_post_meta( $this->icon_id, '_wp_attachment_image_alt', $alt_text ); $image = jetpack_og_get_image(); $this->assertEquals( $image['alt_text'], $alt_text ); } }
projects/plugins/jetpack/tests/php/test_functions.compat.php
<?php /** * Test the compat file. * * @package Automattic/jetpack */ /** * Testing class. */ class WP_Test_Jetpack_Compat_Functions extends WP_UnitTestCase { /** * @dataProvider provider_wp_startswith */ public function test_wp_startswith( $haystack, $needle, $expected ) { $this->assertEquals( $expected, wp_startswith( $haystack, $needle ) ); } public function provider_wp_startswith() { return array( array( 'Random String', 'Random', true ), // Regular usage. array( '12345', 123, true ), // Passing an int as the needle is deprecated, but previously supported. array( 'Random String', 'random', false ), // case-sensitive. array( 'Random String', 'string', false ), // Nope. array( null, 'string', false ), array( array( 'random' ), 'string', false ), ); } /** * @dataProvider provider_wp_endswith */ public function test_wp_endswith( $haystack, $needle, $expected ) { $this->assertEquals( $expected, wp_endswith( $haystack, $needle ) ); } public function provider_wp_endswith() { return array( array( 'Random String', 'String', true ), // Regular usage. array( '12345', 45, true ), // Passing an int as the needle is deprecated, but previously supported. array( 'Random String', 'string', false ), // case-sensitive. array( 'Random String', 'Random', false ), // Nope. array( null, 'string', false ), array( array( 'random' ), 'string', false ), ); } /** * @dataProvider provider_wp_in */ public function test_wp_in( $haystack, $needle, $expected ) { $this->assertEquals( $expected, wp_in( $needle, $haystack ) ); } public function provider_wp_in() { // Notice this is in the $haystack, $needle format, even though this function is $needle, $haystack. return array( array( 'Random String', 'dom', true ), // Regular usage. array( '12345', 23, true ), // Passing an int as the needle is deprecated, but previously supported. array( 'Random String', 'str', false ), // case-sensitive. array( 'Random String', 'Bananas', false ), // Nope. array( null, 'string', false ), array( array( 'random' ), 'string', false ), ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-post-jetpack.php
<?php require_once JETPACK__PLUGIN_DIR . 'sal/class.json-api-platform.php'; class SalPostsTest extends WP_UnitTestCase { public static $token; public static $site; /** * Set up before class. */ public static function set_up_before_class() { parent::set_up_before_class(); self::$token = (object) array( 'blog_id' => get_current_blog_id(), 'user_id' => get_current_user_id(), 'external_user_id' => 2, 'role' => 'administrator', ); $platform = wpcom_get_sal_platform( self::$token ); self::$site = $platform->get_site( self::$token->blog_id ); } public function test_returns_content_wrapped_in_a_post_object() { // Insert the post into the database $post_id = wp_insert_post( array( 'post_title' => 'Title', 'post_content' => 'The content.', 'post_status' => 'publish', 'post_author' => get_current_user_id(), ) ); $post = get_post( $post_id ); $wrapped_post = self::$site->wrap_post( $post, 'display' ); $this->assertEquals( $post->post_type, $wrapped_post->get_type() ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-jetpack-sync-endpoints.php
<?php /** * Jetpack `sites/%s/sync` endpoint unit tests. * * @package automattic/jetpack */ require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Jetpack `site/%s/sync` endpoint unit tests. */ class WP_Test_Jetpack_Sync_Json_Api_Endpoints extends WP_UnitTestCase { /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Prepare the environment for the test. */ public function set_up() { global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } parent::set_up(); $this->set_globals(); WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Unit test for the `/sites/%s/sync/health` endpoint with valid input. */ public function test_modify_sync_health() { global $blog_id; $endpoint = new Jetpack_JSON_API_Sync_Modify_Health_Endpoint( array( 'description' => 'Update sync health', 'method' => 'POST', 'group' => '__do_not_document', 'path' => '/sites/%s/sync/health', 'stat' => 'write-sync-health', 'allow_jetpack_site_auth' => true, 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', ), 'request_format' => array( 'status' => '(string) Sync Health Status of site', ), 'response_format' => array( 'response' => '(string) Current Sync Health ', ), 'example_request' => 'https://public-api.wordpress.com/rest/v1.1/sites/example.wordpress.org/sync/health', ) ); // set input. $endpoint->api->post_body = '{ "status": "in_sync" }'; $endpoint->api->content_type = 'application/json'; $response = $endpoint->callback( 'sync/health', $blog_id ); $this->assertEquals( 'in_sync', $response['success'] ); } /** * Unit test for the `/sites/%s/sync/health` endpoint with invalid input. */ public function test_modify_sync_health_error() { global $blog_id; $endpoint = new Jetpack_JSON_API_Sync_Modify_Health_Endpoint( array( 'description' => 'Update sync health', 'method' => 'POST', 'group' => '__do_not_document', 'path' => '/sites/%s/sync/health', 'stat' => 'write-sync-health', 'allow_jetpack_site_auth' => true, 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', ), 'request_format' => array( 'status' => '(string) Sync Health Status of site', ), 'response_format' => array( 'response' => '(string) Current Sync Health ', ), 'example_request' => 'https://public-api.wordpress.com/rest/v1.1/sites/example.wordpress.org/sync/health', ) ); // set input. $endpoint->api->post_body = '{ "status": "bad_falue" }'; $endpoint->api->content_type = 'application/json'; $response = $endpoint->callback( 'sync/health', $blog_id ); // Verify WP_Error returned on invalid stati. $this->assertInstanceOf( 'WP_Error', $response ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-plugins-endpoints.php
<?php use Automattic\Jetpack\Constants; require_once JETPACK__PLUGIN_DIR . 'class.json-api.php'; require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; class WP_Test_Jetpack_Json_Api_Plugins_Endpoints extends WP_UnitTestCase { private static $super_admin_user_id; public static function wpSetUpBeforeClass( $factory ) { self::$super_admin_user_id = $factory->user->create( array( 'role' => 'administrator' ) ); grant_super_admin( self::$super_admin_user_id ); } /** * Set up. */ public function set_up() { if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } parent::set_up(); $this->set_globals(); // Force direct method. Running the upgrade via PHPUnit can't detect the correct filesystem method. add_filter( 'filesystem_method', array( $this, 'filesystem_method_direct' ) ); } /** * @author lezama * @covers Jetpack_JSON_API_Plugins_Modify_Endpoint * @group external-http */ public function test_Jetpack_JSON_API_Plugins_Modify_Endpoint() { $endpoint = new Jetpack_JSON_API_Plugins_Modify_Endpoint( array( 'description' => 'Update a Plugin on your Jetpack Site', 'group' => 'plugins', 'stat' => 'plugins:1:update', 'method' => 'GET', 'path' => '/sites/%s/plugins/%s/update/', 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', '$plugin' => '(string) The plugin file name', ), 'response_format' => Jetpack_JSON_API_Plugins_Endpoint::$_response_format, 'example_request_data' => array( 'headers' => array( 'authorization' => 'Bearer YOUR_API_TOKEN', ), ), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/example.wordpress.org/plugins/hello/update', ) ); /** * Changes the Accessibility of the protected upgrade_plugin method. */ $class = new ReflectionClass( 'Jetpack_JSON_API_Plugins_Modify_Endpoint' ); $update_plugin_method = $class->getMethod( 'update' ); $update_plugin_method->setAccessible( true ); $plugin_property = $class->getProperty( 'plugins' ); $plugin_property->setAccessible( true ); $plugin_property->setValue( $endpoint, array( 'the/the.php' ) ); $the_plugin_file = 'the/the.php'; $the_real_folder = WP_PLUGIN_DIR . '/the'; $the_real_file = WP_PLUGIN_DIR . '/' . $the_plugin_file; /* * Create an oudated version of 'The' plugin */ // Check if 'The' plugin folder is already there. if ( ! file_exists( $the_real_folder ) ) { mkdir( $the_real_folder ); $clean = true; } file_put_contents( $the_real_file, '<?php /* * Plugin Name: The * Version: 1.0 */' ); // Invoke the upgrade_plugin method. $result = $update_plugin_method->invoke( $endpoint ); if ( isset( $clean ) ) { $this->rmdir( $the_real_folder ); } $this->assertTrue( $result ); } /** * Verify plugin update endpoint adheres to lock. * * @author mdbitz * @covers Jetpack_JSON_API_Plugins_Modify_Endpoint * @group external-http */ public function test_Jetpack_JSON_API_Plugins_Modify_Endpoint_locked() { $endpoint = new Jetpack_JSON_API_Plugins_Modify_Endpoint( array( 'description' => 'Update a Plugin on your Jetpack Site', 'group' => 'plugins', 'stat' => 'plugins:1:update', 'method' => 'GET', 'path' => '/sites/%s/plugins/%s/update/', 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', '$plugin' => '(string) The plugin file name', ), 'response_format' => Jetpack_JSON_API_Plugins_Endpoint::$_response_format, 'example_request_data' => array( 'headers' => array( 'authorization' => 'Bearer YOUR_API_TOKEN', ), ), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/example.wordpress.org/plugins/hello/update', ) ); /** * Changes the Accessibility of the protected upgrade_plugin method. */ $class = new ReflectionClass( 'Jetpack_JSON_API_Plugins_Modify_Endpoint' ); $update_plugin_method = $class->getMethod( 'update' ); $update_plugin_method->setAccessible( true ); $plugin_property = $class->getProperty( 'plugins' ); $plugin_property->setAccessible( true ); $plugin_property->setValue( $endpoint, array( 'the/the.php' ) ); $the_plugin_file = 'the/the.php'; $the_real_folder = WP_PLUGIN_DIR . '/the'; $the_real_file = WP_PLUGIN_DIR . '/' . $the_plugin_file; /* * Create an oudated version of 'The' plugin */ // Check if 'The' plugin folder is already there. if ( ! file_exists( $the_real_folder ) ) { mkdir( $the_real_folder ); $clean = true; } file_put_contents( $the_real_file, '<?php /* * Plugin Name: The * Version: 1.0 */' ); // Obtain lock. include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; Constants::set_constant( 'JETPACK_PLUGIN_AUTOUPDATE', true ); WP_Upgrader::create_lock( 'auto_updater' ); // Invoke the upgrade_plugin method. $result = $update_plugin_method->invoke( $endpoint ); // Release lock. WP_Upgrader::release_lock( 'auto_updater' ); Constants::set_constant( 'JETPACK_PLUGIN_AUTOUPDATE', false ); // clean up. if ( isset( $clean ) ) { $this->rmdir( $the_real_folder ); } $this->assertTrue( is_wp_error( $result ) ); } /** * Verify plugin update endpoint ignores auto_updater lock if not an autoupdate request. * * @author mdbitz * @covers Jetpack_JSON_API_Plugins_Modify_Endpoint * @group external-http */ public function test_Jetpack_JSON_API_Plugins_Modify_Endpoint_locked_not_autoupdate() { $endpoint = new Jetpack_JSON_API_Plugins_Modify_Endpoint( array( 'description' => 'Update a Plugin on your Jetpack Site', 'group' => 'plugins', 'stat' => 'plugins:1:update', 'method' => 'GET', 'path' => '/sites/%s/plugins/%s/update/', 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', '$plugin' => '(string) The plugin file name', ), 'response_format' => Jetpack_JSON_API_Plugins_Endpoint::$_response_format, 'example_request_data' => array( 'headers' => array( 'authorization' => 'Bearer YOUR_API_TOKEN', ), ), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/example.wordpress.org/plugins/hello/update', ) ); /** * Changes the Accessibility of the protected upgrade_plugin method. */ $class = new ReflectionClass( 'Jetpack_JSON_API_Plugins_Modify_Endpoint' ); $update_plugin_method = $class->getMethod( 'update' ); $update_plugin_method->setAccessible( true ); $plugin_property = $class->getProperty( 'plugins' ); $plugin_property->setAccessible( true ); $plugin_property->setValue( $endpoint, array( 'the/the.php' ) ); $the_plugin_file = 'the/the.php'; $the_real_folder = WP_PLUGIN_DIR . '/the'; $the_real_file = WP_PLUGIN_DIR . '/' . $the_plugin_file; /* * Create an oudated version of 'The' plugin */ // Check if 'The' plugin folder is already there. if ( ! file_exists( $the_real_folder ) ) { mkdir( $the_real_folder ); $clean = true; } file_put_contents( $the_real_file, '<?php /* * Plugin Name: The * Version: 1.0 */' ); // Obtain lock. include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; Constants::set_constant( 'JETPACK_PLUGIN_AUTOUPDATE', false ); WP_Upgrader::create_lock( 'auto_updater' ); // Invoke the upgrade_plugin method. $result = $update_plugin_method->invoke( $endpoint ); // Release lock. WP_Upgrader::release_lock( 'auto_updater' ); // clean up. if ( isset( $clean ) ) { $this->rmdir( $the_real_folder ); } $this->assertTrue( $result ); } /** * @author tonykova * @covers Jetpack_API_Plugins_Install_Endpoint * @group external-http */ public function test_Jetpack_API_Plugins_Install_Endpoint() { if ( is_multisite() ) { wp_set_current_user( self::$super_admin_user_id ); } $endpoint = new Jetpack_JSON_API_Plugins_Install_Endpoint( array( 'stat' => 'plugins:1:new', 'method' => 'POST', 'path' => '/sites/%s/plugins/new', 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', ), 'request_format' => array( 'plugin' => '(string) The plugin slug.', ), 'response_format' => Jetpack_JSON_API_Plugins_Endpoint::$_response_format, 'example_request_data' => array( 'headers' => array( 'authorization' => 'Bearer YOUR_API_TOKEN', ), 'body' => array( 'plugin' => 'buddypress', ), ), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/example.wordpress.org/plugins/new', ) ); $the_real_folder = WP_PLUGIN_DIR . '/the'; $the_plugin_slug = 'the'; // Check if 'The' plugin folder is already there. if ( file_exists( $the_real_folder ) ) { $this->markTestSkipped( 'The plugin the test tries to install (the) is already installed. Skipping.' ); } $class = new ReflectionClass( 'Jetpack_JSON_API_Plugins_Install_Endpoint' ); $plugins_property = $class->getProperty( 'plugins' ); $plugins_property->setAccessible( true ); $plugins_property->setValue( $endpoint, array( $the_plugin_slug ) ); $validate_plugins_method = $class->getMethod( 'validate_plugins' ); $validate_plugins_method->setAccessible( true ); $result = $validate_plugins_method->invoke( $endpoint ); $this->assertTrue( $result ); $install_plugin_method = $class->getMethod( 'install' ); $install_plugin_method->setAccessible( true ); $result = $install_plugin_method->invoke( $endpoint ); $this->assertTrue( $result ); $this->assertTrue( file_exists( $the_real_folder ) ); // Clean up $this->rmdir( $the_real_folder ); } public function filesystem_method_direct() { return 'direct'; } public function rmdir( $dir ) { foreach ( scandir( $dir ) as $file ) { if ( is_dir( $file ) ) { continue; } else { unlink( "$dir/$file" ); } } rmdir( $dir ); } /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-jetpack-endpoints.php
<?php /** * Tests for /sites/%s/categories/slug:%s * * @package automattic/jetpack */ if ( ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) && defined( 'JETPACK__PLUGIN_DIR' ) && JETPACK__PLUGIN_DIR ) { require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php'; } require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Tests for /sites/%s/categories/slug:%s */ class WP_Test_Jetpack_Json_Api_Endpoints extends WP_UnitTestCase { /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Called before every test. */ public function set_up() { parent::set_up(); global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } $this->set_globals(); // Initialize some missing stuff for the API. WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Creates a WPCOM_JSON_API_Get_Taxonomy_Endpoint * * @author nylen * * @return WPCOM_JSON_API_Get_Taxonomy_Endpoint */ public function create_get_category_endpoint() { // From json-endpoints/class.wpcom-json-api-get-taxonomy-endpoint.php :( . return new WPCOM_JSON_API_Get_Taxonomy_Endpoint( array( 'description' => 'Get information about a single category.', 'group' => 'taxonomy', 'stat' => 'categories:1', 'method' => 'GET', 'path' => '/sites/%s/categories/slug:%s', 'path_labels' => array( '$site' => '(int|string) Site ID or domain', '$category' => '(string) The category slug', ), 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/categories/slug:community', ) ); } /** * Tests get term feed url with pretty permalinks. * * @author nylen * @covers WPCOM_JSON_API_Get_Taxonomy_Endpoint * @group json-api */ public function test_get_term_feed_url_pretty_permalinks() { global $blog_id; $this->set_permalink_structure( '/%year%/%monthnum%/%postname%/' ); // Reset taxonomy URL structure after changing permalink structure. create_initial_taxonomies(); $category = wp_insert_term( 'test_category', 'category' ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable $endpoint = $this->create_get_category_endpoint(); $response = $endpoint->callback( sprintf( '/sites/%d/categories/slug:test_category', $blog_id ), $blog_id, 'test_category' ); $this->assertStringEndsWith( '/category/test_category/feed/', $response->feed_url ); } /** * Tests get term feed url with ugly permalinks. * * @author nylen * @covers WPCOM_JSON_API_Get_Taxonomy_Endpoint * @group json-api */ public function test_get_term_feed_url_ugly_permalinks() { global $blog_id; $this->set_permalink_structure( '' ); // Reset taxonomy URL structure after changing permalink structure. create_initial_taxonomies(); $category = wp_insert_term( 'test_category', 'category' ); $endpoint = $this->create_get_category_endpoint(); $response = $endpoint->callback( sprintf( '/sites/%d/categories/slug:test_category', $blog_id ), $blog_id, 'test_category' ); $this->assertStringEndsWith( '/?feed=rss2&amp;cat=' . $category['term_id'], $response->feed_url ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-jetpack-endpoints-accessibility.php
<?php /** * Generic tests for Jetpack_JSON_API_Endpoint accessibility. * * @package automattic/jetpack * @phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound */ use Automattic\Jetpack\Status\Cache as StatusCache; if ( defined( 'JETPACK__PLUGIN_DIR' ) && JETPACK__PLUGIN_DIR ) { require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php'; } require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Generic tests for Jetpack_JSON_API_Endpoint accessibility. */ class WP_Test_Jetpack_Json_Api_Endpoints_Accessibility extends WP_UnitTestCase { /** * An admin user_id. * * @var number $admin_user_id. */ private static $admin_user_id; /** * The user_id of a user without read capabilities. * * @var number $no_read_user_id. */ private static $no_read_user_id; /** * Create fixtures once, before any tests in the class have run. * * @param object $factory A factory object needed for creating fixtures. */ public static function wpSetUpBeforeClass( $factory ) { self::$admin_user_id = $factory->user->create( array( 'role' => 'administrator' ) ); self::$no_read_user_id = $factory->user->create(); $no_read_user = get_user_by( 'id', self::$no_read_user_id ); $no_read_user->add_cap( 'read', false ); } /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Called before every test. */ public function set_up() { parent::set_up(); global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } $this->set_globals(); // Initialize some missing stuff for the API. WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Tests accepts_site_based_authentication method. * * @author fgiannar * @covers WPCOM_JSON_API_Endpoint accepts_site_based_authentication * @group json-api * @dataProvider data_provider_test_accepts_site_based_authentication * * @param bool $allow_jetpack_site_auth The endpoint's `allow_jetpack_site_auth` value. * @param bool $is_user_logged_in If a user is logged in. * @param bool $result The expected result. */ public function test_accepts_site_based_authentication( $allow_jetpack_site_auth, $is_user_logged_in, $result ) { $endpoint = new Jetpack_JSON_API_Dummy_Endpoint( array( 'stat' => 'dummy', 'allow_jetpack_site_auth' => $allow_jetpack_site_auth, ) ); if ( $is_user_logged_in ) { wp_set_current_user( self::$admin_user_id ); } $this->assertEquals( $result, $endpoint->accepts_site_based_authentication() ); } /** * Tests api accessibility on a private site. * * @author fgiannar * @covers WPCOM_JSON_API switch_to_blog_and_validate_user * @group json-api * @dataProvider data_provider_test_private_site_accessibility * * @param bool $allow_jetpack_site_auth The endpoint's `allow_jetpack_site_auth` value. * @param bool $use_blog_token If we should simulate a blog token for this test. * @param bool $user_can_read If the current user has read capability. When a blog token is used this has no effect. * @param WP_Error|string $result The expected result. */ public function test_private_site_accessibility( $allow_jetpack_site_auth, $use_blog_token, $user_can_read, $result ) { StatusCache::clear(); // Private site. add_filter( 'jetpack_is_private_site', '__return_true' ); update_option( 'blog_public', '-1' ); $endpoint = new Jetpack_JSON_API_Dummy_Endpoint( array( 'stat' => 'dummy', 'allow_jetpack_site_auth' => $allow_jetpack_site_auth, ) ); if ( ! $use_blog_token ) { $user_id = $user_can_read ? self::$admin_user_id : self::$no_read_user_id; wp_set_current_user( $user_id ); } $this->assertEquals( $result, $endpoint->api->process_request( $endpoint, array() ) ); remove_filter( 'jetpack_is_private_site', '__return_true' ); StatusCache::clear(); } /** * Tests endpoint capabilities. * * @author fgiannar * @covers Jetpack_JSON_API_Endpoint validate_call * @group json-api * @dataProvider data_provider_test_endpoint_capabilities * * @param bool $allow_jetpack_site_auth The endpoint's `allow_jetpack_site_auth` value. * @param bool $use_blog_token If we should simulate a blog token for this test. * @param bool $user_with_permissions If the current user has the needed capabilities to access the endpoint. When a blog token is used this has no effect. * @param WP_Error|string $result The expected result. */ public function test_endpoint_capabilities( $allow_jetpack_site_auth, $use_blog_token, $user_with_permissions, $result ) { $endpoint = new Jetpack_JSON_API_Dummy_Endpoint( array( 'stat' => 'dummy', 'allow_jetpack_site_auth' => $allow_jetpack_site_auth, ) ); if ( ! $use_blog_token ) { $user_id = $user_with_permissions ? self::$admin_user_id : self::$no_read_user_id; wp_set_current_user( $user_id ); } $this->assertEquals( $result, $endpoint->api->process_request( $endpoint, array() ) ); } /** * Data provider for test_accepts_site_based_authentication. */ public function data_provider_test_accepts_site_based_authentication() { return array( 'allow_jetpack_site_auth: true; logged_in_user: false;' => array( true, false, true ), 'allow_jetpack_site_auth: false; logged_in_user: false;' => array( false, false, false ), 'allow_jetpack_site_auth: true; logged_in_user: true;' => array( true, true, false ), ); } /** * Data provider for test_private_site_accessibility. */ public function data_provider_test_private_site_accessibility() { $success = 'success'; $error = new WP_Error( 'unauthorized', 'User cannot access this private blog.', 403 ); return array( 'allow_jetpack_site_auth: true; blog_token: true; can_read: null' => array( true, true, null, $success ), 'allow_jetpack_site_auth: false; blog_token: true; can_read: null' => array( false, true, null, $error ), 'allow_jetpack_site_auth: false; blog_token: false; can_read: false' => array( false, false, false, $error ), 'allow_jetpack_site_auth: false; blog_token: false; can_read: true' => array( false, false, true, $success ), ); } /** * Data provider for test_endpoint_capabilities. */ public function data_provider_test_endpoint_capabilities() { $success = 'success'; $error = new WP_Error( 'unauthorized', 'This user is not authorized to manage_options on this blog.', 403 ); return array( 'allow_jetpack_site_auth: true; blog_token: true; user_with_permissions: null' => array( true, true, null, $success ), 'allow_jetpack_site_auth: false; blog_token: true; user_with_permissions: null' => array( false, true, null, $error ), 'allow_jetpack_site_auth: false; blog_token: false; user_with_permissions: false' => array( false, false, false, $error ), 'allow_jetpack_site_auth: false; blog_token: false; user_with_permissions: true' => array( false, false, true, $success ), ); } } /** * Dummy endpoint for testing. */ class Jetpack_JSON_API_Dummy_Endpoint extends Jetpack_JSON_API_Endpoint { /** * Only accessible to admins. * * @var array|string */ protected $needed_capabilities = 'manage_options'; /** * Dummy result. */ public function result() { return 'success'; } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-jetpack-site-endpoints.php
<?php /** * Jetpack `site/%s` endpoint unit tests. * * @package automattic/jetpack */ require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; // phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed if ( ! function_exists( 'has_blog_sticker' ) ) { /** * "Mock" WPCOM sticker function with 'get_option' */ function has_blog_sticker( $sticker ) { return get_option( $sticker ); } } /** * Jetpack `site/%s` endpoint unit tests. */ class WP_Test_Jetpack_Site_Json_Api_Endpoints extends WP_UnitTestCase { /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Prepare the environment for the test. */ public function set_up() { global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } parent::set_up(); $this->set_globals(); WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Unit test for the `/sites/%s` endpoint. */ public function test_get_site() { global $blog_id; // Fetch as admin so that options is also present in the response. $admin = self::factory()->user->create_and_get( array( 'role' => 'administrator', ) ); wp_set_current_user( $admin->ID ); $endpoint = $this->create_get_site_endpoint(); $response = $endpoint->callback( '', $blog_id ); $this->assertTrue( $response['jetpack'] ); $this->assertTrue( $response['jetpack_connection'] ); $options = (array) $response['options']; $this->assertArrayHasKey( 'jetpack_connection_active_plugins', $options ); } /** * Test that trial flags are returned for sites that have them. * * @author zaerl * @covers WPCOM_JSON_API_GET_Site_Endpoint::build_current_site_response */ public function test_get_site_trials_list() { global $blog_id; // Current trials. $trials = array_keys( WPCOM_JSON_API_GET_Site_Endpoint::$jetpack_enabled_trials ); $admin = self::factory()->user->create_and_get( array( 'role' => 'administrator', ) ); wp_set_current_user( $admin->ID ); $endpoint = $this->create_get_site_endpoint(); /** * The `has_blog_sticker` is a mock function that reads the options database * and returns the value of the option passed to it. * * We add the trial flags to the options database and then check them later. * All even flags are set to true and all odd flags are set to false. */ $i = 0; foreach ( $trials as $trial ) { update_option( $trial, (bool) ( $i & 2 ) ); ++$i; } $response = $endpoint->callback( '', $blog_id ); $i = 0; foreach ( $trials as $trial ) { if ( (bool) ( $i & 2 ) ) { $this->assertTrue( $response[ $trial ] ); } else { $this->assertFalse( $response[ $trial ] ); } } // Remove all the options used. foreach ( $trials as $trial ) { delete_option( $trial ); ++$i; } } public function create_get_site_endpoint() { return new WPCOM_JSON_API_GET_Site_Endpoint( array( 'description' => 'Get information about a site.', 'group' => 'sites', 'stat' => 'sites:X', 'allowed_if_flagged' => true, 'method' => 'GET', 'max_version' => '1.1', 'new_version' => '1.2', 'path' => '/sites/%s', 'path_labels' => array( '$site' => '(int|string) Site ID or domain', ), 'allow_jetpack_site_auth' => true, 'query_parameters' => array( 'context' => false, 'options' => '(string) Optional. Returns specified options only. Comma-separated list. Example: options=login_url,timezone', ), 'response_format' => WPCOM_JSON_API_GET_Site_Endpoint::$site_format, 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/', ) ); } }
projects/plugins/jetpack/tests/php/json-api/test_class.json-api-platform-jetpack.php
<?php require_once JETPACK__PLUGIN_DIR . 'sal/class.json-api-platform.php'; class SalSiteTest extends WP_UnitTestCase { public static $token; public static $site; /** * Set up before class. */ public static function set_up_before_class() { parent::set_up_before_class(); self::$token = (object) array( 'blog_id' => get_current_blog_id(), 'user_id' => get_current_user_id(), 'external_user_id' => 2, 'role' => 'administrator', ); $platform = wpcom_get_sal_platform( self::$token ); self::$site = $platform->get_site( self::$token->blog_id ); } public function test_uses_synced_api_post_type_whitelist_if_available() { $this->assertFalse( self::$site->is_post_type_allowed( 'my_new_type' ) ); } public function test_is_module_active() { // Picking random 3 modules from an array of existing ones to not slow down the test $modules = array_rand( Jetpack::get_available_modules(), 3 ); foreach ( $modules as $module ) { Jetpack::deactivate_module( $module ); $this->assertEquals( Jetpack::is_module_active( $module ), self::$site->is_module_active( $module ) ); Jetpack::activate_module( $module ); $this->assertEquals( Jetpack::is_module_active( $module ), self::$site->is_module_active( $module ) ); } } public function test_interface() { $this->assertTrue( method_exists( 'SAL_Site', 'is_module_active' ) ); } }
projects/plugins/jetpack/tests/php/json-api/test_class.json-api-jetpack-base-endpoint.php
<?php /** * Jetpack_JSON_API_Endpoint class unit tests. * Run this test with command: jetpack docker phpunit -- --filter=WP_Test_Jetpack_Base_Json_Api_Endpoints * * @package automattic/jetpack * @phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound */ require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Generic tests for Jetpack_JSON_API_Endpoint. */ class WP_Test_Jetpack_Base_Json_Api_Endpoints extends WP_UnitTestCase { /** * A super admin user used for test. * * @var int */ private static $super_admin_user_id; /** * Alternative super admin user used for test. * * @var int */ private static $super_admin_alt_user_id; /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Create fixtures once, before any tests in the class have run. * * @param object $factory A factory object needed for creating fixtures. */ public static function wpSetUpBeforeClass( $factory ) { self::$super_admin_user_id = $factory->user->create( array( 'role' => 'administrator' ) ); self::$super_admin_alt_user_id = $factory->user->create( array( 'role' => 'administrator' ) ); } /** * Reset the environment to its original state after the test. */ public function tear_down() { set_error_handler( null ); delete_user_meta( self::$super_admin_user_id, 'user_id' ); parent::tear_down(); } /** * @author zaerl * @covers Jetpack_JSON_API_Endpoint::get_author * @group json-api */ public function test_get_author_should_trigger_error_if_a_user_not_exists() { // Force the error handler to return null. set_error_handler( '__return_null' ); $endpoint = $this->get_dummy_endpoint(); $author = $endpoint->get_author( 0 ); $this->assertNull( $author ); } /** * @author zaerl * @covers Jetpack_JSON_API_Endpoint::get_author * @group json-api */ public function test_get_author_should_return_the_same_user() { $endpoint = $this->get_dummy_endpoint(); $author = $endpoint->get_author( self::$super_admin_user_id ); $this->assertIsObject( $author ); $this->assertSame( self::$super_admin_user_id, $author->ID ); } /** * @author zaerl * @covers Jetpack_JSON_API_Endpoint::get_author * @group json-api */ public function test_get_author_should_return_the_same_user_if_user_meta_is_set() { $endpoint = $this->get_dummy_endpoint(); // Force a 'user_id' pointing to another user in the user meta. add_user_meta( self::$super_admin_user_id, 'user_id', self::$super_admin_alt_user_id ); $user = get_user_by( 'id', self::$super_admin_user_id ); $author = $endpoint->get_author( self::$super_admin_user_id ); // Check that __get magic method is working. $this->assertSame( self::$super_admin_alt_user_id, (int) $user->user_id ); // The user should be the same as the one passed to the method. $this->assertIsObject( $author ); $this->assertSame( self::$super_admin_user_id, $author->ID ); $author = $endpoint->get_author( $user ); // The user should be the same as the one passed as object to the method. $this->assertIsObject( $author ); $this->assertSame( self::$super_admin_user_id, $author->ID ); } /** * Generate a dummy endpoint. */ private function get_dummy_endpoint() { $endpoint = new Jetpack_JSON_API_Dummy_Base_Endpoint( array( 'stat' => 'dummy', ) ); return $endpoint; } } /** * Dummy endpoint for testing. */ class Jetpack_JSON_API_Dummy_Base_Endpoint extends Jetpack_JSON_API_Endpoint { /** * Dummy result. */ public function result() { return 'success'; } }
projects/plugins/jetpack/tests/php/json-api/test-class.wpcom-json-api-site-settings-v1-4-endpoint.php
<?php /** * Jetpack `sites/%s/settings` endpoint unit tests. * Run this test with command: jetpack docker phpunit -- --filter=WP_Test_WPCOM_JSON_API_Site_Settings_V1_4_Endpoint * * @package automattic/jetpack */ require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Jetpack `sites/%s/settings` endpoint unit tests. */ class WP_Test_WPCOM_JSON_API_Site_Settings_V1_4_Endpoint extends WP_UnitTestCase { /** * Example of woocommerce_onboarding_profile value. * * @var array */ private $onboarding_profile_example = array( 'is_agree_marketing' => true, 'store_email' => 'example@gmail.com', 'industry' => array( 0 => array( 'slug' => 'health-beauty', ), 1 => array( 'slug' => 'fashion-apparel-accessories', ), 2 => array( 'slug' => 'other', 'detail' => 'Custom industry', ), ), 'product_types' => array( 0 => 'physical', 1 => 'downloads', 2 => 'memberships', ), 'product_count' => '11-100', 'selling_venues' => 'other-woocommerce', 'revenue' => 'up-to-2500', 'setup_client' => true, 'business_extensions' => array( 0 => 'google-listings-and-ads', ), 'theme' => 'storefront', 'completed' => true, ); /** * Prepare the environment for the test. */ public function set_up() { global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1.4' ); } parent::set_up(); WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Test GET `sites/%s/settings` returns correct keys and key default values when no value is set. * * @dataProvider setting_default_key_values * * @param string $setting_name The setting lookup key. * @param string $expected_default_value The default value we expect when no value is explicitly set. */ public function test_get_settings_contains_key_defaults( $setting_name, $expected_default_value ) { $response = $this->make_get_request(); $settings = $response['settings']; $this->assertSame( $expected_default_value, $settings[ $setting_name ] ); } /** * Test GET `sites/%s/settings` returns correct set value. * * @dataProvider setting_value_pairs_get_request * * @param string $option_name The option lookup key. * @param string $setting_name The setting lookup key. * @param string $setting_value The setting value to test. */ public function test_get_settings_contains_keys_values( $option_name, $setting_name, $setting_value ) { update_option( $option_name, $setting_value ); $response = $this->make_get_request(); $settings = $response['settings']; $this->assertSame( $setting_value, $settings[ $setting_name ] ); } /** * Test POST `sites/%s/settings` sets the correct value. * * @dataProvider setting_value_pairs_post_request * * @param string $setting_name The setting lookup key. * @param string $setting_value The setting value to test. * @param string $expected_value The expected sanitized value. */ public function test_post_settings_sets_key_values( $setting_name, $setting_value, $expected_value ) { $setting = wp_json_encode( array( $setting_name => $setting_value ) ); $response = $this->make_post_request( $setting ); $updated = $response['updated']; $this->assertSame( $expected_value, $updated[ $setting_name ] ); } /** * Returns the response of a successful GET request to `sites/%s/settings`. */ public function make_get_request() { global $blog_id; $admin = self::factory()->user->create_and_get( array( 'role' => 'administrator', ) ); wp_set_current_user( $admin->ID ); $endpoint = new WPCOM_JSON_API_Site_Settings_V1_4_Endpoint( array( 'description' => 'Get detailed settings information about a site.', 'group' => '__do_not_document', 'stat' => 'sites:X', 'min_version' => '1.4', 'method' => 'GET', 'path' => '/sites/%s/settings', 'path_labels' => array( '$site' => '(int|string) Site ID or domain', ), 'query_parameters' => array( 'context' => false, ), 'response_format' => WPCOM_JSON_API_Site_Settings_Endpoint::$site_format, 'example_request' => 'https://public-api.wordpress.com/rest/v1.4/sites/en.blog.wordpress.com/settings?pretty=1', ) ); return $endpoint->callback( '/sites/%s/settings', $blog_id ); } /** * Returns the response of a successful POST request to `sites/%s/settings`. * * @param string $setting The json encoded POST request body containing the test setting key and value. */ public function make_post_request( $setting ) { global $blog_id; $admin = self::factory()->user->create_and_get( array( 'role' => 'administrator', ) ); wp_set_current_user( $admin->ID ); $endpoint = new WPCOM_JSON_API_Site_Settings_V1_4_Endpoint( array( 'description' => 'Update settings for a site.', 'group' => '__do_not_document', 'stat' => 'sites:X', 'min_version' => '1.4', 'method' => 'POST', 'path' => '/sites/%s/settings', 'path_labels' => array( '$site' => '(int|string) Site ID or domain', ), 'request_format' => array( 'blogname' => '(string) Blog name', 'blogdescription' => '(string) Blog description', 'default_pingback_flag' => '(bool) Notify blogs linked from article?', 'default_ping_status' => '(bool) Allow link notifications from other blogs?', 'default_comment_status' => '(bool) Allow comments on new articles?', 'blog_public' => '(string) Site visibility; -1: private, 0: discourage search engines, 1: allow search engines', 'jetpack_sync_non_public_post_stati' => '(bool) allow sync of post and pages with non-public posts stati', 'jetpack_relatedposts_enabled' => '(bool) Enable related posts?', 'jetpack_relatedposts_show_context' => '(bool) Show post\'s tags and category in related posts?', 'jetpack_relatedposts_show_date' => '(bool) Show date in related posts?', 'jetpack_relatedposts_show_headline' => '(bool) Show headline in related posts?', 'jetpack_relatedposts_show_thumbnails' => '(bool) Show thumbnails in related posts?', 'instant_search_enabled' => '(bool) Enable the new Jetpack Instant Search interface', 'jetpack_search_enabled' => '(bool) Enable Jetpack Search', 'jetpack_search_supported' => '(bool) Jetpack Search supported', 'jetpack_protect_whitelist' => '(array) List of IP addresses to always allow', 'infinite_scroll' => '(bool) Support infinite scroll of posts?', 'default_category' => '(int) Default post category', 'default_post_format' => '(string) Default post format', 'require_name_email' => '(bool) Require comment authors to fill out name and email?', 'comment_registration' => '(bool) Require users to be registered and logged in to comment?', 'close_comments_for_old_posts' => '(bool) Automatically close comments on old posts?', 'close_comments_days_old' => '(int) Age at which to close comments', 'thread_comments' => '(bool) Enable threaded comments?', 'thread_comments_depth' => '(int) Depth to thread comments', 'page_comments' => '(bool) Break comments into pages?', 'comments_per_page' => '(int) Number of comments to display per page', 'default_comments_page' => '(string) newest|oldest Which page of comments to display first', 'comment_order' => '(string) asc|desc Order to display comments within page', 'comments_notify' => '(bool) Email me when someone comments?', 'moderation_notify' => '(bool) Email me when a comment is helf for moderation?', 'social_notifications_like' => '(bool) Email me when someone likes my post?', 'social_notifications_reblog' => '(bool) Email me when someone reblogs my post?', 'social_notifications_subscribe' => '(bool) Email me when someone subscribes to my blog?', 'comment_moderation' => '(bool) Moderate comments for manual approval?', 'comment_previously_approved' => '(bool) Moderate comments unless author has a previously-approved comment?', 'comment_max_links' => '(int) Moderate comments that contain X or more links', 'moderation_keys' => '(string) Words or phrases that trigger comment moderation, one per line', 'disallowed_keys' => '(string) Words or phrases that mark comment spam, one per line', 'lang_id' => '(int) ID for language blog is written in', 'locale' => '(string) locale code for language blog is written in', 'wga' => '(array) Google Analytics Settings', 'jetpack_cloudflare_analytics' => '(array) Cloudflare Analytics Settings', 'disabled_likes' => '(bool) Are likes globally disabled (they can still be turned on per post)?', 'disabled_reblogs' => '(bool) Are reblogs disabled on posts?', 'jetpack_comment_likes_enabled' => '(bool) Are comment likes enabled for all comments?', 'sharing_button_style' => '(string) Style to use for sharing buttons (icon-text, icon, text, or official)', 'sharing_label' => '(string) Label to use for sharing buttons, e.g. "Share this:"', 'sharing_show' => '(string|array:string) Post type or array of types where sharing buttons are to be displayed', 'sharing_open_links' => '(string) Link target for sharing buttons (same or new)', 'twitter_via' => '(string) Twitter username to include in tweets when people share using the Twitter button', 'jetpack-twitter-cards-site-tag' => '(string) The Twitter username of the owner of the site\'s domain.', 'eventbrite_api_token' => '(int) The Keyring token ID for an Eventbrite token to associate with the site', 'timezone_string' => '(string) PHP-compatible timezone string like \'UTC-5\'', 'gmt_offset' => '(int) Site offset from UTC in hours', 'date_format' => '(string) PHP Date-compatible date format', 'time_format' => '(string) PHP Date-compatible time format', 'start_of_week' => '(int) Starting day of week (0 = Sunday, 6 = Saturday)', 'woocommerce_onboarding_profile' => '(array) woocommerce_onboarding_profile', 'woocommerce_store_address' => '(string) woocommerce_store_address option', 'woocommerce_store_address_2' => '(string) woocommerce_store_address_2 option', 'woocommerce_store_city' => '(string) woocommerce_store_city option', 'woocommerce_default_country' => '(string) woocommerce_default_country option', 'woocommerce_store_postcode' => '(string) woocommerce_store_postcode option', 'jetpack_testimonial' => '(bool) Whether testimonial custom post type is enabled for the site', 'jetpack_testimonial_posts_per_page' => '(int) Number of testimonials to show per page', 'jetpack_portfolio' => '(bool) Whether portfolio custom post type is enabled for the site', 'jetpack_portfolio_posts_per_page' => '(int) Number of portfolio projects to show per page', Jetpack_SEO_Utils::FRONT_PAGE_META_OPTION => '(string) The SEO meta description for the site.', Jetpack_SEO_Titles::TITLE_FORMATS_OPTION => '(array) SEO meta title formats. Allowed keys: front_page, posts, pages, groups, archives', 'verification_services_codes' => '(array) Website verification codes. Allowed keys: google, pinterest, bing, yandex, facebook', 'podcasting_archive' => '(string) The post category, if any, used for publishing podcasts', 'site_icon' => '(int) Media attachment ID to use as site icon. Set to zero or an otherwise empty value to clear', 'api_cache' => '(bool) Turn on/off the Jetpack JSON API cache', 'posts_per_page' => '(int) Number of posts to show on blog pages', 'posts_per_rss' => '(int) Number of posts to show in the RSS feed', 'rss_use_excerpt' => '(bool) Whether the RSS feed will use post excerpts', 'show_on_front' => '(string) Whether homepage should display related posts or a static page. The expected value is \'posts\' or \'page\'.', 'page_on_front' => '(string) The page ID of the page to use as the site\'s homepage. It will apply only if \'show_on_front\' is set to \'page\'.', 'page_for_posts' => '(string) The page ID of the page to use as the site\'s posts page. It will apply only if \'show_on_front\' is set to \'page\'.', 'subscription_options' => '(array) Array of two options used in subscription email templates: \'invitation\' and \'comment_follow\' strings.', ), 'response_format' => array( 'updated' => '(array)', ), 'example_request' => 'https://public-api.wordpress.com/rest/v1.4/sites/en.blog.wordpress.com/settings?pretty=1', ) ); $endpoint->api->post_body = $setting; $endpoint->api->content_type = 'application/json'; $endpoint->api->method = 'POST'; return $endpoint->callback( '', $blog_id ); } /** * Data provider that contains keys we expect to see returned by the settings endpoint and their default value. * * @return array[ $setting_name, $expected_default_value ] */ public function setting_default_key_values() { return array( 'woocommerce_store_address' => array( 'woocommerce_store_address', '' ), 'woocommerce_store_address_2' => array( 'woocommerce_store_address_2', '' ), 'woocommerce_store_city' => array( 'woocommerce_store_city', '' ), 'woocommerce_default_country' => array( 'woocommerce_default_country', '' ), 'woocommerce_store_postcode' => array( 'woocommerce_store_postcode', '' ), 'woocommerce_onboarding_profile' => array( 'woocommerce_onboarding_profile', array() ), 'wga' => array( 'wga', array( 'code' => '', 'anonymize_ip' => false, 'honor_dnt' => false, 'ec_track_purchases' => false, 'ec_track_add_to_cart' => false, 'enh_ec_tracking' => false, 'enh_ec_track_remove_from_cart' => false, 'enh_ec_track_prod_impression' => false, 'enh_ec_track_prod_click' => false, 'enh_ec_track_prod_detail_view' => false, 'enh_ec_track_checkout_started' => false, ), ), ); } /** * Data provider to test setting value pairs in GET request. * * @return array[ $setting_name, $setting_value ] */ public function setting_value_pairs_get_request() { return array( 'woocommerce_store_address' => array( 'woocommerce_store_address', 'woocommerce_store_address', 'Street 34th 1/2' ), 'woocommerce_store_address_2' => array( 'woocommerce_store_address_2', 'woocommerce_store_address_2', 'Apt #1' ), 'woocommerce_store_city' => array( 'woocommerce_store_city', 'woocommerce_store_city', 'City' ), 'woocommerce_default_country' => array( 'woocommerce_default_country', 'woocommerce_default_country', 'US:NY' ), 'woocommerce_store_postcode' => array( 'woocommerce_store_postcode', 'woocommerce_store_postcode', '98738' ), 'woocommerce_onboarding_profile' => array( 'woocommerce_onboarding_profile', 'woocommerce_onboarding_profile', array( 'test' => 'test value' ) ), 'wga' => array( 'jetpack_wga', 'wga', array( 'code' => 'G-TESTING', 'anonymize_ip' => false, 'honor_dnt' => false, 'ec_track_purchases' => false, 'ec_track_add_to_cart' => false, 'enh_ec_tracking' => false, 'enh_ec_track_remove_from_cart' => false, 'enh_ec_track_prod_impression' => false, 'enh_ec_track_prod_click' => false, 'enh_ec_track_prod_detail_view' => false, 'enh_ec_track_checkout_started' => false, ), ), ); } /** * Data provider to test setting value pairs in POST request. * * @return array[ $setting_name, $setting_value, $expected_value ] */ public function setting_value_pairs_post_request() { return array( 'woocommerce_store_address' => array( 'woocommerce_store_address', '<h1>Street 34th 1/2</h1>', 'Street 34th 1/2' ), 'woocommerce_store_address_2' => array( 'woocommerce_store_address_2', '<h2>Apt #1</h2>', 'Apt #1' ), 'woocommerce_store_city' => array( 'woocommerce_store_city', '<h3>City</h3>', 'City' ), 'woocommerce_default_country' => array( 'woocommerce_default_country', '<p>US:NY</p>', 'US:NY' ), 'woocommerce_store_postcode' => array( 'woocommerce_store_postcode', '<div>98738</div>', '98738' ), 'woocommerce_store_postcode script tag' => array( 'woocommerce_store_postcode', '<script>98738</script>', '' ), 'woocommerce_onboarding_profile' => array( 'woocommerce_onboarding_profile', array( 'test_key' => '<strong>test value</strong>' ), array( 'test_key' => 'test value' ) ), 'woocommerce_onboarding_profile script tag' => array( 'woocommerce_onboarding_profile', array( 'test_key' => '<script>test value</script>' ), array( 'test_key' => '' ) ), 'woocommerce_onboarding_profile string' => array( 'woocommerce_onboarding_profile', 'string', array( 'string' ) ), 'woocommerce_onboarding_profile bool' => array( 'woocommerce_onboarding_profile', true, array( true ) ), 'woocommerce_onboarding_profile example' => array( 'woocommerce_onboarding_profile', $this->onboarding_profile_example, $this->onboarding_profile_example ), 'show_on_front' => array( 'show_on_front', 'page', 'page' ), 'subscription_options html' => array( 'subscription_options', array( 'invitation' => '<strong>Test</strong> string <a href="#">link</a>', 'comment_follow' => "Test string 2\n\n Other line", ), array( 'invitation' => 'Test string <a href="#">link</a>', 'comment_follow' => "Test string 2\n\n Other line", ), ), 'wga' => array( 'wga', array( 'code' => 'G-TESTING', ), array( 'code' => 'G-TESTING', ), ), ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-update-post-endpoints.php
<?php /** * Jetpack `sites/%s/posts/%d` endpoint unit tests. * * @package automattic/jetpack */ require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Jetpack `sites/%s/posts/%d` endpoint unit tests. */ class WP_Test_Json_Api_Update_Post_Endpoints extends WP_UnitTestCase { /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Post'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Prepare the environment for the test. */ public function set_up() { global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } parent::set_up(); $this->set_globals(); WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Unit tests the should untrash post protected method. */ public function test_should_untrash_post_method() { $post_id = $this->get_post(); $endpoint = $this->get_endpoint(); $post = get_post( $post_id ); $this->assertTrue( $this->invoke_method( $endpoint, 'should_untrash_post', array( 'trash', 'draft', $post ) ) ); $this->assertFalse( $this->invoke_method( $endpoint, 'should_untrash_post', array( 'publish', 'trash', $post ) ) ); $this->assertFalse( $this->invoke_method( $endpoint, 'should_untrash_post', array( 'publish', 'draft', $post ) ) ); } /** * Unit tests the untrash post protected method. */ public function test_update_post_api_v1_1_untrash_post() { $post_id = $this->get_post(); $endpoint = $this->get_endpoint(); wp_trash_post( $post_id ); $post = get_post( $post_id ); // hello is coming from the post title. $input = array( 'slug' => 'hello__trashed' ); $updated_input = $this->invoke_method( $endpoint, 'untrash_post', array( $post, $input ) ); // Tests that we remove the slug id it contains the '__trashed' suffix. $this->assertEmpty( $updated_input ); } /** * Helper function that inserts a post. * * @return int|WP_Error */ private function get_post() { return wp_insert_post( array( 'post_title' => 'hello', 'post_content' => 'world', 'post_status' => 'publish', ) ); } /** * Helper function that returns the post endpoint object. * * @return WPCOM_JSON_API_Update_Post_v1_1_Endpoint */ private function get_endpoint() { return new WPCOM_JSON_API_Update_Post_v1_1_Endpoint( array( 'description' => 'Edit a post.', 'group' => 'posts', 'stat' => 'posts:1:POST', 'new_version' => '1.2', 'min_version' => '1.1', 'max_version' => '1.1', 'method' => 'POST', 'path' => '/sites/%s/posts/%d', 'path_labels' => array( '$site' => '(int|string) Site ID or domain', '$post_ID' => '(int) The post ID', ), 'request_format' => array( 'date' => "(ISO 8601 datetime) The post's creation time.", 'title' => '(HTML) The post title.', 'content' => '(HTML) The post content.', 'excerpt' => '(HTML) An optional post excerpt.', 'slug' => '(string) The name (slug) for the post, used in URLs.', 'author' => '(string) The username or ID for the user to assign the post to.', 'publicize' => '(array|bool) True or false if the post be publicized to external services. An array of services if we only want to publicize to a select few. Defaults to true.', 'publicize_message' => '(string) Custom message to be publicized to external services.', 'status' => array( 'publish' => 'Publish the post.', 'private' => 'Privately publish the post.', 'draft' => 'Save the post as a draft.', 'future' => 'Schedule the post (alias for publish; you must also set a future date).', 'pending' => 'Mark the post as pending editorial approval.', 'trash' => 'Set the post as trashed.', ), 'sticky' => array( 'false' => 'Post is not marked as sticky.', 'true' => 'Stick the post to the front page.', ), 'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.', 'parent' => "(int) The post ID of the new post's parent.", 'terms' => '(object) Mapping of taxonomy to comma-separated list or array of terms (name or id)', 'categories' => '(array|string) Comma-separated list or array of categories (name or id)', 'tags' => '(array|string) Comma-separated list or array of tags (name or id)', 'format' => array_merge( array( 'default' => 'Use default post format' ), get_post_format_strings() ), 'discussion' => '(object) A hash containing one or more of the following boolean values, which default to the blog\'s discussion preferences: `comments_open`, `pings_open`', 'likes_enabled' => '(bool) Should the post be open to likes?', 'menu_order' => '(int) (Pages only) the order pages should appear in. Use 0 to maintain alphabetical order.', 'page_template' => '(string) (Pages Only) The page template this page should use.', 'sharing_enabled' => '(bool) Should sharing buttons show on this post?', 'featured_image' => '(string) The post ID of an existing attachment to set as the featured image. Pass an empty string to delete the existing image.', 'media' => '(media) An array of files to attach to the post. To upload media, the entire request should be multipart/form-data encoded. Multiple media items will be displayed in a gallery. Accepts jpg, jpeg, png, gif, pdf, doc, ppt, odt, pptx, docx, pps, ppsx, xls, xlsx, key. Audio and Video may also be available. See <code>allowed_file_types</code> in the options resposne of the site endpoint. <br /><br /><strong>Example</strong>:<br />' . "<code>curl \<br />--form 'title=Image' \<br />--form 'media[]=@/path/to/file.jpg' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/posts/new'</code>", 'media_urls' => '(array) An array of URLs for images to attach to a post. Sideloads the media in for a post.', 'metadata' => '(array) Array of metadata objects containing the following properties: `key` (metadata key), `id` (meta ID), `previous_value` (if set, the action will only occur for the provided previous value), `value` (the new value to set the meta to), `operation` (the operation to perform: `update` or `add`; defaults to `update`). All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are available for authenticated requests with proper capabilities. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.', ), ) ); } /** * Call protected/private method of a class. * * @param object $object Instantiated object that we will run method on. * @param string $method_name Method name to call. * @param array $parameters Array of parameters to pass into method. * * @return mixed Method return. */ public function invoke_method( &$object, $method_name, array $parameters = array() ) { $reflection = new \ReflectionClass( get_class( $object ) ); $method = $reflection->getMethod( $method_name ); $method->setAccessible( true ); return $method->invokeArgs( $object, $parameters ); } }
projects/plugins/jetpack/tests/php/json-api/test-class.json-api-jetpack-modules-endpoints.php
<?php /** * Tests for the `sites/%s/jetpack/modules` endpoints. * * @package automattic/jetpack */ require_once JETPACK__PLUGIN_DIR . 'class.json-api.php'; require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php'; /** * Tests for the `sites/%s/jetpack/modules` endpoints. */ class WP_Test_Jetpack_Modules_Json_Api_Endpoints extends WP_UnitTestCase { /** * Inserts globals needed to initialize the endpoint. */ private function set_globals() { $_SERVER['REQUEST_METHOD'] = 'Get'; $_SERVER['HTTP_HOST'] = '127.0.0.1'; $_SERVER['REQUEST_URI'] = '/'; } /** * Prepare the environment for the test. */ public function set_up() { global $blog_id; if ( ! defined( 'WPCOM_JSON_API__BASE' ) ) { define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' ); } parent::set_up(); $this->set_globals(); WPCOM_JSON_API::init()->token_details = array( 'blog_id' => $blog_id ); } /** * Unit test for the `v1.2/modules/%s` endpoint. */ public function test_get_modules_v1_2() { global $blog_id; $endpoint = new Jetpack_JSON_API_Modules_List_V1_2_Endpoint( array( 'description' => 'Get the list of available Jetpack modules on your site', 'method' => 'GET', 'path' => '/sites/%s/jetpack/modules', 'stat' => 'jetpack:modules', 'min_version' => '1.2', 'path_labels' => array( '$site' => '(int|string) The site ID, The site domain', ), 'response_format' => array( 'modules' => '(array) An array of module objects.', ), 'allow_jetpack_site_auth' => true, 'example_request_data' => array( 'headers' => array( 'authorization' => 'Bearer YOUR_API_TOKEN', ), ), 'example_request' => 'https://public-api.wordpress.com/rest/v1.2/sites/example.wordpress.org/jetpack/modules', ) ); $response = $endpoint->callback( '', $blog_id ); $this->assertArrayHasKey( 'modules', $response ); $this->assertIsArray( $response['modules'] ); $module = array_pop( $response['modules'] ); $this->assertArrayHasKey( 'name', $module ); $this->assertArrayHasKey( 'description', $module ); $this->assertArrayHasKey( 'activated', $module ); $this->assertArrayHasKey( 'available', $module ); } }
projects/plugins/jetpack/tests/php/general/test-class.functions.compat.php
<?php class WP_Test_Functions_Compat extends WP_UnitTestCase { /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_valid_url() { $valid_url = 'https://www.youtube.com/watch?v=snAvGxz7D04'; $sanitized_url = youtube_sanitize_url( $valid_url ); $this->assertEquals( $valid_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_shortened_url() { $valid_short_url = 'https://youtu.be/snAvGxz7D04'; $expected_sanitized_url = 'https://youtu.be/?v=snAvGxz7D04'; $sanitized_url = youtube_sanitize_url( $valid_short_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_slash_v_slash() { $slash_v_slash_url = 'https://www.youtube.com/v/9FhMMmqzbD8'; $expected_sanitized_url = 'https://www.youtube.com/?v=9FhMMmqzbD8'; $sanitized_url = youtube_sanitize_url( $slash_v_slash_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_hashbang() { $hashbang_url = 'https://www.youtube.com/#!v=9FhMMmqzbD8'; $expected_sanitized_url = 'https://www.youtube.com/?v=9FhMMmqzbD8'; $sanitized_url = youtube_sanitize_url( $hashbang_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_amp_ampersand() { $amp_ampersand_url = 'https://www.youtube.com/watch?v=snAvGxz7D04&amp;hl=en_US'; $expected_sanitized_url = 'https://www.youtube.com/watch?v=snAvGxz7D04&hl=en_US'; $sanitized_url = youtube_sanitize_url( $amp_ampersand_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_encoded_ampersand() { $encoded_ampersand_url = 'https://www.youtube.com/watch?v=snAvGxz7D04&#038;hl=en_US'; $expected_sanitized_url = 'https://www.youtube.com/watch?v=snAvGxz7D04&hl=en_US'; $sanitized_url = youtube_sanitize_url( $encoded_ampersand_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_playlist() { $valid_playlist_url = 'https://www.youtube.com/playlist?list=PL56C3506BBE979C1B'; $expected_sanitized_url = 'https://www.youtube.com/videoseries?list=PL56C3506BBE979C1B'; $sanitized_url = youtube_sanitize_url( $valid_playlist_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::youtube_sanitize_url * @since 3.2 */ public function test_youtube_sanitize_url_with_extra_question_mark() { $extra_question_mark_url = 'http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US'; $expected_sanitized_url = 'http://www.youtube.com/?v=9FhMMmqzbD8&fs=1&hl=en_US'; $sanitized_url = youtube_sanitize_url( $extra_question_mark_url ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author robfelty * @covers ::youtube_sanitize_url * @since 13.2 */ public function test_youtube_sanitize_url_as_array() { $url_array = array( 'url' => 'http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US', ); $expected_sanitized_url = 'http://www.youtube.com/?v=9FhMMmqzbD8&fs=1&hl=en_US'; $sanitized_url = youtube_sanitize_url( $url_array ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author robfelty * @covers ::youtube_sanitize_url * @since 13.2 */ public function test_youtube_sanitize_url_invalid_input() { $invalid_url_array = array( 'vv' => 'http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US', ); $expected_sanitized_url = false; $sanitized_url = youtube_sanitize_url( $invalid_url_array ); $this->assertEquals( $expected_sanitized_url, $sanitized_url ); } /** * @author enkrates * @covers ::jetpack_get_youtube_id * @since 3.2 */ public function test_jetpack_get_youtube_id_with_single_video_url() { $single_video_url = 'https://www.youtube.com/watch?v=snAvGxz7D04'; $expected_id = 'snAvGxz7D04'; $youtube_id = jetpack_get_youtube_id( $single_video_url ); $this->assertEquals( $expected_id, $youtube_id ); } /** * @author enkrates * @covers ::jetpack_get_youtube_id * @since 3.2 */ public function test_jetpack_get_youtube_id_with_playlist_url() { $playlist_url = 'https://www.youtube.com/playlist?list=PL56C3506BBE979C1B'; $expected_id = 'PL56C3506BBE979C1B'; $youtube_id = jetpack_get_youtube_id( $playlist_url ); $this->assertEquals( $expected_id, $youtube_id ); } } // end class
projects/plugins/jetpack/tests/php/general/test-class.jetpack-options.php
<?php use Automattic\Jetpack\Constants; class WP_Test_Jetpack_Options extends WP_UnitTestCase { /** * Cache for the test option. * * @var mixed */ private $option_cache = false; /** * Set up a fake cache for the option 'test_option'. * * Note the hooks added here will be automatically removed by * `WP_UnitTestCase_Base::tear_down()`. */ private function setup_option_cache() { $cache_option = function ( $name, $value = false ) { $this->option_cache = $value; }; add_action( 'add_option_test_option', $cache_option, 10, 2 ); add_action( 'update_option_test_option', $cache_option, 10, 2 ); add_action( 'delete_option_test_option', $cache_option, 10, 1 ); add_filter( 'option_test_option', function ( $value ) { return false === $this->option_cache ? $value : $this->option_cache; } ); } public function test_delete_non_compact_option_returns_true_when_successfully_deleted() { Jetpack_Options::update_option( 'migrate_for_idc', true ); // Make sure the option is set $this->assertTrue( Jetpack_Options::get_option( 'migrate_for_idc' ) ); $deleted = Jetpack_Options::delete_option( 'migrate_for_idc' ); // Was the option successfully deleted? $this->assertFalse( Jetpack_Options::get_option( 'migrate_for_idc' ) ); // Check if Jetpack_Options::delete_option() properly returned true? $this->assertTrue( $deleted ); } public function test_raw_option_update_will_bypass_wp_cache_and_filters() { $this->setup_option_cache(); update_option( 'test_option', 'cached_value' ); Jetpack_Options::update_raw_option( 'test_option', 'updated_value' ); $this->assertEquals( 'cached_value', get_option( 'test_option' ) ); } public function test_raw_option_with_constant_does_not_by_pass_wp_cache_filters() { $this->setup_option_cache(); Constants::set_constant( 'JETPACK_DISABLE_RAW_OPTIONS', true ); try { update_option( 'test_option', 'cached_value' ); Jetpack_Options::update_raw_option( 'test_option', 'updated_value' ); $this->assertEquals( 'updated_value', get_option( 'test_option' ) ); $this->assertEquals( 'updated_value', Jetpack_Options::get_raw_option( 'test_option' ) ); } finally { Constants::clear_single_constant( 'JETPACK_DISABLE_RAW_OPTIONS' ); } } public function test_raw_option_with_filter_does_not_by_pass_wp_cache_filters() { $this->setup_option_cache(); add_filter( 'jetpack_disabled_raw_options', function ( $options ) { $options['test_option'] = true; return $options; } ); update_option( 'test_option', 'cached_value' ); Jetpack_Options::update_raw_option( 'test_option', 'updated_value' ); $this->assertEquals( 'updated_value', get_option( 'test_option' ) ); $this->assertEquals( 'updated_value', Jetpack_Options::get_raw_option( 'test_option' ) ); } public function test_raw_option_get_will_bypass_wp_cache_and_filters() { $this->setup_option_cache(); update_option( 'test_option', 'cached_value' ); Jetpack_Options::update_raw_option( 'test_option', 'updated_value' ); $this->assertEquals( 'cached_value', get_option( 'test_option' ) ); $this->assertEquals( 'updated_value', Jetpack_Options::get_raw_option( 'test_option' ) ); } public function test_raw_option_delete_will_bypass_wp_cache_and_filters() { $this->setup_option_cache(); update_option( 'test_option', 'cached_value' ); Jetpack_Options::delete_raw_option( 'test_option' ); $this->assertEquals( 'cached_value', get_option( 'test_option' ) ); $this->assertNull( Jetpack_Options::get_raw_option( 'test_option' ) ); } public function test_raw_option_update_with_duplicate_value_returns_false() { Jetpack_Options::delete_raw_option( 'test_option_2' ); Jetpack_Options::update_raw_option( 'test_option_2', 'blue' ); $this->assertEquals( 'blue', Jetpack_Options::get_raw_option( 'test_option_2' ) ); $this->assertFalse( Jetpack_Options::update_raw_option( 'test_option_2', 'blue' ) ); $this->assertTrue( Jetpack_Options::update_raw_option( 'test_option_2', 'yellow' ) ); } }
projects/plugins/jetpack/tests/php/general/test-class.jetpack-gutenberg.php
<?php use Automattic\Jetpack\Blocks; class WP_Test_Jetpack_Gutenberg extends WP_UnitTestCase { public $master_user_id = false; /** * Set up. */ public function set_up() { parent::set_up(); if ( ! function_exists( 'register_block_type' ) ) { $this->markTestSkipped( 'register_block_type not available' ); return; } if ( ! class_exists( 'WP_Block_Type_Registry' ) ) { $this->markTestSkipped( 'WP_Block_Type_Registry not available' ); return; } // Create a user and set it up as current. $this->master_user_id = self::factory()->user->create( array( 'user_login' => 'current_master' ) ); // Mock a connection Jetpack_Options::update_option( 'master_user', $this->master_user_id ); Jetpack_Options::update_option( 'id', 1234 ); Jetpack_Options::update_option( 'blog_token', 'asd.asd.1' ); add_filter( 'jetpack_set_available_extensions', array( __CLASS__, 'get_extensions_whitelist' ) ); delete_option( 'jetpack_excluded_extensions' ); // These action causing issues in tests in WPCOM context. Since we are not using any real block here, // and we are testing block availability with block stubs - we are safe to remove these actions for these tests. remove_all_actions( 'jetpack_register_gutenberg_extensions' ); } /** * Tear down. */ public function tear_down() { parent::tear_down(); Jetpack_Gutenberg::reset(); remove_filter( 'jetpack_set_available_extensions', array( __CLASS__, 'get_extensions_whitelist' ) ); if ( $this->master_user_id ) { Jetpack_Options::delete_option( array( 'master_user', 'user_tokens' ) ); wp_delete_user( $this->master_user_id ); } if ( class_exists( 'WP_Block_Type_Registry' ) ) { $blocks = WP_Block_Type_Registry::get_instance()->get_all_registered(); foreach ( $blocks as $block_name => $block ) { if ( wp_startswith( $block_name, 'jetpack/' ) ) { unregister_block_type( $block_name ); } } } } public static function get_extensions_whitelist() { return array( // Our Blocks :) 'apple', 'banana', 'coconut', 'grape', // Our Plugins :) 'onion', 'potato', 'tomato', ); } /** * This test will throw an exception/fail if blocks register twice upon repeat calls to get_availability() */ public function test_does_calling_get_availability_twice_result_in_notice() { add_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_block' ) ); Jetpack_Gutenberg::get_availability(); Jetpack_Gutenberg::get_availability(); $result = remove_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_block' ) ); $this->assertTrue( $result ); } public function register_block() { Blocks::jetpack_register_block( 'jetpack/apple' ); } public function test_registered_block_is_available() { Blocks::jetpack_register_block( 'jetpack/apple' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertTrue( $availability['apple']['available'] ); } public function test_registered_block_is_not_available() { Jetpack_Gutenberg::set_extension_unavailable( 'jetpack/banana', 'bar' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertFalse( $availability['banana']['available'], 'banana is available!' ); $this->assertEquals( 'bar', $availability['banana']['unavailable_reason'], 'unavailable_reason is not "bar"' ); } public function test_registered_block_is_not_available_when_not_defined_in_whitelist() { Blocks::jetpack_register_block( 'jetpack/durian' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertArrayNotHasKey( 'durian', $availability, 'durian is available!' ); } public function test_block_is_not_available_when_not_registered_returns_missing_module() { $availability = Jetpack_Gutenberg::get_availability(); // 'unavailable_reason' should be 'missing_module' if the block wasn't registered $this->assertFalse( $availability['grape']['available'], 'Availability is not false exists' ); $this->assertEquals( 'missing_module', $availability['grape']['unavailable_reason'], 'unavailable_reason is not "missing_module"' ); } // Plugins public function test_registered_plugin_is_available() { Jetpack_Gutenberg::set_extension_available( 'jetpack/onion' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertTrue( $availability['onion']['available'] ); } public function test_registered_plugin_is_not_available() { Jetpack_Gutenberg::set_extension_unavailable( 'jetpack/potato', 'bar' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertFalse( $availability['potato']['available'], 'potato is available!' ); $this->assertEquals( 'bar', $availability['potato']['unavailable_reason'], 'unavailable_reason is not "bar"' ); } public function test_registered_plugin_is_not_available_when_not_defined_in_whitelist() { Jetpack_Gutenberg::set_extension_available( 'jetpack/parsnip' ); $availability = Jetpack_Gutenberg::get_availability(); $this->assertArrayNotHasKey( 'parsnip', $availability, 'parsnip is available!' ); } public function test_plugin_is_not_available_when_not_registered_returns_missing_module() { $availability = Jetpack_Gutenberg::get_availability(); // 'unavailable_reason' should be 'missing_module' if the block wasn't registered $this->assertFalse( $availability['tomato']['available'], 'Availability is not false exists' ); $this->assertEquals( 'missing_module', $availability['tomato']['unavailable_reason'], 'unavailable_reason is not "missing_module"' ); } public function test_get_available_extensions() { $extensions = Jetpack_Gutenberg::get_available_extensions( $this->get_extensions_whitelist() ); $this->assertIsArray( $extensions ); $this->assertNotEmpty( $extensions ); $this->assertContains( 'onion', $extensions ); update_option( 'jetpack_excluded_extensions', array( 'onion' ) ); $extensions = Jetpack_Gutenberg::get_available_extensions( $this->get_extensions_whitelist() ); $this->assertIsArray( $extensions ); $this->assertNotEmpty( $extensions ); $this->assertNotContains( 'onion', $extensions ); } public function test_returns_false_if_core_wp_version_less_than_minimum() { $version_gated = Jetpack_Gutenberg::is_gutenberg_version_available( array( 'wp' => '999999', 'gutenberg' => '999999', ), 'gated_block' ); $this->assertFalse( $version_gated ); } /** * Tests whether the environment has the minimum Gutenberg/WordPress installation needed by a block */ public function test_returns_true_if_gutenberg_or_core_wp_version_greater_or_equal_to_minimum() { $version_gated = Jetpack_Gutenberg::is_gutenberg_version_available( array( 'wp' => '1', 'gutenberg' => '1', ), 'ungated_block' ); $this->assertTrue( $version_gated ); } /** * Test that known invalid urls are normalized during validation. * * @dataProvider provider_invalid_urls * * @param string $url Original URL. * @param object $assertion Assertion on the result. */ public function test_validate_normalizes_invalid_domain_url( $url, $assertion ) { $allowed_hosts = array( 'calendar.google.com' ); $url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed_hosts ); $this->assertThat( $url, $assertion ); } /** * Provides Original URL and Expected Validated URL values. * * @return array Array of Test Data */ public function provider_invalid_urls() { return array( array( 'https://calendar.google.com#@evil.com', $this->equalTo( 'https://calendar.google.com/#%40evil.com' ), ), array( 'https://foo@evil.com:80@calendar.google.com', $this->equalTo( 'https://calendar.google.com/' ), ), array( 'https://foo@127.0.0.1 @calendar.google.com', // The fix for https://bugs.php.net/bug.php?id=77423 changed the behavior here. // It's included in PHP 8.0.1, 7.4.14, 7.3.26, and distros might have backported it to // out-of-support versions too, so just expect either option. $this->logicalOr( $this->isFalse(), $this->equalTo( 'https://calendar.google.com/' ) ), ), array( 'https://calendar.google.com/\xFF\x2E\xFF\x2E/passwd', $this->equalTo( 'https://calendar.google.com/\xFF\x2E\xFF\x2E/passwd' ), ), ); } /** * Tests whether a third-party domain can be used in a block. */ public function test_validate_block_embed_third_party_url() { $url = 'https://example.org'; $allowed_hosts = array( 'wordpress.com' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed_hosts ); $this->assertFalse( $validated_url ); } /** * Tests whether a random string (not a URL) can be used in a block. */ public function test_validate_block_embed_string() { $url = 'apple'; $allowed_hosts = array( 'wordpress.com' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed_hosts ); $this->assertFalse( $validated_url ); } /** * Tests whether a schemeless URL can be used in a block. */ public function test_validate_block_embed_scheme() { $url = 'wordpress.com'; $allowed_hosts = array( 'wordpress.com' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed_hosts ); $this->assertFalse( $validated_url ); } /** * Tests whether a URL belonging to a whitelisted list can be used in a block. */ public function test_validate_block_embed_url() { $url = 'https://wordpress.com/tos/'; $allowed_hosts = array( 'wordpress.com' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed_hosts ); $this->assertEquals( $url, $validated_url ); } /** * Tests whether a URL matches a specific regex. */ public function test_validate_block_embed_regex() { $url = 'https://wordpress.com/tos/'; $allowed = array( '#^https?:\/\/(www.)?wordpress\.com(\/)?([^\/]+)?(\/)?$#' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed, true ); $this->assertEquals( $url, $validated_url ); } /** * Tests whether a URL does not match a specific regex. */ public function test_validate_block_embed_regex_mismatch() { $url = 'https://www.facebook.com/WordPresscom/'; $allowed = array( '#^https?:\/\/(www.)?wordpress\.com(\/)?([^\/]+)?(\/)?$#' ); $validated_url = Jetpack_Gutenberg::validate_block_embed_url( $url, $allowed, true ); $this->assertFalse( $validated_url ); } }
projects/plugins/jetpack/tests/php/general/test_class.jetpack-heartbeat.php
<?php class WP_Test_Jetpack_Heartbeat extends WP_UnitTestCase { /** * @covers Jetpack_Heartbeat::init * @since 3.9.0 */ public function test_init() { $this->assertInstanceOf( 'Jetpack_Heartbeat', Jetpack_Heartbeat::init() ); } /** * @covers Jetpack_Heartbeat::generate_stats_array * @since 3.9.0 */ public function test_generate_stats_array() { $prefix = 'test'; $result = Jetpack_Heartbeat::generate_stats_array( $prefix ); $this->assertNotEmpty( $result ); $this->assertArrayHasKey( $prefix . 'version', $result ); } }
projects/plugins/jetpack/tests/php/general/test_class.functions.global.php
<?php /** * Tests for functions in functions.global.php */ class WP_Test_Functions_Global extends WP_UnitTestCase { /** * Test string returned by jetpack_deprecated_function * * @covers ::jetpack_get_future_removed_version * @since 8.8.0 * @dataProvider jetpack_deprecated_function_versions * * @param string $version Version number passed to the function. * @param string $expected Expected removed version number. */ public function test_jetpack_get_future_removed_version( $version, $expected ) { $removed_version = jetpack_get_future_removed_version( $version ); $this->assertEquals( $expected, $removed_version ); } /** * Data provider for the test_jetpack_get_future_removed_version() test. * * @return Array test version numbers potentially passed to the function. */ public function jetpack_deprecated_function_versions() { return array( 'no_version_number' => array( 'jetpack', false, ), 'only_major_number' => array( '8.8', '9.4', ), 'full_version_number_without_text' => array( '8.8.0', '9.4', ), 'full_version_number_with_jetpack_prepended' => array( 'jetpack-8.8.0', '9.4', ), 'full_zero_version_number_with_jetpack' => array( 'jetpack-8.0.0', '8.6', ), 'semver_number_above_10' => array( '9.15.0', false, ), 'full_version_number_above_10' => array( '10.5', '11.1', ), ); } /** * Test jetpack_get_vary_headers. * * @dataProvider get_test_headers * @covers ::jetpack_get_vary_headers * * @param array $headers Array of headers. * @param array $expected Expected array of headers, to be used as Vary header. */ public function test_jetpack_get_vary_headers( $headers, $expected ) { $vary_header_parts = jetpack_get_vary_headers( $headers ); $this->assertEquals( $expected, $vary_header_parts ); } /** * Data provider for the test_jetpack_get_vary_headers() test. * * @return array */ public function get_test_headers() { return array( 'no headers' => array( array(), array( 'accept', 'content-type' ), ), 'Single Vary Encoding header' => array( array( 'Vary: Accept-Encoding', ), array( 'accept', 'content-type', 'accept-encoding' ), ), 'Double Vary: Accept-Encoding & Accept' => array( array( 'Vary: Accept, Accept-Encoding', ), array( 'accept', 'content-type', 'accept-encoding' ), ), 'vary header' => array( array( 'Cache-Control: no-cache, must-revalidate, max-age=0', 'Content-Type: text/html; charset=UTF-8', 'Vary: Accept', ), array( 'accept', 'content-type' ), ), 'Wildcard Vary header' => array( array( 'Cache-Control: no-cache, must-revalidate, max-age=0', 'Content-Type: text/html; charset=UTF-8', 'Vary: *', ), array( '*' ), ), 'Multiple Vary headers' => array( array( 'Cache-Control: no-cache, must-revalidate, max-age=0', 'Content-Type: text/html; charset=UTF-8', 'Vary: Accept', 'Vary: Accept-Encoding', ), array( 'accept', 'content-type', 'accept-encoding' ), ), 'Multiple Vary headers, with a wildcard' => array( array( 'Cache-Control: no-cache, must-revalidate, max-age=0', 'Content-Type: text/html; charset=UTF-8', 'Vary: *', 'Vary: Accept-Encoding', ), array( '*' ), ), ); } }
projects/plugins/jetpack/tests/php/general/test-class.jetpack-network.php
<?php /** * Tests the Jetpack_Network class. * * @package automattic/jetpack */ if ( is_multisite() ) : /** * Test class for the Jetpack_Network class. */ class WP_Test_Jetpack_Network extends WP_UnitTestCase { /** * Confirms the instance is generated from the init. * * @since 2.5 */ public function test_jetpack_network_init_returns_jetpack_network() { $this->assertInstanceOf( 'Jetpack_Network', Jetpack_Network::init() ); } /** * Tests the get_url function. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_correct_string_for_network_admin_page() { $jpms = Jetpack_Network::init(); $url = $jpms->get_url( 'network_admin_page' ); $expected_url = '/wp-admin/network/admin.php?page=jetpack'; $this->assertIsString( $url ); $this->assertStringEndsWith( $expected_url, $url ); } /** * Tests that null is returned for invalid input. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_null_for_invalid_input() { $jpms = Jetpack_Network::init(); $this->assertNull( $jpms->get_url( 1234 ) ); } /** * Tests if get_url returns the correct string. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_correct_string_for_subsiteregister() { $jpms = Jetpack_Network::init(); $url = $jpms->get_url( array( 'name' => 'subsiteregister', 'site_id' => 123, ) ); $expected_url = '/wp-admin/network/admin.php?page=jetpack&action=subsiteregister&site_id=123'; $this->assertIsString( $url ); $this->assertStringEndsWith( $expected_url, $url ); } /** * Tests if get_url returns the correct string for an unspecified site. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_null_for_underspecified_subsiteregister() { $jpms = Jetpack_Network::init(); $this->assertNull( $jpms->get_url( array( 'name' => 'subsiteregister' ) ) ); } /** * Tests if get_url returns the correct string for subsite disconnect. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_correct_string_for_subsitedisconnect() { $jpms = Jetpack_Network::init(); $url = $jpms->get_url( array( 'name' => 'subsitedisconnect', 'site_id' => 123, ) ); $expected_url = '/wp-admin/network/admin.php?page=jetpack&action=subsitedisconnect&site_id=123'; $this->assertIsString( $url ); $this->assertStringEndsWith( $expected_url, $url ); } /** * Tests if get_url returns the correct string for an unspecified disconnect. * * @author enkrates * @covers Jetpack_Network::get_url * @since 3.2 */ public function test_get_url_returns_null_for_underspecified_subsitedisconnect() { $jpms = Jetpack_Network::init(); $this->assertNull( $jpms->get_url( array( 'name' => 'subsitedisconnect' ) ) ); } /** * Tests the body class includes 'network-admin'/ * * @since 2.8 **/ public function test_body_class_contains_network_admin() { $jpms = Jetpack_Network::init(); $classes = $jpms->body_class( '' ); $this->assertIsString( $classes ); $this->assertStringContainsString( 'network-admin', $classes ); } /** * Tests that the network option exists. * * @author igmoweb * @covers Jetpack_Options::is_network_option * @since 4.8 */ public function test_is_network_option() { $network_options = Jetpack_Options::get_option_names( 'network' ); foreach ( $network_options as $option_name ) { $this->assertTrue( Jetpack_Options::is_network_option( $option_name ) ); } $this->assertFalse( Jetpack_Options::is_network_option( 'version' ) ); } /** * Tests that the file_data option exists. * * @author igmoweb * @covers Jetpack_Options::update_option * @since 4.8 */ public function test_update_file_data_network_options() { $value = array( 'just', 'a', 'sample' ); Jetpack_Options::update_option( 'file_data', $value ); $this->assertEquals( $value, Jetpack_Options::get_option( 'file_data' ) ); // Make sure that the option is in wp_sitemeta. $this->assertEquals( $value, get_site_option( 'jetpack_file_data' ) ); // And is not in wp_options. $this->assertFalse( get_option( 'jetpack_file_data' ) ); } /** * Tests that we can delete the file_data option. * * @author igmoweb * @covers Jetpack_Options::get_option_and_ensure_autoload * @since 4.8 */ public function test_delete_file_data_network_options() { $value = array( 'just', 'a', 'sample' ); Jetpack_Options::update_option( 'file_data', $value ); Jetpack_Options::delete_option( 'file_data' ); $this->assertFalse( Jetpack_Options::get_option( 'file_data' ) ); } /** * Tests that network options are ensured autoloaded. * * @author igmoweb * @covers Jetpack_Options::delete_option * @since 4.8 */ public function test_get_network_option_and_ensure_autoload() { $default = array( 'just', 'a', 'sample' ); Jetpack_Options::get_option_and_ensure_autoload( 'jetpack_file_data', $default ); $this->assertEquals( $default, Jetpack_Options::get_option( 'file_data' ) ); } /** * Tests the Jetpack_Network::set_multisite_disconnect_cap method. * * @param bool $is_super_admin Whether the current user is a super admin. * @param bool $connection_override The sub-site connection override setting. * @param bool $disconnect_allowed Whether the disconnect capability should be allowed. * * @covers Jetpack_Network::set_multisite_disconnect_cap * @dataProvider data_provider_test_set_multisite_disconnect_caps */ public function test_set_multisite_disconnect_cap( $is_super_admin, $connection_override, $disconnect_allowed ) { $test_cap = array( 'test_cap' ); $expected_output = $disconnect_allowed ? $test_cap : array( 'do_not_allow' ); $user_id = self::factory()->user->create( array( 'user_login' => 'test_user' ) ); wp_set_current_user( $user_id ); if ( $is_super_admin ) { grant_super_admin( $user_id ); } update_site_option( 'jetpack-network-settings', array( 'sub-site-connection-override' => $connection_override ) ); $this->assertEquals( $expected_output, Jetpack_Network::init()->set_multisite_disconnect_cap( $test_cap ) ); } /** * Data provider for test_set_multisite_disconnect_caps. * * Each test data set is provided as an array: * array { * bool $is_super_admin Whether the current user is a super admin. * bool $connection_override The sub-site connection override setting. * bool $disconnect_allowed Whether the user should have the jetpack_disconnect capability. This value is set * based on the values of $is_super_admin and $connection_override. * } */ public function data_provider_test_set_multisite_disconnect_caps() { return array( 'is_super_admin: true; connection_override: true' => array( true, true, true ), 'is_super_admin: true; connection_override: false' => array( true, false, true ), 'is_super_admin: false; connection_override: true' => array( false, true, true ), 'is_super_admin: false; connection_override: false' => array( false, false, false ), ); } } // end class endif;
projects/plugins/jetpack/tests/php/general/test_class.jetpack-client-server.php
<?php /** * Tests for Jetpack_Client_Server. * * @covers Jetpack_Client_Server */ class WP_Test_Jetpack_Client_Server extends WP_UnitTestCase { /** * Set up before class. */ public static function set_up_before_class() { parent::set_up_before_class(); self::$ignore_files = true; } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_initialize() { $client_server = new Jetpack_Client_Server(); $this->assertNotNull( $client_server ); } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_authorize_role_cap() { $author_id = self::factory()->user->create( array( 'role' => 'administrator', ) ); wp_set_current_user( $author_id ); $client_server = $this->getMockBuilder( 'Jetpack_Client_Server' ) // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable ->setMethods( array( 'do_exit' ) ) ->getMock(); $result = Jetpack::connection()->authorize(); $this->assertNotEquals( 'no_role', $result->get_error_code() ); $this->assertNotEquals( 'no_cap', $result->get_error_code() ); } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_authorize_no_role() { $author_id = self::factory()->user->create( array( 'role' => 'imagination_mover', ) ); wp_set_current_user( $author_id ); $client_server = $this->getMockBuilder( 'Jetpack_Client_Server' ) // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable ->setMethods( array( 'do_exit' ) ) ->getMock(); $result = Jetpack::connection()->authorize(); $this->assertEquals( 'no_role', $result->get_error_code() ); } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_authorize_data_error() { $author_id = self::factory()->user->create( array( 'role' => 'administrator', ) ); wp_set_current_user( $author_id ); $client_server = $this->getMockBuilder( 'Jetpack_Client_Server' ) // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable ->setMethods( array( 'do_exit' ) ) ->getMock(); $result = Jetpack::connection()->authorize( array( 'error' => 'test_error' ) ); $this->assertEquals( 'test_error', $result->get_error_code() ); } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_deactivate_plugin() { $client_server = new Jetpack_Client_Server(); $return_value = $client_server->deactivate_plugin( 'herp', 'derp' ); $this->assertSame( 0, $return_value ); } /** * @author scotchfield * @since 3.2 */ public function test_jetpack_client_server_get_token() { $author_id = self::factory()->user->create( array( 'role' => 'administrator', ) ); wp_set_current_user( $author_id ); $return_value = Jetpack::connection()->get_token( 'test' ); $this->assertInstanceOf( 'WP_Error', $return_value ); } }
projects/plugins/jetpack/tests/php/general/test_class.jetpack-user-agent.php
<?php /** * Tests for Jetpack's legacy User Agent class. * * @package automattic/jetpack */ /** * Class WP_Test_Jetpack_User_Agent */ class WP_Test_Jetpack_User_Agent extends WP_UnitTestCase { /** * Confirm an old improper static use of Jetpack_User_Agent_Info still functions. */ public function test_jetpack_user_agent_is_tablet() { $this->setExpectedDeprecated( 'Jetpack_User_Agent_Info::is_tablet' ); $this->assertFalse( Jetpack_User_Agent_Info::is_tablet() ); } /** * Confirm an old improper static use of Jetpack_User_Agent_Info still functions. */ public function test_jetpack_user_agent_is_iphoneOrIpod() { $this->setExpectedDeprecated( 'Jetpack_User_Agent_Info::is_iphoneOrIpod' ); $this->assertFalse( Jetpack_User_Agent_Info::is_iphoneOrIpod() ); } }
projects/plugins/jetpack/tests/php/general/test_class.jetpack-xmlrpc-server.php
<?php use Automattic\Jetpack\Connection\Tokens; class WP_Test_Jetpack_XMLRPC_Server extends WP_UnitTestCase { public static $xmlrpc_admin = 0; public static function wpSetupBeforeClass( $factory ) { $user_id = $factory->user->create(); $user = get_user_by( 'ID', $user_id ); $user->set_role( 'administrator' ); ( new Tokens() )->update_user_token( $user_id, sprintf( '%s.%s.%d', 'key', 'private', $user_id ), false ); self::$xmlrpc_admin = $user_id; } /** * Tests that the Jetpack plugin XMLRPC methods are being added * * @param string $method The XMLRPC method name. * * @dataProvider data_xmlrpc_methods_exist */ public function test_xmlrpc_methods_exist( $method ) { $methods = ( new Jetpack_XMLRPC_Server() )->xmlrpc_methods( array() ); $this->assertArrayHasKey( $method, $methods ); } /** * Data provider for test_xmlrpc_methods_exist */ public function data_xmlrpc_methods_exist() { return array( array( 'jetpack.featuresAvailable' ), array( 'jetpack.featuresEnabled' ), array( 'jetpack.disconnectBlog' ), array( 'jetpack.jsonAPI' ), array( 'jetpack.remoteProvision' ), ); } /** * Test test_xmlrpc_features_available */ public function test_xmlrpc_features_available() { $response = Jetpack_XMLRPC_Methods::features_available(); // trivial assertion. $this->assertContains( 'publicize', $response ); } /** * Test test_xmlrpc_remote_provision_fails_no_local_user * * @return void */ public function test_xmlrpc_remote_provision_fails_no_local_user() { $server = new Jetpack_XMLRPC_Server(); $response = $server->remote_provision( array( 'nonce' => '12345' ) ); $this->assertInstanceOf( 'IXR_Error', $response ); $this->assertEquals( 400, $response->code ); $this->assertStringContainsString( '[local_user_missing]', $response->message ); } /** * Test test_remote_provision_error_nonexistent_user */ public function test_remote_provision_error_nonexistent_user() { $server = new Jetpack_XMLRPC_Server(); $response = $server->remote_provision( array() ); $this->assertInstanceOf( 'IXR_Error', $response ); $this->assertStringContainsString( 'local_user_missing', $response->message ); $response = $server->remote_provision( array( 'local_user' => 'nonexistent' ) ); $this->assertInstanceOf( 'IXR_Error', $response ); $this->assertEquals( 'Jetpack: [input_error] Valid user is required', $response->message ); } /** * Test test_remote_provision_success */ public function test_remote_provision_success() { $server = new Jetpack_XMLRPC_Server(); $response = $server->remote_provision( array( 'local_user' => 1 ) ); $this->assertIsArray( $response ); $expected_keys = array( 'jp_version', 'redirect_uri', 'user_id', 'user_email', 'user_login', 'scope', 'secret', 'is_active', ); foreach ( $expected_keys as $key ) { $this->assertArrayHasKey( $key, $response ); } } /** * Test remote_provision filter is working and adding the onboarding token. */ public function test_remote_provision_onboarding_filter() { $request = array( 'local_user' => 1, 'onboarding' => 1, ); $response = ( new Jetpack_XMLRPC_Server() )->remote_provision( $request ); $this->assertArrayHasKey( 'onboarding_token', $response, 'onboard_token should be present in the response.' ); $this->assertNotEmpty( $response['onboarding_token'], 'onboard_token should not be empty.' ); } /** * Test remote_provision filter is not adding onboard_token when it is not supposed to */ public function test_remote_provision_onboarding_filter_unchanged() { $request = array( 'local_user' => 1, ); $response = ( new Jetpack_XMLRPC_Server() )->remote_provision( $request ); $this->assertArrayNotHasKey( 'onboarding_token', $response, 'onboard_token should not be present in the response.' ); } /** * Asserts that the jetpack_remote_connect_end is properly hooked */ public function test_remote_connect_hook() { $xml = $this->getMockBuilder( 'Jetpack_IXR_Client' ) ->setMethods( array( 'query', 'isError', 'getResponse', ) ) ->getMock(); $xml->expects( $this->once() ) ->method( 'query' ) ->willReturn( 'sadlkjdasd.sadlikdj' ); $xml->expects( $this->once() ) ->method( 'isError' ) ->willReturn( empty( $error ) ? false : true ); $xml->expects( $this->once() ) ->method( 'getResponse' ) ->willReturn( 'asdadsasd' ); $server = new Jetpack_XMLRPC_Server(); $this->assertSame( 10, has_action( 'jetpack_remote_connect_end', array( 'Jetpack_XMLRPC_Methods', 'remote_connect_end' ) ), 'Action jetpack_remote_connect_end not hooked' ); $server->remote_connect( array( 'nonce' => '1234', 'local_user' => self::$xmlrpc_admin, ), $xml ); $this->assertSame( 1, did_action( 'jetpack_remote_connect_end' ), 'Action was not fired' ); } /** * Tests if the remote_register redirect uri is being filtered */ public function test_remote_register_redirect_uri_filter() { $request = array( 'local_user' => 1, ); // The filter should modify the URI because there's no Connection owner. (see conditions in Jetpack_XMLRPC_Methods::remote_register_redirect_uri). $response = ( new Jetpack_XMLRPC_Server() )->remote_provision( $request ); $expected_uri = Jetpack_XMLRPC_Methods::remote_register_redirect_uri( 'dummy' ); $this->assertNotSame( 'dummy', $expected_uri ); $this->assertSame( $expected_uri, $response['redirect_uri'] ); } /** * Tests if the remote_register redirect uri is not being filtered when conditions do not apply */ public function test_remote_register_redirect_uri_filter_not_applied() { $request = array( 'local_user' => 1, ); ( new Tokens() )->update_user_token( 1, 'asd.qwe.1', true ); // The filter should not modify the URI because there's a Connection owner and sso is not enabled. (see conditions in Jetpack_XMLRPC_Methods::remote_register_redirect_uri). $response = ( new Jetpack_XMLRPC_Server() )->remote_provision( $request ); $not_expected_uri = Jetpack_XMLRPC_Methods::remote_register_redirect_uri( 'dummy' ); $this->assertSame( 'dummy', $not_expected_uri ); $this->assertNotSame( $not_expected_uri, $response['redirect_uri'] ); } }
projects/plugins/jetpack/tests/php/general/test_class.jetpack.php
<?php /** * Tests for the main Jetpack class. * * @package automattic/jetpack * * phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound */ use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\Constants; use Automattic\Jetpack\Partner; use Automattic\Jetpack\Status; use Automattic\Jetpack\Status\Cache as StatusCache; // Extend with a public constructor so that can be mocked in tests class MockJetpack extends Jetpack { /** * Holds the singleton instance of this class * * @var MockJetpack */ public static $instance = false; /** * We are redefining this to overcome the lack of late static binding in the parent Jetpack class. * * @static */ public static function init() { if ( ! self::$instance ) { self::$instance = new self(); } return self::$instance; } public function __construct() { $this->connection_manager = new Connection_Manager(); } } class MockJetpack_XMLRPC_Server extends Jetpack_XMLRPC_Server { private $mockLoginUser = false; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public function __construct( $user ) { $this->mockLoginUser = $user; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } public function login() { return $this->mockLoginUser; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } } /** * Tests for the Jetpack monolith-class. * * @covers Jetpack */ class WP_Test_Jetpack extends WP_UnitTestCase { public static $admin_id = 0; /** * Activated modules. * * @var array */ public static $activated_modules = array(); /** * Deactivated modules. * * @var array */ public static $deactivated_modules = array(); public static function wpSetupBeforeClass() { self::$admin_id = self::factory()->user->create( array( 'role' => 'administrator', ) ); } /** * Set up. */ public function set_up() { parent::set_up(); StatusCache::clear(); } /** * Tear down. */ public function tear_down() { parent::tear_down(); Constants::clear_constants(); StatusCache::clear(); } /** * Make sure that MockJetpack creates separate instances of `Jetpack` and `Automattic\Jetpack\Connection\Manager`. */ public function test_static_binding() { $this->assertNotEquals( spl_object_hash( MockJetpack::init() ), spl_object_hash( Jetpack::init() ) ); $this->assertNotEquals( spl_object_hash( MockJetpack::connection() ), spl_object_hash( Jetpack::connection() ) ); } /** * @author blobaugh * @since 2.3.3 */ public function test_init() { $this->assertInstanceOf( 'Jetpack', Jetpack::init() ); } /** * @author enkrates * @since 3.2 */ public function test_sort_modules_with_equal_sort_values() { $first_file = array( 'sort' => 5 ); $second_file = array( 'sort' => 5 ); $sort_value = Jetpack::sort_modules( $first_file, $second_file ); $this->assertEquals( 0, $sort_value ); } /** * @author enkrates * @since 3.2 */ public function test_sort_modules_with_different_sort_values() { $first_file = array( 'sort' => 10 ); $second_file = array( 'sort' => 5 ); $sort_value = Jetpack::sort_modules( $first_file, $second_file ); $reversed_sort_value = Jetpack::sort_modules( $second_file, $first_file ); $this->assertEquals( 1, $sort_value ); $this->assertEquals( -1, $reversed_sort_value ); } /** * @author georgestephanis */ public function test_absolutize_css_urls_properly_handles_use_cases() { $css = <<<CSS .test-it { background: url(same-dir.png); background: url('same-dir.png'); background: url("same-dir.png"); background: url( same-dir.png ); background: url( 'same-dir.png' ); background: url( "same-dir.png" ); background: url( same-dir.png ); background: url( 'same-dir.png' ); background: url( "same-dir.png" ); background: url(./same-dir.png); background: url(down/down-dir.png); background: url(../up-dir.png); background: url(../../up-2-dirs.png); background: url(/at-root.png); background: url(//other-domain.com/root.png); background: url(https://other-domain.com/root.png); background: url(data:image/gif;base64,eh129ehiuehjdhsa==); } CSS; $expected = <<<EXPECTED .test-it { background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/same-dir.png"); background: url("http://example.com/dir1/dir2/./same-dir.png"); background: url("http://example.com/dir1/dir2/down/down-dir.png"); background: url("http://example.com/dir1/dir2/../up-dir.png"); background: url("http://example.com/dir1/dir2/../../up-2-dirs.png"); background: url("http://example.com/at-root.png"); background: url(//other-domain.com/root.png); background: url(https://other-domain.com/root.png); background: url(data:image/gif;base64,eh129ehiuehjdhsa==); } EXPECTED; $result = Jetpack::absolutize_css_urls( $css, 'http://example.com/dir1/dir2/style.css' ); $this->assertEquals( $expected, $result ); } /* * @author tonykova */ public function test_implode_frontend_css_enqueues_bundle_file_handle() { global $wp_styles; $wp_styles = new WP_Styles(); add_filter( 'jetpack_implode_frontend_css', '__return_true' ); if ( ! file_exists( plugins_url( 'jetpack-carousel.css', __FILE__ ) ) ) { $this->markTestSkipped( 'Required CSS file not found.' ); } // Enqueue some script on the $to_dequeue list $style_handle = 'jetpack-carousel'; wp_enqueue_style( 'jetpack-carousel', plugins_url( 'jetpack-carousel.css', __FILE__ ) ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion Jetpack::init()->implode_frontend_css( true ); $seen_bundle = false; foreach ( $wp_styles->registered as $handle => $handle_obj ) { if ( $style_handle === $handle ) { $expected = ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? "<!-- `{$style_handle}` is included in the concatenated jetpack.css -->\r\n" : ''; $this->assertEquals( $expected, get_echo( array( $wp_styles, 'do_item' ), array( $handle ) ) ); } elseif ( 'jetpack_css' === $handle ) { $seen_bundle = true; } } $this->assertTrue( $seen_bundle ); } /** * @author tonykova * @since 3.2.0 */ public function test_implode_frontend_css_does_not_enqueue_bundle_when_disabled_through_filter() { global $wp_styles; $wp_styles = new WP_Styles(); add_filter( 'jetpack_implode_frontend_css', '__return_false' ); // Enqueue some script on the $to_dequeue list wp_enqueue_style( 'jetpack-carousel', plugins_url( 'jetpack-carousel.css', __FILE__ ) ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion Jetpack::init()->implode_frontend_css(); $seen_orig = false; foreach ( $wp_styles->registered as $handle => $handle_obj ) { $this->assertNotEquals( 'jetpack_css', $handle ); if ( 'jetpack-carousel' === $handle ) { $seen_orig = true; } } $this->assertTrue( $seen_orig ); } public function test_activating_deactivating_modules_fires_actions() { self::reset_tracking_of_module_activation(); add_action( 'jetpack_activate_module', array( __CLASS__, 'track_activated_modules' ) ); add_action( 'jetpack_deactivate_module', array( __CLASS__, 'track_deactivated_modules' ) ); Jetpack::update_active_modules( array( 'stats' ) ); Jetpack::update_active_modules( array( 'stats' ) ); Jetpack::update_active_modules( array( 'json-api' ) ); Jetpack::update_active_modules( array( 'json-api' ) ); $this->assertEquals( self::$activated_modules, array( 'stats', 'json-api' ) ); $this->assertEquals( self::$deactivated_modules, array( 'stats' ) ); remove_action( 'jetpack_activate_module', array( __CLASS__, 'track_activated_modules' ) ); remove_action( 'jetpack_deactivate_module', array( __CLASS__, 'track_deactivated_modules' ) ); } public function test_activating_deactivating_modules_fires_specific_actions() { self::reset_tracking_of_module_activation(); add_action( 'jetpack_activate_module_stats', array( __CLASS__, 'track_activated_modules' ) ); add_action( 'jetpack_deactivate_module_stats', array( __CLASS__, 'track_deactivated_modules' ) ); Jetpack::update_active_modules( array( 'stats' ) ); Jetpack::update_active_modules( array( 'stats' ) ); Jetpack::update_active_modules( array( 'json-api' ) ); Jetpack::update_active_modules( array( 'json-api' ) ); $this->assertEquals( self::$activated_modules, array( 'stats' ) ); $this->assertEquals( self::$deactivated_modules, array( 'stats' ) ); remove_action( 'jetpack_activate_module_stats', array( __CLASS__, 'track_activated_modules' ) ); remove_action( 'jetpack_deactivate_module_stats', array( __CLASS__, 'track_deactivated_modules' ) ); } /** * Test Jetpack::update_active_modules with pre_update_option_jetpack_active_modules filter. * * @author fgiannar */ public function test_activating_deactivating_modules_with_pre_update_filter() { self::reset_tracking_of_module_activation(); add_action( 'jetpack_activate_module', array( __CLASS__, 'track_activated_modules' ) ); add_action( 'jetpack_deactivate_module', array( __CLASS__, 'track_deactivated_modules' ) ); add_filter( 'pre_update_option_jetpack_active_modules', array( __CLASS__, 'filter_pre_update_option_jetpack_active_modules' ), 10, 2 ); Jetpack::update_active_modules( array( 'json-api' ) ); Jetpack::update_active_modules( array( 'json-api' ) ); $this->assertEquals( self::$activated_modules, array( 'json-api', 'stats' ) ); $this->assertEmpty( self::$deactivated_modules ); remove_filter( 'pre_update_option_jetpack_active_modules', array( __CLASS__, 'filter_pre_update_option_jetpack_active_modules' ) ); remove_action( 'jetpack_activate_module', array( __CLASS__, 'track_activated_modules' ) ); remove_action( 'jetpack_deactivate_module', array( __CLASS__, 'track_deactivated_modules' ) ); } public function test_active_modules_filter_restores_state() { self::reset_tracking_of_module_activation(); add_action( 'jetpack_activate_module', array( __CLASS__, 'track_activated_modules' ) ); add_action( 'jetpack_deactivate_module', array( __CLASS__, 'track_deactivated_modules' ) ); add_filter( 'jetpack_active_modules', array( __CLASS__, 'e2e_test_filter' ) ); Jetpack::update_active_modules( array( 'monitor' ) ); $this->assertEquals( self::$activated_modules, array( 'monitor' ) ); $this->assertEquals( self::$deactivated_modules, array() ); // Simce we override the 'monitor' module, verify it does not appear in get_active_modules(). $active_modules = Jetpack::get_active_modules(); $this->assertEquals( $active_modules, array() ); // Verify that activating a new module does not deactivate 'monitor' module. Jetpack::update_active_modules( array( 'stats' ) ); $this->assertEquals( self::$activated_modules, array( 'monitor', 'stats' ) ); $this->assertEquals( self::$deactivated_modules, array() ); remove_filter( 'jetpack_active_modules', array( __CLASS__, 'e2e_test_filter' ) ); // With the module override filter removed, verify that monitor module appears in get_active_modules(). $active_modules = Jetpack::get_active_modules(); $this->assertEquals( $active_modules, array( 'monitor', 'stats' ) ); } // This filter overrides the 'monitor' module. public static function e2e_test_filter( $modules ) { $disabled_modules = array( 'monitor' ); foreach ( $disabled_modules as $module_slug ) { $found = array_search( $module_slug, $modules, true ); if ( false !== $found ) { unset( $modules[ $found ] ); } } return $modules; } public function test_get_other_linked_admins_one_admin_returns_false() { delete_transient( 'jetpack_other_linked_admins' ); $other_admins = Jetpack::get_other_linked_admins(); $this->assertFalse( $other_admins ); $this->assertEquals( 0, get_transient( 'jetpack_other_linked_admins' ) ); } public function test_get_other_linked_admins_more_than_one_not_false() { delete_transient( 'jetpack_other_linked_admins' ); $master_user = self::factory()->user->create( array( 'role' => 'administrator' ) ); $connected_admin = self::factory()->user->create( array( 'role' => 'administrator' ) ); Jetpack_Options::update_option( 'master_user', $master_user ); Jetpack_Options::update_option( 'user_tokens', array( $connected_admin => 'apple.a.' . $connected_admin, $master_user => 'kiwi.a.' . $master_user, ) ); $other_admins = Jetpack::get_other_linked_admins(); $this->assertIsInt( $other_admins ); $this->assertIsInt( get_transient( 'jetpack_other_linked_admins' ) ); } public function test_promoting_admin_clears_other_linked_admins_transient() { set_transient( 'jetpack_other_linked_admins', 2, HOUR_IN_SECONDS ); $editor_user = self::factory()->user->create( array( 'role' => 'editor' ) ); wp_update_user( array( 'ID' => $editor_user, 'role' => 'administrator', ) ); $this->assertFalse( get_transient( 'jetpack_other_linked_admins' ) ); } public function test_demoting_admin_clear_other_linked_admins_transiet() { set_transient( 'jetpack_other_linked_admins', 2, HOUR_IN_SECONDS ); $admin_user = self::factory()->user->create( array( 'role' => 'administrator' ) ); wp_update_user( array( 'ID' => $admin_user, 'role' => 'editor', ) ); $this->assertFalse( get_transient( 'jetpack_other_linked_admins' ) ); } public function test_null_old_roles_clears_linked_admins_transient() { set_transient( 'jetpack_other_linked_admins', 2, HOUR_IN_SECONDS ); $admin_user = self::factory()->user->create( array( 'role' => 'administrator' ) ); wp_update_user( array( 'ID' => $admin_user, 'role' => 'editor', ) ); /** This action is documented in wp-includes/class-wp-user.php */ do_action( 'set_user_role', $admin_user, 'contributor' ); $this->assertFalse( get_transient( 'jetpack_other_linked_admins' ) ); } public function test_changing_non_admin_roles_does_not_clear_other_linked_admins_transient() { set_transient( 'jetpack_other_linked_admins', 2, HOUR_IN_SECONDS ); $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) ); foreach ( array( 'contributor', 'author', 'editor' ) as $role ) { wp_update_user( array( 'ID' => $user_id, 'role' => $role, ) ); } $this->assertEquals( 2, get_transient( 'jetpack_other_linked_admins' ) ); } public function test_other_linked_admins_transient_set_to_zero_returns_false() { set_transient( 'jetpack_other_linked_admins', 0, HOUR_IN_SECONDS ); $this->assertFalse( Jetpack::get_other_linked_admins() ); } public function test_is_dev_version_true_with_alpha() { Constants::set_constant( 'JETPACK__VERSION', '4.3.1-alpha' ); $this->assertTrue( Jetpack::is_development_version() ); } public function test_is_dev_version_true_with_beta() { Constants::set_constant( 'JETPACK__VERSION', '4.3-beta2' ); $this->assertTrue( Jetpack::is_development_version() ); } public function test_is_dev_version_true_with_rc() { Constants::set_constant( 'JETPACK__VERSION', '4.3-rc2' ); $this->assertTrue( Jetpack::is_development_version() ); } public function test_is_dev_version_false_with_number_dot_number() { Constants::set_constant( 'JETPACK__VERSION', '4.3' ); $this->assertFalse( Jetpack::is_development_version() ); } public function test_is_dev_version_false_with_number_dot_number_dot_number() { Constants::set_constant( 'JETPACK__VERSION', '4.3.1' ); $this->assertFalse( Jetpack::is_development_version() ); } /** * Tests is_offline_mode filter. */ public function test_is_offline_mode_filter() { add_filter( 'jetpack_offline_mode', '__return_true' ); $this->assertTrue( ( new Status() )->is_offline_mode() ); remove_filter( 'jetpack_offline_mode', '__return_true' ); } /** * Tests is_offline_mode filter's bool type casting. */ public function test_is_offline_mode_bool() { add_filter( 'jetpack_offline_mode', '__return_zero' ); $this->assertFalse( ( new Status() )->is_offline_mode() ); remove_filter( 'jetpack_offline_mode', '__return_zero' ); } public function test_normalize_url_protocol_agnostic_strips_protocol_and_www_for_subdir_subdomain() { $url = 'https://www.subdomain.myfaketestsite.com/what'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'subdomain.myfaketestsite.com/what/' === $url_normalized ); $url = 'http://subdomain.myfaketestsite.com'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'subdomain.myfaketestsite.com/' === $url_normalized ); $url = 'www.subdomain.myfaketestsite.com'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'subdomain.myfaketestsite.com/' === $url_normalized ); } public function test_normalize_url_protocol_agnostic_strips_protocol_and_www_for_normal_urls() { $url = 'https://www.myfaketestsite.com'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'myfaketestsite.com/' === $url_normalized ); $url = 'www.myfaketestsite.com'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'myfaketestsite.com/' === $url_normalized ); $url = 'myfaketestsite.com'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( 'myfaketestsite.com/' === $url_normalized ); } public function test_normalize_url_protocol_agnostic_strips_protocol_for_ip() { $url = 'http://123.456.789.0'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( '123.456.789.0/' === $url_normalized ); $url = '123.456.789.0'; $url_normalized = Jetpack::normalize_url_protocol_agnostic( $url ); $this->assertTrue( '123.456.789.0/' === $url_normalized ); } /** * Parse the referer on plugin activation and record the activation source * - featured plugins page * - popular plugins page * - search (with query) * - plugins list * - other */ public function test_get_activation_source() { $plugins_url = admin_url( 'plugins.php' ); $plugin_install_url = admin_url( 'plugin-install.php' ); $unknown_url = admin_url( 'unknown.php' ); $this->assertEquals( array( 'list', null ), Jetpack::get_activation_source( $plugins_url . '?plugin_status=all&paged=1&s' ) ); $this->assertEquals( array( 'featured', null ), Jetpack::get_activation_source( $plugin_install_url ) ); $this->assertEquals( array( 'popular', null ), Jetpack::get_activation_source( $plugin_install_url . '?tab=popular' ) ); $this->assertEquals( array( 'recommended', null ), Jetpack::get_activation_source( $plugin_install_url . '?tab=recommended' ) ); $this->assertEquals( array( 'favorites', null ), Jetpack::get_activation_source( $plugin_install_url . '?tab=favorites' ) ); $this->assertEquals( array( 'search-term', 'jetpack' ), Jetpack::get_activation_source( $plugin_install_url . '?s=jetpack&tab=search&type=term' ) ); $this->assertEquals( array( 'search-author', 'foo' ), Jetpack::get_activation_source( $plugin_install_url . '?s=foo&tab=search&type=author' ) ); $this->assertEquals( array( 'search-tag', 'social' ), Jetpack::get_activation_source( $plugin_install_url . '?s=social&tab=search&type=tag' ) ); $this->assertEquals( array( 'unknown', null ), Jetpack::get_activation_source( $unknown_url ) ); } /** * @author tyxla */ public function test_get_assumed_site_creation_date_user_earliest() { $user_id = self::factory()->user->create( array( 'role' => 'administrator', 'user_registered' => '1990-01-01 00:00:00', ) ); $post_id = self::factory()->post->create( array( 'post_date' => '1995-01-01 00:00:00', ) ); $jetpack = new MockJetpack(); $this->assertEquals( '1990-01-01 00:00:00', $jetpack::connection()->get_assumed_site_creation_date() ); wp_delete_user( $user_id ); wp_delete_post( $post_id, true ); } /** * @author tyxla */ public function test_get_assumed_site_creation_date_post_earliest() { $user_id = self::factory()->user->create( array( 'role' => 'administrator', 'user_registered' => '1994-01-01 00:00:00', ) ); $post_id = self::factory()->post->create( array( 'post_date' => '1991-01-01 00:00:00', ) ); $jetpack = new MockJetpack(); $this->assertEquals( '1991-01-01 00:00:00', $jetpack::connection()->get_assumed_site_creation_date() ); wp_delete_user( $user_id ); wp_delete_post( $post_id, true ); } /** * @author tyxla */ public function test_get_assumed_site_creation_date_only_admins() { $admin_id = self::factory()->user->create( array( 'role' => 'administrator', 'user_registered' => '1994-01-01 00:00:00', ) ); $editor_id = self::factory()->user->create( array( 'role' => 'editor', 'user_registered' => '1992-01-01 00:00:00', ) ); $jetpack = new MockJetpack(); $this->assertEquals( '1994-01-01 00:00:00', $jetpack::connection()->get_assumed_site_creation_date() ); wp_delete_user( $admin_id ); wp_delete_user( $editor_id ); } /** * @author ebinnion * @dataProvider get_file_url_for_environment_data_provider */ public function test_get_file_url_for_environment( $min_path, $non_min_path, $is_script_debug, $expected, $not_expected ) { Constants::set_constant( 'SCRIPT_DEBUG', $is_script_debug ); $file_url = Jetpack::get_file_url_for_environment( $min_path, $non_min_path ); $this->assertStringContainsString( $$expected, $file_url ); $this->assertStringNotContainsString( $$not_expected, $file_url ); } public function get_file_url_for_environment_data_provider() { return array( 'script-debug-true' => array( '_inc/build/shortcodes/js/recipes.js', 'modules/shortcodes/js/recipes.js', true, 'non_min_path', 'min_path', ), 'script-debug-false' => array( '_inc/build/shortcodes/js/recipes.js', 'modules/shortcodes/js/recipes.js', false, 'min_path', 'non_min_path', ), ); } /** * @dataProvider get_content_width_data */ public function test_get_content_width( $expected, $content_width ) { $GLOBALS['content_width'] = $content_width; $this->assertSame( $expected, Jetpack::get_content_width() ); } public function get_content_width_data() { return array( 'zero' => array( 0, 0, ), 'int' => array( 100, 100, ), 'numeric_string' => array( '100', '100', ), 'non_numeric_string' => array( false, 'meh', ), 'content_width_not_set' => array( false, null, ), ); } /** * Return a Cyrillic salt. * * @param string $password String to add salt to. * @return string */ public static function cyrillic_salt( $password ) { return 'ленка' . $password . 'пенка'; } /** * Return a Kanji salt. * * @param string $password String to add salt to. * @return string */ public static function kanji_salt( $password ) { return '強熊' . $password . '清珠'; } /** * Filter to increase a string length. * * @param string $password String to expand. * @return string */ public static function multiply_filter( $password ) { for ( $i = 0; $i < 10; $i++ ) { $password .= $password; } return $password; } /** * Reset tracking of module activation. */ public static function reset_tracking_of_module_activation() { self::$activated_modules = array(); self::$deactivated_modules = array(); } /** * Track activated modules. * * @param mixed $module Module. */ public static function track_activated_modules( $module ) { self::$activated_modules[] = $module; } /** * Track deactivated modules. * * @param mixed $module Module. */ public static function track_deactivated_modules( $module ) { self::$deactivated_modules[] = $module; } /** * Hooks the WP pre_update filter on the jetpack_active_modules option to * add 'stats' module to the array. * * @param array $modules An array of Jetpack module slugs. * * @return array An array of Jetpack module slugs */ public static function filter_pre_update_option_jetpack_active_modules( $modules ) { $modules = array_merge( $modules, array( 'stats' ) ); $modules = array_unique( $modules ); $modules = array_values( $modules ); return $modules; } /** * Mocked `setup_xmlrpc_handlers`. * * @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 WP_User|false $user User for the mocked Jetpack_XMLRPC_Server. * @return bool */ private function mocked_setup_xmlrpc_handlers( $request_params, $has_connected_owner, $is_signed, $user = false ) { $GLOBALS['HTTP_RAW_POST_DATA'] = ''; Constants::set_constant( 'XMLRPC_REQUEST', true ); $jetpack = new MockJetpack(); $xmlrpc_server = new MockJetpack_XMLRPC_Server( $user ); return $jetpack::connection()->setup_xmlrpc_handlers( $request_params, $has_connected_owner, $is_signed, $xmlrpc_server ); } /** * Asserts that: * - all of the required xmlrpc methods are in the actual method list. * - all of the actual xmlrpc methods are in the required or allowed lists. * * @param string[] $required List of XML-RPC methods that must be contained in $actual. * @param string[] $allowed Additional list of XML-RPC methods that may be contained in $actual. * Useful for listing methods that are added by modules that may or may * not be active during the test run. * @param string[] $actual The list of XML-RPC methods. */ private function assertXMLRPCMethodsComply( $required, $allowed, $actual ) { $this->assertEquals( array(), array_diff( $required, $actual ) ); $this->assertEquals( array(), array_diff( $actual, $required, $allowed ) ); } /** * Tests the setup of the xmlrpc methods when the site is active, the request is signed, and without a user. * * @group xmlrpc */ public function test_classic_xmlrpc_when_active_and_signed_with_no_user() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), true, true ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true' ) ); $required = array( 'jetpack.verifyAction', 'jetpack.getUser', 'jetpack.remoteRegister', 'jetpack.remoteProvision', 'jetpack.remoteConnect', 'jetpack.jsonAPI', 'jetpack.idcUrlValidation', 'jetpack.unlinkUser', 'jetpack.testConnection', 'jetpack.featuresAvailable', 'jetpack.featuresEnabled', 'jetpack.disconnectBlog', ); $allowed = array( 'jetpack.getHeartbeatData', 'jetpack.syncObject', 'jetpack.updatePublicizeConnections', 'jetpack.getBlog', ); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Tests the setup of the xmlrpc methods when the site is active, the request is signed, and with a user. * * @group xmlrpc */ public function test_classic_xmlrpc_when_active_and_signed_with_user() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), true, true, get_user_by( 'ID', self::$admin_id ) ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true' ) ); $required = array( 'jetpack.verifyAction', 'jetpack.getUser', 'jetpack.remoteRegister', 'jetpack.remoteProvision', 'jetpack.remoteConnect', 'jetpack.jsonAPI', 'jetpack.testAPIUserCode', 'jetpack.disconnectBlog', 'jetpack.unlinkUser', 'jetpack.idcUrlValidation', 'jetpack.testConnection', 'jetpack.featuresAvailable', 'jetpack.featuresEnabled', 'jetpack.syncObject', ); // It's OK if these module-added methods are present (module active in tests). // It's OK if they are not (module inactive in tests). $allowed = array( 'jetpack.subscriptions.subscribe', 'jetpack.updatePublicizeConnections', 'jetpack.getHeartbeatData', ); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Tests the setup of the xmlrpc methods when the site is active, the request is signed, with a user, * and with edit methods enabled. * * @group xmlrpc */ public function test_classic_xmlrpc_when_active_and_signed_with_user_with_edit() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), true, true, get_user_by( 'ID', self::$admin_id ) ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true', 'metaWeblog.editPost' => '__return_true', 'metaWeblog.newMediaObject' => '__return_true', ) ); $required = array( 'jetpack.verifyAction', 'jetpack.getUser', 'jetpack.remoteRegister', 'jetpack.remoteProvision', 'jetpack.remoteConnect', 'jetpack.jsonAPI', 'jetpack.testAPIUserCode', 'jetpack.disconnectBlog', 'jetpack.unlinkUser', 'jetpack.idcUrlValidation', 'jetpack.testConnection', 'jetpack.featuresAvailable', 'jetpack.featuresEnabled', 'metaWeblog.newMediaObject', 'jetpack.updateAttachmentParent', 'jetpack.syncObject', ); // It's OK if these module-added methods are present (module active in tests). // It's OK if they are not (module inactive in tests). $allowed = array( 'jetpack.subscriptions.subscribe', 'jetpack.updatePublicizeConnections', 'jetpack.getHeartbeatData', ); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Tests the setup of the xmlrpc methods when the site is active and the request is not signed. * * @group xmlrpc */ public function test_classic_xmlrpc_when_active_and_not_signed() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), true, false ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true' ) ); $required = array( 'jetpack.remoteAuthorize', 'jetpack.remoteRegister', ); // Nothing else is allowed. $allowed = array(); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Tests the setup of the xmlrpc methods when the site is not active and the request is not signed. * * @group xmlrpc */ public function test_classic_xmlrpc_when_not_active_and_not_signed() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), false, false ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true' ) ); $required = array( 'jetpack.remoteAuthorize', 'jetpack.remoteRegister', 'jetpack.verifyRegistration', ); // Nothing else is allowed. $allowed = array(); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Tests the setup of the xmlrpc methods when the site is not active and the request is signed. * * @group xmlrpc */ public function test_classic_xmlrpc_when_not_active_and_signed() { $this->mocked_setup_xmlrpc_handlers( array( 'for' => 'jetpack' ), false, true ); $methods = apply_filters( 'xmlrpc_methods', array( 'test.test' => '__return_true' ) ); $required = array( 'jetpack.verifyAction', 'jetpack.getUser', 'jetpack.remoteRegister', 'jetpack.remoteProvision', 'jetpack.remoteConnect', 'jetpack.jsonAPI', 'jetpack.disconnectBlog', 'jetpack.unlinkUser', 'jetpack.idcUrlValidation', 'jetpack.testConnection', 'jetpack.featuresAvailable', 'jetpack.featuresEnabled', 'jetpack.syncObject', ); $allowed = array( 'jetpack.subscriptions.subscribe', 'jetpack.updatePublicizeConnections', 'jetpack.getHeartbeatData', ); $this->assertXMLRPCMethodsComply( $required, $allowed, array_keys( $methods ) ); } /** * Test "wp_getOptions_hook_in_place". * * @see https://github.com/Automattic/jetpack/pull/13514 * * @group xmlrpc */ public function test_wp_getOptions_hook_in_place() { $options = apply_filters( 'xmlrpc_blog_options', array() ); $this->assertArrayHasKey( 'jetpack_version', $options ); } /** * Tests if Partner codes are added to the connect url. * * @dataProvider partner_code_provider * * @param string $code_type Partner code type. * @param string $option_name Option and filter name. * @param string $query_string_name Query string variable name. */ public function test_partner_codes_are_added_to_authorize_url( $code_type, $option_name, $query_string_name ) { $test_code = 'abc-123'; Partner::init(); add_filter( $option_name, function () use ( $test_code ) { return $test_code; } ); $jetpack = \Jetpack::init(); $url = $jetpack->build_authorize_url(); $parsed_vars = array(); parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $parsed_vars ); $this->assertArrayHasKey( $query_string_name, $parsed_vars ); $this->assertSame( $test_code, $parsed_vars[ $query_string_name ] ); } /** * Provides code for test_partner_codes_are_added_to_authorize_url. * * @return array */ public function partner_code_provider() { return array( 'subsidiary_code' => array( Partner::SUBSIDIARY_CODE, // Code type. 'jetpack_partner_subsidiary_id', // filter/option key. 'subsidiaryId', // Query string parameter. ), 'affiliate_code' => array( Partner::AFFILIATE_CODE, 'jetpack_affiliate_code', 'aff', ), ); } /** * Tests login URL only adds redirect param when redirect param is in original request. * * @since 8.4.0 * @return void */ public function test_login_url_add_redirect() { $login_url = wp_login_url( '/wp-admin' ); $this->assertFalse( strpos( $login_url, Jetpack::$jetpack_redirect_login ) ); $login_url = wp_login_url( '/wp-admin?' . Jetpack::$jetpack_redirect_login . '=true' ); parse_str( wp_parse_url( $login_url, PHP_URL_QUERY ), $login_parts ); $this->assertArrayHasKey( Jetpack::$jetpack_redirect_login, $login_parts ); $this->assertSame( 'true', $login_parts[ Jetpack::$jetpack_redirect_login ] ); } /** * Tests login redirect sending users to Calypso when redirect param is set. * * @since 8.4.0 * @return void */ public function test_login_init_redirect() { tests_add_filter( 'wp_redirect', function ( $location ) { $expected_location = add_query_arg( array( 'forceInstall' => 1, 'url' => rawurlencode( get_site_url() ), ), 'https://wordpress.com/jetpack/connect' ); $this->assertEquals( $location, $expected_location ); throw new Exception(); // Cause an exception, as we don't want to run exit. } ); // Remove core filters that add headers. remove_filter( 'login_init', 'wp_admin_headers' ); remove_filter( 'login_init', 'send_frame_options_header' ); // Run it once and no exception is thrown. do_action( 'login_init' ); $this->expectException( Exception::class ); $_GET[ Jetpack::$jetpack_redirect_login ] = 'true'; do_action( 'login_init' ); // Now expect an exception. } /** * Tests getting the correct Calypso host. * * @since 8.4.0 * @return void */ public function test_get_calypso_host() { // No env. $this->assertEquals( 'https://wordpress.com/', Jetpack::get_calypso_host() ); $_GET['calypso_env'] = 'development'; $this->assertEquals( 'http://calypso.localhost:3000/', Jetpack::get_calypso_host() ); $_GET['calypso_env'] = 'wpcalypso'; $this->assertEquals( 'https://wpcalypso.wordpress.com/', Jetpack::get_calypso_host() ); $_GET['calypso_env'] = 'horizon'; $this->assertEquals( 'https://horizon.wordpress.com/', Jetpack::get_calypso_host() ); $_GET['calypso_env'] = 'stage'; $this->assertEquals( 'https://wordpress.com/', Jetpack::get_calypso_host() ); $_GET['calypso_env'] = 'production'; $this->assertEquals( 'https://wordpress.com/', Jetpack::get_calypso_host() ); } /** * Tests the Jetpack::should_set_cookie() method. * * @param string $key The state key test value. * @param string $set_screen The $current_screen->base test value. * @param boolean $expected_output The expected output of Jetpack::should_set_cookie(). * * @dataProvider should_set_cookie_provider */ public function test_should_set_cookie( $key, $set_screen, $expected_output ) { global $current_screen; $old_current_screen = $current_screen; $current_screen = new stdClass(); $current_screen->base = $set_screen; $this->assertEquals( $expected_output, Jetpack::should_set_cookie( $key ) ); $current_screen = $old_current_screen; } /** * The data provider for test_should_set_cookie(). Provides an array of * test data. Each data set is an array with the structure: * [0] => The state key test value. * [1] => The $current_screen->base test value. * [2] => The expected output of Jetpack::should_set_cookie(). */ public function should_set_cookie_provider() { return array( array( 'display_update_modal', 'toplevel_page_jetpack', false ), array( 'display_update_modal', 'test_page', true ), array( 'display_update_modal', null, true ), array( 'message', 'toplevel_page_jetpack', true ), array( 'message', 'test_page', true ), array( 'message', null, true ), ); } /** * Testing that a deprecated action triggers Jetpack functionality. * * Using the `jetpack_updated_theme` action for the sake of testing. * * @expectedDeprecated jetpack_updated_theme */ public function test_deprecated_action_fires() { add_action( 'jetpack_updated_theme', '__return_false' ); Jetpack::init()->deprecated_hooks(); remove_action( 'jetpack_updated_theme', '__return_false' ); } /** * Testing that a deprecated filter triggers Jetpack functionality. * * Using the `jetpack_bail_on_shortcode` filter for the sake of testing. * * @expectedDeprecated jetpack_bail_on_shortcode */ public function test_deprecated_filter_fires() { add_filter( 'jetpack_bail_on_shortcode', '__return_false' ); Jetpack::init()->deprecated_hooks(); remove_filter( 'jetpack_bail_on_shortcode', '__return_false' ); } /** * Testing that the 'jetpack_version' option will be removed when Jetpack is deactivated. * * @group jetpack_deactivation */ public function test_jetpack_version_removed_on_jetpack_deactivation() { Jetpack_Options::update_option( 'version', '10.5' ); Jetpack::plugin_deactivation(); $this->assertFalse( Jetpack_Options::get_option( 'version' ) ); } } // end class
projects/plugins/jetpack/tests/php/3rd-party/test_class.jetpack-amp-support.php
<?php /** * Test class for Jetpack_AMP_Support. * * @package automattic/jetpack */ /** * Include the code to test. */ require_once JETPACK__PLUGIN_DIR . '3rd-party/class.jetpack-amp-support.php'; require_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php'; /** * Class WP_Test_Jetpack_AMP_Support */ class WP_Test_Jetpack_AMP_Support extends WP_UnitTestCase { /** * Setup tests. */ public function set_up() { parent::set_up(); add_filter( 'jetpack_is_amp_request', '__return_true' ); } /** * Clean up tests. */ public function tear_down() { remove_filter( 'jetpack_is_amp_request', '__return_true' ); parent::tear_down(); } /** * Test rendering AMP social icons. */ public function test_render_sharing_html() { global $post; $post = self::factory()->post->create_and_get( array( 'post_title' => 'Test post' ) ); // Facebook. $services = array( 'visible' => array( 'facebook' => new Share_Facebook( 'facebook', array() ), ), ); $social_icons = Jetpack_AMP_Support::render_sharing_html( '<div class="sd-content"><ul><li>Facebook</li></ul></div>', $services ); $this->assertEquals( '<div class="sd-content"><amp-social-share type="facebook" height="32px" width="32px" aria-label="Click to share on Facebook" title="Click to share on Facebook" data-param-app_id="249643311490"></amp-social-share></div>', $social_icons ); // Print. $services = array( 'visible' => array( 'print' => new Share_Print( 'print', array() ), ), ); $social_icons = Jetpack_AMP_Support::render_sharing_html( '<div class="sd-content"><ul><li>Print</li></ul></div>', $services ); $this->assertEquals( '<div class="sd-content"><button class="amp-social-share print" on="tap:AMP.print">Print</button></div>', $social_icons ); // Whatsapp. $services = array( 'visible' => array( 'jetpack-whatsapp' => new Jetpack_Share_WhatsApp( 'jetpack-whatsapp', array() ), ), ); $social_icons = Jetpack_AMP_Support::render_sharing_html( '<div class="sd-content"><ul><li>Whatsapp</li></ul></div>', $services ); $this->assertEquals( '<div class="sd-content"><amp-social-share type="whatsapp" height="32px" width="32px" aria-label="Click to share on WhatsApp" title="Click to share on WhatsApp"></amp-social-share></div>', $social_icons ); // Pocket. $services = array( 'visible' => array( 'pocket' => new Share_Pocket( 'pocket', array() ), ), ); $social_icons = Jetpack_AMP_Support::render_sharing_html( '<div class="sd-content"><ul><li>Pocket</li></ul></div>', $services ); $this->assertEquals( '<div class="sd-content"><amp-social-share type="pocket" height="32px" width="32px" aria-label="Click to share on Pocket" title="Click to share on Pocket" data-share-endpoint="https://getpocket.com/save/?url=http%3A%2F%2Fexample.org%2F%3Fp%3D' . $post->ID . '&amp;title=Test%20post"></amp-social-share></div>', $social_icons ); // Reset global post. $post = null; } }
projects/plugins/jetpack/tests/php/3rd-party/test_class-domain-mapping.php
<?php /** * Tests for the 3rd-party domain mapping plugin integration. * * @package automattic/jetpack * @phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound */ namespace Automattic\Jetpack\Third_Party; use Automattic\Jetpack\Constants; require_once JETPACK__PLUGIN_DIR . '3rd-party/class-domain-mapping.php'; /** * Class MockDomainMapping * * Extend with a public constructor so we can test. * * @package automattic/jetpack */ class MockDomainMapping extends Domain_Mapping { /** * MockDomainMapping constructor. */ public function __construct() { } } /** * Class WP_Test_Domain_Mapping * * @package automattic/jetpack */ class WP_Test_Domain_Mapping extends \WP_UnitTestCase { /** * Test Tear down. */ public function tear_down() { Constants::clear_constants(); foreach ( $this->get_jetpack_sync_filters() as $filter ) { remove_all_filters( $filter ); } parent::tear_down(); } /** * Tests that hooks will be hooked when SUNRISE is not true. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::attempt_to_hook_domain_mapping_plugins */ public function test_domain_mapping_should_not_try_to_hook_when_sunrise_disable() { $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'hook_wordpress_mu_domain_mapping', 'hook_wpmu_dev_domain_mapping' ) ) ->disableOriginalConstructor() ->getMock(); // Both of these methods should not be called. $stub->expects( $this->exactly( 0 ) ) ->method( 'hook_wordpress_mu_domain_mapping' ) ->will( $this->returnValue( false ) ); $stub->expects( $this->exactly( 0 ) ) ->method( 'hook_wpmu_dev_domain_mapping' ) ->will( $this->returnValue( false ) ); $stub->attempt_to_hook_domain_mapping_plugins(); } /** * Tests that hooks will only be applied once. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::attempt_to_hook_domain_mapping_plugins */ public function test_domain_mapping_should_stop_search_after_hooking_once() { Constants::set_constant( 'SUNRISE', true ); $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'hook_wordpress_mu_domain_mapping', 'hook_wpmu_dev_domain_mapping' ) ) ->disableOriginalConstructor() ->getMock(); // The first method in the array should be the only one called. $stub->expects( $this->exactly( 1 ) ) ->method( 'hook_wordpress_mu_domain_mapping' ) ->will( $this->returnValue( true ) ); $stub->expects( $this->exactly( 0 ) ) ->method( 'hook_wpmu_dev_domain_mapping' ) ->will( $this->returnValue( false ) ); $stub->attempt_to_hook_domain_mapping_plugins(); } /** * Tests if domain mapping hooks for Domain Mapping when the function does not exists. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::hook_wordpress_mu_domain_mapping */ public function test_domain_mapping_mu_domain_mapping_not_hooked_when_function_not_exists() { Constants::set_constant( 'SUNRISE_LOADED', true ); $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'function_exists' ) ) ->disableOriginalConstructor() ->getMock(); $stub->expects( $this->once() ) ->method( 'function_exists' ) ->will( $this->returnValue( false ) ); $this->assertFalse( $stub->hook_wordpress_mu_domain_mapping() ); foreach ( $this->get_jetpack_sync_filters() as $filter ) { $this->assertFalse( $this->filter_has_hook( $filter ) ); } } /** * Tests if domain mapping hooks for Domain Mapping when the function exists. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::hook_wordpress_mu_domain_mapping */ public function test_domain_mapping_mu_domain_mapping_hooked_when_function_exists() { Constants::set_constant( 'SUNRISE_LOADED', true ); $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'function_exists' ) ) ->disableOriginalConstructor() ->getMock(); $stub->expects( $this->once() ) ->method( 'function_exists' ) ->will( $this->returnValue( true ) ); $this->assertTrue( $stub->hook_wordpress_mu_domain_mapping() ); foreach ( $this->get_jetpack_sync_filters() as $filter ) { $this->assertTrue( $this->filter_has_hook( $filter ) ); } } /** * Tests if domain mapping hooks for WPMU DEV's Domain Mapping when the function doesn't exists. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::hook_wpmu_dev_domain_mapping */ public function test_domain_mapping_wpmu_dev_domain_mapping_not_hooked_when_functions_not_exist() { $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'class_exists', 'method_exists' ) ) ->disableOriginalConstructor() ->getMock(); $stub->expects( $this->once() ) ->method( 'class_exists' ) ->will( $this->returnValue( false ) ); $stub->expects( $this->exactly( 0 ) ) ->method( 'method_exists' ) ->will( $this->returnValue( false ) ); $this->assertFalse( $stub->hook_wpmu_dev_domain_mapping() ); foreach ( $this->get_jetpack_sync_filters() as $filter ) { $this->assertFalse( $this->filter_has_hook( $filter ) ); } } /** * Tests if domain mapping hooks for WPMU DEV's Domain Mapping when the function exists. * * @covers Automattic\Jetpack\Third_Party\Domain_Mapping::hook_wpmu_dev_domain_mapping */ public function test_domain_mapping_wpmu_dev_domain_mapping_hooked_when_functions_exist() { $stub = $this->getMockBuilder( MockDomainMapping::class ) ->setMethods( array( 'class_exists', 'method_exists', 'get_domain_mapping_utils_instance' ) ) ->disableOriginalConstructor() ->getMock(); $stub->expects( $this->once() ) ->method( 'class_exists' ) ->will( $this->returnValue( true ) ); $stub->expects( $this->once() ) ->method( 'method_exists' ) ->will( $this->returnValue( true ) ); $stub->expects( $this->once() ) ->method( 'get_domain_mapping_utils_instance' ) ->will( $this->returnValue( new \stdClass() ) ); $this->assertTrue( $stub->hook_wpmu_dev_domain_mapping() ); foreach ( $this->get_jetpack_sync_filters() as $filter ) { $this->assertTrue( $this->filter_has_hook( $filter ) ); } } /** * Checks if a filter has a particular hook. * * @param string $hook Hook name. * * @return bool */ public function filter_has_hook( $hook ) { global $wp_filter; return isset( $wp_filter[ $hook ] ) && ! empty( $wp_filter[ $hook ] ); } /** * Return array of Jetpack Sync Filters. * * @return string[] */ public function get_jetpack_sync_filters() { return array( 'jetpack_sync_home_url', 'jetpack_sync_site_url', ); } }
projects/plugins/jetpack/tests/php/3rd-party/test__atomic.php
<?php /** * Tests functionality in the atomic.php file. */ use Automattic\Jetpack\Constants; use Automattic\Jetpack\Modules; require_once JETPACK__PLUGIN_DIR . '3rd-party/atomic.php'; /** * Class WP_Test_Atomic_Override_Support */ class WP_Test_Atomic_Override_Support extends WP_UnitTestCase { /** * Clean up tests. */ public function tear_down() { Constants::clear_constants(); parent::tear_down(); } /** * Helper to setup the Atomic constants as needed. */ public function helper__set_atomic_constants() { Constants::set_constant( 'ATOMIC_CLIENT_ID', 999 ); Constants::set_constant( 'ATOMIC_SITE_ID', 999 ); Constants::set_constant( 'JETPACK__VERSION', '10.3-a.1' ); } /** * Test that Development Versions are suppressed on Atomic. */ public function test_atomic_returns_false_on_dev_version() { $this->helper__set_atomic_constants(); $this->assertFalse( Jetpack::is_development_version() ); } /** * Test that Development Versions via the Beta plugin are still considered as Development versions. */ public function test_atomic_returns_true_on_beta_plugin_version() { $this->helper__set_atomic_constants(); Constants::set_constant( 'JETPACK__PLUGIN_DIR', '/srv/www/public/wp-content/plugins/jetpack-dev/' ); $this->assertTrue( Jetpack::is_development_version() ); Constants::clear_single_constant( 'JETPACK__PLUGIN_DIR' ); } /** * Test that Development Versions via the Beta plugin are still considered as Development versions. */ public function test_atomic_returns_expected_if_not_on_atomic() { Constants::set_constant( 'JETPACK__VERSION', '10.3-a.1' ); $this->assertTrue( Jetpack::is_development_version() ); Constants::set_constant( 'JETPACK__VERSION', '10.3.0' ); $this->assertFalse( Jetpack::is_development_version() ); } /** * Test that the WAF is not available on Atomic. */ public function test_atomic_no_waf() { $this->helper__set_atomic_constants(); $this->assertNotContains( 'waf', ( new Modules() )->get_available() ); } }
projects/plugins/jetpack/tests/php/extensions/blocks/test-class.pinterest.php
<?php /** * Pinterest Block tests. * * @package automattic/jetpack */ use Automattic\Jetpack\Extensions\Pinterest; require_once JETPACK__PLUGIN_DIR . '/extensions/blocks/pinterest/pinterest.php'; /** * Pinterest block tests. */ class WP_Test_Pinterest extends \WP_UnitTestCase { /** * Test the Pin type detected for a given Pinterest URL. * * @covers ::Automattic\Jetpack\Extensions\Pinterest\pin_type * @dataProvider get_pinterest_urls * * @since 9.2.0 * * @param null|string $url Pinterest URL. * @param string $expected Pinterest pin type. */ public function test_pin_type( $url, $expected ) { $pin_type = Pinterest\pin_type( $url ); $this->assertSame( $expected, $pin_type ); } /** * URL variations to be used by the Pinterest block. */ public function get_pinterest_urls() { return array( 'null_url' => array( null, '', ), 'empty_url' => array( '', '', ), 'invalid_url' => array( 'abcdefghijk', '', ), 'invalid_protocol' => array( 'file://www.pinterest.com/pin/12345', '', ), 'invalid_subdomain_url' => array( 'https://abc.pinterest.com/pin/12345', '', ), 'invalid_path' => array( 'https://www.pinterest.com/', '', ), 'www_subdomain' => array( 'https://www.pinterest.com/pin/12345', 'embedPin', ), 'locale_subdomain' => array( 'https://in.pinterest.com/pin/12345', 'embedPin', ), 'username_url' => array( 'https://www.pinterest.ca/foo/', 'embedUser', ), 'username_and_board_url' => array( 'https://www.pinterest.ca/foo/bar/', 'embedBoard', ), ); } }
projects/plugins/jetpack/tests/php/extensions/blocks/test-story.php
<?php /** * Story Block tests * * @package automattic/jetpack */ /** * Include the file containing the block's registration and render functions. */ require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/story/story.php'; /** * Story Block tests. * * These tests primarily check that server rendered markup is not changing unexpectedly * when serialized fixtures are updated via the block's JS-based save behaviour. * * The goal is to catch when changes to serialized markup affects server rendering of the block. */ class Story_Block_Test extends \WP_UnitTestCase { /** * A variable to track whether or not the block was already registered before the test was run. * * @access private * * @var boolean */ private $was_registered = false; /** * Setup and ensure the block is registered before running the tests. * * @before */ public function set_up() { parent::set_up(); $this->was_registered = \Automattic\Jetpack\Blocks::is_registered( 'jetpack/story' ); \Automattic\Jetpack\Extensions\Story\register_block(); add_filter( 'get_post_metadata', array( $this, 'get_metadata' ), 10, 2 ); } /** * Teardown and unregister the block if it wasn't registered before running these tests. * * @after */ public function tear_down() { if ( ! $this->was_registered ) { unregister_block_type( 'jetpack/story' ); } remove_filter( 'get_post_metadata', array( $this, 'get_attachment_metadata' ) ); parent::tear_down(); } /** * Mock function to retrieve metadata about some post attachement * * @param mixed $metadata Current metadata value. * @param int $object_id ID of the object. */ public function get_metadata( $metadata, $object_id ) { // Attachment with id 14 represents the videopress media // in `extensions/blocks/story/test/fixtures/jetpack__story__story-with-videopress.html`. if ( 14 === $object_id ) { return array( array( 'width' => 320, 'height' => 640, 'original' => array( 'url' => 'https://videos.files.wordpress.com/xxyyzz/videopress.mp4', ), 'videopress' => array( 'description' => 'This is the video description', 'poster' => 'http://localhost/wp-includes/images/videopress_poster.png', ), ), ); } return $metadata; } /** * Test that the block is registered, which means that it can be registered. */ public function test_block_can_be_registered() { $is_registered = \Automattic\Jetpack\Blocks::is_registered( 'jetpack/story' ); $this->assertTrue( $is_registered ); } /** * This test iterates over the block's serialized fixtures, and tests that the generated * markup matches a fixture for the server rendered markup for the block. * * If no server rendered fixture can be found, then one is created. */ public function test_server_side_rendering_based_on_serialized_fixtures() { $fixtures_path = 'extensions/blocks/story/test/fixtures/'; $file_pattern = '*.serialized.html'; $files = glob( JETPACK__PLUGIN_DIR . $fixtures_path . $file_pattern ); $fail_messages = array(); foreach ( $files as $file ) { $block_markup = trim( file_get_contents( $file ) ); $parsed_blocks = parse_blocks( $block_markup ); $rendered_output = render_block( $parsed_blocks[0] ); $target_markup_filename = str_replace( '.serialized.html', '.server-rendered.html', $file ); // Create a server rendered fixture if one does not exist. if ( ! file_exists( $target_markup_filename ) ) { file_put_contents( $target_markup_filename, $rendered_output ); $fail_messages[] = sprintf( "No server rendered fixture could be found for the %s block's %s fixture\n" . "A fixture file has been created in: %s\n", 'jetpack/story', basename( $file ), $fixtures_path . basename( $target_markup_filename ) ); } $server_rendered_fixture = file_get_contents( $target_markup_filename ); $this->assertEquals( $rendered_output, trim( $server_rendered_fixture ), sprintf( 'The results of render_block for %s called with serialized markup from %s do not match ' . "the server-rendered fixture: %s\n", 'jetpack/story', basename( $file ), basename( $target_markup_filename ) ) ); } // Fail the test if any fixtures were missing, and report that fixtures have been generated. if ( ! empty( $fail_messages ) ) { $this->fail( implode( "\n", $fail_messages ) . "\nTry running this test again. Be sure to commit generated fixture files with any code changes." ); } } }
projects/plugins/jetpack/tests/php/extensions/blocks/class-block-fixture-testcase.php
<?php /** * Jetpack Block Fixture Test Case. * * @package automattic/jetpack */ /** * Jetpack Block Fixture Test Case with method for testing against the block's * serialized HTML test fixtures, generated by the block's `save` method in JavaScript. */ abstract class Jetpack_Block_Fixture_TestCase extends WP_UnitTestCase { /** * This test iterates over the block's serialized fixtures, and tests that the generated * markup matches a fixture for the server rendered markup for the block. * * If no server rendered fixture can be found, then one is created. * * @param string $block_name The name used to register the block (e.g. `jetpack/repeat-visitor`). * @param string $block_slug The slug of the directory containing the code for the block (e.g. `repeat-visitor`). * @param string $target_extension The extension for the target markup of the rendered block. */ public function generate_server_side_rendering_based_on_serialized_fixtures( $block_name, $block_slug, $target_extension = '.server-rendered.html' ) { $fixtures_path = "extensions/blocks/{$block_slug}/test/fixtures/"; $file_pattern = '*.serialized.html'; $files = glob( JETPACK__PLUGIN_DIR . $fixtures_path . $file_pattern ); $fail_messages = array(); foreach ( $files as $file ) { $block_markup = trim( file_get_contents( $file ) ); $parsed_blocks = parse_blocks( $block_markup ); $rendered_output = trim( render_block( $parsed_blocks[0] ) ); $target_markup_filename = str_replace( '.serialized.html', $target_extension, $file ); // Create a server rendered fixture if one does not exist. if ( ! file_exists( $target_markup_filename ) ) { file_put_contents( $target_markup_filename, $rendered_output ); $fail_messages[] = sprintf( "No server rendered fixture could be found for the %s block's %s fixture\n" . "A fixture file has been created in: %s\n", $block_name, basename( $file ), $fixtures_path . basename( $target_markup_filename ) ); } $server_rendered_fixture = file_get_contents( $target_markup_filename ); $this->assertEquals( $rendered_output, trim( $server_rendered_fixture ), sprintf( 'The results of render_block for %s called with serialized markup from %s do not match ' . "the server-rendered fixture: %s\n", $block_name, basename( $file ), basename( $target_markup_filename ) ) ); } // Fail the test if any fixtures were missing, and report that fixtures have been generated. if ( ! empty( $fail_messages ) ) { $this->fail( implode( "\n", $fail_messages ) . "\nTry running this test again. Be sure to commit generated fixture files with any code changes." ); } } }
projects/plugins/jetpack/tests/php/extensions/blocks/test-repeat-visitor.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Repeat Visitor Block tests * * @package automattic/jetpack */ /** * Include the file containing the block's registration and render functions. */ require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/repeat-visitor/repeat-visitor.php'; /** * Include a test case that we can inherit from to make it easier to test against existing fixtures. */ require_once __DIR__ . '/class-block-fixture-testcase.php'; /** * Repeat Visitor Block tests. * * These tests primarily check that server rendered markup is not changing unexpectedly * when serialized fixtures are updated via the block's JS-based save behaviour. * * The goal is to catch when changes to serialized markup affects server rendering of the block. * * Because the Repeat Visitor block can render in two different states depending on the number * of times a visitor has visited the page, in this set of tests, we generate two different kinds * of server-rendered fixtures: a set where the visitor is below the visit threshold, and a set * where the visitor is above the visit threshold. */ class Repeat_Visitor_Block_Test extends \Jetpack_Block_Fixture_TestCase { /** * A variable to track whether or not the block was already registered before the test was run. * * @access private * * @var boolean */ private $was_registered = false; /** * A variable to track the current cookie value of repeat visits. * * @access private * * @var number */ private $original_visit_counter; /** * The name of the block under test. * * @access private * * @var string */ const BLOCK_NAME = 'jetpack/repeat-visitor'; /** * Setup and ensure the block is registered before running the tests. * * @before */ public function set_up() { parent::set_up(); $this->was_registered = \Automattic\Jetpack\Blocks::is_registered( self::BLOCK_NAME ); \Automattic\Jetpack\Extensions\Repeat_Visitor\register_block(); if ( isset( $_COOKIE['jp-visit-counter'] ) ) { $this->original_visit_counter = intval( $_COOKIE['jp-visit-counter'] ); } } /** * Teardown and unregister the block if it wasn't registered before running these tests. * * @after */ public function tear_down() { if ( ! $this->was_registered ) { unregister_block_type( self::BLOCK_NAME ); } if ( isset( $this->original_visit_counter ) ) { $_COOKIE['jp-visit-counter'] = $this->original_visit_counter; } parent::tear_down(); } /** * Test that the block is registered, which means that it can be registered. */ public function test_block_can_be_registered() { $is_registered = \Automattic\Jetpack\Blocks::is_registered( self::BLOCK_NAME ); $this->assertTrue( $is_registered ); } /** * Set the visit counter to zero, and test the serialized fixtures as though the visitor * is below the Repeat Visitor block's threshold. * * This will generate server-rendered fixtures if they do not exist. */ public function test_server_side_rendering_based_on_serialized_fixtures_below_threshold() { $_COOKIE['jp-visit-counter'] = 0; $this->generate_server_side_rendering_based_on_serialized_fixtures( self::BLOCK_NAME, 'repeat-visitor', '.server-rendered-below-threshold.html' ); } /** * Set the visit counter to zero, and test the serialized fixtures as though the visitor * is above the Repeat Visitor block's threshold. * * This will generate server-rendered fixtures if they do not exist. */ public function test_server_side_rendering_based_on_serialized_fixtures_above_threshold() { $_COOKIE['jp-visit-counter'] = 999; $this->generate_server_side_rendering_based_on_serialized_fixtures( self::BLOCK_NAME, 'repeat-visitor', '.server-rendered-above-threshold.html' ); } }
projects/plugins/jetpack/tests/php/extensions/blocks/test-class.opentable.php
<?php /** * OpenTable Block tests. * * @package automattic/jetpack */ use Automattic\Jetpack\Extensions\OpenTable; require_once JETPACK__PLUGIN_DIR . '/extensions/blocks/opentable/opentable.php'; /** * OpenTable block tests */ class WP_Test_OpenTable extends \WP_UnitTestCase { /** * `load_assets` with empty attributes */ public function test_load_assets_with_empty_attributes() { $attributes = array(); $content = OpenTable\load_assets( $attributes ); $this->assertTrue( is_string( $content ) ); } /** * `load_assets` with `rid` attribute set to null */ public function test_load_assets_rid_not_valid() { $attributes = array( 'rid' => null ); $content = OpenTable\load_assets( $attributes ); $this->assertTrue( is_string( $content ) ); } /** * `load_assets` with `rid` as array */ public function test_load_assets_rid_empty_array() { $attributes = array( 'rid' => array() ); $content = OpenTable\load_assets( $attributes ); $this->assertTrue( is_string( $content ) ); } }
projects/plugins/jetpack/tests/php/extensions/blocks/test-business-hours.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Business Hours Block tests * * @package automattic/jetpack */ /** * Include the file containing the block's registration and render functions. */ require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/business-hours/business-hours.php'; /** * Include a test case that we can inherit from to make it easier to test against existing fixtures. */ require_once __DIR__ . '/class-block-fixture-testcase.php'; /** * Business Hours Block tests. * * These tests primarily check that server rendered markup is not changing unexpectedly * when serialized fixtures are updated via the block's JS-based save behaviour. * * The goal is to catch when changes to serialized markup affects server rendering of the block. */ class Business_Hours_Block_Test extends \Jetpack_Block_Fixture_TestCase { /** * A variable to track whether or not the block was already registered before the test was run. * * @access private * * @var boolean */ private $was_registered = false; /** * The name of the block under test. * * @access private * * @var string */ const BLOCK_NAME = 'jetpack/business-hours'; /** * Setup and ensure the block is registered before running the tests. * * @before */ public function set_up() { parent::set_up(); $this->was_registered = \Automattic\Jetpack\Blocks::is_registered( self::BLOCK_NAME ); \Automattic\Jetpack\Extensions\Business_Hours\register_block(); } /** * Teardown and unregister the block if it wasn't registered before running these tests. * * @after */ public function tear_down() { if ( ! $this->was_registered ) { unregister_block_type( 'jetpack/business-hours' ); } parent::tear_down(); } /** * Test that the block is registered, which means that it can be registered. */ public function test_block_can_be_registered() { $is_registered = \Automattic\Jetpack\Blocks::is_registered( self::BLOCK_NAME ); $this->assertTrue( $is_registered ); } /** * This test iterates over the block's serialized fixtures, and tests that the generated * markup matches a fixture for the server rendered markup for the block. * * If no server rendered fixture can be found, then one is created. */ public function test_server_side_rendering_based_on_serialized_fixtures() { $this->generate_server_side_rendering_based_on_serialized_fixtures( self::BLOCK_NAME, 'business-hours', '.server-rendered.html' ); } }
projects/plugins/jetpack/tests/php/extensions/blocks/premium-content/class-test-jetpack-token-subscription-service.php
<?php namespace Tests\Automattic\Jetpack\Extensions\Premium_Content; use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Jetpack_Token_Subscription_Service; // Overrides the way Jetpack_Token_Subscription_Service get its JWT key class Test_Jetpack_Token_Subscription_Service extends Jetpack_Token_Subscription_Service { public function get_key() { return 'whatever'; } }
projects/plugins/jetpack/tests/php/extensions/blocks/premium-content/test_class.jetpack-premium-content.php
<?php require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions.php'; require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/access-check.php'; require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php'; require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php'; require_once __DIR__ . '/class-test-jetpack-token-subscription-service.php'; use Automattic\Jetpack\Extensions\Premium_Content\JWT; use Tests\Automattic\Jetpack\Extensions\Premium_Content\Test_Jetpack_Token_Subscription_Service; use function Automattic\Jetpack\Extensions\Premium_Content\current_visitor_can_access; use function Automattic\Jetpack\Extensions\Premium_Content\subscription_service; use const Automattic\Jetpack\Extensions\Premium_Content\PAYWALL_FILTER; class WP_Test_Jetpack_Premium_Content extends WP_UnitTestCase { protected $product_id = 1234; public function set_up() { parent::set_up(); Jetpack_Subscriptions::init(); add_filter( 'jetpack_is_connection_ready', '__return_true' ); add_filter( PAYWALL_FILTER, function () { return new Test_Jetpack_Token_Subscription_Service(); } ); } public function tear_down() { // Clean up remove_all_filters( 'earn_get_user_subscriptions_for_site_id' ); remove_all_filters( 'jetpack_is_connection_ready' ); remove_all_filters( PAYWALL_FILTER ); parent::tear_down(); } /** * Retrieves payload for JWT token * * @param bool $is_subscribed * @param bool $is_paid_subscriber * @param int|null $subscription_end_date * @return array */ private function get_payload( $is_subscribed, $is_paid_subscriber, $subscription_end_date = null, $status = null ) { $subscriptions = ! $is_paid_subscriber ? array() : array( $this->product_id => array( 'status' => $status ? $status : 'active', 'end_date' => $subscription_end_date ? $subscription_end_date : time() + HOUR_IN_SECONDS, 'product_id' => $this->product_id, ), ); return array( 'blog_sub' => $is_subscribed ? 'active' : 'inactive', 'subscriptions' => $subscriptions, ); } /** * Stubs Jetpack_Token_Subscription_Service in order to return the provided token. * * @param array $payload * @return mixed */ private function set_returned_token( $payload ) { // We remove anything else $service = subscription_service(); $this->assertTrue( is_a( $service, '\Tests\Automattic\Jetpack\Extensions\Premium_Content\Test_Jetpack_Token_Subscription_Service' ) ); $_GET['token'] = JWT::encode( $payload, $service->get_key() ); } private function set_up_users_and_plans() { // We create a paid subscriber $paid_subscriber_id = $this->factory->user->create( array( 'user_email' => 'test-paid@example.com', ) ); $regular_subscriber_id = $this->factory->user->create( array( 'user_email' => 'test-subscriber@example.com', ) ); $non_subscriber_id = $this->factory->user->create( array( 'user_email' => 'test@example.com', ) ); // We create a plan $plan_id = $this->factory->post->create( array( 'post_type' => Jetpack_Memberships::$post_type_plan, ) ); update_post_meta( $plan_id, 'jetpack_memberships_product_id', $this->product_id ); $this->factory->post->create(); // We set the plan to the paid_subscriber_id add_filter( 'earn_get_user_subscriptions_for_site_id', static function ( $subscriptions, $subscriber_id ) use ( $paid_subscriber_id, $plan_id ) { if ( $subscriber_id === $paid_subscriber_id ) { $subscriptions = array_merge( $subscriptions, array( $plan_id ) ); } return $subscriptions; }, 10, 2 ); return array( $non_subscriber_id, $regular_subscriber_id, $paid_subscriber_id, $plan_id ); } /** * Admin has access all the time * * @covers \Automattic\Jetpack\Extensions\Premium_Content\current_visitor_can_access * * @return void */ public function test_access_check_current_visitor_can_access_admin() { $admin_user_id = $this->factory->user->create( array( 'user_email' => 'test-admin@example.com', ) ); get_user_by( 'id', $admin_user_id )->add_role( 'administrator' ); $post_id = $this->factory->post->create(); $GLOBALS['post'] = get_post( $post_id ); wp_set_current_user( $admin_user_id ); $this->assertTrue( current_visitor_can_access( array(), array() ) ); } /** * Test current_visitor_can_access works for different types of users * * @covers \Automattic\Jetpack\Extensions\Premium_Content\current_visitor_can_access * * @return void */ public function test_access_check_current_visitor_can_access_regular_users() { $users_plans = $this->set_up_users_and_plans(); $non_subscriber_id = $users_plans[0]; $regular_subscriber_id = $users_plans[1]; $paid_subscriber_id = $users_plans[2]; $plan_id = $users_plans[3]; $selected_plan_ids = array( $plan_id ); // We setup the token for the regular user wp_set_current_user( $non_subscriber_id ); $payload = $this->get_payload( false, false ); $this->set_returned_token( $payload ); $this->assertFalse( current_visitor_can_access( array( 'selectedPlanIds' => $selected_plan_ids ), array() ) ); // We setup the token for the regular subscriber wp_set_current_user( $regular_subscriber_id ); $payload = $this->get_payload( true, false ); $this->set_returned_token( $payload ); $this->assertFalse( current_visitor_can_access( array( 'selectedPlanIds' => $selected_plan_ids ), array() ) ); // We setup the token for the paid user wp_set_current_user( $paid_subscriber_id ); $payload = $this->get_payload( true, true ); $this->set_returned_token( $payload ); $this->assertTrue( current_visitor_can_access( array( 'selectedPlanIds' => $selected_plan_ids ), array() ) ); } /** * Test that plan id can be passed 2 ways * * @covers \Automattic\Jetpack\Extensions\Premium_Content\current_visitor_can_access * * @return void */ public function test_access_check_current_visitor_can_access_passing_plan_id() { $users_plans = $this->set_up_users_and_plans(); $paid_subscriber_id = $users_plans[2]; $plan_id = $users_plans[3]; wp_set_current_user( $paid_subscriber_id ); $payload = $this->get_payload( true, true ); $this->set_returned_token( $payload ); // We check it fails if the plan is not passed $this->assertFalse( current_visitor_can_access( array(), array() ) ); // The plan id can be passed in 2 ways. $this->assertTrue( current_visitor_can_access( array( 'selectedPlanIds' => array( $plan_id ) ), array() ) ); $this->assertTrue( current_visitor_can_access( array(), (object) array( 'context' => array( 'premium-content/planIds' => array( $plan_id ) ) ) ) ); } }