filename
stringlengths
11
137
content
stringlengths
6
292k
jetpack.php
<?php /** * Plugin Name: Jetpack Monorepo (not a real plugin) * Plugin URI: https://github.com/Automattic/jetpack#jetpack-monorepo * Description: The Jetpack Monorepo is not a plugin. Don't try to use it as one. See the Jetpack Monorepo documentation for instructions on correctly installing Jetpack. * Author: Automattic * Version: 9.5-alpha * Author URI: https://jetpack.com * License: GPL2+ * Text Domain: jetpack * * @package automattic/jetpack * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ // phpcs:disable WordPress.WP.I18n.TextDomainMismatch /** * Notify the admin that the Jetpack Monorepo is not a plugin, * if they tried to install it as one. */ function jetpack_monorepo_is_not_a_plugin() { echo '<div class="notice notice-error"><p>'; printf( wp_kses( /* translators: Link to Jetpack installation instructions. */ __( 'The Jetpack Monorepo is not a plugin, and should not be installed as one. See <a href="%s">the Jetpack Monorepo documentation</a> for instructions on correctly installing Jetpack.', 'jetpack' ), array( 'a' => array( 'href' => array() ), ) ), esc_url( 'https://github.com/Automattic/jetpack#jetpack-monorepo' ) ); echo "</p></div>\n"; } add_action( 'admin_notices', 'jetpack_monorepo_is_not_a_plugin' );
tools/get-wp-version.php
<?php /** * Script to be directly executed to output the latest version of WP. * * @package automattic/jetpack */ $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, 'https://api.wordpress.org/core/version-check/1.7/' ); // Set so curl_exec returns the result instead of outputting it. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // Get the response and close the channel. $response = curl_exec( $ch ); curl_close( $ch ); $versions = json_decode( $response ); $versions = $versions->offers; /** * Sorting available WordPress offers by version number. * * @param object $first WordPress update offer object. * @param object $second WordPress update offer object. * * @return bool|int */ function offer_version_sort( $first, $second ) { return version_compare( $second->version, $first->version ); } uasort( $versions, 'offer_version_sort' ); $version_stack = array(); foreach ( $versions as $offer ) { list( $major, $minor ) = explode( '.', $offer->version ); $base = $major . '.' . $minor; if ( ! isset( $version_stack[ $base ] ) || version_compare( $offer->version, $version_stack[ $base ], '>' ) ) { // There is no version like this yet or there is a newer patch to this major version. $version_stack[ $base ] = $offer->version; } if ( count( $version_stack ) === 2 ) { break; } } $wp_versions = array_values( $version_stack ); if ( empty( $argv[1] ) ) { print $wp_versions[0] . "\n"; } elseif ( '--previous' === $argv[1] ) { print $wp_versions[1] . "\n"; } else { die( 'Unknown argument: ' . $argv[1] . "\n" . "Use with no arguments to get the latest stable WordPress version, or use `--previous' to get the previous stable major release.\n" ); }
tools/check-changelogger-use.php
#!/usr/bin/env php <?php /** * Tool to list whether projects have been touched so as to need a changelog entry. * * @package automattic/jetpack */ // phpcs:disable WordPress.WP.GlobalVariablesOverride chdir( __DIR__ . '/../' ); /** * Display usage information and exit. */ function usage() { global $argv; echo <<<EOH USAGE: {$argv[0]} [--debug|-v] [--list] <base-ref> <head-ref> Checks that a monorepo commit contains a Changelogger change entry for each project touched. --debug, -v Display verbose output. --list Just list projects, no explanatory output. --maybe-merge If unmerged change entries are detected, offer to merge them. <base-ref> Base git ref to compare for changed files. <head-ref> Head git ref to compare for changed files. Exit codes: 0: No change entries are needed. 1: Execution failure of some kind. 2: Projects lack a change entry. 4: Projects have uncommitted change entries. None are missing an entry. 6: Some projects have uncommitted change entries, and some lack a change entry. 8: Change entries were committed. No more change entries are needed. 10: Change entries were committed. Some change entries are still needed. EOH; exit( 1 ); } $exit = 0; $idx = 0; $verbose = false; $list = false; $maybe_merge = false; $base = null; $head = null; for ( $i = 1; $i < $argc; $i++ ) { switch ( $argv[ $i ] ) { case '-v': case '--debug': $verbose = true; break; case '--list': $list = true; break; case '--maybe-merge': $maybe_merge = true; break; case '-h': case '--help': usage(); break; default: if ( ! str_starts_with( $argv[ $i ], '-' ) ) { switch ( $idx++ ) { case 0: $base = $argv[ $i ]; break; case 1: $head = $argv[ $i ]; break; default: fprintf( STDERR, "\e[1;31mToo many arguments.\e[0m\n" ); usage(); } } else { fprintf( STDERR, "\e[1;31mUnrecognized parameter `%s`.\e[0m\n", $argv[ $i ] ); usage(); } break; } } if ( null === $head ) { fprintf( STDERR, "\e[1;31mBase and head refs are required.\e[0m\n" ); usage(); } if ( $verbose ) { /** * Output debug info. * * @param array ...$args Arguments to printf. A newline is automatically appended. */ function debug( ...$args ) { if ( getenv( 'CI' ) ) { $args[0] = "\e[34m{$args[0]}\e[0m\n"; } else { $args[0] = "\e[1;30m{$args[0]}\e[0m\n"; } fprintf( STDERR, ...$args ); } } else { /** * Do not output debug info. */ function debug() { } } if ( $maybe_merge && $list ) { debug( 'Ignoring --maybe-merge, --list was provided' ); $maybe_merge = false; } if ( $maybe_merge && getenv( 'CI' ) ) { debug( 'Ignoring --maybe-merge, running in CI mode' ); $maybe_merge = false; } if ( $maybe_merge && ! ( is_callable( 'posix_isatty' ) && posix_isatty( STDIN ) ) ) { debug( 'Ignoring --maybe-merge, stdin is not a tty' ); $maybe_merge = false; } if ( $maybe_merge ) { $ver = shell_exec( 'git version' ); if ( ! $ver || ! preg_match( '/git version (\d+\.\d+\.\d+)/', $ver, $m ) || // PHP's version_compare is kind of broken, but works for all-numeric versions. version_compare( $m[1], '2.25.0', '<' ) ) { debug( 'Ignoring --maybe-merge, git is unavailable or too old (version 2.25+ is required)' ); $maybe_merge = false; } } // Find projects that use changelogger, and read the relevant config. $changelogger_projects = array(); foreach ( glob( 'projects/*/*/composer.json' ) as $file ) { $data = json_decode( file_get_contents( $file ), true ); if ( 'projects/packages/changelogger/composer.json' !== $file && ! isset( $data['require']['automattic/jetpack-changelogger'] ) && ! isset( $data['require-dev']['automattic/jetpack-changelogger'] ) ) { continue; } $data = isset( $data['extra']['changelogger'] ) ? $data['extra']['changelogger'] : array(); $data += array( 'changelog' => 'CHANGELOG.md', 'changes-dir' => 'changelog', ); $changelogger_projects[ substr( $file, 9, -14 ) ] = $data; } // Process the diff. debug( 'Checking diff from %s...%s.', $base, $head ); $pipes = null; $p = proc_open( sprintf( 'git -c core.quotepath=off diff --no-renames --name-status %s...%s', escapeshellarg( $base ), escapeshellarg( $head ) ), array( array( 'pipe', 'r' ), array( 'pipe', 'w' ), STDERR ), $pipes ); if ( ! $p ) { exit( 1 ); } fclose( $pipes[0] ); $ok_projects = array(); $touched_projects = array(); // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition while ( ( $line = fgets( $pipes[1] ) ) ) { $line = trim( $line ); list( $status, $file ) = explode( "\t", $line, 2 ); $parts = explode( '/', $file, 5 ); if ( count( $parts ) < 4 || 'projects' !== $parts[0] ) { debug( 'Ignoring non-project file %s.', $file ); continue; } $slug = "{$parts[1]}/{$parts[2]}"; if ( ! isset( $changelogger_projects[ $slug ] ) ) { debug( 'Ignoring file %s, project %s does not use changelogger.', $file, $slug ); continue; } if ( $parts[3] === $changelogger_projects[ $slug ]['changelog'] ) { if ( $status === 'A' ) { debug( 'PR adds changelog file %s, this does not count as having a change file.', $file ); } else { debug( 'PR touches changelog file %s, marking %s as having a change file.', $file, $slug ); $ok_projects[ $slug ] = true; continue; } } if ( $parts[3] === $changelogger_projects[ $slug ]['changes-dir'] ) { if ( '.' === $parts[4][0] ) { debug( 'Ignoring changes dir dotfile %s.', $file ); } else { debug( 'PR touches file %s, marking %s as having a change file.', $file, $slug ); $ok_projects[ $slug ] = true; } continue; } debug( 'PR touches file %s, marking %s as touched.', $file, $slug ); if ( ! isset( $touched_projects[ $slug ] ) ) { $touched_projects[ $slug ][] = $file; } } fclose( $pipes[1] ); $status = proc_close( $p ); if ( $status ) { exit( 1 ); } // Check if any projects needing change entries were found. $needed_projects = array_diff_key( $touched_projects, $ok_projects ); if ( ! $needed_projects ) { exit( 0 ); } // Look for unmerged change entry files. debug( 'Checking for unmerged change entry files.' ); $pipes = null; $p = proc_open( 'git -c core.quotepath=off status --no-renames --porcelain', array( array( 'pipe', 'r' ), array( 'pipe', 'w' ), STDERR ), $pipes ); if ( ! $p ) { exit( 1 ); } fclose( $pipes[0] ); $unmerged_projects = array(); // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition while ( ( $line = fgets( $pipes[1] ) ) ) { $file = trim( substr( $line, 3 ) ); $parts = explode( '/', $file, 5 ); if ( count( $parts ) < 4 || 'projects' !== $parts[0] ) { debug( 'Ignoring non-project file %s.', $file ); continue; } $slug = "{$parts[1]}/{$parts[2]}"; if ( ! isset( $changelogger_projects[ $slug ] ) ) { debug( 'Ignoring file %s, project %s does not use changelogger.', $file, $slug ); continue; } if ( $parts[3] === $changelogger_projects[ $slug ]['changes-dir'] && '.' !== $parts[4][0] ) { if ( empty( $needed_projects[ $slug ] ) ) { debug( 'Ignoring unmerged change entry file %s, project %s is already ok.', $file, $slug ); } else { debug( 'Unmerged changes touch change entry file %s, marking %s as having an unmerged change file.', $file, $slug ); $unmerged_projects[ $slug ][] = $file; } continue; } debug( 'Ignoring non-change-entry file %s.', $file ); } fclose( $pipes[1] ); $status = proc_close( $p ); if ( $status ) { exit( 1 ); } // Offer to merge, if applicable. if ( $unmerged_projects && $maybe_merge ) { echo "The following change entry files exist and are needed but are not committed.\n"; echo ' - ' . implode( "\n - ", array_merge( ...( array_values( $unmerged_projects ) ) ) ) . "\n"; echo 'Shall I merge them for you? [Y/n] '; $do_merge = null; while ( $do_merge === null ) { $c = fgets( STDIN ); if ( $c === false || $c === '' ) { $do_merge = false; } else { $c = substr( trim( $c ), 0, 1 ); if ( $c === '' || $c === 'y' || $c === 'Y' ) { $do_merge = true; } elseif ( $c === 'n' || $c === 'N' ) { $do_merge = false; } } } if ( $do_merge ) { foreach ( array( 'add', 'commit -m "Changelog"' ) as $cmd ) { $pipes = null; $p = proc_open( "git --literal-pathspecs $cmd --pathspec-from-file=- --pathspec-file-nul", array( array( 'pipe', 'r' ), STDOUT, STDERR ), $pipes ); if ( ! $p ) { exit( 1 ); } $str = implode( "\0", array_merge( ...( array_values( $unmerged_projects ) ) ) ); while ( $str !== '' ) { $l = fwrite( $pipes[0], $str ); if ( $l === false ) { exit( 1 ); } $str = (string) substr( $str, $l ); } fclose( $pipes[0] ); $status = proc_close( $p ); if ( $status ) { exit( 1 ); } } $ok_projects += $unmerged_projects; $unmerged_projects = array(); $exit |= 8; } } // Output. ksort( $touched_projects ); foreach ( $touched_projects as $slug => $files ) { if ( empty( $ok_projects[ $slug ] ) ) { if ( ! empty( $unmerged_projects[ $slug ] ) ) { $ct = count( $unmerged_projects[ $slug ] ); if ( $ct > 1 ) { $msg = 'Project %s is being changed, and change files %s exist but are not committed!'; $unmerged_projects[ $slug ][ $ct - 1 ] = 'and ' . $unmerged_projects[ $slug ][ $ct - 1 ]; } else { $msg = 'Project %s is being changed, and change file %s exists but is not committed!'; } $msg = sprintf( $msg, $slug, implode( $ct > 2 ? ', ' : ' ', $unmerged_projects[ $slug ] ) ); $msg2 = ''; $exit |= 4; } else { $msg = sprintf( 'Project %s is being changed, but no change file in %s is touched!', $slug, "projects/$slug/{$changelogger_projects[ $slug ]['changes-dir']}/" ); $msg2 = sprintf( "\n\nUse `jetpack changelogger add %s` to add a change file.\nGuidelines: https://github.com/Automattic/jetpack/blob/trunk/docs/writing-a-good-changelog-entry.md", $slug ); $exit |= 2; } if ( $list ) { echo "$slug\n"; } elseif ( getenv( 'CI' ) ) { $msg = strtr( $msg . $msg2, array( "\n" => '%0A' ) ); echo "---\n::error::$msg\n---\n"; } else { echo "\e[1;31m$msg\e[0m\n"; } } } if ( ( $exit & 2 ) && ! getenv( 'CI' ) && ! $list ) { printf( "\e[32mUse `jetpack changelogger add <slug>` to add a change file for each project.\e[0m\n" ); printf( "\e[32mGuidelines: https://github.com/Automattic/jetpack/blob/trunk/docs/writing-a-good-changelog-entry.md\e[0m\n" ); } exit( $exit );
tools/class-jetpack-phpcs-exclude-filter.php
<?php /** * Filter for PHPCS to exclude files in bin/phpcs-excludelist.json. * * @package automattic/jetpack */ use PHP_CodeSniffer\Files\LocalFile; use PHP_CodeSniffer\Util; /** * Filter for PHPCS to exclude files in bin/phpcs-excludelist.json. */ class Jetpack_Phpcs_Exclude_Filter extends Automattic\Jetpack\PhpcsFilter { /** * Files to exclude. * * @var string[]|null */ private $exclude; /** * Load exclusion list, if necessary. */ private function load_exclude() { if ( null !== $this->exclude ) { return; } $lines = json_decode( file_get_contents( __DIR__ . '/phpcs-excludelist.json' ) ); $lines = array_map( function ( $line ) { return $this->filterBaseDir . '/' . $line; }, $lines ); $this->exclude = array_flip( $lines ); } /** * Check whether the current element of the iterator is acceptable. * * @return bool */ public function accept() { if ( ! parent::accept() ) { return false; } $this->load_exclude(); $current = $this->current(); $file = Util\Common::realpath( $current instanceof LocalFile ? $current->getFilename() : $current ); return ! isset( $this->exclude[ $file ] ); } /** * Returns an iterator for the current entry. * * @return \RecursiveIterator */ public function getChildren() { $ret = parent::getChildren(); $ret->exclude = $this->exclude; return $ret; } }
tools/docker/config/wp-tests-config.php
<?php /** * A wp-config for testing. * * @package automattic/jetpack */ /* Path to the WordPress codebase you'd like to test. Add a forward slash in the end. */ define( 'ABSPATH', '/var/www/html/' ); /* * Path to the theme to test with. * * The 'default' theme is symlinked from test/phpunit/data/themedir1/default into * the themes directory of the WordPress installation defined above. */ define( 'WP_DEFAULT_THEME', 'default' ); // Test with multisite enabled. // Alternatively, use the tests/phpunit/multisite.xml configuration file. // phpcs:ignore Squiz.Commenting.InlineComment.InvalidEndChar // define( 'WP_TESTS_MULTISITE', true ); // Force known bugs to be run. // Tests with an associated Trac ticket that is still open are normally skipped. // phpcs:ignore Squiz.Commenting.InlineComment.InvalidEndChar // define( 'WP_TESTS_FORCE_KNOWN_BUGS', true ); // Test with WordPress debug mode (default). define( 'WP_DEBUG', true ); // Enable error logging for tests. define( 'WP_DEBUG_LOG', true ); // Additional constants for better error log. @error_reporting( E_ALL ); // phpcs:ignore @ini_set( 'log_errors', true ); // phpcs:ignore @ini_set( 'log_errors_max_len', '0' ); // phpcs:ignore define( 'WP_DEBUG_DISPLAY', false ); define( 'CONCATENATE_SCRIPTS', false ); define( 'SCRIPT_DEBUG', true ); define( 'SAVEQUERIES', true ); // ** MySQL settings ** // // This configuration file will be used by the copy of WordPress being tested. // wordpress/wp-config.php will be ignored. // WARNING WARNING WARNING! // These tests will DROP ALL TABLES in the database with the prefix named below. // DO NOT use a production database or one that is shared with something else. define( 'DB_NAME', getenv( 'MYSQL_DATABASE' ) ); define( 'DB_USER', getenv( 'MYSQL_USER' ) ); define( 'DB_PASSWORD', getenv( 'MYSQL_PASSWORD' ) ); define( 'DB_HOST', getenv( 'MYSQL_HOST' ) ); define( 'DB_CHARSET', 'utf8' ); define( 'DB_COLLATE', '' ); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} */ define( 'AUTH_KEY', 'put your unique phrase here' ); define( 'SECURE_AUTH_KEY', 'put your unique phrase here' ); define( 'LOGGED_IN_KEY', 'put your unique phrase here' ); define( 'NONCE_KEY', 'put your unique phrase here' ); define( 'AUTH_SALT', 'put your unique phrase here' ); define( 'SECURE_AUTH_SALT', 'put your unique phrase here' ); define( 'LOGGED_IN_SALT', 'put your unique phrase here' ); define( 'NONCE_SALT', 'put your unique phrase here' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited, VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable $table_prefix = 'wptests_'; // Only numbers, letters, and underscores please! define( 'WP_TESTS_DOMAIN', 'example.org' ); define( 'WP_TESTS_EMAIL', 'admin@example.org' ); define( 'WP_TESTS_TITLE', 'Test Blog' ); define( 'WP_PHP_BINARY', 'php' ); define( 'WPLANG', '' );
tools/docker/mu-plugins/offline-mode-force-wpcom-disconnect.php
<?php /** * Plugin Name: Force WPCOM disconnect in Offline Mode * Description: Connection package will skip disconnect on WPCOM in Offline Mode. Due to Monorepo's `DOCKER_REQUEST_URL` trick, we need this plugin to properly detect offline mode in CLI. * Version: 1.0 * Author: Automattic * Author URI: https://automattic.com/ * Text Domain: jetpack * * @package automattic/jetpack */ /** * Force WPCOM disconnect in CLI, because CLI is always in Offline Mode in Monorepo. * * @param bool $force The decision made earlier in the filter stack. * * @return bool */ function jetpack_docker_offline_mode_force_wpcom_disconnect( $force ) { return $force || ( defined( 'WP_CLI' ) && WP_CLI && defined( 'DOCKER_REQUEST_URL' ) ); } add_filter( 'jetpack_connection_disconnect_site_wpcom_offline_mode', 'jetpack_docker_offline_mode_force_wpcom_disconnect' );
tools/docker/mu-plugins/01-monorepo.php
<?php /** * Plugin Name: Monorepo Helper * Description: A common place for monorepo things. * Version: 1.0 * Author: Automattic * Author URI: https://automattic.com/ * Text Domain: jetpack * * @package automattic/jetpack */ namespace Jetpack\Docker\MuPlugin; /** * Monorepo Tools. */ class Monorepo { /** * Path to monorepo. * * @var string */ protected $monorepo; /** * Path to monorepo plugins. * * @var string */ protected $plugins; /** * Path to monorepo packages. * * @var string */ protected $packages; /** * Class constructor. */ public function __construct() { /** * Filter the monorepo path for development environments. * * @since $$next-version$$ * * @param string $path Monorepo file path. */ $this->monorepo = apply_filters( 'jetpack_monorepo_path', '/usr/local/src/jetpack-monorepo/' ); $this->plugins = $this->monorepo . 'projects/plugins/'; $this->packages = $this->monorepo . 'projects/packages/'; } /** * Property Getter * * @param string $var Property to get. * * @throws Exception If the requested property does not exist. */ public function get( $var ) { if ( is_string( $var ) && isset( $this->$var ) ) { return $this->$var; } throw new Exception( "Class property $var does not exist." ); } /** * The same as Core's get_plugins, without forcing a passed value to be within the wp-content/plugins folder. * * @param string $plugin_folder Folder to find plugins within. */ private function get_plugins( $plugin_folder = '' ) { $cache_plugins = wp_cache_get( 'monorepo_plugins', 'monorepo_plugins' ); // Updated cache values to not conflict. if ( ! $cache_plugins ) { $cache_plugins = array(); } if ( isset( $cache_plugins[ $plugin_folder ] ) ) { return $cache_plugins[ $plugin_folder ]; } $wp_plugins = array(); $plugin_root = WP_PLUGIN_DIR; if ( ! empty( $plugin_folder ) ) { $plugin_root = $plugin_folder; // This is what we changed, but it's dangerous. Thus a private function. } // Files in wp-content/plugins directory. $plugins_dir = @opendir( $plugin_root ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $plugin_files = array(); if ( $plugins_dir ) { while ( ( $file = readdir( $plugins_dir ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition if ( '.' === substr( $file, 0, 1 ) ) { continue; } if ( is_dir( $plugin_root . '/' . $file ) ) { $plugins_subdir = @opendir( $plugin_root . '/' . $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( $plugins_subdir ) { while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition if ( '.' === substr( $subfile, 0, 1 ) ) { continue; } if ( '.php' === substr( $subfile, -4 ) ) { $plugin_files[] = "$file/$subfile"; } } closedir( $plugins_subdir ); } } else { if ( '.php' === substr( $file, -4 ) ) { $plugin_files[] = $file; } } } closedir( $plugins_dir ); } if ( empty( $plugin_files ) ) { return $wp_plugins; } require_once ABSPATH . 'wp-admin/includes/plugin.php'; foreach ( $plugin_files as $plugin_file ) { if ( ! is_readable( "$plugin_root/$plugin_file" ) ) { continue; } // Do not apply markup/translate as it will be cached. $plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false ); if ( empty( $plugin_data['Name'] ) ) { continue; } $wp_plugins[ plugin_basename( $plugin_file ) ] = $plugin_data; } uasort( $wp_plugins, '_sort_uname_callback' ); $cache_plugins[ $plugin_folder ] = $wp_plugins; wp_cache_set( 'monorepo_plugins', $cache_plugins, 'monorepo_plugins' ); // Updated cache values to not conflict. return $wp_plugins; } /** * Returns an array of monorepo plugins. * * @return array Array of monorepo plugins. */ public function plugins() { return array_keys( $this->get_plugins( $this->plugins ) ); } }
tools/docker/mu-plugins/fix-monorepo-plugins-url.php
<?php /** * Plugin Name: Fix monorepo plugins_url * Description: In the Jetpack Docker dev environment, plugins_url fails for packages becuase the symlinks from vendor cause it to be unable to find the "plugin" that the URL is supposed to be relative to. * Version: 1.0 * Author: Automattic * Author URI: https://automattic.com/ * Text Domain: jetpack * * @package automattic/jetpack */ namespace Jetpack\Docker\MuPlugin\FixMonorepoPluginsUrl; use Jetpack\Docker\MuPlugin\Monorepo; // This allows us to use the most unstable version of packages, e.g. the monorepo versions. if ( ! defined( 'JETPACK_AUTOLOAD_DEV' ) ) { define( 'JETPACK_AUTOLOAD_DEV', true ); } /** * Fix the plugins_url in the Docker dev environment. * * @param string $url The complete URL to the plugins directory including scheme and path. * @param string $path Path relative to the URL to the plugins directory. Blank string * if no path is specified. * @param string $plugin The plugin file path to be relative to. Blank string if no plugin * is specified. * @return string Filtered URL */ function jetpack_docker_plugins_url( $url, $path, $plugin ) { global $wp_plugin_paths; $packages = ( new Monorepo() )->get( 'packages' ); if ( strpos( $url, $packages ) !== false && strpos( $plugin, $packages ) === 0 ) { // Look through available monorepo plugins until we find one with the plugin symlink. $suffix1 = '/jetpack_vendor/automattic/jetpack-' . substr( $plugin, strlen( $packages ) ); $suffix2 = '/vendor/automattic/jetpack-' . substr( $plugin, strlen( $packages ) ); $real_plugin = realpath( $plugin ); if ( false !== $real_plugin ) { foreach ( $wp_plugin_paths as $dir ) { if ( realpath( $dir . $suffix1 ) === $real_plugin ) { return plugins_url( $path, $dir . $suffix1 ); } if ( realpath( $dir . $suffix2 ) === $real_plugin ) { return plugins_url( $path, $dir . $suffix2 ); } } } } return $url; } add_filter( 'plugins_url', __NAMESPACE__ . '\jetpack_docker_plugins_url', 1, 3 );
tools/docker/mu-plugins/debug.php
<?php /** * Plugin Name: Automattic Debug Helpers * Description: <code>l( 'Code is Poetry' )</code> * Version: 1.0 * Author: Automattic * Author URI: https://automattic.com/ * Text Domain: jetpack * * @package automattic/jetpack */ // phpcs:disable WordPress.PHP.DevelopmentFunctions /** * Sweet error logging * * The first call of l() will print an extra line containing a random ID & PID * and the script name or URL. The ID prefixes every l() log entry thereafter. * The extra line and ID will help you to identify and correlate log entries. * * l($something_to_log); // error_log(print_r($something_to_log, true)); * l(compact('v1','v2'); // log several variables with labels * l($thing5, $thing10); // log two things * l(); // log the file:line * l(null, $stuff, $ba); // log the file:line, then log two things. * * Example: * wpsh> l('yo') * wpsh> l('dude') * /tmp/php-errors: * [21-Jun-2012 14:45:13] 1566-32201 => /home/wpcom/public_html/bin/wpshell/wpshell.php * [21-Jun-2012 14:45:13] 1566-32201 yo * [21-Jun-2012 14:50:23] 1566-32201 dude * * l() returns its input so you can safely wrap most kinds of expressions to log them. * l($arg1, $arg2) will call l($arg1) and l($arg2) and then return $arg1. * * A null argument will log the file and line number of the l() call. * * @param mixed $stuff Information to log. */ function l( $stuff = null ) { // Do nothing when debugging is off. if ( ! defined( 'WP_DEBUG' ) || WP_DEBUG === false ) { return $stuff; } static $pageload; // Call l() on each argument. if ( func_num_args() > 1 ) { foreach ( func_get_args() as $arg ) { // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection l( $arg ); } return $stuff; } if ( ! isset( $pageload ) ) { $pageload = substr( md5( wp_rand() ), 0, 4 ); if ( ! empty( $_SERVER['argv'] ) ) { $hint = implode( ' ', array_map( 'filter_var', wp_unslash( $_SERVER['argv'] ) ) ); } elseif ( isset( $_SERVER['HTTP_HOST'] ) && isset( $_SERVER['REQUEST_URI'] ) ) { $hint = filter_var( wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ); } else { $hint = php_sapi_name(); } error_log( sprintf( '[%s-%s => %s]', $pageload, getmypid(), $hint ) ); } $pid = $pageload . '-' . getmypid(); if ( $stuff === null ) { // Log the file and line number. $backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection while ( isset( $backtrace[1]['function'] ) && __FUNCTION__ === $backtrace[1]['function'] ) { array_shift( $backtrace ); } $log = sprintf( '%s line %d', $backtrace[0]['file'], $backtrace[0]['line'] ); } elseif ( is_bool( $stuff ) ) { $log = $stuff ? 'TRUE' : 'FALSE'; } elseif ( is_scalar( $stuff ) ) { // Strings and numbers can be logged exactly. $log = $stuff; } else { /* * Are we in an output buffer handler? * If so, print_r($stuff, true) is fatal so we must avoid that. * This is not as slow as it looks: <1ms when !$in_ob_handler. * Using json_encode_pretty() all the time is much slower. */ do { $in_ob_handler = false; $ob_status = ob_get_status( true ); $obs = array(); if ( ! $ob_status ) { break; } foreach ( $ob_status as $ob ) { $obs[] = $ob['name']; } // This is not perfect: anonymous handlers appear as default. if ( array( 'default output handler' ) === $obs ) { break; } $backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection $bts = array(); foreach ( $backtrace as $level ) { $caller = ''; if ( isset( $level['class'] ) ) { $caller = $level['class'] . '::'; } $caller .= $level['function']; $bts[] = $caller; } if ( array_intersect( $obs, $bts ) ) { $in_ob_handler = true; } } while ( false ); if ( $in_ob_handler ) { $log = l_json_encode_pretty( $stuff ); } else { $log = print_r( $stuff, true ); } } error_log( sprintf( '[%s] %s', $pid, $log ) ); return $stuff; } /** * Log only once (suppresses logging on subsequent calls from the same file+line). * * @param mixed $stuff Information to log. */ function lo( $stuff ) { static $callers = array(); $args = func_get_args(); $backtrace = debug_backtrace( false ); $caller = md5( $backtrace[0]['file'] . $backtrace[0]['line'] ); if ( isset( $callers[ $caller ] ) ) { return $stuff; } $callers[ $caller ] = true; return call_user_func_array( 'l', $args ); } /** * Pretty print for JSON (stolen from public.api) * * Previously, this function actually did stuff, but since JSON_PRETTY_PRINT is available as of PHP 5.4, let's use that. * * @param mixed $data Data to encode. * * @return false|string */ function l_json_encode_pretty( $data ) { return wp_json_encode( $data, JSON_PRETTY_PRINT ); } /** * A timer. * * Call once to start, call again to stop. Returns a float. * Calling e($name) with different names permits simultaneous timers. * * e('stuff'); * do_stuff(); * $elapsed = e('stuff'); * * @param string $name Timer name. * * @return mixed void or elapsed time. */ function e( $name = '' ) { static $times = array(); if ( ! array_key_exists( $name, $times ) ) { $times[ $name ] = microtime( true ); return; } $elapsed = microtime( true ) - $times[ $name ]; unset( $times[ $name ] ); return $elapsed; } /** * A wrapper for e() which also logs the result with l(). * * Each log entry begins with a tag common to that pageload. * You can save a keystroke by calling e() then el(). * * e($name); * do_stuff(); * el($name); * * @param string $name Timer name. */ function el( $name = '' ) { $elapsed = e( $name ); if ( null !== $elapsed ) { l( sprintf( "%9.6f e('%s')", $elapsed, $name ) ); } return $elapsed; } /** * A persistent timer. After the initial call, each call to t() * will log the file:line and time elapsed since the initial call. */ function t() { static $start; $now = microtime( true ); if ( ! isset( $start ) ) { $start = $now; } $backtrace = debug_backtrace( false ); while ( isset( $backtrace[1]['function'] ) && __FUNCTION__ === $backtrace[1]['function'] ) { array_shift( $backtrace ); } $file = $backtrace[0]['file']; $line = $backtrace[0]['line']; $format = 't() => %9.6f at %s line %d'; $elapsed = $now - $start; l( sprintf( $format, $elapsed, $file, $line ) ); } // phpcs:enable
tools/docker/mu-plugins/avoid-plugin-deletion.php
<?php /** * Plugin Name: Disable deleting and updating Jetpack * Description: Disable deleting and updating -actions for Jetpack plugin. Being able to delete your local development directory from WordPress is catastrophic and you can lose your git history in the process. * Version: 2.0 * Author: Automattic * Author URI: https://automattic.com/ * Text Domain: jetpack * * @package automattic/jetpack */ use Jetpack\Docker\MuPlugin\Monorepo; /** * Remove the Delete link from your plugins list for important plugins * * @param string[] $actions An array of plugin action links. By default this can include 'activate', * 'deactivate', and 'delete'. With Multisite active this can also include * 'network_active' and 'network_only' items. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * 'recently_activated', 'upgrade', 'mustuse', 'dropins', and 'search'. * * @return mixed */ function jetpack_docker_disable_plugin_deletion_link( $actions, $plugin_file ) { $jetpack_docker_avoided_plugins = apply_filters( 'jetpack_docker_avoided_plugins', ( new Monorepo() )->plugins() ); if ( array_key_exists( 'delete', $actions ) && in_array( $plugin_file, $jetpack_docker_avoided_plugins, true ) ) { unset( $actions['delete'] ); } return $actions; } add_filter( 'plugin_action_links', 'jetpack_docker_disable_plugin_deletion_link', 10, 2 ); /** * Fail deletion attempts of our important plugins * * @param string $plugin_file Path to the plugin file relative to the plugins directory. */ function jetpack_docker_disable_delete_plugin( $plugin_file ) { $jetpack_docker_avoided_plugins = apply_filters( 'jetpack_docker_avoided_plugins', ( new Monorepo() )->plugins() ); if ( in_array( $plugin_file, $jetpack_docker_avoided_plugins, true ) ) { wp_die( esc_html( 'Deleting plugin "' . $plugin_file . '" is disabled at mu-plugins/avoid-plugin-deletion.php' ), 403 ); } } add_action( 'delete_plugin', 'jetpack_docker_disable_delete_plugin', 10, 2 ); /** * Stop WordPress noticing plugin updates for important plugins. * * @param mixed $plugins Value of site transient. */ function jetpack_docker_disable_plugin_update( $plugins ) { $jetpack_docker_avoided_plugins = apply_filters( 'jetpack_docker_avoided_plugins', ( new Monorepo() )->plugins() ); if ( ! is_array( $jetpack_docker_avoided_plugins ) ) { return $plugins; } foreach ( $jetpack_docker_avoided_plugins as $avoided_plugin ) { if ( isset( $plugins->response[ $avoided_plugin ] ) ) { unset( $plugins->response[ $avoided_plugin ] ); } } return $plugins; } add_filter( 'site_transient_update_plugins', 'jetpack_docker_disable_plugin_update' );
tools/e2e-commons/plugins/e2e-beta-autoupdate-api.php
<?php /** * Plugin Name: E2E Jetpack Beta Autoupdate API * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } use Automattic\JetpackBeta\Utils; /** * Class E2eJetpackBetaAutoupdateApi */ class E2eJetpackBetaAutoupdateApi { /** * E2eJetpackBetaAutoupdateApi constructor. */ public function __construct() { add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) ); } /** * Register the REST API routes. */ public static function register_rest_routes() { register_rest_route( 'jp-e2e/v1', '/beta-autoupdate', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => __CLASS__ . '::trigger_autoupdate', 'permission_callback' => __CLASS__ . '::autoupdate_permissions_check', ) ); } /** * Callback for the /beta-autoupdate endpoint. */ public static function trigger_autoupdate() { $result = array( 'is_set_to_autoupdate' => false ); if ( Utils::is_set_to_autoupdate() ) { $result['is_set_to_autoupdate'] = true; $plugins = array_keys( Utils::plugins_needing_update() ); if ( ! $plugins ) { $result['plugins_needing_update'] = false; } else { $result['plugins_needing_update'] = $plugins; wp_schedule_single_event( time() + 10, 'jetpack_beta_autoupdate_hourly_cron' ); } } return rest_ensure_response( $result ); } /** * Check if the current user has permission to trigger autoupdates. */ public static function autoupdate_permissions_check() { require_once ABSPATH . 'wp-admin/includes/plugin.php'; if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_plugins', __( 'Sorry, you are not allowed to manage plugins for this site.', 'e2e' ), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch array( 'status' => rest_authorization_required_code() ) ); } return true; } } new E2eJetpackBetaAutoupdateApi();
tools/e2e-commons/plugins/e2e-waf-data-interceptor.php
<?php /** * Plugin Name: Jetpack E2E waf data interceptor * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ add_filter( 'pre_http_request', 'e2e_intercept_waf_data_request', 1, 3 ); /** * Intercept WPCOM waf data request and replaces it with mocked data * * @param result $return result. * @param r $r not used. * @param string $url request URL. */ function e2e_intercept_waf_data_request( $return, $r, $url ) { if ( ! class_exists( 'Jetpack_Options' ) ) { return $return; } $site_id = Jetpack_Options::get_option( 'id' ); if ( empty( $site_id ) ) { return $return; } if ( 1 === preg_match( sprintf( '/\/sites\/%d\/waf-rules/', $site_id ), $url ) ) { $rules = <<<'RULES' <?php $rule = (object) array( 'id' => 941110, 'reason' => '', 'tags' => array ( 0 => 'application-multi', 1 => 'language-multi', 2 => 'platform-multi', 3 => 'attack-xss', 4 => 'paranoia-level/1', 5 => 'owasp_crs', 6 => 'capec/1000/152/242', ) ); try { if($waf->match_targets(array ( ),array ( 'request_cookies' => array ( 'except' => array ( 0 => '/__utm/', ), ), 'request_cookies_names' => array ( ), 'request_filename' => array ( ), 'request_headers' => array ( 'only' => array ( 0 => 'user-agent', 1 => 'referer', ), ), 'args_names' => array ( ), 'args' => array ( ), ),'rx','#(?i)<script[^>]*>[\\s\\S]*?#Ds',false,true)) { $waf->inc_var('tx.xss_score',htmlentities($waf->get_var('tx.critical_anomaly_score'), ENT_QUOTES, 'UTF-8') ); $waf->inc_var('tx.anomaly_score_pl1',htmlentities($waf->get_var('tx.critical_anomaly_score'), ENT_QUOTES, 'UTF-8') ); $rule->reason = 'XSS Filter - Category 1: Script Tag Vector Matched Data: '.htmlentities($waf->get_var('tx.0'), ENT_QUOTES, 'UTF-8') .' found within '. htmlentities($waf->matched_var_name, ENT_QUOTES, 'UTF-8') .': '. htmlentities($waf->matched_var, ENT_QUOTES, 'UTF-8') ; return $waf->block('block',$rule->id,$rule->reason,403); } } catch ( \Throwable $t ) { error_log( 'Rule ' . $rule->id . ' failed: ' . $t ); } catch ( \Exception $e ) { error_log( 'Rule ' . $rule->id . ' failed: ' . $e ); } RULES; return array( 'response' => array( 'code' => 200 ), 'body' => wp_json_encode( array( 'data' => $rules, ) ), ); } return $return; }
tools/e2e-commons/plugins/e2e-plan-data-interceptor.php
<?php /** * Plugin Name: Jetpack E2E plan data interceptor * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ add_filter( 'pre_http_request', 'e2e_intercept_plan_data_request', 1, 3 ); /** * Intercept WPCOM plan data request and replaces it with mocked data * * @param result $return result. * @param r $r not used. * @param string $url request URL. */ function e2e_intercept_plan_data_request( $return, $r, $url ) { if ( ! class_exists( 'Jetpack_Options' ) ) { return $return; } $site_id = Jetpack_Options::get_option( 'id' ); if ( empty( $site_id ) ) { return $return; } // match both /sites/$site_id && /sites/$site_id? urls. if ( 1 === preg_match( sprintf( '/\/sites\/%d($|\?)/', $site_id ), $url ) ) { $plan_data = get_option( 'e2e_jetpack_plan_data' ); if ( empty( $plan_data ) ) { return $return; } delete_option( 'jetpack_active_plan' ); return array( 'response' => array( 'code' => 200 ), 'body' => $plan_data, ); } if ( false !== stripos( $url, sprintf( '/sites/%d/wordads/status', $site_id ) ) ) { $site_url = site_url(); $json_data = sprintf( '{"ID":%d,"name":"E2E Testing","URL":"%s","approved":true,"active":true,"house":true,"unsafe":false,"status":false}', $site_id, $site_url ); return array( 'response' => array( 'code' => 200 ), 'body' => $json_data, ); } return $return; }
tools/e2e-commons/plugins/e2e-search-test-helper.php
<?php /** * Plugin Name: Jetpack Search E2E Helper * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ add_filter( 'pre_http_request', 'e2e_jetpack_search_intercept_plan_data_request', 3, 3 ); add_action( 'wp_footer', 'e2e_jetpack_search_maybe_show_link_in_footer' ); /** * Intercept WPCOM plan data request and replaces it with mocked data * * @param result $return result. * @param r $r not used. * @param string $url request URL. */ function e2e_jetpack_search_intercept_plan_data_request( $return, $r, $url ) { if ( ! class_exists( 'Jetpack_Options' ) ) { return $return; } $site_id = Jetpack_Options::get_option( 'id' ); if ( empty( $site_id ) ) { return $return; } if ( false !== stripos( $url, sprintf( '/sites/%d/jetpack-search/plan', $site_id ) ) ) { return array( 'response' => array( 'code' => 200 ), 'body' => '{"search_subscriptions":[{"ID":"123","user_id":"123","blog_id":"123","product_id":"2130","expiry":"0000-00-00","subscribed_date":"2022-11-1523:35:45","renew":false,"auto_renew":false,"ownership_id":"123","most_recent_renew_date":"","subscription_status":"active","product_name":"JetpackSearchFree","product_name_en":"JetpackSearchFree","product_slug":"jetpack_search_free","product_type":"search","cost":0,"currency":"USD","bill_period":"-1","available":"yes","multi":false,"support_document":null,"is_instant_search":true,"tier":null}],"effective_subscription":{"ID":"123","user_id":"123","blog_id":"123","product_id":"2130","expiry":"0000-00-00","subscribed_date":"2022-11-1523:35:45","renew":false,"auto_renew":false,"ownership_id":"36306380","most_recent_renew_date":"","subscription_status":"active","product_name":"JetpackSearchFree","product_name_en":"JetpackSearchFree","product_slug":"jetpack_search_free","product_type":"search","cost":0,"currency":"USD","bill_period":"-1","available":"yes","multi":false,"support_document":null,"is_instant_search":true,"tier":null},"supports_instant_search":true,"supports_only_classic_search":false,"supports_search":true,"default_upgrade_bill_period":"yearly","tier_maximum_records":5000,"plan_usage":{"months_over_plan_requests_limit":0,"months_over_plan_records_limit":0,"num_requests_3m_median":0,"num_requests_3m":[{"start_date":"2022-10-15","end_date":"2022-11-14","num_requests":0},{"start_date":"2022-09-15","end_date":"2022-10-14","num_requests":0},{"start_date":"2022-08-15","end_date":"2022-09-14","num_requests":0}],"num_records":625,"should_upgrade":false,"must_upgrade":false,"upgrade_reason":{"records":false,"requests":false}},"plan_current":{"record_limit":5000,"monthly_search_request_limit":500}}', ); } return $return; } /** * Output a link for E2E tests * * @return void */ function e2e_jetpack_search_maybe_show_link_in_footer() { if ( isset( $_GET['jetpack_search_link_in_footer'] ) ) { echo '<a href="#" class="wp-button jetpack-search-filter__link">Click to search</a>'; } }
tools/e2e-commons/plugins/e2e-wpcom-request-interceptor.php
<?php /** * Plugin Name: WPCOM Request Tracker * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ add_filter( 'pre_http_request', 'e2e_intercept_wpcom_request', -999, 3 ); /** * Intercept WPCOM request. * * @param result $return result. * @param r $r not used. * @param string $url request URL. */ function e2e_intercept_wpcom_request( $return, $r, $url ) { $url_host = wp_parse_url( $url, PHP_URL_HOST ); if ( 'public-api.wordpress.com' === $url_host ) { $transient_name = 'wpcom_request_counter'; $transient_value = get_transient( $transient_name ); if ( false === $transient_value ) { $transient_value = 1; } else { ++$transient_value; } set_transient( $transient_name, $transient_value ); } return $return; }
tools/e2e-commons/plugins/e2e-plugin-updater.php
<?php /** * Plugin Name: Jetpack E2E plugin updater * Plugin URI: https://github.com/automattic/jetpack * Author: Jetpack Team * Version: 1.0.0 * Text Domain: jetpack * * @package automattic/jetpack */ add_filter( 'site_transient_update_plugins', 'e2e_set_jetpack_update', 10, 1 ); /** * Injects new available Jetpack version and download url into core updater * * @param Object $value Value object. * * @return array */ function e2e_set_jetpack_update( $value ) { $update_version = get_option( 'e2e_jetpack_upgrader_update_version' ); $update_package = get_option( 'e2e_jetpack_upgrader_plugin_url' ); if ( ! isset( $update_package ) || ! isset( $update_version ) ) { return $value; } if ( ! file_exists( trailingslashit( WP_PLUGIN_DIR ) . 'jetpack/jetpack.php' ) ) { // Jetpack not installed so bail. return $value; } $current_version = get_file_data( trailingslashit( WP_PLUGIN_DIR ) . 'jetpack/jetpack.php', array( 'Version' => 'Version' ) )['Version']; if ( $current_version === $update_version ) { // Already on desired Jetpack version. return $value; } // Override an existing Jetpack update. if ( ! empty( $value->response['jetpack/jetpack.php'] ) ) { $value->response['jetpack/jetpack.php']->new_version = $update_version; $value->response['jetpack/jetpack.php']->package = $update_package; return $value; } // Cause a new Jetpack update. if ( ! empty( $value->no_update['jetpack/jetpack.php'] ) ) { $jetpack = $value->no_update['jetpack/jetpack.php']; $jetpack->new_version = $update_version; $jetpack->package = $update_package; $value->response['jetpack/jetpack.php'] = $jetpack; } return $value; }
tools/cli/skeletons/plugins/plugin.php
<?php /** * * Plugin Name: TBD * Plugin URI: TBD * Description: TBD * Version: 1.0.0-alpha * Author: Automattic * Author URI: https://jetpack.com/ * License: GPLv2 or later * Text Domain: jetpack * * @package automattic/TBD */ // Code some good stuff!
tools/cli/skeletons/plugins/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php';
tools/cli/skeletons/plugins/src/example.php
<?php /** * Put your classes in this `src` folder! * * @package automattic/PACKAGE-NAME */ // Start your code here!
tools/cli/skeletons/packages/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php';
tools/cli/skeletons/packages/src/class-example.php
<?php /** * Package description here * * @package automattic/package-name */ namespace Automattic\Jetpack; /** * Class description. */ class Package_Name { const PACKAGE_VERSION = '1.0.0-alpha'; }
tools/cli/helpers/doc-parser/runner.php
<?php /** * A runner file that is used by Jetpack CLI to start the parsing process. * * @package automattic/jetpack-doc-parser */ use Michelf\Markdown; /** * Loading the autoloader and starting the process. */ require __DIR__ . '/vendor/autoload.php'; $args = array_slice( $argv, 1 ); $parser = new \Automattic\Jetpack\Doc_Parser(); $parser->generate( array( $args, 'phpdoc.json' ) ); $docs_json = json_decode( file_get_contents( __DIR__ . '/docs.json' ), true ); $processed_docs = array(); $result = array(); // Each parent file has to be present in the import. foreach ( $docs_json['parents'] as $parent => $child_docs ) { if ( ! in_array( $parent, $processed_docs, true ) ) { printf( 'Extracting Markdown from %1$s.' . PHP_EOL, $parent ); $result[] = get_html_from_markdown( $parent ); $processed_docs[] = $parent; } foreach ( $child_docs as $doc ) { if ( in_array( $doc, $processed_docs, true ) ) { continue; } printf( 'Extracting Markdown from %1$s.' . PHP_EOL, $doc ); $data = get_html_from_markdown( $doc ); $data['parent'] = $parent; $processed_docs[] = $doc; $result[] = $data; } } file_put_contents( './markdown.json', json_encode( $result ) ); print( 'Data exported to markdown.json' . PHP_EOL ); /** * Retrieves Markdown content from a specified file in HTML format. * * @param string $file_path the string containing the path to the file relative to Monorepo root. * @return array [ content => the HTML content, title => document title ] * @throws Exception $e if the file cannot be read. */ function get_html_from_markdown( $file_path ) { // We're assuming files are in the Monorepo root. $parser = new Markdown(); $markdown = file_get_contents( dirname( __DIR__, 4 ) . DIRECTORY_SEPARATOR . $file_path ); if ( false === $markdown ) { throw new Exception( 'Could not read Markdown from ' . $file_path ); } $contents = $parser->defaultTransform( $markdown ); $document = new DOMDocument(); $document->loadHTML( '<!DOCTYPE html><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' . $contents ); $doc_title = $file_path; $anchors = $document->getElementsByTagName( 'a' ); foreach ( $anchors as $anchor ) { $link = parse_url( $anchor->getAttribute( 'href' ) ); if ( ! $link || isset( $link['host'] ) || ! isset( $link['path'] ) ) { continue; } // Replace any relative links with absolute links to the GitHub repo. If it's deeper than 2 levels, it's a link to a file in the repo. if ( str_starts_with( $link['path'], '../' ) || str_starts_with( $link['path'], '/projects/' ) || ( substr_count( $link['path'], '/' ) > 2 ) ) { $link['path'] = preg_replace( '~^(\./|../)~', '', $link['path'], 1 ); // Remove leading ./ or ../ $link['path'] = 'https://github.com/Automattic/jetpack/blob/trunk' . ( ! str_starts_with( $link['path'], '/' ) ? '/' : '' ) . $link['path']; } // Handle docs that just live in github, ending in anything other than .md. $extension = pathinfo( $link['path'], PATHINFO_EXTENSION ); if ( ( $extension !== 'md' || $extension === '' ) && ! str_starts_with( $link['path'], 'http' ) ) { $link['path'] = preg_replace( '~^(\./|/)~', '', $link['path'], 1 ); // Remove leading ./ or / $link['path'] = 'https://github.com/Automattic/jetpack/blob/trunk/' . ( str_contains( $link['path'], 'examples/' ) ? 'docs/' : '' ) . $link['path']; } // If the Path starts with ./docs/ and contains 2 slashes, it's a relative link to another doc. if ( ( str_starts_with( $link['path'], './docs' ) || str_starts_with( $link['path'], '/docs/' ) || str_starts_with( $file_path, 'docs/' ) ) && substr_count( $link['path'], '/' ) <= 2 ) { $link['path'] = str_replace( array( './docs/', '/docs/', './' ), '', $link['path'] ); $link['path'] = '/docs-' . $link['path']; } // Replace any non-github path endings with -md to link to the correct document page. if ( ! str_starts_with( $link['path'], 'http' ) ) { $link['path'] = str_replace( '.md', '-md', $link['path'] ); } // Set the parsed attribute. $anchor->setAttribute( 'href', $link['path'] . ( isset( $link['fragment'] ) ? '#' . $link['fragment'] : '' ) ); } $headers = $document->getElementsByTagName( 'h1' ); if ( count( $headers ) ) { $doc_title = $headers[0]->textContent; $headers[0]->remove(); } // Add IDs to all headers. $headers_ids = array(); for ( $i = 1; $i <= 6; $i++ ) { $elements = $document->getElementsByTagName( 'h' . $i ); foreach ( $elements as $element ) { $headers_ids[] = $element; } } foreach ( $headers_ids as $header ) { $header_id = strtolower( str_replace( ' ', '-', $header->textContent ) ); $header_id = preg_replace( '/[^A-Za-z0-9\-]/', '', $header_id ); $header->setAttribute( 'id', $header_id ); } return array( 'path' => $file_path, 'title' => $doc_title, 'content' => $document->saveHTML(), ); }
tools/cli/helpers/doc-parser/src/class-doc-parser.php
<?php /** * Package description here * * @package automattic/jetpack-doc-parser */ namespace Automattic\Jetpack; /** * Converts PHPDoc markup into a template ready for import to a WordPress blog. */ class Doc_Parser { const PACKAGE_VERSION = '0.1.0-alpha'; /** * Generate a JSON file containing the PHPDoc markup, and save to filesystem. * * @param Array $args this function takes a path as its argument, * as well as optionally an output file name. */ public function generate( $args ) { list( $directories, $output_file ) = $args; if ( empty( $output_file ) ) { $output_file = 'phpdoc.json'; } $json = array(); foreach ( $directories as $directory ) { $directory = realpath( $directory ); echo PHP_EOL; // Get data from the PHPDoc $json[] = $this->get_phpdoc_data( $directory, 'raw' ); } $output = json_encode( $json ); // Write to $output_file $error = ! file_put_contents( $output_file, $output ); if ( $error ) { printf( 'Problem writing %1$s bytes of data to %2$s' . PHP_EOL, strlen( $output ), $output_file ); exit( 1 ); } printf( 'Data exported to %1$s' . PHP_EOL, $output_file ); } /** * Generate the data from the PHPDoc markup. * * @param string $path Directory to scan for PHPDoc. * @param string $format Optional. What format the data is returned in: [json*|array]. * @return string */ protected function get_phpdoc_data( $path, $format = 'json' ) { printf( 'Extracting PHPDoc from %1$s.' . PHP_EOL, $path ); // Find the files to get the PHPDoc data from. $path can either be a folder or an absolute ref to a file. if ( is_file( $path ) ) { $files = array( $path ); $path = dirname( $path ); } else { ob_start(); $files = \WP_Parser\get_wp_files( $path ); $error = ob_get_clean(); if ( $error ) { printf( 'Problem with %1$s: %2$s' . PHP_EOL, $path, $error ); exit( 1 ); } } // Maybe we should automatically import definitions from .gitignore. $ignore = array( '/.sass-cache/', '/node_modules', 'vendor/', 'jetpack_vendor/', '/.nova/', '/.vscode/', '/logs', '/allure-results/', 'tests/', 'wordpress/', ); $files = array_filter( $files, function ( $item ) use ( $ignore ) { foreach ( $ignore as $path_chunk ) { if ( false !== strpos( $item, $path_chunk ) ) { return false; } } return true; } ); // Extract PHPDoc. ob_start(); $output = \WP_Parser\parse_files( $files, $path ); ob_get_clean(); if ( 'json' === $format ) { $output = json_encode( $output, JSON_PRETTY_PRINT ); } return $output; } }
projects/plugins/beta/jetpack-beta.php
<?php /** * Plugin Name: Jetpack Beta Tester * Plugin URI: https://jetpack.com/beta/ * Description: Use the Beta plugin to get a sneak peek at new features and test them on your site. * Version: 4.0.1-alpha * Author: Automattic * Author URI: https://jetpack.com/ * Update URI: https://jetpack.com/download-jetpack-beta/ * License: GPLv2 or later * Text Domain: jetpack-beta * * @package automattic/jetpack-beta */ /* 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. */ // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } define( 'JPBETA__PLUGIN_FOLDER', dirname( plugin_basename( __FILE__ ) ) ); define( 'JPBETA_VERSION', '4.0.1-alpha' ); define( 'JETPACK_BETA_PLUGINS_URL', 'https://betadownload.jetpack.me/plugins.json' ); /** * This is where the loading of Jetpack Beta begins. * * First, we try to load our composer autoloader. * * - If it fails, we "pause" Jetpack Beta 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 continue. */ $jetpack_beta_autoloader = plugin_dir_path( __FILE__ ) . '/vendor/autoload_packages.php'; if ( is_readable( $jetpack_beta_autoloader ) ) { require $jetpack_beta_autoloader; } 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 Beta is incomplete. If you installed Jetpack Beta from GitHub, please refer to this document to set up your development environment: %1$s', 'jetpack-beta' ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md' ) ); } /** * Outputs an admin notice for folks running Jetpack Beta without having run composer install. * * @since 3.0.0 */ function jetpack_beta_admin_missing_autoloader() { ?> <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 Beta is incomplete. If you installed Jetpack Beta from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment.', 'jetpack-beta' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md' ); ?> </p> </div> <?php } add_action( 'admin_notices', 'jetpack_beta_admin_missing_autoloader' ); return; } add_action( 'init', array( Automattic\JetpackBeta\AutoupdateSelf::class, 'instance' ) ); Automattic\JetpackBeta\Hooks::setup(); register_activation_hook( __FILE__, array( Automattic\JetpackBeta\Hooks::class, 'activate' ) ); register_deactivation_hook( __FILE__, array( Automattic\JetpackBeta\Hooks::class, 'deactivate' ) ); add_action( 'init', array( Automattic\JetpackBeta\Hooks::class, 'instance' ) ); add_action( 'muplugins_loaded', array( Automattic\JetpackBeta\Hooks::class, 'is_network_enabled' ) ); if ( defined( 'WP_CLI' ) && WP_CLI ) { WP_CLI::add_command( 'jetpack-beta', Automattic\JetpackBeta\CliCommand::class ); }
projects/plugins/beta/src/class-clicommand.php
<?php /** * Jetpack Beta Tester CLI controls * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use WP_CLI; use WP_CLI_Command; if ( ! class_exists( 'WP_CLI_Command' ) ) { return; } /** * Control your local Jetpack Beta Tester plugin. */ class CliCommand extends WP_CLI_Command { /** * Deprecated entry point. * * ## Options * * <subcommand> * : Subcommand to run. Either 'list' or 'activate'. * * [<args>...] * : Any additional args to the subcommand. * * @deprecated since 3.0.0 * @param array $args Arguments passed to CLI. */ public function branch( $args ) { $this->validation_checks(); $subcommand = array_shift( $args ); if ( 'list' === $subcommand ) { WP_CLI::warning( __( 'Command `wp jetpack-beta branch list` is deprecated. Use `wp jetpack-beta list jetpack` instead.', 'jetpack-beta' ) ); WP_CLI::run_command( array( 'jetpack-beta', 'list', 'jetpack' ) ); } elseif ( 'activate' === $subcommand ) { WP_CLI::warning( __( 'Command `wp jetpack-beta branch activate <branch>` is deprecated. Use `wp jetpack-beta activate jetpack <branch>` instead.', 'jetpack-beta' ) ); WP_CLI::run_command( array_merge( array( 'jetpack-beta', 'activate', 'jetpack' ), $args ) ); } else { WP_CLI::warning( __( 'Command `wp jetpack-beta branch` is deprecated. See `wp help jetpack-beta` for available commands.', 'jetpack-beta' ) ); WP_CLI::error( __( 'Specify subcommand. "activate" and "list" subcommands are supported', 'jetpack-beta' ) ); } } /** * List available plugins or branches. * * ## Options * * [<plugin>] * : If specified, list branches available for the plugin. * * ## Examples * * wp jetpack-beta list * wp jetpack-beta list jetpack * * @subcommand list * @param array $args Arguments passed to CLI. */ public function do_list( $args ) { $this->validation_checks(); if ( ! $args ) { try { $plugins = Plugin::get_all_plugins( true ); } catch ( PluginDataException $ex ) { WP_CLI::error( $ex->getMessage() ); } if ( ! $plugins ) { WP_CLI::error( __( 'No plugins are available', 'jetpack-beta' ) ); } $l = 0; foreach ( $plugins as $slug => $plugin ) { $l = max( $l, strlen( $slug ) ); } WP_CLI::line( 'Available plugins: ' ); foreach ( $plugins as $slug => $plugin ) { WP_CLI::line( sprintf( " %-{$l}s - %s", $slug, $plugin->get_name() ) ); } return; } $plugin = Plugin::get_plugin( $args[0], true ); if ( ! $plugin ) { // translators: %s: subcommand that was not found. WP_CLI::error( sprintf( __( 'Plugin \'%s\' is not known. Use `wp jetpack-beta list` to list known plugins', 'jetpack-beta' ), $args[0] ) ); } $manifest = $plugin->get_manifest(); $dev_info = $plugin->dev_info(); $active_branch = $dev_info ? $dev_info->branch : null; $branches = array( 'stable', 'trunk', 'rc' ); foreach ( $manifest->pr as $pr ) { $branches[] = $pr->branch; } asort( $branches ); WP_CLI::line( 'Available branches: ' ); foreach ( $branches as $branch ) { WP_CLI::line( ( $active_branch === $branch ? '* ' : ' ' ) . $branch ); } } /** * Activate a branch for a plugin. * * ## Options * * <plugin> * : The plugin to activate a branch for. * * <branch> * : The branch to activate. * * ## Examples * * wp jetpack-beta activate jetpack trunk * wp jetpack-beta activate jetpack master (deprecated alias for trunk) * wp jetpack-beta activate jetpack stable * wp jetpack-beta activate jetpack rc * wp jetpack-beta activate jetpack 9.8 * wp jetpack-beta activate jetpack update/some-branch * * @param array $args Arguments passed to CLI. */ public function activate( $args ) { $this->validation_checks(); $plugin = Plugin::get_plugin( $args[0], true ); if ( ! $plugin ) { // translators: %s: Plugin slug that was not found. WP_CLI::error( sprintf( __( 'Plugin \'%s\' is not known. Use `wp jetpack-beta list` to list known plugins', 'jetpack-beta' ), $args[0] ) ); } if ( 'trunk' === $args[1] || 'master' === $args[1] ) { $source = 'trunk'; $id = ''; // translators: %1$s: Plugin name. $premsg = __( 'Activating %1$s trunk branch', 'jetpack-beta' ); // translators: %1$s: Plugin name. $postmsg = __( '%1$s is now on the trunk branch', 'jetpack-beta' ); } elseif ( 'stable' === $args[1] ) { $source = 'stable'; $id = ''; // translators: %1$s: Plugin name. $premsg = __( 'Activating %1$s latest release', 'jetpack-beta' ); // translators: %1$s: Plugin name. $postmsg = __( '%1$s is now on the latest release', 'jetpack-beta' ); } elseif ( 'rc' === $args[1] ) { $source = 'rc'; $id = ''; // translators: %1$s: Plugin name. $premsg = __( 'Activating %1$s release candidate', 'jetpack-beta' ); // translators: %1$s: Plugin name. $postmsg = __( '%1$s is now on the latest release candidate', 'jetpack-beta' ); } elseif ( preg_match( '/^\d+(?:\.\d+)(?:-beta\d*)?$/', $args[1] ) ) { $source = 'release'; $id = $args[1]; // translators: %1$s: Plugin name. %2$s: Version number. $premsg = __( 'Activating %1$s release version %2$s', 'jetpack-beta' ); // translators: %1$s: Plugin name. %2$s: Version number. $postmsg = __( '%1$s is now on release version %2$s', 'jetpack-beta' ); } else { $source = 'pr'; $id = $args[1]; // translators: %1$s: Plugin name. %2$s: Branch name. $premsg = __( 'Activating %1$s branch %2$s', 'jetpack-beta' ); // translators: %1$s: Plugin name. %2$s: Branch name. $postmsg = __( '%1$s is now on branch %2$s', 'jetpack-beta' ); } WP_CLI::line( sprintf( $premsg, $plugin->get_name(), $id ) ); $ret = $plugin->install_and_activate( $source, $id ); if ( is_wp_error( $ret ) ) { WP_CLI::error( $ret->get_error_message() ); } else { WP_CLI::line( sprintf( $postmsg, $plugin->get_name(), $id ) ); } } /** * Validate environment. */ private function validation_checks() { if ( is_multisite() && ! is_main_site() ) { WP_CLI::error( __( 'Secondary sites in multisite instalations are not supported', 'jetpack-beta' ) ); } } }
projects/plugins/beta/src/class-utils.php
<?php /** * Utilities class file for the Jetpack Beta plugin. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; /** * Utilities class file for the Jetpack Beta plugin. */ class Utils { /** * Normalize a branch name. * * @param string $branch Branch name. * @return string Normalized branch name. */ public static function normalize_branch_name( $branch ) { return preg_replace( '#^\.|[/\p{Cc}\p{Cn}\p{Co}\p{Cs}]#u', '_', $branch ); } /** * Builds URL to the admin area for the current site and specified query param. * * @param array $query Query string data. */ public static function admin_url( $query = array() ) { $query = array_merge( array( 'page' => 'jetpack-beta' ), $query ); // If it's multisite, and a plugin is specified, and the plugin is network-activated, // link to the network URL instead of the regular one. if ( is_multisite() && isset( $query['plugin'] ) ) { $prefix = $query['plugin'] . '/'; $l = strlen( $prefix ); foreach ( Plugin::get_plugin_file_map() as $nondev => $dev ) { if ( substr( $nondev, 0, $l ) !== $prefix ) { continue; } if ( ! function_exists( 'is_plugin_active_for_network' ) ) { require_once ABSPATH . '/wp-admin/includes/plugin.php'; } if ( is_plugin_active_for_network( $nondev ) || is_plugin_active_for_network( $dev ) ) { return network_admin_url( 'admin.php?' . http_build_query( $query ) ); } break; } } return admin_url( 'admin.php?' . http_build_query( $query ) ); } /** * List options to sync. */ public static function options_to_sync() { return array( 'jp_beta_autoupdate', 'jp_beta_email_notifications', ); } /** * Get WP Option: jp_beta_autoupdate */ public static function is_set_to_autoupdate() { return get_option( 'jp_beta_autoupdate', false ); } /** * Get WP Option: jp_beta_email_notifications */ public static function is_set_to_email_notifications() { return get_option( 'jp_beta_email_notifications', true ); } /** * Helper function used to fetch remote data from WordPress.org, GitHub, and betadownload.jetpack.me * * @param string $url - Url being fetched. * @param string $transient - Transient name (manifest|org_data|github_commits_). * @param bool $bypass - Whether to bypass cached response. */ public static function get_remote_data( $url, $transient, $bypass = false ) { $prefix = 'jetpack_beta_'; $cache = get_site_transient( $prefix . $transient ); if ( $cache && ! $bypass ) { return $cache; } $remote_manifest = wp_remote_get( $url ); if ( is_wp_error( $remote_manifest ) ) { return false; } $cache = json_decode( wp_remote_retrieve_body( $remote_manifest ) ); set_site_transient( $prefix . $transient, $cache, MINUTE_IN_SECONDS * 15 ); return $cache; } /** * Delete set transients, e.g. when plugin is deactivated. */ public static function delete_all_transiants() { global $wpdb; // Multisite uses wp_sitemeta for transients. Non-multisite uses wp_options. if ( is_multisite() ) { $sql = "SELECT meta_key AS n FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s AND site_id = %d"; $extra_vals = array( get_current_network_id() ); } else { $sql = "SELECT option_name AS n FROM {$wpdb->options} WHERE option_name LIKE %s"; $extra_vals = array(); } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $results = $wpdb->get_results( $wpdb->prepare( $sql, $wpdb->esc_like( '_site_transient_jetpack_beta_' ) . '%', ...$extra_vals ) ); foreach ( $results as $row ) { delete_site_transient( substr( $row->n, 16 ) ); } } /** * Test whether the Beta Tester has been used. * * In other words, if any -dev version has been downloaded yet. * * @return bool */ public static function has_been_used() { foreach ( Plugin::get_plugin_file_map() as $dev ) { if ( file_exists( WP_PLUGIN_DIR . "/$dev" ) ) { return true; } } return false; } /** * Lists plugins needing an update. * * @param bool $include_stable Set true to include stable versions. * @return object[] Keys are plugin files, values are the plugin objects. */ public static function plugins_needing_update( $include_stable = false ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; require_once ABSPATH . 'wp-admin/includes/update.php'; // Determine the plugins needing updating. wp_clean_plugins_cache(); ob_start(); wp_update_plugins(); ob_end_clean(); $updates = get_plugin_updates(); // See if any of our plugins are to be updated. $our_plugins = Plugin::get_plugin_file_map(); if ( $include_stable ) { $our_plugins += array_flip( $our_plugins ); } $our_plugins[] = JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php'; return array_intersect_key( $updates, array_flip( $our_plugins ) ); } /** * Rendering markdown for testing instructions. * * @param Plugin $plugin Plugin being processed. * @param string $content Markdown content to render. * @return string HTML. */ public static function render_markdown( Plugin $plugin, $content ) { return ParsedownExt::instance() ->setSafeMode( true ) ->setPRLinkFormat( "https://github.com/{$plugin->repo()}/pull/%d" ) ->text( $content ); } }
projects/plugins/beta/src/class-admin.php
<?php /** * Handles the Jetpack Admin functions. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use Automattic\Jetpack\Admin_UI\Admin_Menu; /** * Handles the Jetpack Beta plugin Admin functions. */ class Admin { /** * Admin page hook name. * * @var string|false */ private static $hookname = false; /** * Initialize admin hooks. */ public static function init() { add_action( 'admin_menu', array( self::class, 'add_actions' ), 998 ); add_action( 'network_admin_menu', array( self::class, 'add_actions' ), 998 ); add_action( 'admin_notices', array( self::class, 'render_banner' ) ); } /** * Action: Attach hooks common to all Jetpack admin pages. * * Action for `admin_menu` and `network_admin_menu`. */ public static function add_actions() { self::$hookname = Admin_Menu::add_menu( 'Beta Tester', 'Beta Tester', 'update_plugins', 'jetpack-beta', array( self::class, 'render' ) ); if ( false !== self::$hookname ) { add_action( 'load-' . self::$hookname, array( self::class, 'admin_page_load' ) ); } add_action( 'admin_enqueue_scripts', array( self::class, 'admin_enqueue_scripts' ) ); add_filter( 'plugin_action_links_' . JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php', array( self::class, 'plugin_action_links' ) ); } /** * Filter: Create the action links for the plugin's row on the plugins page. * * Filter for `plugin_action_links_{$slug}`. * * @param array $actions An array of plugin action links. * @return array $actions */ public static function plugin_action_links( $actions ) { $settings_link = '<a href="' . esc_url( Utils::admin_url() ) . '">' . __( 'Settings', 'jetpack-beta' ) . '</a>'; array_unshift( $actions, $settings_link ); return $actions; } /** * Admin page 'view' entry point. * * This will write the page content to standard output. * * @throws PluginDataException It doesn't really, but phpcs is dumb. */ public static function render() { if ( is_network_admin() && ! is_plugin_active_for_network( JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php' ) ) { $exception = new \RuntimeException( __( 'Jetpack Beta Tester must be activated for the network to be used from Network Admin.', 'jetpack-beta' ) ); require_once __DIR__ . '/admin/exception.template.php'; exit; } ob_start(); try { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $plugin_name = isset( $_GET['plugin'] ) ? filter_var( wp_unslash( $_GET['plugin'] ) ) : null; if ( null === $plugin_name ) { require_once __DIR__ . '/admin/plugin-select.template.php'; return; } $plugin = Plugin::get_plugin( $plugin_name, true ); if ( ! $plugin ) { throw new PluginDataException( // translators: %s: Requested plugin slug. sprintf( __( 'Plugin %s is not known.', 'jetpack-beta' ), $plugin_name ) ); } require_once __DIR__ . '/admin/plugin-manage.template.php'; } catch ( PluginDataException $exception ) { ob_clean(); require_once __DIR__ . '/admin/exception.template.php'; } finally { ob_end_flush(); } } /** * Action: Handles Beta plugin admin page load. * * Action for `load-{$hook}`. */ public static function admin_page_load() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $plugin_name = isset( $_GET['plugin'] ) ? filter_var( wp_unslash( $_GET['plugin'] ) ) : null; $plugin = null; // If a plugin is specified, check that it's valid. // This comes before the nonce check for the access control. if ( null !== $plugin_name ) { $plugin = Plugin::get_plugin( $plugin_name ); // Access control: If the plugin being managed is network-activated, redirect to Network Admin if `! is_network_admin()`. if ( $plugin && is_multisite() && ! is_network_admin() && ( is_plugin_active_for_network( $plugin->plugin_file() ) || is_plugin_active_for_network( $plugin->dev_plugin_file() ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended wp_safe_redirect( Utils::admin_url( $_GET ) ); exit(); } } // No nonce? Nothing else to do. if ( ! isset( $_GET['_wpnonce'] ) ) { return; } // Install and activate Jetpack Version. if ( wp_verify_nonce( $_GET['_wpnonce'], 'activate_branch' ) && // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- WP core doesn't pre-sanitize nonces either. isset( $_GET['activate-branch'] ) && $plugin ) { list( $source, $id ) = explode( ':', filter_var( wp_unslash( $_GET['activate-branch'] ) ), 2 ); $res = $plugin->install_and_activate( $source, $id ); if ( is_wp_error( $res ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped wp_die( $res ); } } // Toggle autoupdates. if ( self::is_toggle_action( 'autoupdates' ) ) { $autoupdate = (bool) Utils::is_set_to_autoupdate(); update_option( 'jp_beta_autoupdate', (int) ! $autoupdate ); if ( Utils::is_set_to_autoupdate() ) { Hooks::maybe_schedule_autoupdate(); } } // Toggle email notifications. if ( self::is_toggle_action( 'email_notifications' ) ) { $enable_email_notifications = (bool) Utils::is_set_to_email_notifications(); update_option( 'jp_beta_email_notifications', (int) ! $enable_email_notifications ); } wp_safe_redirect( Utils::admin_url( $plugin ? array( 'plugin' => $plugin_name ) : array() ) ); exit(); } /** * Checks if autoupdates and email notifications are toggled. * * @param string $option - Which option is being toggled. */ private static function is_toggle_action( $option ) { return ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], "enable_$option" ) && // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- WP core doesn't pre-sanitize nonces either. isset( $_GET['_action'] ) && "toggle_enable_$option" === $_GET['_action'] ); } /** * Action: Render beta plugin banner. * * Shows a banner on the plugins page if no dev versions have been downloaded yet. * * Action for `admin_notices`. */ public static function render_banner() { global $current_screen; if ( 'plugins' !== $current_screen->base || Utils::has_been_used() ) { return; } require __DIR__ . '/admin/notice.template.php'; } /** * Action: Enqueue styles and scripts for admin page. * * Action for `admin_enqueue_scripts`. * * @param string $hookname Admin page being loaded. */ public static function admin_enqueue_scripts( $hookname ) { if ( $hookname !== self::$hookname ) { return; } wp_enqueue_style( 'jetpack-beta-admin', plugins_url( 'admin/admin.css', __FILE__ ), array(), JPBETA_VERSION ); wp_enqueue_script( 'jetpack-admin-js', plugins_url( 'admin/admin.js', __FILE__ ), array(), JPBETA_VERSION, true ); wp_localize_script( 'jetpack-admin-js', 'JetpackBeta', array( 'activate' => __( 'Activate', 'jetpack-beta' ), 'activating' => __( 'Activating...', 'jetpack-beta' ), 'update' => __( 'Update', 'jetpack-beta' ), 'updating' => __( 'Updating...', 'jetpack-beta' ), 'failed' => __( 'Failed', 'jetpack-beta' ), // translators: %s: Error message. 'failedmsg' => __( 'Update failed: %s', 'jetpack-beta' ), ) ); } /** * Determine content for "To test" and "What changed" boxes. * * @param Plugin $plugin Plugin being processed. * @return (string|null)[] HTML and diff summary. */ public static function to_test_content( Plugin $plugin ) { if ( is_plugin_active( $plugin->plugin_file() ) ) { $path = WP_PLUGIN_DIR . '/' . $plugin->plugin_slug(); $info = (object) array( 'source' => 'stable', ); } elseif ( is_plugin_active( $plugin->dev_plugin_file() ) ) { $path = WP_PLUGIN_DIR . '/' . $plugin->dev_plugin_slug(); $info = $plugin->dev_info(); if ( ! $info ) { return array( sprintf( // translators: %s: Plugin name. __( 'This development instance of %s seems to be from an old verison of Jetpack Beta Tester, or has otherwise lost essential metadata. You should use Jetpack Beta Tester to reinstall the desired PR, Release Candidate, or Bleeding Edge version.', 'jetpack-beta' ), $plugin->get_name() ), null, ); } } else { return array( null, null ); } if ( 'pr' === $info->source ) { $res = Utils::get_remote_data( sprintf( 'https://api.github.com/repos/%s/pulls/%d', $plugin->repo(), $info->pr ), "github/pulls/$info->pr" ); if ( ! isset( $res->body ) ) { return array( 'GitHub commit info is unavailable.', null ); } $html = Utils::render_markdown( $plugin, $res->body ); $res = Utils::get_remote_data( sprintf( 'https://api.github.com/repos/%s/pulls/%d/files', $plugin->repo(), $info->pr ), "github/pulls/$info->pr/files" ); $diff = null; if ( is_array( $res ) ) { // translators: %d: number of files changed. $diff = '<div>' . sprintf( _n( '%d file changed ', '%d files changed', count( $res ), 'jetpack-beta' ), count( $res ) ) . "<br />\n"; $diff .= "<ul class=\"ul-square jpbeta-file-list\">\n"; foreach ( $res as $file ) { $added_deleted_changed = array(); if ( $file->additions ) { $added_deleted_changed[] = '+' . $file->additions; } if ( $file->deletions ) { $added_deleted_changed[] = '-' . $file->deletions; } $diff .= sprintf( '<li><span class="container"><span class="filename">%s</span><span class="status">&nbsp;(%s %s)</span></span></li>', esc_html( $file->filename ), esc_html( $file->status ), implode( ' ', $added_deleted_changed ) ) . "\n"; } $diff .= "</ul></div>\n\n"; } return array( $html, $diff ); } WP_Filesystem(); global $wp_filesystem; $file = $path . '/to-test.md'; if ( ! file_exists( $file ) ) { $file = __DIR__ . '/../docs/testing/testing-tips.md'; } return array( Utils::render_markdown( $plugin, $wp_filesystem->get_contents( $file ) ), null ); } /** Display autoupdate toggle */ public static function show_toggle_autoupdates() { $autoupdate = (bool) Utils::is_set_to_autoupdate(); self::show_toggle( __( 'Autoupdates', 'jetpack-beta' ), 'autoupdates', $autoupdate ); } /** Display email notification toggle */ public static function show_toggle_emails() { if ( ! Utils::is_set_to_autoupdate() || defined( 'JETPACK_BETA_SKIP_EMAIL' ) ) { return; } $email_notification = (bool) Utils::is_set_to_email_notifications(); self::show_toggle( __( 'Email Notifications', 'jetpack-beta' ), 'email_notifications', $email_notification ); } /** * Display autoupdate and email notification toggles * * @param string $name name of toggle. * @param string $option Which toggle (autoupdates, email_notification). * @param bool $value If toggle is active or not. */ public static function show_toggle( $name, $option, $value ) { $query = array( '_action' => "toggle_enable_$option", ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( isset( $_GET['plugin'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $query['plugin'] = filter_var( wp_unslash( $_GET['plugin'] ) ); } ?> <a href="<?php echo esc_url( wp_nonce_url( Utils::admin_url( $query ), "enable_$option" ) ); ?>" class="form-toggle__label <?php echo ( $value ? 'is-active' : '' ); ?>" data-jptracks-name="jetpack_beta_toggle_<?php echo esc_attr( $option ); ?>" data-jptracks-prop="<?php echo absint( ! $value ); ?>" > <span class="form-toggle-explanation" ><?php echo esc_html( $name ); ?></span> <span class="form-toggle__switch" tabindex="0" ></span> <span class="form-toggle__label-content" ></span> </a> <?php } }
projects/plugins/beta/src/class-autoupdateself.php
<?php /** * Allow the Jetpack Beta plugin to autoupdate itself. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use Composer\Semver\Comparator as Semver; use WP_Error; /** * Allow the Jetpack Beta plugin to autoupdate itself. * * This registers some hooks in its constructor to point WordPress's plugin * upgrader to the GitHub repository for the plugin, as this plugin isn't in * the WordPress Plugin Directory to be updated normally. */ class AutoupdateSelf { /** * Singleton class instance. * * @var static */ private static $instance = null; /** * Configuration. * * @var array */ private $config; /** * Main Instance */ public static function instance() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Constructor */ private function __construct() { $this->config = array( 'plugin_file' => JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php', 'slug' => JPBETA__PLUGIN_FOLDER, 'proper_folder_name' => JPBETA__PLUGIN_FOLDER, 'api_url' => 'https://api.github.com/repos/Automattic/jetpack-beta', 'github_url' => 'https://github.com/Automattic/jetpack-beta', 'requires' => '4.7', 'tested' => '4.7', ); add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'api_check' ) ); add_filter( 'plugins_api', array( $this, 'get_plugin_info' ), 10, 3 ); add_filter( 'upgrader_source_selection', array( $this, 'upgrader_source_selection' ), 10, 3 ); } /** * Set update arguments in `$this->config`. */ private function set_update_args() { $plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $this->config['plugin_file'] ); $github_data = $this->get_github_data(); $tagged_version = $this->get_latest_prerelease(); $this->config['plugin_name'] = $plugin_data['Name']; $this->config['version'] = $plugin_data['Version']; $this->config['author'] = $plugin_data['Author']; $this->config['homepage'] = $plugin_data['PluginURI']; $this->config['new_version'] = ltrim( $tagged_version, 'v' ); $this->config['last_updated'] = empty( $github_data->updated_at ) ? false : gmdate( 'Y-m-d', strtotime( $github_data->updated_at ) ); $this->config['description'] = empty( $github_data->description ) ? false : $github_data->description; $this->config['zip_url'] = 'https://github.com/Automattic/jetpack-beta/zipball/' . $tagged_version; } /** * Check for latest pre-release plugin every six hours and update. * * @return string|false Prerelease version, or false on failure. */ private function get_latest_prerelease() { $tagged_version = get_site_transient( 'jetpack_beta_latest_tag' ); if ( $this->overrule_transients() || ! $tagged_version ) { $raw_response = wp_remote_get( trailingslashit( $this->config['api_url'] ) . 'releases' ); if ( is_wp_error( $raw_response ) ) { return false; } $releases = json_decode( $raw_response['body'] ); $tagged_version = false; if ( is_array( $releases ) ) { foreach ( $releases as $release ) { // Since 2.2, so that we don't have to maker the Jetpack Beta 2.0.3 as prerelease. if ( ! $release->prerelease ) { $tagged_version = $release->tag_name; break; } } } // Refresh every 6 hours. if ( $tagged_version ) { set_site_transient( 'jetpack_beta_latest_tag', $tagged_version, 60 * 60 * 6 ); } } return $tagged_version; } /** * Whether to override transients to force update. * * @return bool */ private function overrule_transients() { return ( defined( 'Jetpack_Beta_FORCE_UPDATE' ) && Jetpack_Beta_FORCE_UPDATE ); } /** * Get update data from Github. * * @return object|false Data from GitHub's API, or false on error. */ private function get_github_data() { $github_data = get_site_transient( 'jetpack_beta_autoupdate_github_data' ); if ( $this->overrule_transients() || ! $github_data ) { $github_data = wp_remote_get( $this->config['api_url'] ); if ( is_wp_error( $github_data ) ) { return false; } $github_data = json_decode( $github_data['body'] ); // Refresh every 6 hours. set_site_transient( 'jetpack_beta_autoupdate_github_data', $github_data, 60 * 60 * 6 ); } return $github_data; } /** * Check if there's a newer version. * * @return bool */ public function has_newer_version() { if ( ! isset( $this->config['new_version'] ) ) { $this->set_update_args(); } return Semver::greaterThan( $this->config['new_version'], $this->config['version'] ); } /** * Filter: Check the latest transient data and update if necessary. * * Filter for `pre_set_site_transient_update_plugins`. * * We need to somehow inject ourself into the list of plugins needing update * when an update is available. This is the way: catch the setting of the relevant * transient and add ourself in. * * @todo Consider switching to the `update_plugins_${hostmane}` hook introduced in WP 5.8. * * @param object $transient The transient we're checking. * @return object $transient */ public function api_check( $transient ) { // Check if the transient contains the 'checked' information. // If not, just return its value without hacking it. if ( ! isset( $transient->no_update ) ) { return $transient; } // Get the latest version. delete_site_transient( 'jetpack_beta_latest_tag' ); if ( $this->has_newer_version() ) { $transient->response[ $this->config['plugin_file'] ] = (object) array( 'plugin' => $this->config['slug'], 'new_version' => $this->config['new_version'], 'slug' => $this->config['slug'], 'url' => $this->config['github_url'], 'package' => $this->config['zip_url'], ); } return $transient; } /** * Filter: Get latest plugin information. * * Filter for `plugins_api`. * * As the plugin isn't in the WordPress Plugin Directory, we need to fake * up a record for it so the upgrader will know how to upgrade it. * * @param false|object|array $result Result from plugins_api. * @param string $action The type of information being requested from the Plugin Installation API. * @param object $args Plugin API arguments. * @return false|object|array $result */ public function get_plugin_info( $result, $action, $args ) { // Check if this is a 'plugin_information' request for this plugin. if ( 'plugin_information' !== $action || $args->slug !== $this->config['slug'] ) { return $result; } // Update tags. $this->set_update_args(); return (object) array( 'slug' => $this->config['slug'], 'plugin' => $this->config['slug'], 'name' => $this->config['plugin_name'], 'plugin_name' => $this->config['plugin_name'], 'version' => $this->config['new_version'], 'author' => $this->config['author'], 'homepage' => $this->config['homepage'], 'requires' => $this->config['requires'], 'tested' => $this->config['tested'], 'downloaded' => 0, 'last_updated' => $this->config['last_updated'], 'sections' => array( 'description' => $this->config['description'] ), 'download_link' => $this->config['zip_url'], ); } /** * Filter: Updates the source file location for the upgrade package. * * Filter for `upgrader_source_selection`. * * The download from GitHub will produce a directory named like "Automattic-jetpack-beta-xxxxxxx". * We need to correct that so it will overwrite the current instance of the plugin. * * @param string $source File source location. Something like "/path/to/workdir/Automattic-jetpack-beta-xxxxxxx/". * @param string $remote_source Remote file source location. Something like "/path/to/workdir/". * @return string $source */ public function upgrader_source_selection( $source, $remote_source ) { global $wp_filesystem; if ( strstr( $source, '/Automattic-jetpack-beta-' ) ) { $corrected_source = trailingslashit( $remote_source ) . trailingslashit( $this->config['proper_folder_name'] ); if ( $wp_filesystem->move( $source, $corrected_source, true ) ) { return $corrected_source; } else { return new WP_Error(); } } return $source; } }
projects/plugins/beta/src/class-plugindataexception.php
<?php /** * Exception thrown when plugin data cannot be loaded. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use RuntimeException; /** * Exception thrown when plugin data cannot be loaded. */ class PluginDataException extends RuntimeException { }
projects/plugins/beta/src/class-plugin.php
<?php /** * The Plugin class handles all the stuff that varies between different plugins. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use Composer\Semver\Comparator as Semver; use InvalidArgumentException; use Plugin_Upgrader; use WP_Ajax_Upgrader_Skin; use WP_Error; /** * The Plugin class handles all the stuff that varies between different plugins. */ class Plugin { /** * Class instances. * * @var Plugin[] */ protected static $instances = null; /** * Plugin file map. * * @var string[] */ protected static $file_map = null; /** * WordPress plugin slug. * * @var string */ protected $slug; /** * Plugin name (for display). * * @var string */ protected $name; /** * Plugin file name. * * @var string */ protected $plugin_file; /** * GitHub source repo slug. * * @var string */ protected $repo; /** * GitHub mirror repo slug. * * @var string */ protected $mirror; /** * Manifest URL. * * @var string */ protected $manifest_url; /** * Beta homepage URL. * * @var string */ protected $beta_homepage_url; /** * Bug report URL. * * @var string */ protected $bug_report_url; /** * If the plugin is not published to the WordPress Plugin Repository. * * @var bool */ protected $unpublished = false; /** * Manifest data. * * @var object|null */ protected $manifest_data = null; /** * WordPress.org data. * * @var object|null */ protected $wporg_data = null; /** * Get instances for all known plugins. * * @param bool $bypass_cache Set true to bypass the transients cache. * * @return Plugin[] * @throws PluginDataException If the plugin data cannot be fetched or is invalid. */ public static function get_all_plugins( $bypass_cache = false ) { if ( null === self::$instances ) { $data = Utils::get_remote_data( JETPACK_BETA_PLUGINS_URL, 'plugins_json', $bypass_cache ); if ( ! is_object( $data ) ) { throw new PluginDataException( __( 'Failed to download list of plugins. Check your Internet connection.', 'jetpack-beta' ) ); } $plugins = array(); foreach ( $data as $slug => $info ) { try { $plugins[ $slug ] = new self( $slug, (array) $info ); } catch ( InvalidArgumentException $ex ) { throw new PluginDataException( // translators: %1$s: Plugin slug. %2$s: Error message. sprintf( __( 'Invalid data for plugin %1$s: %2$s', 'jetpack-beta' ), $slug, $ex->getMessage() ), 0, $ex ); } } self::$instances = $plugins; // Save the list of plugins to an option, so that we don't have to potentially hit the network // on every request if we only want the list of plugin files (since transients aren't guaranteed last even 1 second). $map = array(); foreach ( $plugins as $plugin ) { $plugin_file = $plugin->plugin_file(); $dev_plugin_file = $plugin->dev_plugin_file(); $map[ $plugin_file ] = $dev_plugin_file; } ksort( $map ); update_option( 'jetpack_beta_plugin_file_map', $map ); self::$file_map = $map; } return self::$instances; } /** * Get an instance by slug. * * @param string $slug WordPress plugin slug. * @param bool $no_cache Set true to bypass the transients cache. * @return Plugin|null * @throws PluginDataException If the plugin data cannot be fetched or is invalid. */ public static function get_plugin( $slug, $no_cache = false ) { $plugins = self::get_all_plugins( $no_cache ); return isset( $plugins[ $slug ] ) ? $plugins[ $slug ] : null; } /** * Get a map of plugin files. * * @return string[] Map from dev to non-dev plugin files, and vice versa. */ public static function get_plugin_file_map() { if ( null === self::$file_map ) { self::$file_map = get_option( 'jetpack_beta_plugin_file_map', null ); if ( null === self::$file_map ) { try { self::get_all_plugins(); } catch ( PluginDataException $ex ) { return array(); } } } return self::$file_map; } /** * Constructor. * * @param string $slug WordPress plugin slug. * @param array $config Configuration data. * @throws InvalidArgumentException If config is invalid. */ public function __construct( $slug, array $config ) { $this->slug = $slug; foreach ( array( 'name' => array( $this, 'is_nonempty_string' ), 'plugin_file' => array( $this, 'is_nonempty_string' ), 'repo' => array( $this, 'is_repo' ), 'mirror' => array( $this, 'is_repo' ), 'manifest_url' => array( $this, 'is_valid_url' ), 'beta_homepage_url' => array( $this, 'is_valid_url' ), 'bug_report_url' => array( $this, 'is_valid_url' ), ) as $k => $validator ) { if ( ! isset( $config[ $k ] ) ) { throw new InvalidArgumentException( "Missing configuration field $k" ); } if ( ! $validator( $config[ $k ] ) ) { throw new InvalidArgumentException( "Configuration field $k is not valid" ); } $this->{$k} = $config[ $k ]; } $this->unpublished = ! empty( $config['unpublished'] ); } /** * Validate as a non-empty string. * * @param string $v Value. * @return bool */ protected function is_nonempty_string( $v ) { return is_string( $v ) && '' !== $v; } /** * Validate as a GitHub repo slug. * * @param string $v Value. * @return bool */ protected function is_repo( $v ) { return (bool) preg_match( '!^[a-zA-Z0-9][a-zA-Z0-9-]*/[a-zA-Z0-9.-]+$!', $v ); } /** * Validate as a valid URL. * * @param string $v Value. * @return bool */ protected function is_valid_url( &$v ) { $v = filter_var( $v, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED ); return $v && str_starts_with( $v, 'https://' ); } /** * Get the name of the plugin. * * @return string */ public function get_name() { return $this->name; } /** * Get the GitHub slug for the plugin's repo. * * @return string */ public function repo() { return $this->repo; } /** * Get the GitHub slug for the plugin's mirror repo. * * @return string */ public function mirror_repo() { return $this->mirror; } /** * Get the Beta homepage URL. * * @return string */ public function beta_homepage_url() { return $this->beta_homepage_url; } /** * Get the bug report URL. * * @return string */ public function bug_report_url() { return $this->bug_report_url; } /** * Get the plugin slug. * * @return string */ public function plugin_slug() { return $this->slug; } /** * Get the dev plugin slug. * * @return string */ public function dev_plugin_slug() { return "{$this->slug}-dev"; } /** * Get the plugin file name. * * @return string */ public function plugin_file() { return $this->plugin_slug() . '/' . $this->plugin_file; } /** * Get the dev plugin file name. * * @return string */ public function dev_plugin_file() { return $this->dev_plugin_slug() . '/' . $this->plugin_file; } /** * Get the manifest data (i.e. branches) for the plugin. * * @param bool $no_cache Set true to bypass the transients cache. * @return object * @throws PluginDataException If the plugin manifest cannot be fetched or is invalid. */ public function get_manifest( $no_cache = false ) { if ( null === $this->manifest_data ) { $data = Utils::get_remote_data( $this->manifest_url, "manifest_$this->slug", $no_cache ); if ( ! is_object( $data ) ) { throw new PluginDataException( // translators: %s: Plugin slug. sprintf( __( 'Failed to download manifest for plugin \'%s\'. Check your Internet connection.', 'jetpack-beta' ), $this->slug ) ); } // Update old data. if ( ! isset( $data->trunk ) && isset( $data->master ) ) { $data->trunk = $data->master; } unset( $data->master ); $this->manifest_data = $data; } return $this->manifest_data; } /** * Get the WordPress.org plugin data for the plugin. * * @param bool $no_cache Set true to bypass the transients cache. * @return object * @throws PluginDataException If the data cannot be fetched or is invalid. */ public function get_wporg_data( $no_cache = false ) { if ( $this->unpublished ) { return (object) array(); } if ( null === $this->wporg_data ) { $url = sprintf( 'https://api.wordpress.org/plugins/info/1.0/%s.json', $this->slug ); $data = Utils::get_remote_data( $url, "wporg_data_$this->slug", $no_cache ); if ( ! is_object( $data ) ) { throw new PluginDataException( // translators: %s: Plugin slug. sprintf( __( 'Failed to download WordPress.org data for plugin \'%s\'. Check your Internet connection.', 'jetpack-beta' ), $this->slug ) ); } $this->wporg_data = $data; } return $this->wporg_data; } /** * Get the information for the installed dev version of the plugin. * * @return object|null */ public function dev_info() { $file = WP_PLUGIN_DIR . "/{$this->dev_plugin_slug()}/.jpbeta.json"; if ( ! file_exists( $file ) ) { return null; } // Initialize the WP_Filesystem API. require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() . '/wp-admin/', '', false, false, array() ); if ( ! WP_Filesystem( $creds ) ) { return new WP_Error( 'fs_api_error', __( 'Jetpack Beta: No File System access', 'jetpack-beta' ) ); } global $wp_filesystem; $info = json_decode( $wp_filesystem->get_contents( $file ) ); if ( is_object( $info ) && $info->source === 'master' ) { // Update old data. $info->source = 'trunk'; } return is_object( $info ) ? $info : null; } /** * Swap the activation record for the plugin. * * @param string $which Which version to make active: "stable" or "dev". * @param bool $activate Call `activate_plugin()` if the plugin wasn't already active. * @return null|WP_Error * @throws InvalidArgumentException If `$which` is invalid. */ public function select_active( $which, $activate = false ) { // The autoloader sets the cache in a shutdown hook. Clear it after the autoloader sets it. add_action( 'shutdown', array( self::class, 'clear_autoloader_plugin_cache' ), 99 ); if ( 'stable' === $which ) { $from = $this->dev_plugin_file(); $to = $this->plugin_file(); } elseif ( 'dev' === $which ) { $from = $this->plugin_file(); $to = $this->dev_plugin_file(); } else { throw new InvalidArgumentException( __METHOD__ . ': $which must be "stable" or "dev".' ); } // If the target is already active, nothing to do. if ( is_plugin_active( $to ) ) { return null; } // If the target doesn't exist, just deactivate the source. if ( ! file_exists( WP_PLUGIN_DIR . '/' . $to ) ) { return deactivate_plugins( $from ); } if ( is_plugin_active_for_network( $from ) ) { // Iterate and replace so as to preserve order. // I don't know if that's important, or just accidental behavior of the old code. $arr = array(); foreach ( get_site_option( 'active_sitewide_plugins' ) as $file => $date ) { $arr[ $file === $from ? $to : $file ] = $date; } update_site_option( 'active_sitewide_plugins', $arr ); return null; } elseif ( is_plugin_active( $from ) ) { $arr = get_option( 'active_plugins' ); $i = array_search( $from, $arr, true ); if ( false !== $i ) { $arr[ $i ] = $to; } update_option( 'active_plugins', $arr ); return null; } elseif ( $activate ) { return activate_plugin( $to ); } } /** * Install & activate the plugin for the given branch. * * @param string $source Source of installation: "stable", "trunk", "rc", "pr", or "release". * @param string $id When `$source` is "pr", the PR branch name. When "release", the version. * @return null|WP_Error * @throws InvalidArgumentException If `$source` is invalid. */ public function install_and_activate( $source, $id ) { // Cleanup after previous version of the beta plugin. if ( $this->plugin_slug() === 'jetpack' && file_exists( WP_PLUGIN_DIR . '/jetpack-pressable-beta' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() . '/wp-admin/', '', false, false, array() ); if ( ! WP_Filesystem( $creds ) ) { // Any problems and we exit. return new WP_error( 'Filesystem Problem' ); } global $wp_filesystem; if ( ! $wp_filesystem ) { return new WP_error( '$wp_filesystem is not global' ); } $working_dir = WP_PLUGIN_DIR . '/jetpack-pressable-beta'; // Delete the folder `JETPACK_BETA_PLUGIN_FOLDER`. if ( $wp_filesystem->is_dir( $working_dir ) ) { $wp_filesystem->delete( $working_dir, true ); } // Deactivate the plugin. deactivate_plugins( 'jetpack-pressable-beta/jetpack.php' ); } // If we're asked to install "unknown", that means the unknown stable version. if ( 'unknown' === $source ) { return $this->select_active( 'stable', true ); } // Load the info array and identify if it's "dev" or "stable". $ret = $this->get_which_and_info( $source, $id ); if ( is_wp_error( $ret ) ) { return $ret; } list( $which, $info ) = $ret; // Get info for the currently installed version. Return early if that version is what we need. if ( 'dev' === $which ) { $fs_info = $this->dev_info(); } else { $file = WP_PLUGIN_DIR . '/' . $this->plugin_file(); if ( file_exists( $file ) ) { $tmp = get_plugin_data( $file, false, false ); $fs_info = (object) array( 'source' => $info->source, 'version' => $tmp['Version'], ); } else { $fs_info = null; } } if ( $fs_info && $fs_info->source === $info->source && $fs_info->version === $info->version ) { return $this->select_active( $which, true ); } // Download and install. $ret = $this->install( $which, $info ); if ( is_wp_error( $ret ) ) { return $ret; } // And activate it. return $this->select_active( $which, true ); } /** * Get branch info for a source and ID. * * @param string $source Source of installation: "stable", "trunk", "rc", "pr", or "release". * @param string $id When `$source` is "pr", the PR branch name. When "release", the version. * @return object|WP_Error * @throws InvalidArgumentException If `$source` is invalid. */ public function source_info( $source, $id ) { // Load the info array and identify if it's "dev" or "stable". $ret = $this->get_which_and_info( $source, $id ); if ( is_wp_error( $ret ) ) { return $ret; } list( $which, $info ) = $ret; $info->which = $which; $info->pretty_version = $this->pretty_version( $info ); return $info; } /** * Get the WordPress upgrader response for the plugin, if any. * * @return null|object */ public function dev_upgrader_response() { $dev_info = $this->dev_info(); if ( ! $dev_info ) { // We can't know how to upgrade if there's no info. return array( null, null ); } $manifest = $this->get_manifest( true ); $slug = $this->dev_plugin_slug(); $info = null; if ( 'pr' === $dev_info->source && ! isset( $manifest->pr->{$dev_info->id} ) && isset( $manifest->trunk ) ) { // It's a PR that is gone. Update to trunk. list( , $info ) = $this->get_which_and_info( 'trunk', '' ); } elseif ( 'pr' === $dev_info->source && isset( $manifest->pr->{$dev_info->id} ) && Semver::greaterThan( $manifest->pr->{$dev_info->id}->version, $dev_info->version ) ) { // It's a PR that has been updated. list( , $info ) = $this->get_which_and_info( 'pr', $dev_info->id ); } elseif ( 'rc' === $dev_info->source && isset( $manifest->rc->download_url ) && Semver::greaterThan( $manifest->rc->version, $dev_info->version ) ) { // It's an RC that has a new version. list( , $info ) = $this->get_which_and_info( 'rc', '' ); } elseif ( 'trunk' === $dev_info->source && isset( $manifest->trunk ) && Semver::greaterThan( $manifest->trunk->version, $dev_info->version ) ) { // Trunk has been updated. list( , $info ) = $this->get_which_and_info( 'trunk', '' ); } if ( $info ) { return array( (object) array( 'id' => $slug, 'plugin' => $slug, 'slug' => $slug, 'new_version' => $info->version, 'package' => $info->download_url, 'url' => $info->plugin_url, 'jpbeta_info' => $info, ), null, ); } else { return array( null, (object) array( 'id' => $slug, 'plugin' => $slug, 'slug' => $slug, 'new_version' => $dev_info->version, 'url' => $dev_info->plugin_url, 'package' => $dev_info->download_url, ), ); } } /** * Get a WordPress API response for the dev plugin, if any. * * @param false|object|array $default Default value, if we can't fake up a response. * @return false|object|array */ public function dev_plugins_api_response( $default = false ) { $dev_info = $this->dev_info(); if ( ! $dev_info ) { return $default; } $file = WP_PLUGIN_DIR . '/' . $this->dev_plugin_file(); if ( ! file_exists( $file ) ) { return $default; } $tmp = get_plugin_data( $file, false, false ); // Read the plugin's to-test.md, or our generic testing tips should that not exist. $file = WP_PLUGIN_DIR . '/' . $this->dev_plugin_slug() . '/to-test.md'; if ( ! file_exists( $file ) ) { $file = __DIR__ . '/../docs/testing/testing-tips.md'; } WP_Filesystem(); global $wp_filesystem; $content = Utils::render_markdown( $this, $wp_filesystem->get_contents( $file ) ); $slug = $this->dev_plugin_slug(); $name = "{$this->get_name()} | {$this->dev_pretty_version()}"; return (object) array( 'slug' => $slug, 'plugin' => $slug, 'name' => $name, 'plugin_name' => $name, 'version' => $dev_info->version, 'author' => $tmp['Author'], 'homepage' => $this->beta_homepage_url(), 'downloaded' => false, 'last_updated' => date_create( $dev_info->update_date, timezone_open( 'UTC' ) )->format( 'Y-m-d g:i a \G\M\T' ), 'sections' => array( 'description' => $content ), 'download_link' => $dev_info->download_url, ); } /** * Get a "pretty" version of the current stable plugin version. * * @return string|null */ public function stable_pretty_version() { $file = WP_PLUGIN_DIR . '/' . $this->plugin_file(); if ( ! file_exists( $file ) ) { return null; } $tmp = get_plugin_data( $file, false, false ); return $this->pretty_version( (object) array( 'source' => 'release', 'version' => $tmp['Version'], ) ); } /** * Get a "pretty" version of the current dev plugin version. * * @return string|null */ public function dev_pretty_version() { $dev_info = $this->dev_info(); if ( ! $dev_info ) { $file = WP_PLUGIN_DIR . '/' . $this->dev_plugin_file(); if ( file_exists( $file ) ) { $tmp = get_plugin_data( $file, false, false ); return $tmp['Version']; } return null; } return $this->pretty_version( $dev_info ); } /** * Get a "pretty" version for the specified info object. * * @param object $info Info. * @return string */ private function pretty_version( $info ) { switch ( $info->source ) { case 'trunk': return __( 'Bleeding Edge', 'jetpack-beta' ); case 'rc': return __( 'Release Candidate', 'jetpack-beta' ); case 'pr': return sprintf( // translators: %1$s: Branch name. __( 'Feature Branch: %1$s', 'jetpack-beta' ), $info->branch ); case 'release': // translators: %s: Plugin version. return sprintf( __( 'Release version %s', 'jetpack-beta' ), $info->version ); default: return $info->version; } } /** * Get the "which" and info for the requested source and ID. * * @param string $source Source of installation: "stable", "trunk", "rc", "pr", or "release". * @param string $id When `$source` is "pr", the PR branch name. When "release", the version. * @return array|WP_Error ( $which, $info ) * @throws InvalidArgumentException If `$source` is invalid. */ private function get_which_and_info( $source, $id ) { // Get the info based on the source. switch ( $source ) { case 'stable': $which = 'stable'; $wporg_data = $this->get_wporg_data(); if ( ! isset( $wporg_data->download_link ) ) { return new WP_Error( 'stable_url_missing', // translators: %s: Plugin slug. sprintf( __( 'No stable download URL is available for %s.', 'jetpack-beta' ), $this->plugin_slug() ) ); } $info = (object) array( 'download_url' => $wporg_data->download_link, 'version' => $wporg_data->version, 'update_date' => date_create( $wporg_data->last_updated, timezone_open( 'UTC' ) )->format( 'Y-m-d H:i:s' ), ); $source = 'release'; $id = $wporg_data->version; break; // Master case remains purely for back-compatibility (in case anyone has bookmarked URLs). case 'master': $source = 'trunk'; // Change source to trunk, then fall-through to the 'trunk' case. case 'trunk': $id = ''; $which = 'dev'; $manifest = $this->get_manifest(); if ( ! isset( $manifest->trunk->download_url ) ) { return new WP_Error( 'trunk_missing', // translators: %s: Plugin slug. Also, "trunk" is the branch name and should not be translated. sprintf( __( 'No trunk build is available for %s.', 'jetpack-beta' ), $this->plugin_slug() ) ); } $info = $manifest->trunk; $info->plugin_url = sprintf( 'https://github.com/%s', $this->mirror_repo() ); break; case 'pr': $which = 'dev'; $manifest = $this->get_manifest(); $branch = Utils::normalize_branch_name( $id ); if ( ! isset( $manifest->pr->{$branch}->download_url ) ) { return new WP_Error( 'branch_missing', // translators: %1$s: Branch name. %2$s: Plugin slug. sprintf( __( 'No build is available for branch %1$s of %2$s.', 'jetpack-beta' ), $id, $this->plugin_slug() ) ); } $info = $manifest->pr->{$branch}; $info->plugin_url = sprintf( 'https://github.com/%s/pull/%d', $this->repo(), $info->pr ); $id = $branch; break; case 'rc': $which = 'dev'; $manifest = $this->get_manifest(); if ( isset( $manifest->rc->download_url ) ) { $info = $manifest->rc; $info->plugin_url = sprintf( 'https://github.com/%s/tree/%s', $this->mirror_repo(), $info->branch ); break; } return new WP_Error( 'rc_missing', // translators: %s: Plugin slug. sprintf( __( 'No release candidate build is available for %s.', 'jetpack-beta' ), $this->plugin_slug() ) ); case 'release': $which = 'stable'; $wporg_data = $this->get_wporg_data(); if ( ! isset( $wporg_data->versions->{$id} ) ) { return new WP_Error( 'release_missing', // translators: %1$s: Version number. %2$s: Plugin slug. sprintf( __( 'Version %1$s does not exist for %2$s.', 'jetpack-beta' ), $id, $this->plugin_slug() ) ); } $info = (object) array( 'download_url' => $wporg_data->versions->{$id}, 'version' => $id, ); break; default: throw new InvalidArgumentException( __METHOD__ . ': $source is invalid.' ); } $info->source = $source; $info->id = $id; return array( $which, $info ); } /** * Download and install the specified plugin. * * @param string $which "dev" or "stable". * @param object $info Plugin info. * @return null|WP_Error */ private function install( $which, $info ) { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Plugin_Upgrader( $skin ); $upgrader->init(); $result = $upgrader->install( $info->download_url, array( 'overwrite_package' => true, ) ); if ( is_wp_error( $result ) ) { return $result; } $errors = $upgrader->skin->get_errors(); if ( is_wp_error( $errors ) && $errors->get_error_code() ) { return $errors; } if ( $result === false ) { return new WP_Error( 'install_error', __( 'There was an error installing your plugin.', 'jetpack-beta' ) ); } // Record the source info, if it's a dev version. if ( 'dev' === $which ) { global $wp_filesystem; // Should have been set up by the upgrader already. $wp_filesystem->put_contents( WP_PLUGIN_DIR . '/' . $this->dev_plugin_slug() . '/.jpbeta.json', wp_json_encode( $info, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ); } return null; } /** * Action: Clears the autoloader transient. * * Action for `shutdown`. */ public static function clear_autoloader_plugin_cache() { delete_transient( 'jetpack_autoloader_plugin_paths' ); } }
projects/plugins/beta/src/class-parsedownext.php
<?php /** * Extension for Parsedown. * * @package automattic/jetpack-beta */ // phpcs:disable WordPress.NamingConventions.ValidVariableName namespace Automattic\JetpackBeta; use Parsedown; /** * Extension for Parsedown. * * Adds linking of GitHub PRs. */ class ParsedownExt extends Parsedown { /** * Format for generating PR links. * * @var string|null */ protected $prLinkFormat = null; /** * Constructor. */ public function __construct() { $this->InlineTypes['#'][] = 'PRLink'; $this->inlineMarkerList .= '#'; } /** * Set the PR link format (and enable PR links). * * @param string $format Printf-style format string. Should include `%d` for the PR number. * @return $this */ public function setPRLinkFormat( $format ) { $this->prLinkFormat = $format; return $this; } /** * Link PRs. * * @param array $excerpt Excerpt. * @return array|null */ protected function inlinePRLink( $excerpt ) { if ( null === $this->prLinkFormat || ! preg_match( '/^#(\d+)/', $excerpt['text'], $m ) ) { return null; } return array( 'extent' => strlen( $m[0] ), 'element' => array( 'name' => 'a', 'text' => $m[0], 'attributes' => array( 'href' => sprintf( $this->prLinkFormat, (int) $m[1] ), ), ), ); } }
projects/plugins/beta/src/class-hooks.php
<?php /** * Hooks class class file for the Jetpack Beta plugin. * * @package automattic/jetpack-beta */ namespace Automattic\JetpackBeta; use Jetpack; use Language_Pack_Upgrader; use Plugin_Upgrader; use WP_Ajax_Upgrader_Skin; use WP_Error; /** * Hooks class class file for the Jetpack Beta plugin. */ class Hooks { /** * Singleton class instance. * * @var static */ protected static $instance = null; /** * Previous error handler. * * @var callable */ protected static $prev_error_handler = null; /** * Main Instance */ public static function instance() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Constructor */ public function __construct() { add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'maybe_plugins_update_transient' ) ); add_filter( 'upgrader_post_install', array( $this, 'upgrader_post_install' ), 10, 3 ); add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ) ); add_filter( 'plugin_action_links', array( $this, 'remove_activate_link' ), 10, 2 ); add_filter( 'network_admin_plugin_action_links', array( $this, 'remove_activate_link' ), 10, 2 ); add_filter( 'all_plugins', array( $this, 'update_all_plugins' ) ); add_filter( 'plugins_api', array( $this, 'get_plugin_info' ), 10, 3 ); add_action( 'jetpack_beta_autoupdate_hourly_cron', array( self::class, 'run_autoupdate' ) ); add_filter( 'jetpack_options_whitelist', array( $this, 'add_to_options_whitelist' ) ); if ( is_admin() ) { self::maybe_schedule_autoupdate(); Admin::init(); } } /** * Filter: Inject dev plugins into `update_plugins` transient. * * Filter for `pre_set_site_transient_update_plugins`. * * We need to somehow inject our dev plugins into the list of plugins needing update * when an update is available. This is the way: catch the setting of the relevant * transient and add them in. * * @param object $transient Plugin update data. */ public function maybe_plugins_update_transient( $transient ) { if ( ! isset( $transient->no_update ) ) { return $transient; } foreach ( Plugin::get_plugin_file_map() as $nondev => $dev ) { unset( $transient->response[ $dev ] ); unset( $transient->no_update[ $dev ] ); // If the dev version is active, populate it into the transient. if ( is_plugin_active( $dev ) ) { list( $response, $no_update ) = Plugin::get_plugin( dirname( $nondev ) )->dev_upgrader_response(); if ( $response ) { $transient->response[ $dev ] = $response; } if ( $no_update ) { $transient->no_update[ $dev ] = $no_update; } } } return $transient; } /** * Filter: Called after the upgraded package has been installed. * * Filter for `upgrader_post_install`. * * We need to preserve the dev_info data across the upgrade. We do that by having * `maybe_plugins_update_transient()` include the info string in the transient, and * then this hook writes it to the filesystem post-upgrade. * * @param bool $worked Installation response. * @param array $hook_extras Extra args passed to hooked filters. * @param array $result Installation result data. * @return bool|WP_Error */ public function upgrader_post_install( $worked, $hook_extras, $result ) { global $wp_filesystem; if ( ! isset( $hook_extras['plugin'] ) ) { return $worked; } $updates = get_plugin_updates(); if ( isset( $updates[ $hook_extras['plugin'] ]->update->jpbeta_info ) ) { $info = $updates[ $hook_extras['plugin'] ]->update->jpbeta_info; $wp_filesystem->put_contents( $result['remote_destination'] . '/.jpbeta.json', wp_json_encode( $info, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ); } return $worked; } /** * If `is_multisite()`, filter the active_plugins option to ensure we don't have both * dev and non-dev versions of a plugin enabled at the same time (one network and one not). */ public static function is_network_enabled() { if ( is_multisite() ) { if ( ! function_exists( 'is_plugin_active_for_network' ) ) { require_once ABSPATH . '/wp-admin/includes/plugin.php'; } add_filter( 'option_active_plugins', array( self::class, 'override_active_plugins' ) ); } } /** * Filter: If a managed plugin is enabled sitewide, do not allow the other version to be enabled non-sitewide. * * Filter for `option_active_plugins`, only added when `is_multisite()`. * * @param array $active_plugins Currently activated plugins. * @return array Updated array of active plugins. */ public static function override_active_plugins( $active_plugins ) { $remove = array(); foreach ( Plugin::get_plugin_file_map() as $nondev => $dev ) { if ( is_plugin_active_for_network( $nondev ) || is_plugin_active_for_network( $dev ) ) { $remove[] = $nondev; $remove[] = $dev; } } if ( $remove ) { $active_plugins = array_values( array_diff( $active_plugins, $remove ) ); } return $active_plugins; } /** * Filter: Replace activate links in the other copy of our activated plugins. * * Filter for `plugin_action_links` and `network_admin_plugin_action_links`. * * @param string[] $actions Array of plugin action links. * @param string $plugin_file Plugin file. * @return $actions */ public function remove_activate_link( $actions, $plugin_file ) { if ( isset( $actions['activate'] ) ) { $map = Plugin::get_plugin_file_map(); $map += array_flip( $map ); if ( isset( $map[ $plugin_file ] ) && is_plugin_active( $map[ $plugin_file ] ) ) { $actions['activate'] = __( 'Plugin Already Active', 'jetpack-beta' ); } } return $actions; } /** * Filter: Hide duplicate entries in the Plugins list table. * * Filter for `all_plugins`. * * @param array $plugins Array of arrays of plugin data. * @return array Updated array of plugin data. */ public function update_all_plugins( $plugins ) { foreach ( Plugin::get_plugin_file_map() as $nondev => $dev ) { // WP.com requests away show regular plugin. if ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST ) { // Ensure that it reports the version it's using on account of the Jetpack Beta plugin to Calypso. if ( is_plugin_active( $dev ) ) { $plugins[ $nondev ]['Version'] = $plugins[ $dev ]['Version']; } unset( $plugins[ $dev ] ); } elseif ( is_plugin_active( $dev ) ) { unset( $plugins[ $nondev ] ); } else { unset( $plugins[ $dev ] ); } } return $plugins; } /** * Filter: WordPress.org Plugins API results. * * Filter for `plugins_api`. * * As the dev plugins aren't in the WordPress Plugin Directory, we need to fake * up records for them so the upgrader will know how to upgrade them. * * @param false|object|array $result Result from plugins_api. * @param string $action The type of information being requested from the Plugin Installation API. * @param object $args Plugin API arguments. * @return false|object|array $result */ public function get_plugin_info( $result, $action, $args ) { // Check if this is a 'plugin_information' request for a '-dev' plugin. if ( 'plugin_information' !== $action || ! str_ends_with( $args->slug, '-dev' ) ) { return $result; } // Get the plugin, and return a mocked-up API response. $plugin = Plugin::get_plugin( substr( $args->slug, 0, -4 ) ); return $plugin ? $plugin->dev_plugins_api_response( $result ) : $result; } /** * Activation hook. */ public static function activate() { // Don't do anyting funnly. if ( defined( 'DOING_CRON' ) ) { return; } require_once ABSPATH . 'wp-admin/includes/plugin.php'; wp_clean_plugins_cache( true ); } /** * Deactivation hook. */ public static function deactivate() { // Don't do anyting funnly. if ( defined( 'DOING_CRON' ) ) { return; } $plugins = Plugin::get_all_plugins(); add_action( 'shutdown', static function () use ( $plugins ) { foreach ( $plugins as $plugin ) { $plugin->select_active( 'stable' ); } }, 5 ); add_action( 'shutdown', static function () use ( $plugins ) { self::remove_dev_plugins( $plugins ); }, 20 ); self::clear_autoupdate_cron(); Utils::delete_all_transiants(); delete_option( 'jetpack_beta_plugin_file_map' ); } /** * When Jetpack Beta plugin is deactivated, remove any dev plugins. * * @param Plugin[] $plugins Plugins to remove. */ private static function remove_dev_plugins( array $plugins ) { // Don't do it on multisite, in case some other site still has it active. if ( is_multisite() ) { return; } // Initialize the WP_Filesystem API. require_once ABSPATH . 'wp-admin/includes/file.php'; $creds = request_filesystem_credentials( site_url() . '/wp-admin/', '', false, false, array() ); if ( ! WP_Filesystem( $creds ) ) { // Any problems and we exit. return; } global $wp_filesystem; if ( ! $wp_filesystem ) { return; } // Delete dev plugin dirs. foreach ( $plugins as $plugin ) { $working_dir = WP_PLUGIN_DIR . '/' . $plugin->dev_plugin_slug(); if ( $wp_filesystem->is_dir( $working_dir ) ) { $wp_filesystem->delete( $working_dir, true ); } } } /** * Action: Build the "Jetpack Beta" admin bar menu items. * * Action for `admin_bar_menu`. */ public function admin_bar_menu() { global $wp_admin_bar; if ( ! is_object( $wp_admin_bar ) ) { return; } require_once ABSPATH . 'wp-admin/includes/plugin.php'; // If no managed plugins are active, we don't want to display anything. $any = array(); foreach ( Plugin::get_plugin_file_map() as $nondev => $dev ) { if ( is_plugin_active( $nondev ) || is_plugin_active( $dev ) ) { $any = true; break; } } if ( ! $any ) { return; } // Add the main menu. $args = array( 'id' => 'jetpack-beta_admin_bar', 'title' => 'Jetpack Beta', 'parent' => 'top-secondary', 'href' => current_user_can( 'update_plugins' ) ? Utils::admin_url() : '', ); $wp_admin_bar->add_node( $args ); // Add child items for each active plugin. $any_dev = false; try { $plugins = Plugin::get_all_plugins(); } catch ( PluginDataException $ex ) { $plugins = array(); // Add a child item to our parent item. $args = array( 'id' => 'jetpack-beta_version_error', 'title' => $ex->getMessage(), 'parent' => 'jetpack-beta_admin_bar', ); $wp_admin_bar->add_node( $args ); } foreach ( $plugins as $slug => $plugin ) { if ( is_plugin_active( $plugin->plugin_file() ) ) { $is_dev = false; $version = $plugin->stable_pretty_version(); $dev_info = null; } elseif ( is_plugin_active( $plugin->dev_plugin_file() ) ) { $is_dev = true; $any_dev = true; $version = $plugin->dev_pretty_version(); $dev_info = $plugin->dev_info(); } else { continue; } // Add a child item to our parent item. $args = array( 'id' => 'jetpack-beta_version_' . $slug, // translators: %1$s: Plugin name. %2$s: Text denoting the active version. 'title' => sprintf( __( '%1$s: %2$s', 'jetpack-beta' ), $plugin->get_name(), $version ), 'parent' => 'jetpack-beta_admin_bar', ); if ( $is_dev ) { $args['meta'] = array( 'class' => 'jpbeta-highlight' ); } $wp_admin_bar->add_node( $args ); if ( current_user_can( 'update_plugins' ) ) { $args = array( 'id' => 'jetpack-beta_version_' . $slug . '_manage', // translators: %1$s: Plugin name. %2$s: Text denoting the active version. 'title' => __( 'Manage', 'jetpack-beta' ), 'parent' => 'jetpack-beta_version_' . $slug, 'href' => Utils::admin_url( array( 'plugin' => $slug ) ), ); $wp_admin_bar->add_node( $args ); } $args = array( 'id' => 'jetpack-beta_version_' . $slug . '_report', 'title' => __( 'Report Bug', 'jetpack-beta' ), 'parent' => 'jetpack-beta_version_' . $slug, 'href' => $plugin->bug_report_url(), ); $wp_admin_bar->add_node( $args ); if ( $dev_info && $dev_info->plugin_url ) { $args = array( 'id' => 'jetpack-beta_version_' . $slug . '_moreinfo', 'title' => __( 'More Info ', 'jetpack-beta' ), 'parent' => 'jetpack-beta_version_' . $slug, 'href' => $dev_info->plugin_url, ); $wp_admin_bar->add_node( $args ); } } // Highlight the menu if you are running the BETA Versions.. if ( $any_dev ) { $wp_admin_bar->add_node( array( 'id' => 'jetpack-beta_admin_bar', 'meta' => array( 'class' => 'jpbeta-highlight' ), ) ); // Use Jetpack Green 50 rather than 40 for accessibility, per pcdRpT-if-p2. echo "<style>#wpadminbar #wp-admin-bar-jetpack-beta_admin_bar.jpbeta-highlight, #wpadminbar #wp-admin-bar-jetpack-beta_admin_bar .jpbeta-highlight { background: #008710; }\n"; echo '#wpadminbar #wp-admin-bar-jetpack-beta_admin_bar.jpbeta-highlight > .ab-item, #wpadminbar #wp-admin-bar-jetpack-beta_admin_bar .jpbeta-highlight > .ab-item { color: white; }</style>'; } } /** * Clear scheduled WP-Cron jobs on plugin deactivation. */ private static function clear_autoupdate_cron() { if ( ! is_main_site() ) { return; } wp_clear_scheduled_hook( 'jetpack_beta_autoupdate_hourly_cron' ); wp_unschedule_hook( 'jetpack_beta_autoupdate_hourly_cron' ); } /** * Schedule plugin update jobs, if appropriate. */ public static function maybe_schedule_autoupdate() { if ( ! is_main_site() || ! Utils::is_set_to_autoupdate() ) { return; } $has_schedule_already = wp_get_schedule( 'jetpack_beta_autoupdate_hourly_cron' ); if ( ! $has_schedule_already ) { wp_clear_scheduled_hook( 'jetpack_beta_autoupdate_hourly_cron' ); wp_schedule_event( time(), 'hourly', 'jetpack_beta_autoupdate_hourly_cron' ); } } /** * The jetpack_beta_autoupdate_hourly_cron job - does not update Stable. */ public static function run_autoupdate() { if ( ! is_main_site() || ! Utils::is_set_to_autoupdate() ) { return; } $plugins = array_keys( Utils::plugins_needing_update() ); if ( ! $plugins ) { return; } // Unhook this functions that output things before we send our response header. remove_action( 'upgrader_process_complete', array( Language_Pack_Upgrader::class, 'async_upgrade' ), 20 ); remove_action( 'upgrader_process_complete', 'wp_version_check' ); remove_action( 'upgrader_process_complete', 'wp_update_themes' ); require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Plugin_Upgrader( $skin ); $upgrader->init(); // This avoids the plugin to be deactivated. // Using bulk upgrade puts the site into maintenance mode during the upgrades. $result = $upgrader->bulk_upgrade( $plugins ); $errors = $upgrader->skin->get_errors(); $log = $upgrader->skin->get_upgrade_messages(); if ( is_wp_error( $errors ) && $errors->get_error_code() ) { return $errors; } if ( $result && ! defined( 'JETPACK_BETA_SKIP_EMAIL' ) && Utils::is_set_to_email_notifications() ) { self::send_autoupdate_email( $plugins, $log ); } } /** * Builds and sends an email about succesfull plugin autoupdate. * * @param Array $plugins - List of plugins that were updated. * @param String $log - Upgrade message from core's plugin upgrader. */ private static function send_autoupdate_email( $plugins, $log ) { $admin_email = get_site_option( 'admin_email' ); if ( empty( $admin_email ) ) { return; } $site_title = get_bloginfo( 'name' ) ? get_bloginfo( 'name' ) : get_site_url(); // translators: %s: The site title. $subject = sprintf( __( '[%s] Jetpack Beta Tester auto-updates', 'jetpack-beta' ), $site_title ); $message = sprintf( // translators: %1$s: site url, $2$s: text of what has updated. __( 'Howdy! Your site at %1$s has autoupdated some plugins.', 'jetpack-beta' ), home_url() ); $message .= "\n\n"; // translators: %1$s: Plugin name. %2$s: pretty plugin version, %3$s: raw plugin version (eg 9.3.2-beta). $fmt = __( '%1$s updated to %2$s (%3$s)', 'jetpack-beta' ); $fmt = " - $fmt\n"; if ( in_array( JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php', $plugins, true ) ) { $file = WP_PLUGIN_DIR . '/' . JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php'; $tmp = get_plugin_data( $file, false, false ); $message .= sprintf( $fmt, 'Jetpack Beta Tester', $tmp['Version'], $tmp['Version'] ); } foreach ( Plugin::get_all_plugins() as $plugin ) { if ( ! in_array( $plugin->dev_plugin_file(), $plugins, true ) ) { continue; } $file = WP_PLUGIN_DIR . '/' . $plugin->dev_plugin_file(); $tmp = get_plugin_data( $file, false, false ); $message .= sprintf( $fmt, $plugin->get_name(), $plugin->dev_pretty_version(), $tmp['Version'] ); $dev_info = $plugin->dev_info(); if ( $dev_info && $dev_info->plugin_url ) { $message .= " $dev_info->plugin_url\n"; } } $message .= "\n"; $message .= __( 'During the autoupdate the following happened:', 'jetpack-beta' ); $message .= "\n\n"; // Can only reference the About screen if their update was successful. $log = array_map( 'html_entity_decode', $log ); $message .= ' - ' . implode( "\n - ", $log ); $message .= "\n\n"; wp_mail( $admin_email, $subject, $message ); } /** * Callback function to include Jetpack beta options into Jetpack sync whitelist. * * @param Array $whitelist List of whitelisted options to sync. */ public function add_to_options_whitelist( $whitelist ) { $whitelist = array_merge( $whitelist, Utils::options_to_sync() ); return $whitelist; } /** * Set up at plugin load. */ public static function setup() { self::$prev_error_handler = set_error_handler( array( self::class, 'custom_error_handler' ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler } /** * Custom error handler to intercept errors and log them using Jetpack's own logger. * * @param int $errno - Error code. * @param string $errstr - Error message. * @param string $errfile - File name where the error happened. * @param int $errline - Line in the code. * @return bool Whether to make the default handler handle the error as well. */ public static function custom_error_handler( $errno, $errstr, $errfile, $errline ) { if ( method_exists( Jetpack::class, 'log' ) ) { $error_string = sprintf( '%s, %s:%d', $errstr, $errfile, $errline ); // Only adding to log if the message is related to Jetpack. if ( false !== stripos( $error_string, 'jetpack' ) ) { Jetpack::log( $errno, $error_string ); } } if ( self::$prev_error_handler ) { return call_user_func( self::$prev_error_handler, $errno, $errstr, $errfile, $errline ); } else { // Returning false makes the error go through the standard error handler as well. return false; } } }
projects/plugins/beta/src/admin/show-needed-updates.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin template to show needed updates. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Plugin; use Automattic\JetpackBeta\Utils; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } // @global Plugin|null $plugin The plugin being managed, if any. May be unset, not just null. $plugin = isset( $plugin ) ? $plugin : null; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited // ------------- ( function ( $plugin ) { $updates = Utils::plugins_needing_update( true ); if ( isset( $plugin ) ) { $updates = array_intersect_key( $updates, array( $plugin->plugin_file() => 1, $plugin->dev_plugin_file() => 1, JPBETA__PLUGIN_FOLDER . '/jetpack-beta.php' => 1, ) ); } if ( ! $updates ) { return; } wp_enqueue_script( 'jetpack-beta-updates', plugins_url( 'updates.js', __FILE__ ), array( 'jquery', 'updates' ), JPBETA_VERSION, true ); wp_localize_script( 'jetpack-beta-updates', 'JetpackBetaUpdates', array( 'activate' => __( 'Activate', 'jetpack-beta' ), 'activating' => __( 'Activating...', 'jetpack-beta' ), 'updating' => __( 'Updating...', 'jetpack-beta' ), 'leaving' => __( 'Don\'t go Plugin is still installing!', 'jetpack-beta' ), ) ); // Junk needed by core's 'updates' JS. wp_print_admin_notice_templates(); wp_localize_script( 'updates', '_wpUpdatesItemCounts', array( 'totals' => wp_get_update_data(), ) ); ?> <div class="jetpack-beta__wrap jetpack-beta__update-needed"> <h2><?php esc_html_e( 'Some updates are available', 'jetpack-beta' ); ?></h2> <?php foreach ( $updates as $file => $update ) { $slug = dirname( $file ); if ( JPBETA__PLUGIN_FOLDER === $slug ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase $name = $update->Name; } else { $isdev = false; if ( str_ends_with( $slug, '-dev' ) ) { $isdev = true; $slug = substr( $slug, 0, -4 ); } $plugin = Plugin::get_plugin( $slug ); $name = $plugin->get_name() . ' | ' . ( $isdev ? $plugin->dev_pretty_version() : $plugin->stable_pretty_version() ); } $url = wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' . rawurlencode( $file ) ), 'upgrade-plugin_' . $file ); // translators: %s: Version number. $sub_header = sprintf( __( 'Version %s is available', 'jetpack-beta' ), $update->update->new_version ); ?> <div class="dops-foldable-card has-expanded-summary dops-card is-compact" data-slug="<?php echo esc_attr( $isdev ? "$slug-dev" : $slug ); ?>" data-plugin="<?php echo esc_attr( $file ); ?>"> <div class="dops-foldable-card__header has-border" > <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text branch-card-header"><?php echo esc_html( $name ); ?></div> <div class="dops-foldable-card__subheader"><?php echo esc_html( $sub_header ); ?></div> </div> </span> <span class="dops-foldable-card__secondary"> <span class="dops-foldable-card__summary"> <a href="<?php echo esc_url( $url ); ?>" class="is-primary jp-form-button update-branch dops-button is-compact"><?php esc_html_e( 'Update', 'jetpack-beta' ); ?></a> </span> </span> </div> </div> <?php } ?> </div> <?php } )( $plugin );
projects/plugins/beta/src/admin/exception.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Template to display an exception. * * @package automattic/jetpack-beta */ // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } // @global Exception $exception Exception to display. if ( ! isset( $exception ) ) { throw new InvalidArgumentException( 'Template parameter $exception missing' ); } $exception = $exception; // Dummy assignment to fool VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable. // ------------- ?> <div class="notice notice-error"> <p><?php echo esc_html( $exception->getMessage() ); ?></p> <!-- <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo str_replace( '--', '−−', $exception->__toString() ); ?> --> </div>
projects/plugins/beta/src/admin/plugin-select.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin page to select a plugin to manage. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Plugin; use Automattic\JetpackBeta\Utils; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } // ------------- // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $plugins = Plugin::get_all_plugins( true ); ?> <?php require __DIR__ . '/header.template.php'; ?> <div class="jetpack-beta-container" > <?php if ( ! Utils::has_been_used() ) { require __DIR__ . '/notice.template.php'; } ?> <?php require __DIR__ . '/toggles.template.php'; ?> <?php require __DIR__ . '/show-needed-updates.template.php'; ?> <div class="jetpack-beta__wrap"> <?php // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited foreach ( $plugins as $slug => $plugin ) { $classes = array( 'dops-foldable-card', 'has-expanded-summary', 'dops-card' ); if ( is_plugin_active( $plugin->plugin_file() ) ) { $classes[] = 'plugin-stable'; $verslug = $plugin->plugin_slug(); $version = $plugin->stable_pretty_version(); } elseif ( is_plugin_active( $plugin->dev_plugin_file() ) ) { $classes[] = 'plugin-dev'; $verslug = $plugin->dev_plugin_slug(); $version = $plugin->dev_pretty_version(); } else { $classes[] = 'plugin-inactive'; $verslug = ''; $version = __( 'Plugin is not active', 'jetpack-beta' ); } $classes[] = 'is-compact'; $url = Utils::admin_url( array( 'plugin' => $slug, ) ); ?> <div data-plugin="<?php echo esc_attr( $slug ); ?>" class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>"> <div class="dops-foldable-card__header has-border" > <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text branch-card-header"><?php echo esc_html( $plugin->get_name() ); ?></div> <div class="dops-foldable-card__subheader" data-jpbeta-version-for="<?php echo esc_attr( $verslug ); ?>"><?php echo esc_html( $version ); ?></div> </div> </span> <span class="dops-foldable-card__secondary"> <span class="dops-foldable-card__summary"> <a href="<?php echo esc_url( $url ); ?>" class="is-primary jp-form-button manage-plugin dops-button is-compact jptracks" data-jptracks-name="jetpack_beta_manage_plugin" data-jptracks-prop="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html__( 'Manage', 'jetpack-beta' ); ?></a> </span> </span> </div> </div> <?php } ?> </div>
projects/plugins/beta/src/admin/toggles.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin page toggles template. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Admin; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } ?> <span class="dops-foldable-card__secondary"> <?php Admin::show_toggle_emails(); ?> <?php Admin::show_toggle_autoupdates(); ?> </span>
projects/plugins/beta/src/admin/plugin-manage.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin manage page contents. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Admin; use Automattic\JetpackBeta\Utils; use Composer\Semver\Semver; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } // @global \Automattic\JetpackBeta\Plugin $plugin Plugin being managed. if ( ! isset( $plugin ) ) { throw new InvalidArgumentException( 'Template parameter $plugin missing' ); } // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $plugin = $plugin; // Dummy assignment to fool VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable. // ------------- $manifest = $plugin->get_manifest( true ); $wporg_data = $plugin->get_wporg_data( true ); $existing_branch = null; if ( file_exists( WP_PLUGIN_DIR . '/' . $plugin->plugin_file() ) ) { $tmp = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin->plugin_file(), false, false ); $existing_branch = $plugin->source_info( 'release', $tmp['Version'] ); if ( ! $existing_branch || is_wp_error( $existing_branch ) ) { $existing_branch = (object) array( 'which' => 'stable', 'source' => 'unknown', 'id' => $tmp['Version'], 'version' => $tmp['Version'], 'pretty_version' => $plugin->stable_pretty_version(), ); } } $active_branch = (object) array( 'which' => null, 'source' => null, 'id' => null, ); $version = null; if ( is_plugin_active( $plugin->plugin_file() ) ) { $active_branch = $existing_branch; $verslug = $plugin->plugin_slug(); $version = $active_branch->pretty_version; } elseif ( is_plugin_active( $plugin->dev_plugin_file() ) ) { $active_branch = $plugin->dev_info(); if ( $active_branch ) { $active_branch->which = 'dev'; $active_branch->pretty_version = $plugin->dev_pretty_version(); } else { $tmp = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin->dev_plugin_file(), false, false ); $active_branch = (object) array( 'which' => 'dev', 'source' => 'unknown', 'id' => $tmp['Version'], 'version' => $tmp['Version'], 'pretty_version' => __( 'Unknown Development Version', 'jetpack-beta' ), ); } $verslug = $plugin->dev_plugin_slug(); $version = $active_branch->pretty_version . ' | ' . $active_branch->version; } ?> <?php require __DIR__ . '/header.template.php'; ?> <div class="jetpack-beta-container" > <div id="jetpack-beta-tester__breadcrumb"> <a href="<?php echo esc_url( Utils::admin_url() ); ?>"> <?php esc_html_e( 'Jetpack Beta Tester Home', 'jetpack-beta' ); ?> </a> <span>&nbsp;&gt; <?php echo esc_html( $plugin->get_name() ); ?></span> </div> <?php if ( ! Utils::has_been_used() ) { require __DIR__ . '/notice.template.php'; } ?> <?php require __DIR__ . '/toggles.template.php'; ?> <?php require __DIR__ . '/show-needed-updates.template.php'; ?> <?php if ( null !== $version ) { ?> <div class="dops-foldable-card is-expanded has-expanded-summary dops-card is-compact"> <div class="dops-foldable-card__header has-border"> <span class="dops-foldable-card__main"> <span class="dops-foldable-card__header-text"> <?php echo esc_html( $plugin->get_name() ); ?> - Currently Running </span> </span> </div> <div class="dops-foldable-card__content"> <p data-jpbeta-version-for="<?php echo esc_attr( $verslug ); ?>"><?php echo wp_kses_post( $version ); ?></p> </div> </div> <div class="dops-foldable-card has-expanded-summary dops-card"> <div class="dops-foldable-card__header has-border"> <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text"><?php esc_html_e( 'Found a bug?', 'jetpack-beta' ); ?></div> </div> </span> <span class="dops-foldable-card__secondary" > <span class="dops-foldable-card__summary"> <a type="button" href="<?php echo esc_url( $plugin->bug_report_url() ); ?>" class="is-primary jp-form-button dops-button is-primary is-compact jptracks" data-jptracks-name="jetpack_beta_submit_report" data-jptracks-prop="<?php echo esc_attr( $plugin->plugin_slug() . ' ' . $active_branch->version ); ?>" > <?php esc_html_e( 'Report it!', 'jetpack-beta' ); ?> </a> </span> </span> </div> </div> <?php } ?> <div class="jetpack-beta__wrap"> <?php if ( $existing_branch && 'unknown' === $existing_branch->source ) { $branch = clone $existing_branch; $branch->pretty_version = __( 'Existing Version', 'jetpack-beta' ); require __DIR__ . '/branch-card.template.php'; } ?> <?php $branch = $plugin->source_info( 'stable', '' ); if ( $branch && ! is_wp_error( $branch ) ) { $branch->pretty_version = __( 'Latest Stable', 'jetpack-beta' ); require __DIR__ . '/branch-card.template.php'; // Fixup `$active_branch` so it doesn't show up as "active" under releases below. if ( $active_branch->source === $branch->source && $active_branch->id === $branch->id ) { $active_branch->source = 'stable'; $active_branch->id = ''; } } ?> <?php $branch = $plugin->source_info( 'rc', '' ); if ( $branch && ! is_wp_error( $branch ) ) { require __DIR__ . '/branch-card.template.php'; } ?> <?php $branch = $plugin->source_info( 'trunk', '' ); if ( $branch && ! is_wp_error( $branch ) ) { require __DIR__ . '/branch-card.template.php'; } ?> <?php if ( empty( $manifest->pr ) || ! (array) $manifest->pr ) { ?> <div id="section-pr"> <?php if ( 'pr' === $active_branch->source ) { $branch = clone $active_branch; $branch->pretty_version = $branch->branch; require __DIR__ . '/branch-card.template.php'; } ?> </div> <?php } else { ?> <div class="dops-navigation"> <div class="dops-section-nav has-pinned-items"> <div class="dops-section-nav__panel"> <div class="is-pinned is-open dops-search" role="search"> <div aria-controls="search-component" aria-label="<?php esc_attr_e( 'Open Search', 'jetpack-beta' ); ?>" tabindex="-1"> <svg class="gridicon gridicons-search dops-search-open__icon" height="24" viewbox="0 0 24 24" width="24"> <g> <path d="M21 19l-5.154-5.154C16.574 12.742 17 11.42 17 10c0-3.866-3.134-7-7-7s-7 3.134-7 7 3.134 7 7 7c1.42 0 2.742-.426 3.846-1.154L19 21l2-2zM5 10c0-2.757 2.243-5 5-5s5 2.243 5 5-2.243 5-5 5-5-2.243-5-5z"></path> </g> </svg> </div> <input aria-hidden="false" class="dops-search__input" id="search-component-prs" placeholder="<?php esc_attr_e( 'Search for a Feature Branch', 'jetpack-beta' ); ?>" role="search" type="search" value=""> <span aria-controls="search-component" id="search-component-prs-close" aria-label="<?php esc_attr_e( 'Close Search', 'jetpack-beta' ); ?>" tabindex="0"> <svg class="gridicon gridicons-cross dops-search-close__icon" height="24" viewbox="0 0 24 24" width="24"> <g> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path> </g> </svg> </span> </div> </div> </div> </div> <div id="section-pr"> <?php $pr_list = (array) $manifest->pr; end( $pr_list ); $last = key( $pr_list ); foreach ( $pr_list as $k => $pr ) { $branch = $plugin->source_info( 'pr', $pr->branch ); if ( $branch && ! is_wp_error( $branch ) ) { // Add spaces around the branch name for historical reasons. $branch->pretty_version = strtr( $branch->branch, array( '/' => ' / ', '-' => ' ', ) ); $branch->is_last = $k === $last; require __DIR__ . '/branch-card.template.php'; } } ?> </div> <?php } ?> <?php if ( empty( $wporg_data->versions ) || ! (array) $wporg_data->versions ) { ?> <div id="section-releases"> <?php if ( 'release' === $active_branch->source && $wporg_data->version !== $active_branch->id ) { $branch = $active_branch; require __DIR__ . '/branch-card.template.php'; } ?> </div> <?php } else { ?> <div class="dops-navigation"> <div class="dops-section-nav has-pinned-items"> <div class="dops-section-nav__panel"> <div class="is-pinned is-open dops-search" role="search"> <div aria-controls="search-component" aria-label="<?php esc_attr_e( 'Open Search', 'jetpack-beta' ); ?>" tabindex="-1"> <svg class="gridicon gridicons-search dops-search-open__icon" height="24" viewbox="0 0 24 24" width="24"> <g> <path d="M21 19l-5.154-5.154C16.574 12.742 17 11.42 17 10c0-3.866-3.134-7-7-7s-7 3.134-7 7 3.134 7 7 7c1.42 0 2.742-.426 3.846-1.154L19 21l2-2zM5 10c0-2.757 2.243-5 5-5s5 2.243 5 5-2.243 5-5 5-5-2.243-5-5z"></path> </g> </svg> </div> <input aria-hidden="false" class="dops-search__input" id="search-component-releases" placeholder="<?php esc_attr_e( 'Search for a release', 'jetpack-beta' ); ?>" role="search" type="search" value=""> <span aria-controls="search-component" id="search-component-releases-close" aria-label="<?php esc_attr_e( 'Close Search', 'jetpack-beta' ); ?>" tabindex="0"> <svg class="gridicon gridicons-cross dops-search-close__icon" height="24" viewbox="0 0 24 24" width="24"> <g> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path> </g> </svg> </span> </div> </div> </div> </div> <div id="section-releases"> <?php $versions = array_keys( (array) $wporg_data->versions ); $versions = Semver::rsort( $versions ); end( $versions ); $last = key( $versions ); foreach ( $versions as $k => $v ) { $branch = $plugin->source_info( 'release', $v ); if ( $branch && ! is_wp_error( $branch ) ) { unset( $branch->updated_date ); $branch->pretty_version = $branch->version; $branch->is_last = $k === $last; require __DIR__ . '/branch-card.template.php'; } } ?> </div> <?php } ?> </div> <?php list( $to_test, $what_changed ) = Admin::to_test_content( $plugin ); if ( $to_test ) { ?> <div class="dops-foldable-card is-expanded has-expanded-summary dops-card is-compact"> <div class="dops-foldable-card__header has-border"> <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text"><?php esc_html_e( 'To Test', 'jetpack-beta' ); ?></div> </div> </span> </div> <div class="dops-foldable-card__content"> <?php echo wp_kses_post( $to_test ); ?> </div> </div> <?php } if ( $what_changed ) { ?> <div class="dops-foldable-card is-expanded has-expanded-summary dops-card is-compact"> <div class="dops-foldable-card__header has-border"> <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text"><?php esc_html_e( 'What changed', 'jetpack-beta' ); ?></div> </div> </span> </div> <div class="dops-foldable-card__content"> <?php echo wp_kses_post( $what_changed ); ?> </div> </div> <?php } ?> </div>
projects/plugins/beta/src/admin/header.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin page header. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Utils; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } ?> <div class="jetpack-beta__bleeding-edge-head"> <div class="jetpack-beta-container"> <a class="jp-masthead__logo-link" href="<?php echo esc_url( Utils::admin_url() ); ?>"> <svg className="jetpack-beta-logo" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" height="32" viewBox="0 0 118 32"> <path fill="#069e08" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16s16-7.2,16-16S24.8,0,16,0z M15,19H7l8-16V19z M17,29V13h8L17,29z" /> <path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" /> <path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" /> <path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" /> <path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" /> <path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" /> <path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" /> <path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" /> </svg> <span>Beta Tester</span> </a> </div> </div>
projects/plugins/beta/src/admin/notice.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Jetpack Beta wp-admin page notice. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Utils; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } global $current_screen; // ------------- $is_notice = ( 'plugins' === $current_screen->base ? true : false ); ?> <style type="text/css"> #jetpack-beta-tester__start { background: #FFF; padding: 20px; margin-top:20px; box-shadow: 0 0 0 1px rgba(200, 215, 225, 0.5), 0 1px 2px #e9eff3; position: relative; } #jetpack-beta-tester__start.updated { border-left: 3px solid #8CC258; } #jetpack-beta-tester__start h1 { font-weight: 400; margin: 0; font-size: 20px; } #jetpack-beta-tester__start p { margin-bottom:1em; } </style> <div id="jetpack-beta-tester__start" class="<?php echo ( $is_notice ? 'notice notice-updated' : 'dops-card' ); ?>"> <h1><?php esc_html_e( 'Welcome to Jetpack Beta Tester', 'jetpack-beta' ); ?></h1> <p><?php esc_html_e( 'Thank you for helping to test our plugins! We appreciate your time and effort.', 'jetpack-beta' ); ?></p> <p> <?php echo wp_kses_post( __( 'When you select a branch to test, Jetpack Beta Tester will install and activate it on your behalf and keep it up to date. When you are finished testing, you can switch back to the current version by selecting <em>Latest Stable</em>.', 'jetpack-beta' ) ); ?> </p> <p> <?php echo wp_kses_post( __( 'Not sure where to start? If you select <em>Bleeding Edge</em>, you\'ll get all the cool new features we\'re planning to ship in our next release.', 'jetpack-beta' ) ); ?> </p> <?php if ( $is_notice ) { ?> <a href="<?php echo esc_url( Utils::admin_url() ); ?>"><?php esc_html_e( 'Let\'s get testing!', 'jetpack-beta' ); ?></a> <?php } ?> </div>
projects/plugins/beta/src/admin/branch-card.template.php
<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase /** * Template to display a branch card. * * @package automattic/jetpack-beta */ use Automattic\JetpackBeta\Utils; // Check that the file is not accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; } // @global \Automattic\JetpackBeta\Plugin $plugin Plugin being managed. if ( ! isset( $plugin ) ) { throw new InvalidArgumentException( 'Template parameter $plugin missing' ); } // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $plugin = $plugin; // Dummy assignment to fool VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable. // @global object $branch Branch data. if ( ! isset( $branch ) ) { throw new InvalidArgumentException( 'Template parameter $branch missing' ); } $branch = $branch; // Dummy assignment to fool VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable. // @global object $active_branch Active branch data. if ( ! isset( $active_branch ) ) { throw new InvalidArgumentException( 'Template parameter $active_branch missing' ); } $active_branch = $active_branch; // Dummy assignment to fool VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable. // ------------- ( function ( $plugin, $branch, $active_branch ) { $slug = 'dev' === $branch->which ? $plugin->dev_plugin_slug() : $plugin->plugin_slug(); $classes = array( 'dops-foldable-card', 'has-expanded-summary', 'dops-card', 'branch-card' ); $data_attr = ''; $more_info = array(); if ( isset( $branch->pr ) && is_int( $branch->pr ) ) { $data_attr = sprintf( 'data-pr="%s"', esc_attr( $branch->pr ) ); // translators: Translates the `More info` link. %1$s: URL. %2$s: PR number. $more_info[] = sprintf( __( '<a target="_blank" rel="external noopener noreferrer" href="%1$s">more info #%2$s</a>', 'jetpack-beta' ), $branch->plugin_url, $branch->pr ); } elseif ( 'release' === $branch->source ) { $data_attr = sprintf( 'data-release="%s"', esc_attr( $branch->version ) ); $more_info[] = sprintf( // translators: Which release is being selected. __( 'Public release (%1$s) <a href="https://plugins.trac.wordpress.org/browser/jetpack/tags/%2$s" target="_blank" rel="">available on WordPress.org</a>', 'jetpack-beta' ), esc_html( $branch->version ), esc_attr( $branch->version ) ); } elseif ( 'rc' === $branch->source || 'trunk' === $branch->source || 'unknown' === $branch->source ) { $more_info[] = sprintf( // translators: %s: Version number. __( 'Version %s', 'jetpack-beta' ), $branch->version ); } if ( isset( $branch->update_date ) ) { // translators: %s is how long ago the branch was updated. $more_info[] = sprintf( __( 'last updated %s ago', 'jetpack-beta' ), human_time_diff( strtotime( $branch->update_date ) ) ); } $activate_url = wp_nonce_url( Utils::admin_url( array( 'activate-branch' => "{$branch->source}:{$branch->id}", 'plugin' => $plugin->plugin_slug(), ) ), 'activate_branch' ); if ( $active_branch->source === $branch->source && $active_branch->id === $branch->id ) { $classes[] = 'branch-card-active'; } if ( 'unknown' === $branch->source ) { $classes[] = 'existing-branch-for-' . $plugin->plugin_slug(); } if ( empty( $branch->is_last ) ) { $classes[] = 'is-compact'; } // Needs to match what core's wp_ajax_update_plugin() will return. // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment, WordPress.WP.I18n.TextDomainMismatch $updater_version = sprintf( __( 'Version %s', 'default' ), $branch->version ); ?> <div <?php echo $data_attr; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>" data-slug="<?php echo esc_attr( $slug ); ?>" data-updater-version="<?php echo esc_attr( $updater_version ); ?>"> <div class="dops-foldable-card__header has-border" > <span class="dops-foldable-card__main"> <div class="dops-foldable-card__header-text"> <div class="dops-foldable-card__header-text branch-card-header"><?php echo esc_html( $branch->pretty_version ); ?></div> <div class="dops-foldable-card__subheader"> <?php echo wp_kses_post( implode( ' - ', $more_info ) ); ?> </div> </div> </span> <span class="dops-foldable-card__secondary"> <span class="dops-foldable-card__summary" data-active="<?php echo esc_attr( __( 'Active', 'jetpack-beta' ) ); ?>"> <a href="<?php echo esc_html( $activate_url ); ?>" class="is-primary jp-form-button activate-branch dops-button is-compact jptracks" data-jptracks-name="jetpack_beta_activate_branch" data-jptracks-prop="<?php echo esc_attr( "{$branch->source}:{$branch->id}" ); ?>"><?php echo esc_html__( 'Activate', 'jetpack-beta' ); ?></a> </span> </span> </div> </div> <?php } )( $plugin, $branch, $active_branch );
projects/plugins/videopress/jetpack-videopress.php
<?php /** * * Plugin Name: Jetpack VideoPress * Plugin URI: https://wordpress.org/plugins/jetpack-videopress * Description: High quality, ad-free video. * Version: 1.8-alpha * Author: Automattic - Jetpack Video team * Author URI: https://jetpack.com/videopress/ * License: GPLv2 or later * Text Domain: jetpack-videopress * * @package automattic/jetpack-videopress-plugin */ /* 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. */ if ( ! defined( 'ABSPATH' ) ) { exit; } define( 'JETPACK_VIDEOPRESS_DIR', plugin_dir_path( __FILE__ ) ); define( 'JETPACK_VIDEOPRESS_ROOT_FILE', __FILE__ ); define( 'JETPACK_VIDEOPRESS_ROOT_FILE_RELATIVE_PATH', plugin_basename( __FILE__ ) ); define( 'JETPACK_VIDEOPRESS_SLUG', 'jetpack-videopress' ); define( 'JETPACK_VIDEOPRESS_NAME', 'Jetpack VideoPress' ); define( 'JETPACK_VIDEOPRESS_URI', 'https://jetpack.com/jetpack-videopress' ); define( 'JETPACK_VIDEOPRESS_FOLDER', dirname( plugin_basename( __FILE__ ) ) ); // Jetpack Autoloader. $jetpack_autoloader = JETPACK_VIDEOPRESS_DIR . 'vendor/autoload_packages.php'; if ( is_readable( $jetpack_autoloader ) ) { require_once $jetpack_autoloader; if ( method_exists( \Automattic\Jetpack\Assets::class, 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( JETPACK_VIDEOPRESS_DIR . 'jetpack_vendor/i18n-map.php' ); } } else { // Something very unexpected. Error out gently with an admin_notice and exit loading. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log __( 'Error loading autoloader file for Jetpack VideoPress plugin', 'jetpack-videopress' ) ); } add_action( 'admin_notices', function () { ?> <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 VideoPress is incomplete. If you installed Jetpack VideoPress from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. Jetpack VideoPress must have Composer dependencies installed and built via the build command.', 'jetpack-videopress' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project' ); ?> </p> </div> <?php } ); return; } // Redirect to plugin page when the plugin is activated. add_action( 'activated_plugin', 'jetpack_videopress_activation' ); /** * Redirects to plugin page when the plugin is activated * * @param string $plugin Path to the plugin file relative to the plugins directory. */ function jetpack_videopress_activation( $plugin ) { if ( JETPACK_VIDEOPRESS_ROOT_FILE_RELATIVE_PATH === $plugin && \Automattic\Jetpack\Plugins_Installer::is_current_request_activating_plugin_from_plugins_screen( JETPACK_VIDEOPRESS_ROOT_FILE_RELATIVE_PATH ) ) { wp_safe_redirect( esc_url( admin_url( 'admin.php?page=jetpack-videopress' ) ) ); exit; } } // Add "Settings" link to plugins page. add_filter( 'plugin_action_links_' . JETPACK_VIDEOPRESS_FOLDER . '/jetpack-videopress.php', function ( $actions ) { $settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=jetpack-videopress' ) ) . '">' . __( 'Settings', 'jetpack-videopress' ) . '</a>'; array_unshift( $actions, $settings_link ); return $actions; } ); register_deactivation_hook( __FILE__, array( 'Jetpack_VideoPress_Plugin', 'plugin_deactivation' ) ); // Main plugin class. new Jetpack_VideoPress_Plugin();
projects/plugins/videopress/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php';
projects/plugins/videopress/src/class-jetpack-videopress-plugin.php
<?php /** * Primary class file for the Jetpack VideoPress plugin. * * @package automattic/jetpack-videopress-plugin-plugin */ if ( ! defined( 'ABSPATH' ) ) { exit; } use Automattic\Jetpack\Connection\Manager as Connection_Manager; use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication; use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer; use Automattic\Jetpack\VideoPress\Initializer as VideoPress_Pkg_Initializer; /** * Class Jetpack_VideoPress_Plugin */ class Jetpack_VideoPress_Plugin { /** * Constructor. */ public function __construct() { // Set up the REST authentication hooks. Connection_Rest_Authentication::init(); // Init Jetpack packages add_action( 'plugins_loaded', function () { $config = new Automattic\Jetpack\Config(); // Connection package. $config->ensure( 'connection', array( 'slug' => JETPACK_VIDEOPRESS_SLUG, 'name' => JETPACK_VIDEOPRESS_NAME, 'url_info' => JETPACK_VIDEOPRESS_URI, ) ); // Sync package. $config->ensure( 'sync' ); // Identity crisis package. $config->ensure( 'identity_crisis' ); $config->ensure( 'videopress', array( 'admin_ui' => true ) ); }, 1 ); add_filter( 'my_jetpack_videopress_activation', array( $this, 'my_jetpack_activation' ) ); // Register VideoPress block add_action( 'init', array( $this, 'register_videopress_blocks' ) ); My_Jetpack_Initializer::init(); } /** * Removes plugin from the connection manager * If it's the last plugin using the connection, the site will be disconnected. * * @access public * @static */ public static function plugin_deactivation() { $manager = new Connection_Manager( 'jetpack-videopress' ); $manager->remove_connection(); } /** * Register the VideoPress block. */ public function register_videopress_blocks() { VideoPress_Pkg_Initializer::register_videopress_blocks(); } /** * Initializes the package when the plugin is activated via My Jetpack * * This assures that the module will be filtered and considered active and that the Manage link will point to the VideoPress Admin UI * * @param bool|WP_Error $result The result of the activation. * @return bool|WP_Error */ public function my_jetpack_activation( $result ) { if ( is_wp_error( $result ) ) { return $result; } VideoPress_Pkg_Initializer::update_init_options( array( 'admin_ui' => true ) ); VideoPress_Pkg_Initializer::init(); return $result; } }
projects/plugins/inspect/functions.php
<?php use Automattic\Jetpack\Connection\Client; function jetpack_inspect_default_args( $args = array() ) { $defaults = array( 'method' => 'GET', 'body' => null, 'headers' => array(), ); return wp_parse_args( $args, $defaults ); } function jetpack_inspect_connection_request( $url, $args = array() ) { $args = jetpack_inspect_default_args( $args ); // Building signed request interface differs from wp_remote_request. // Body is passed as an argument. $body = $args['body']; unset( $args['body'] ); // Request signing process expects the URL to be provided in arguments. $args['url'] = $url; // Workaround the Jetpack Connection empty body feature/bug: // @TODO: Maybe show this as a warning/error in the UI? // This might lead to situations "Works in Jetpack Inspector but not IRL" if ( empty( $body ) ) { $body = null; } $signature = Client::build_signed_request( $args, $body ); if ( ! $signature || is_wp_error( $signature ) ) { return $signature; } return array( 'signature' => $signature, 'result' => Client::_wp_remote_request( $signature['url'], $signature['request'] ), ); } function silent_json_decode( $string ) { try { $json = json_decode( $string, false, 512, JSON_THROW_ON_ERROR ); if ( is_object( $json ) ) { return $json; } } catch ( Exception $e ) { return $string; } } function jetpack_inspect_wp_request() { } function jetpack_inspect_request( $url, $args ) { $args = jetpack_inspect_default_args( $args ); // I've been using this for a while now, can't remember why anymore. Nice. // Commented out for now. // if ( ! isset( $headers['Content-Type'] ) ) { // $headers['Content-Type'] = 'application/json; charset=utf-8;'; // } $request = jetpack_inspect_connection_request( $url, $args ); if ( is_wp_error( $request ) ) { return $request; } $signature = $request['signature']; $result = $request['result']; $body = wp_remote_retrieve_body( $result ); return array( 'body' => silent_json_decode( $body ), 'headers' => wp_remote_retrieve_headers( $result ), 'cookies' => wp_remote_retrieve_cookies( $result ), 'signature' => $signature, 'args' => $args, 'response' => $result, ); }
projects/plugins/inspect/options.php
<?php use Automattic\Jetpack\Packages\Async_Option\Async_Option; use Automattic\Jetpack\Packages\Async_Option\Async_Options; use Automattic\Jetpack\Packages\Async_Option\Registry; use Automattic\Jetpack_Inspect\Options\Monitor_Status; use Automattic\Jetpack_Inspect\Options\Observer_Settings; /** * Functions to make it easier to interface with Async Option: */ function jetpack_inspect_register_option( $name, $handler ) { return Registry::get_instance( 'jetpack_inspect' ) ->register( $name, $handler ); } /** * @param $name * * @return Async_Option */ function jetpack_inspect_option( $name ) { return Registry::get_instance( 'jetpack_inspect' )->get_option( $name ); } function jetpack_inspect_get_option( $option ) { return jetpack_inspect_option( $option )->get(); } function jetpack_inspect_update_option( $option, $value ) { return jetpack_inspect_option( $option )->set( $value ); } /** * Ensure that Async Options are passed to the relevant scripts. */ add_action( 'admin_init', function () { Async_Options::setup( 'jetpack_inspect', 'jetpack-inspect-main' ); } ); jetpack_inspect_register_option( 'monitor_status', new Monitor_Status() ); jetpack_inspect_register_option( 'observer_incoming', new Observer_Settings() ); jetpack_inspect_register_option( 'observer_outgoing', new Observer_Settings() );
projects/plugins/inspect/jetpack-inspect.php
<?php /** * Jetpack Inspect plugin * * @link https://automattic.com * @since 0.1.0 * * @wordpress-plugin * Plugin Name: Jetpack Inspect * Version: 0.1.0-alpha * Plugin URI: https://automattic.com * Description: Inspect HTTP incoming and outgoing requests and responses. * Author: pyronaur * Author URI: https://automattic.com * Requires at least: 6.0 * Text Domain: jetpack-inspect * * @package automattic/jetpack-inspect */ use Automattic\Jetpack\Config; use Automattic\Jetpack\Connection\Manager; use Automattic\Jetpack_Inspect\Admin_Page; use Automattic\Jetpack_Inspect\Log; use Automattic\Jetpack_Inspect\Monitors; use Automattic\Jetpack_Inspect\REST_API\Endpoints\Clear; use Automattic\Jetpack_Inspect\REST_API\Endpoints\Latest; use Automattic\Jetpack_Inspect\REST_API\Endpoints\Send_Request; use Automattic\Jetpack_Inspect\REST_API\Endpoints\Test_Request; use Automattic\Jetpack_Inspect\REST_API\REST_API; require_once plugin_dir_path( __FILE__ ) . '/vendor/autoload_packages.php'; if ( method_exists( \Automattic\Jetpack\Assets::class, 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( plugin_dir_path( __FILE__ ) . 'jetpack_vendor/i18n-map.php' ); } require __DIR__ . '/functions.php'; require __DIR__ . '/options.php'; /** * Enables Jetpack Connection support. */ function jetpack_inspect_connection() { // Here we enable the Jetpack packages. $config = new Config(); $config->ensure( 'connection', array( 'slug' => 'jetpack-inspect', 'name' => 'Jetpack Inspect', ) ); } /** * Attempts Jetpack Connection. */ function jetpack_inspect_attempt_connection() { $manager = new Manager( 'jetpack-inspect' ); if ( ! $manager->is_connected() ) { $manager->try_registration(); } } /** * Enables Jetpack Inspect custom post type and a special REST API endpoint. */ function jetpack_inspect_initialize() { Log::register_post_type(); REST_API::register( array( Latest::class, Clear::class, Send_Request::class, ) ); if ( defined( 'JETPACK_INSPECT_DEBUG' ) && JETPACK_INSPECT_DEBUG ) { REST_API::register( Test_Request::class ); } } add_action( 'init', 'jetpack_inspect_initialize' ); add_action( 'admin_menu', array( new Admin_Page(), 'register' ) ); add_action( 'plugins_loaded', array( Monitors::class, 'initialize' ) ); // Jetpack Connection. add_action( 'plugins_loaded', 'jetpack_inspect_connection', 1 ); add_action( 'admin_init', 'jetpack_inspect_attempt_connection' );
projects/plugins/inspect/app/Monitors.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack_Inspect; use Automattic\Jetpack_Inspect\Monitor\Incoming_REST_API; use Automattic\Jetpack_Inspect\Monitor\Outgoing; /** * The Monitors class. */ class Monitors { const AVAILABLE_OBSERVERS = array( 'outgoing' => Outgoing::class, 'incoming' => Incoming_REST_API::class, ); /** * Array of existing instances. * * @var array */ protected static $instances = array(); /** * Returns an instance that observer with a specific name. * * @param String $name observer name. */ public static function get( $name ) { if ( ! isset( static::AVAILABLE_OBSERVERS[ $name ] ) ) { return new \WP_Error( "The requested monitor doesn't exist." ); } if ( ! isset( static::$instances[ $name ] ) ) { $class = static::AVAILABLE_OBSERVERS[ $name ]; static::$instances[ $name ] = new Monitor( "observer_{$name}", new $class() ); } return static::$instances[ $name ]; } /** * Initializes the instance holder. */ public static function initialize() { foreach ( self::AVAILABLE_OBSERVERS as $name => $class ) { self::get( $name )->initialize(); } } }
projects/plugins/inspect/app/Monitor.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack_Inspect; use Automattic\Jetpack\Packages\Async_Option\Async_Option; use Automattic\Jetpack_Inspect\Monitor\Observable; /** * The Monitor class. */ class Monitor { /** * The observable object. * * @var Observable */ protected $observer; /** * The option name. * * @var String */ protected $name; /** * Whether to bypass the filter. * * @var Boolean * */ protected $bypass_filter = false; /** * The async option object. * * @var Async_Option */ protected $option; /** * Creates a Monitor object. * * @param String $name the option name. * @param Observable $observable the object to attach hooks to. */ public function __construct( $name, $observable ) { $this->name = $name; $this->observer = $observable; $this->option = jetpack_inspect_option( $name ); } /** * Initializes the object. */ public function initialize() { if ( defined( 'DOING_CRON' ) && DOING_CRON ) { return false; } if ( $this->is_enabled() ) { $this->observer->attach_hooks(); } add_action( 'shutdown', array( $this, 'save' ) ); } /** * Ensures that the hooks are attached. */ public function ensure_enabled() { if ( $this->is_enabled() ) { return; } $this->observer->attach_hooks(); add_action( 'shutdown', array( $this, 'log' ) ); } /** * Returns true whether the request url matches the filter. * * @param String $url the request URL. */ protected function match_request_filter( $url ) { if ( $this->bypass_filter ) { return true; } $filter = $this->get_filter(); if ( ! $filter ) { return true; } // https://example.com/?foo=bar will match "*example[s].com*. if ( str_contains( $filter, '*' ) || ( str_contains( $filter, '[' ) && str_contains( $filter, ']' ) ) ) { return fnmatch( $filter, $url ); } // https://example.com/?foo=bar will match "https://example.com/?foo=bar". if ( $filter[0] === $filter[ strlen( $filter ) - 1 ] && $filter[0] === '"' ) { $filter = substr( $filter, 1, - 1 ); return $filter === $url; } // https://example.com/?foo=bar will match example.com. return str_contains( $url, $filter ); } /** * Saves the log data. */ public function save() { $log_data = $this->observer->get(); if ( ! $log_data ) { return; } foreach ( $log_data as $data ) { if ( empty( $data ) || ! $this->match_request_filter( $data['url'] ) ) { continue; } // @TODO: Create a Log object. This will do for now. $url = $data['url']; unset( $data['url'] ); $log_name = $this->name; if ( isset( $data['error'] ) ) { $log_name = 'wp_error'; } $log = array( 'url' => $url, $log_name => $data, ); Log::insert( $url, $log ); } } /** * Generate keys for wp options dynamically * Example keys: * * observer_incoming * * observer_outgoing * * @param String $name option name. */ private function key( $name ) { return "{$this->name}_{$name}"; } /** * Returns the Monitor status. */ public function is_enabled() { return jetpack_inspect_get_option( 'monitor_status' ) && $this->option->get()['enabled']; } /** * Returns the currently set filter. */ public function get_filter() { return $this->option->get()['filter']; } }
projects/plugins/inspect/app/Admin_Page.php
<?php namespace Automattic\Jetpack_Inspect; class Admin_Page { public function enqueue() { wp_enqueue_script( 'jetpack-inspect-main', plugins_url( '../app-ui/build/jetpack-inspect.js', __FILE__ ), array(), '1.0.0', true ); wp_enqueue_style( 'jetpack-inspect-css', plugins_url( '../app-ui/build/jetpack-inspect.css', __FILE__ ), array(), '1.0.0' ); } /** * Create an admin menu item for Jetpack Boost Svelte edition. */ public function register() { $title = __( 'Jetpack Inspect', 'jetpack-inspect' ); $page = add_menu_page( $title, $title, 'manage_options', 'jetpack-inspect', array( $this, 'render' ), 'dashicons-hammer', 50 ); add_action( 'load-' . $page, array( $this, 'enqueue' ) ); } public function render() { ?> <div id="jetpack-inspect"></div> <?php } }
projects/plugins/inspect/app/Log.php
<?php namespace Automattic\Jetpack_Inspect; class Log { const POST_TYPE_NAME = 'jetpack_inspect_log'; /** * Static initialization. */ public static function register_post_type() { // Check if post type already registered. if ( post_type_exists( static::POST_TYPE_NAME ) ) { return; } register_post_type( static::POST_TYPE_NAME, array( 'label' => 'Jetpack Inspect Log', 'description' => 'Cache entries for the Jetpack Boost plugin.', 'public' => false, ) ); } public static function insert( $url, $data ) { $data_post_data = array( 'post_type' => static::POST_TYPE_NAME, 'post_title' => $url, 'post_name' => uniqid( 'jetpack_inspect_log_', true ), 'post_status' => 'publish', 'post_content' => base64_encode( wp_json_encode( $data ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ); wp_insert_post( $data_post_data ); } public static function post_to_entry( \WP_Post $post ): array { $post_id = $post->ID; try { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $data = json_decode( base64_decode( $post->post_content ), true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING | JSON_OBJECT_AS_ARRAY ); } catch ( \JsonException $e ) { $data = 'Error decoding JSON: ' . $e->getMessage(); } return array_merge( array( 'id' => $post_id, 'date' => $post->post_date, ), $data ); } public static function get_latest() { $posts = get_posts( array( 'post_type' => static::POST_TYPE_NAME, 'numberposts' => 50, 'orderby' => 'date', 'order' => 'DESC', 'no_found_rows' => true, 'ignore_sticky_posts' => true, ) ); return array_map( array( __CLASS__, 'post_to_entry' ), $posts ); } public static function clear() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->delete( $wpdb->posts, array( 'post_type' => static::POST_TYPE_NAME ), array( '%s' ) ); } }
projects/plugins/inspect/app/Options/Monitor_Status.php
<?php namespace Automattic\Jetpack_Inspect\Options; use Automattic\Jetpack\Packages\Async_Option\Async_Option_Template; class Monitor_Status extends Async_Option_Template { /** * @param $value * * @return bool */ public function sanitize( $value ) { return (bool) $value; } public function validate( $value ) { if ( ! is_bool( $value ) ) { return sprintf( // translators: %s is a PHP type name. __( "Status should be a 'boolean'. Received '%s'.", 'jetpack-inspect' ), gettype( $value ) ); } return true; } public function transform( $value ) { return (bool) $value; } public function parse( $value ) { return filter_var( $value, FILTER_VALIDATE_BOOLEAN ); } }
projects/plugins/inspect/app/Options/Observer_Settings.php
<?php namespace Automattic\Jetpack_Inspect\Options; use Automattic\Jetpack\Packages\Async_Option\Async_Option_Template; class Observer_Settings extends Async_Option_Template { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase public static $DEFAULT_VALUE = array( 'enabled' => true, 'filter' => '', ); public function sanitize( $value ) { return array( 'enabled' => filter_var( $value['enabled'], FILTER_VALIDATE_BOOLEAN ), 'filter' => sanitize_text_field( $value['filter'] ), ); } public function validate( $value ) { if ( ! isset( $value['enabled'] ) ) { $this->add_error( "Missing required key 'enabled'" ); } if ( ! isset( $value['filter'] ) ) { $this->add_error( "Missing required key 'filters'" ); } return ! $this->has_errors(); } public function parse( $value ) { return json_decode( $value, ARRAY_A ); } }
projects/plugins/inspect/app/Monitor/Outgoing.php
<?php namespace Automattic\Jetpack_Inspect\Monitor; class Outgoing implements Observable { private $start_time = array(); private $logs = array(); public function attach_hooks() { add_filter( 'http_request_args', array( $this, 'start_timer' ), 10, 2 ); add_action( 'http_api_debug', array( $this, 'log' ), 10, 5 ); } public function detach_hooks() { remove_filter( 'http_request_args', array( $this, 'start_timer' ), 10 ); remove_action( 'http_api_debug', array( $this, 'log' ), 5 ); } public function start_timer( $args, $url ) { $this->start_time[ $url ] = microtime( true ); return $args; } public function log( $response, $context, $transport, $args, $url ) { $log = array( 'url' => $url, 'args' => $args, 'duration' => floor( 1000 * ( microtime( true ) - $this->start_time[ $url ] ) ), ); if ( is_wp_error( $response ) ) { $log['error'] = $response; } else { $log['response'] = $response; } $this->logs[] = $log; } public function get() { return $this->logs; } }
projects/plugins/inspect/app/Monitor/Observable.php
<?php namespace Automattic\Jetpack_Inspect\Monitor; interface Observable { public function attach_hooks(); public function detach_hooks(); public function get(); }
projects/plugins/inspect/app/Monitor/Incoming_REST_API.php
<?php namespace Automattic\Jetpack_Inspect\Monitor; class Incoming_REST_API implements Observable { private $logs = array(); public function attach_hooks() { add_action( 'rest_request_after_callbacks', array( $this, 'log' ), 10, 3 ); } public function detach_hooks() { remove_action( 'rest_request_after_callbacks', array( $this, 'log' ) ); } public function log( $response, $handler, $request ) { // We might accidentally log too much. // If route starts with `/jetpack-inspect` ignore it: if ( strpos( $request->get_route(), '/jetpack-inspect' ) === 0 ) { return $response; } $url = rest_url( $request->get_route() ); $headers = $request->get_headers(); if ( isset( $headers['cookie'] ) && ! ( defined( 'JETPACK_INSPECT_DEBUG' ) && JETPACK_INSPECT_DEBUG ) ) { $headers['cookie'] = '<hidden>'; } $this->logs[] = array( 'url' => $url, 'request' => array( 'method' => $request->get_method(), 'body' => $request->get_body(), 'query' => $request->get_query_params(), 'headers' => $headers, ), 'response' => $response, ); return $response; } public function get() { return $this->logs; } }
projects/plugins/inspect/app/REST_API/REST_API.php
<?php namespace Automattic\Jetpack_Inspect\REST_API; use Automattic\Jetpack_Inspect\REST_API\Contracts\Endpoint; class REST_API { /** * @var Route[] */ protected $routes = array(); /** * @param Endpoint[] $routes */ public function __construct( $routes ) { foreach ( $routes as $route_class ) { $this->routes[] = new Route( $route_class ); } } public function register_rest_routes() { foreach ( $this->routes as $route ) { $route->register_rest_route(); } } /** * @param string|array $endpoints * * @return void */ public static function register( $endpoints ) { // If endpoints are passed as a string, // (array) will convert it to an array. $rest_api = new REST_API( (array) $endpoints ); add_action( 'rest_api_init', array( $rest_api, 'register_rest_routes' ) ); } }
projects/plugins/inspect/app/REST_API/Route.php
<?php namespace Automattic\Jetpack_Inspect\REST_API; class Route { /** * @var \Automattic\Jetpack_Inspect\REST_API\Contracts\Endpoint */ protected $endpoint; protected $permissions; public function __construct( $endpoint ) { $this->endpoint = new $endpoint(); $this->permissions = $this->endpoint->permissions(); } public function register_rest_route() { register_rest_route( 'jetpack-inspect', $this->endpoint->name(), array( 'methods' => $this->endpoint->request_methods(), 'callback' => array( $this->endpoint, 'response' ), 'permission_callback' => array( $this, 'verify_permissions' ), ) ); } /** * This method is going to run and try to verify that * all the permission callbacks are successful. * * If any of them fail - return false immediately. * * @param \WP_REST_Request $request * * @return bool */ public function verify_permissions( $request ) { if ( defined( 'WP_ENVIRONMENT_TYPE' ) && 'development' === WP_ENVIRONMENT_TYPE && defined( 'JETPACK_INSPECT_DEBUG' ) && JETPACK_INSPECT_DEBUG ) { return true; } if ( is_bool( $this->permissions ) ) { return $this->permissions; } foreach ( $this->permissions as $permission ) { if ( true !== $permission->verify( $request ) ) { return false; } } return true; } }
projects/plugins/inspect/app/REST_API/Endpoints/Clear.php
<?php /** * Create a new request for cloud critical CSS. * * Handler for POST 'cloud-css/request-generate'. */ namespace Automattic\Jetpack_Inspect\REST_API\Endpoints; use Automattic\Jetpack_Inspect\Log; use Automattic\Jetpack_Inspect\REST_API\Contracts\Endpoint; use Automattic\Jetpack_Inspect\REST_API\Permissions\Current_User_Admin; class Clear implements Endpoint { public function name() { return 'clear'; } public function request_methods() { return \WP_REST_Server::DELETABLE; } //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function response( $request ) { return rest_ensure_response( Log::clear() ? 'OK' : '' ); } public function permissions() { return array( new Current_User_Admin(), ); } }
projects/plugins/inspect/app/REST_API/Endpoints/Send_Request.php
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName namespace Automattic\Jetpack_Inspect\REST_API\Endpoints; use Automattic\Jetpack_Inspect\Monitors; use Automattic\Jetpack_Inspect\REST_API\Permissions\Current_User_Admin; use WP_REST_Server; /** * Request sender endpoint class. */ class Send_Request { /** * Returns the endpoint name. */ public function name() { return 'send-request'; } /** * Returns the endpoint read/write setting. */ public function request_methods() { return WP_REST_Server::EDITABLE; } /** * Returns a parsed value from a JSON string, or throws. * * @param String $value JSON value. */ public function maybe_get_json( $value ) { if ( ! is_string( $value ) ) { return $value; } try { return json_decode( $value, ARRAY_A, 512, JSON_THROW_ON_ERROR ); } catch ( \Exception $e ) { if ( '' === $value ) { return array(); } } return $value; } /** * Handle the request and return the response. * * @param Request $request request. */ public function response( $request ) { $body = $request->get_param( 'body' ); $headers = $request->get_param( 'headers' ); $method = $request->get_param( 'method' ); $url = $request->get_param( 'url' ); $headers = $this->maybe_get_json( $headers ); $body = $this->maybe_get_json( $body ); $args = array( 'method' => $method, 'body' => $body, 'headers' => $headers, ); $function = $this->get_transport_function( $request ); if ( is_wp_error( $function ) ) { return rest_ensure_response( $function ); } $monitor = Monitors::get( 'outgoing' ); if ( is_wp_error( $monitor ) ) { return rest_ensure_response( $monitor ); } $monitor->ensure_enabled(); $results = $function( $url, $args, ); return rest_ensure_response( $results ); } /** * Returns transport function name. * * @param Request $request request. */ private function get_transport_function( $request ) { $transport_name = $request->get_param( 'transport' ) ?? 'wp_remote_request'; $available_transports = array( 'jetpack_connection' => 'jetpack_inspect_request', 'wp' => 'wp_remote_request', ); if ( isset( $available_transports[ $transport_name ] ) ) { $function = $available_transports[ $transport_name ]; } if ( ! isset( $function ) || ! function_exists( $function ) ) { return new \WP_Error( 'Invalid Request Type' ); } return $function; } /** * Returns access permissions for the endpoint. */ public function permissions() { return array( new Current_User_Admin(), ); } }
projects/plugins/inspect/app/REST_API/Endpoints/Latest.php
<?php /** * Create a new request for cloud critical CSS. * * Handler for POST 'cloud-css/request-generate'. */ namespace Automattic\Jetpack_Inspect\REST_API\Endpoints; use Automattic\Jetpack_Inspect\Log; use Automattic\Jetpack_Inspect\REST_API\Contracts\Endpoint; use Automattic\Jetpack_Inspect\REST_API\Permissions\Current_User_Admin; use WP_REST_Server; class Latest implements Endpoint { public function name() { return 'latest'; } public function request_methods() { return WP_REST_Server::READABLE; } //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function response( $request ) { return rest_ensure_response( Log::get_latest() ); } public function permissions() { return array( new Current_User_Admin(), ); } }
projects/plugins/inspect/app/REST_API/Endpoints/Test_Request.php
<?php /** * Create a new request for cloud critical CSS. * * Handler for POST 'cloud-css/request-generate'. */ namespace Automattic\Jetpack_Inspect\REST_API\Endpoints; use Automattic\Jetpack_Inspect\REST_API\Contracts\Endpoint; class Test_Request implements Endpoint { public function name() { return 'test-request'; } public function request_methods() { return \WP_REST_Server::READABLE; } //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function response( $request ) { return rest_ensure_response( wp_remote_request( 'http://timeout.comm' . time() ) ); } public function permissions() { return true; } }
projects/plugins/inspect/app/REST_API/Contracts/Has_Endpoints.php
<?php namespace Automattic\Jetpack_Inspect\REST_API\Contracts; interface Has_Endpoints { /** * @return Endpoint[] */ public function get_endpoints(); }
projects/plugins/inspect/app/REST_API/Contracts/Endpoint.php
<?php namespace Automattic\Jetpack_Inspect\REST_API\Contracts; interface Endpoint { public function name(); public function request_methods(); public function response( $request ); public function permissions(); }
projects/plugins/inspect/app/REST_API/Contracts/Permission.php
<?php namespace Automattic\Jetpack_Inspect\REST_API\Contracts; /** * API Endpoints have permissions that are checked by WordPress on `permission_callback`. * * These permissions repeat themselves, for example: * * current_user_can * * wp_verify_nonce * * And in the case of nonces - they also need to interact with the rest of the application. * Permission contract helps make the permission callbacks more predictable. * This is especially necessary to deal with nonces * (or more on that, read `permissions/Nonce.php` */ interface Permission { /** * A method to verify whether this request * can be run in the current environment. * * @param \WP_REST_Request $request * * @return bool */ public function verify( $request ); }
projects/plugins/inspect/app/REST_API/Permissions/Nonce.php
<?php namespace Automattic\Jetpack_Inspect\REST_API\Permissions; use Automattic\Jetpack_Inspect\REST_API\Contracts\Permission; /** * Nonces are tricky in REST. * * `rest_api_init` action is only tirggered when visiting an URL that looks like a REST Endpoint. * This means that if nonces are generated there, they won't be available in regular * `init` or `admin_init` parts of the app. But that's exactly where we need them. * * So we need a way to both generate named nonces, but also know what nonces * we have generated and pass them to the front-end of the application. * * To do this without scattering nonce names across the application, * this class is using static properties while complying to with * the Permission contract and keeping track of the nonces * that have been generated, that way they can be * retrieved later using: * * Nonce::get_generated_nonces() */ class Nonce implements Permission { /** * WordPress calls nonce keys "actions" * * @var string The nonce key to validate */ private $action; /** * @var string Key used by `verify` method to validate \WP_Request */ private $request_key; /** * Whenever this class is invoked, it will statically save the generated nonce * So that they can be retrieved and passed to the admin UI * * @var array Associate array of nonces */ private static $saved_nonces = array(); public function __construct( $action, $request_key = 'nonce' ) { $this->action = $action; $this->request_key = $request_key; $this->generate_nonce( $action ); } public function verify( $request ) { if ( ! isset( $request[ $this->request_key ] ) ) { return false; } return false !== wp_verify_nonce( $request[ $this->request_key ], $this->action ); } public function generate_nonce() { $nonce = wp_create_nonce( $this->action ); static::save_generated_nonce( $this->action, $nonce ); return $nonce; } /** * Keep track of the nonces created using this class. * * @param string $action - The action where this nonce is used. * @param string $nonce - The nonce value. * * @return void */ private static function save_generated_nonce( $action, $nonce ) { static::$saved_nonces[ $action ] = $nonce; } /** * @return array Array of saved [action => nonce] pairs. */ public static function get_generated_nonces() { return static::$saved_nonces; } }
projects/plugins/inspect/app/REST_API/Permissions/Current_User_Admin.php
<?php namespace Automattic\Jetpack_Inspect\REST_API\Permissions; use Automattic\Jetpack_Inspect\REST_API\Contracts\Permission; class Current_User_Admin implements Permission { // $request is required to adhere to the contract. //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public function verify( $request ) { return current_user_can( 'manage_options' ); } }
projects/plugins/inspect/tests/php/bootstrap.php
<?php /** * Bootstrap. * * @package automattic/ */ /** * Include the composer autoloader. */ require_once __DIR__ . '/../../vendor/autoload.php';
projects/plugins/inspect/packages/Async_Option/Registry.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; class Registry { /** * @var Registry[] */ private static $instance = array(); /** * @var Async_Option[] */ private $options = array(); /** * @var Endpoint[] */ private $endpoints = array(); /** * @var string */ private $namespace; private function __construct( $namespace ) { $this->namespace = $namespace; } public static function get_instance( $namespace ) { if ( ! isset( static::$instance[ $namespace ] ) ) { static::$instance[ $namespace ] = new static( $namespace ); } return static::$instance[ $namespace ]; } public function sanitize_option_name( $key ) { $sanitized_key = sanitize_key( $key ); $sanitized_key = str_replace( '-', '_', $sanitized_key ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG && $sanitized_key !== $key ) { throw new \Exception( "Invalid key '$key'. Keys should only include alphanumeric characters and underscores." ); } return $sanitized_key; } public function sanitize_http_name( $key ) { return str_replace( '_', '-', sanitize_key( $key ) ); } /** * Register an option using an Async Option Template. * * @param $option_name string * @param $value Async_Option_Template * * @return Async_Option * @throws \Exception */ public function register( $key, $template ) { $key = $this->sanitize_option_name( $key ); $option = new Async_Option( $this->namespace, $key, $template ); $this->options[ $key ] = $option; $endpoint = new Endpoint( $this->get_namespace_http(), $this->sanitize_http_name( $option->key() ), $option ); $this->endpoints[ $key ] = $endpoint; add_action( 'rest_api_init', array( $endpoint, 'register_rest_route' ) ); return $option; } public function all() { return $this->options; } public function get_endpoint( $key ) { if ( ! isset( $this->endpoints[ $key ] ) ) { return false; } return $this->endpoints[ $key ]; } public function get_option( $key ) { if ( ! isset( $this->options[ $key ] ) ) { return false; } return $this->options[ $key ]; } public function get_namespace() { return $this->namespace; } public function get_namespace_http() { return $this->sanitize_http_name( $this->namespace ); } }
projects/plugins/inspect/packages/Async_Option/Async_Option_Template.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; use Automattic\Jetpack\Packages\Async_Option\Storage\Storage; use Automattic\Jetpack\Packages\Async_Option\Storage\WP_Option; /** * Any registered async option should use this async option template * and extend the methods that are necessary. */ abstract class Async_Option_Template { /** * The default value if no option is found. */ public static $DEFAULT_VALUE = false; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase /** * @var string[] */ private $errors = array(); /** * Setup storage mechanism that subscribes to `Storage` contract * * @param $storage_namespace string * * @return Storage */ public function setup_storage( $storage_namespace ) { return new WP_Option( $storage_namespace ); } /** * On get, * Transform the value when it's retrieved from storage. * * @param $value * * @return mixed */ public function transform( $value ) { return $value; } /** * 1) On submit, * Parse the received value before it's validated. * * This can be used for things like json_decode or casting types. * * @param $value * * @return mixed */ public function parse( $value ) { return $value; } /** * 2) On submit, * Validate a received value before storing it. * * Use this method to provide feedback if the value isn't valid. * Using `$this->add_error()` will prevent the value from being stored. * * @param $value * * @return bool - Return true on success, false on failure. */ public function validate( $value ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Used in subclasses. return ! $this->has_errors(); } /** * 3) On submit, * Sanitize the value before inserting it into storage. * * This is the only required method of any async option * because values shouldn't be stored unsanitized. * Wash your values, friends. * * @param $value * * @return mixed */ abstract public function sanitize( $value ); /** * * Methods to help handling errors */ public function has_errors() { return ! empty( $this->errors ); } public function get_errors() { return implode( "\n", $this->errors ); } protected function add_error( $message ) { $this->errors[] = $message; } }
projects/plugins/inspect/packages/Async_Option/Async_Option.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; use Automattic\Jetpack\Packages\Async_Option\Storage\Storage; class Async_Option { /** * @var string */ private $key; /** * @var Storage */ protected $storage; /** * @var Async_Option_Template */ protected $option; /** * @param $namespace string * @param $key string * @param $value Async_Option_Template */ public function __construct( $namespace, $key, $value ) { $this->key = $key; $this->option = $value; $this->storage = $this->option->setup_storage( $namespace ); } public function get() { return $this->option->transform( // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase, VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable -- False positive on the latter. $this->storage->get( $this->key, ( $this->option )::$DEFAULT_VALUE ) ); } public function set( $input ) { $value = $this->option->parse( $input ); if ( true !== $this->option->validate( $value ) ) { return $this->option->get_errors(); } if ( ! empty( $this->storage ) ) { return $this->storage->set( $this->key, $this->option->sanitize( $value ) ); } return false; } public function delete() { return $this->storage->delete( $this->key ); } public function key() { return $this->key; } public function has_errors() { return $this->option->has_errors(); } public function get_errors() { return $this->option->get_errors(); } }
projects/plugins/inspect/packages/Async_Option/Endpoint.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; class Endpoint { /** * @var Async_Option $option */ private $option; /** * @var string $rest_namespace */ private $rest_namespace; /** * @var string $route */ private $route; /** * @var Authenticated_Nonce */ private $nonce; /** * @param string $namespace * @param Async_Option $option */ public function __construct( $namespace, $route, Async_Option $option ) { $this->option = $option; $this->rest_namespace = $namespace; $this->route = $route; $this->nonce = new Authenticated_Nonce( "{$namespace}_{$option->key()}" ); } public function register_rest_route() { register_rest_route( $this->rest_namespace, $this->route, array( 'methods' => \WP_REST_Server::ALLMETHODS, 'callback' => array( $this, 'handler' ), 'permission_callback' => array( $this, 'permissions' ), ) ); } /** * Route the request to the apropriate handler. * * @param \WP_REST_Request $request */ public function handler( $request ) { $methods = array( 'GET' => 'handle_get', 'POST' => 'handle_post', 'DELETE' => 'handle_delete', ); if ( ! isset( $methods[ $request->get_method() ] ) ) { return new \WP_Error( 'invalid_method', 'Invalid method.', array( 'status' => 400 ) ); } $method = $methods[ $request->get_method() ]; return rest_ensure_response( $this->$method( $request ) ); } /** * Handle GET Requests */ public function handle_get() { return $this->option->get(); } /** * Handle POST Requests * * @param \WP_REST_Request $request */ public function handle_post( $request ) { $this->option->set( $request->get_body() ); if ( $this->option->has_errors() ) { return new \WP_Error( 400, $this->option->get_errors(), array( 'status' => 400 ) ); } return $this->option->get(); } /** * Handle DELETE Requests. */ public function handle_delete() { $this->option->delete(); return $this->option->get(); } /** * Create a nonce for this endpoint * * @return false|string */ public function create_nonce() { return $this->nonce->create(); } /** * @param \WP_REST_Request $request */ public function permissions( $request ) { return current_user_can( 'manage_options' ) && $this->nonce->verify( $request->get_header( 'X-Async-Options-Nonce' ) ); } }
projects/plugins/inspect/packages/Async_Option/Async_Options.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; class Async_Options { /** * @var Registry */ protected $registry; /** * @var string Script Handle name to pass the variables to. */ protected $script_handle; public function __construct( $script_handle, Registry $registry ) { $this->script_handle = $script_handle; $this->registry = $registry; } /** * Don't call this method directly. * It's only public so that it can be called as a hook * * @return void */ public function _print_options_script_tag() { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore $data = array( 'rest_api' => array( 'value' => rest_url( $this->registry->get_namespace_http() ), 'nonce' => wp_create_nonce( 'wp_rest' ), ), ); foreach ( $this->registry->all() as $option ) { $data[ $option->key() ] = array( 'value' => $option->get(), 'nonce' => $this->registry->get_endpoint( $option->key() )->create_nonce(), ); } wp_localize_script( $this->script_handle, $this->registry->get_namespace(), $data ); } /** * Tell WordPress to print script tags in the specified plugin page * * @param string $plugin_page The slug name of the plugin page. * @param string $parent_page The slug name for the parent menu (or the file name of a standard * WordPress admin page). * * @return void */ public function add_to_plugin_page( $plugin_page, $parent_page ) { $plugin_page_hook = get_plugin_page_hook( $plugin_page, $parent_page ); add_action( $plugin_page_hook, array( $this, '_print_options_script_tag' ) ); } public static function setup( $registry_name, $script_handle, $plugin_page = null, $parent_page = 'admin' ) { $registry = Registry::get_instance( $registry_name ); /** * The plugin page slug can be anything, but makes setup easier to read by making assumptions. * This assumes that the plugin page string is going to match the registry namespace, * formatted as a http parameter. (kebab case) * * Example: * Registry with namespace: `jetpack_boost` should be * automatically attached to `admin.php?page=jetpack-boost` */ if ( $plugin_page === null ) { $plugin_page = $registry->get_namespace_http(); } $instance = new self( $script_handle, $registry ); $instance->add_to_plugin_page( $plugin_page, $parent_page ); } }
projects/plugins/inspect/packages/Async_Option/Authenticated_Nonce.php
<?php namespace Automattic\Jetpack\Packages\Async_Option; class Authenticated_Nonce { /** * @var string Nonce key */ private $key; public function __construct( $key ) { $this->key = $key; } public function create() { if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! did_action( 'set_current_user' ) ) { throw new \Exception( "Debug: Attempting to create {$this->key} nonce before the user is set." ); } return wp_create_nonce( $this->key ); } public function verify( $nonce ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! did_action( 'set_current_user' ) ) { throw new \Exception( "Debug: Attempting to validate {$this->key} nonce before the user is set." ); } return wp_verify_nonce( $nonce, $this->key ); } }
projects/plugins/inspect/packages/Async_Option/Storage/WP_Option.php
<?php namespace Automattic\Jetpack\Packages\Async_Option\Storage; class WP_Option implements Storage { public function __construct( $namepsace ) { $this->namespace = $namepsace; } public function get( $key, $default = false ) { return get_option( $this->key( $key ), $default ); } public function set( $key, $value ) { return update_option( $this->key( $key ), $value ); } public function delete( $key ) { return delete_option( $this->key( $key ) ); } public function key( $key ) { return $this->namespace . '_' . $key; } }
projects/plugins/inspect/packages/Async_Option/Storage/Storage.php
<?php namespace Automattic\Jetpack\Packages\Async_Option\Storage; interface Storage { public function get( $key ); public function set( $key, $value ); public function delete( $key ); }
projects/plugins/boost/index.php
<?php //phpcs:ignoreFile /** * Empty file. */ // Silence is golden.
projects/plugins/boost/wp-js-data-sync.php
<?php use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Entry; use Automattic\Jetpack\WP_JS_Data_Sync\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Data_Sync_Readonly; use Automattic\Jetpack\WP_JS_Data_Sync\Schema\Schema; use Automattic\Jetpack_Boost\Data_Sync\Critical_CSS_Meta_Entry; use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry; use Automattic\Jetpack_Boost\Data_Sync\Mergeable_Array_Entry; use Automattic\Jetpack_Boost\Data_Sync\Minify_Excludes_State_Entry; use Automattic\Jetpack_Boost\Data_Sync\Modules_State_Entry; use Automattic\Jetpack_Boost\Lib\Connection; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions\Regenerate_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions\Set_Provider_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions\Set_Provider_Error_Dismissed; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions\Set_Provider_Errors; use Automattic\Jetpack_Boost\Lib\Premium_Features; use Automattic\Jetpack_Boost\Lib\Premium_Pricing; use Automattic\Jetpack_Boost\Lib\Super_Cache_Info; use Automattic\Jetpack_Boost\Modules\Optimizations\Minify\Minify_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Minify\Minify_JS; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync\Page_Cache_Entry; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync_Actions\Clear_Page_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync_Actions\Run_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Logger; if ( ! defined( 'JETPACK_BOOST_DATASYNC_NAMESPACE' ) ) { define( 'JETPACK_BOOST_DATASYNC_NAMESPACE', 'jetpack_boost_ds' ); } /** * Make it easier to register a Jetpack Boost Data-Sync option. * * @param $key string - The key for this option. * @param $parser Automattic\Jetpack\WP_JS_Data_Sync\Schema\Parser - The schema for this option. * @param $entry Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Entry|null - The entry handler for this option. */ function jetpack_boost_register_option( $key, $parser, $entry = null ) { Data_Sync::get_instance( JETPACK_BOOST_DATASYNC_NAMESPACE ) ->register( $key, $parser, $entry ); } /** * Register a new Jetpack Boost Data_Sync Action * * @param $key string * @param $action_name string * @param $instance Data_Sync_Action * * @return void */ function jetpack_boost_register_action( $key, $action_name, $request_schema, $instance ) { Data_Sync::get_instance( JETPACK_BOOST_DATASYNC_NAMESPACE ) ->register_action( $key, $action_name, $request_schema, $instance ); } /** * Make it easier to register a Jetpack Boost Read-only Data-Sync option. */ function jetpack_boost_register_readonly_option( $key, $callback ) { jetpack_boost_register_option( $key, Schema::as_unsafe_any(), new Data_Sync_Readonly( $callback ) ); } /** * @param $key * * @return Data_Sync_Entry */ function jetpack_boost_ds_entry( $key ) { return Data_Sync::get_instance( JETPACK_BOOST_DATASYNC_NAMESPACE ) ->get_registry() ->get_entry( $key ); } function jetpack_boost_ds_get( $key ) { $entry = jetpack_boost_ds_entry( $key ); if ( ! $entry ) { return null; } return $entry->get(); } function jetpack_boost_ds_set( $key, $value ) { $entry = jetpack_boost_ds_entry( $key ); if ( ! $entry ) { return null; } return $entry->set( $value ); } function jetpack_boost_ds_delete( $key ) { $entry = jetpack_boost_ds_entry( $key ); if ( ! $entry ) { return null; } return $entry->delete(); } /** * Ensure that Async Options are passed to the relevant scripts. */ function jetpack_boost_initialize_datasync() { $data_sync = Data_Sync::get_instance( JETPACK_BOOST_DATASYNC_NAMESPACE ); $data_sync->attach_to_plugin( 'jetpack-boost-admin', 'jetpack_page_jetpack-boost' ); } add_action( 'admin_init', 'jetpack_boost_initialize_datasync' ); // Represents a set of errors that can be stored for a single Provider Key in a Critical CSS state block. $critical_css_provider_error_set_schema = Schema::as_array( Schema::as_assoc_array( array( 'url' => Schema::as_string(), 'message' => Schema::as_string(), 'type' => Schema::as_string(), 'meta' => Schema::any_json_data()->nullable(), ) )->fallback( array( 'url' => '', 'message' => '', 'type' => '', ) ) ); $critical_css_state_schema = Schema::as_assoc_array( array( 'providers' => Schema::as_array( Schema::as_assoc_array( array( 'key' => Schema::as_string(), 'label' => Schema::as_string(), 'urls' => Schema::as_array( Schema::as_string() ), 'success_ratio' => Schema::as_float(), 'status' => Schema::enum( array( 'success', 'pending', 'error', 'validation-error' ) )->fallback( 'validation-error' ), 'error_status' => Schema::enum( array( 'active', 'dismissed' ) )->nullable(), 'errors' => $critical_css_provider_error_set_schema->nullable(), ) ) )->nullable(), 'status' => Schema::enum( array( 'not_generated', 'generated', 'pending', 'error' ) )->fallback( 'not_generated' ), 'created' => Schema::as_float()->nullable(), 'updated' => Schema::as_float()->nullable(), 'status_error' => Schema::as_string()->nullable(), ) )->fallback( array( 'providers' => array(), 'status' => 'not_generated', 'created' => null, 'updated' => null, ) ); $critical_css_meta_schema = Schema::as_assoc_array( array( 'proxy_nonce' => Schema::as_string()->nullable(), ) ); $critical_css_suggest_regenerate_schema = Schema::enum( array( '1', // Old versions of Boost stored a boolean in the DB. 'page_saved', 'post_saved', 'switched_theme', 'plugin_change', ) )->nullable(); /** * Register Data Sync Stores */ jetpack_boost_register_option( 'critical_css_state', $critical_css_state_schema ); jetpack_boost_register_option( 'critical_css_meta', $critical_css_meta_schema, new Critical_CSS_Meta_Entry() ); jetpack_boost_register_option( 'critical_css_suggest_regenerate', $critical_css_suggest_regenerate_schema ); jetpack_boost_register_action( 'critical_css_state', 'request-regenerate', Schema::as_void(), new Regenerate_CSS() ); jetpack_boost_register_action( 'critical_css_state', 'set-provider-css', Schema::as_assoc_array( array( 'key' => Schema::as_string(), 'css' => Schema::as_string(), ) ), new Set_Provider_CSS() ); jetpack_boost_register_action( 'critical_css_state', 'set-provider-errors', Schema::as_assoc_array( array( 'key' => Schema::as_string(), 'errors' => $critical_css_provider_error_set_schema, ) ), new Set_Provider_Errors() ); jetpack_boost_register_action( 'critical_css_state', 'set-provider-errors-dismissed', Schema::as_array( Schema::as_assoc_array( array( 'key' => Schema::as_string(), 'dismissed' => Schema::as_boolean(), ) ) ), new Set_Provider_Error_Dismissed() ); $modules_state_schema = Schema::as_array( Schema::as_assoc_array( array( 'active' => Schema::as_boolean()->fallback( false ), 'available' => Schema::as_boolean()->nullable(), ) ) )->fallback( array() ); $entry = new Modules_State_Entry(); jetpack_boost_register_option( 'modules_state', $modules_state_schema, $entry ); require_once __DIR__ . '/app/modules/image-size-analysis/data-sync/init.php'; /** * Register Minify Excludes stores. */ $js_excludes_entry = new Minify_Excludes_State_Entry( 'minify_js_excludes' ); $css_excludes_entry = new Minify_Excludes_State_Entry( 'minify_css_excludes' ); jetpack_boost_register_option( 'minify_js_excludes', Schema::as_array( Schema::as_string() )->fallback( Minify_JS::$default_excludes ), $js_excludes_entry ); jetpack_boost_register_option( 'minify_css_excludes', Schema::as_array( Schema::as_string() )->fallback( Minify_CSS::$default_excludes ), $css_excludes_entry ); jetpack_boost_register_option( 'image_cdn_quality', Schema::as_assoc_array( array( 'jpg' => Schema::as_assoc_array( array( 'quality' => Schema::as_number(), 'lossless' => Schema::as_boolean(), ) ), 'png' => Schema::as_assoc_array( array( 'quality' => Schema::as_number(), 'lossless' => Schema::as_boolean(), ) ), 'webp' => Schema::as_assoc_array( array( 'quality' => Schema::as_number(), 'lossless' => Schema::as_boolean(), ) ), ) )->fallback( array( 'jpg' => array( 'quality' => 89, 'lossless' => false, ), 'png' => array( 'quality' => 80, 'lossless' => false, ), 'webp' => array( 'quality' => 80, 'lossless' => false, ), ) ) ); jetpack_boost_register_option( 'performance_history_toggle', Schema::as_boolean()->fallback( false ) ); jetpack_boost_register_option( 'performance_history', Schema::as_assoc_array( array( 'periods' => Schema::as_array( Schema::as_assoc_array( array( 'timestamp' => Schema::as_number(), 'dimensions' => Schema::as_assoc_array( array( 'desktop_overall_score' => Schema::as_number(), 'mobile_overall_score' => Schema::as_number(), 'desktop_cls' => Schema::as_number(), 'desktop_lcp' => Schema::as_number(), 'desktop_tbt' => Schema::as_number(), 'mobile_cls' => Schema::as_number(), 'mobile_lcp' => Schema::as_number(), 'mobile_tbt' => Schema::as_number(), ) ), ) ) ), 'annotations' => Schema::as_array( Schema::as_assoc_array( array( 'timestamp' => Schema::as_number(), 'text' => Schema::as_string(), ) ) ), 'startDate' => Schema::as_number(), 'endDate' => Schema::as_number(), ) ), new Performance_History_Entry() ); /** * Register Super Cache Notice Disabled store. */ jetpack_boost_register_option( 'super_cache_notice_disabled', Schema::as_boolean()->fallback( false ) ); /** * Entry to store alerts that shouldn't be shown again. */ jetpack_boost_register_option( 'dismissed_alerts', Schema::as_assoc_array( array( 'performance_history_fresh_start' => Schema::as_boolean(), 'score_increase' => Schema::as_boolean(), 'score_decrease' => Schema::as_boolean(), ) )->fallback( array( 'performance_history_fresh_start' => false, 'score_increase' => false, 'score_decrease' => false, ) ), new Mergeable_Array_Entry( JETPACK_BOOST_DATASYNC_NAMESPACE . '_dismissed_alerts' ) ); jetpack_boost_register_readonly_option( 'connection', array( new Connection(), 'get_connection_api_response' ) ); jetpack_boost_register_readonly_option( 'pricing', array( Premium_Pricing::class, 'get_yearly_pricing' ) ); jetpack_boost_register_readonly_option( 'premium_features', array( Premium_Features::class, 'get_features' ) ); jetpack_boost_register_readonly_option( 'super_cache', array( Super_Cache_Info::class, 'get_info' ) ); jetpack_boost_register_readonly_option( 'cache_debug_log', array( Logger::class, 'read' ) ); jetpack_boost_register_option( 'getting_started', Schema::as_boolean()->fallback( false ), new Getting_Started_Entry() ); // Page Cache error jetpack_boost_register_option( 'page_cache_error', Schema::as_assoc_array( array( 'code' => Schema::as_string(), 'message' => Schema::as_string(), 'dismissed' => Schema::as_boolean()->fallback( false ), ) )->nullable() ); jetpack_boost_register_action( 'page_cache', 'run-setup', Schema::as_void(), new Run_Setup() ); jetpack_boost_register_option( 'page_cache', Schema::as_assoc_array( array( 'bypass_patterns' => Schema::as_array( Schema::as_string() ), 'logging' => Schema::as_boolean(), ) ), new Page_Cache_Entry( JETPACK_BOOST_DATASYNC_NAMESPACE . '_page_cache' ) ); jetpack_boost_register_action( 'page_cache', 'clear-page-cache', Schema::as_void(), new Clear_Page_Cache() );
projects/plugins/boost/serve-minified-content.php
<?php if ( ! defined( 'JETPACK_BOOST_CONCAT_USE_WP' ) ) { define( 'JETPACK_BOOST_CONCAT_USE_WP', false ); // Load CSSmin. require_once __DIR__ . '/vendor/tubalmartin/cssmin/src/Colors.php'; require_once __DIR__ . '/vendor/tubalmartin/cssmin/src/Utils.php'; require_once __DIR__ . '/vendor/tubalmartin/cssmin/src/Minifier.php'; } // Load minify library code. require_once __DIR__ . '/app/lib/minify/Utils.php'; require_once __DIR__ . '/app/lib/minify/Config.php'; require_once __DIR__ . '/app/lib/minify/Dependency_Path_Mapping.php'; require_once __DIR__ . '/app/lib/minify/functions-helpers.php'; require_once __DIR__ . '/app/lib/minify/functions-service.php'; jetpack_boost_page_optimize_service_request();
projects/plugins/boost/jetpack-boost.php
<?php /** * Jetpack Boost Plugin * * @link https://automattic.com * @since 0.1.0 * * @wordpress-plugin * Plugin Name: Jetpack Boost * Plugin URI: https://jetpack.com/boost * Description: Boost your WordPress site's performance, from the creators of Jetpack * Version: 3.1.2-alpha * Author: Automattic - Jetpack Site Speed team * Author URI: https://jetpack.com/boost/ * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: jetpack-boost * Domain Path: /languages * Requires at least: 5.5 * Requires PHP: 7.0 * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost; // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } define( 'JETPACK_BOOST_VERSION', '3.1.2-alpha' ); define( 'JETPACK_BOOST_SLUG', 'jetpack-boost' ); if ( ! defined( 'JETPACK_BOOST_CLIENT_NAME' ) ) { define( 'JETPACK_BOOST_CLIENT_NAME', 'jetpack-boost-wp-plugin' ); } define( 'JETPACK_BOOST_DIR_PATH', __DIR__ ); define( 'JETPACK_BOOST_PATH', __FILE__ ); if ( ! defined( 'JETPACK_BOOST_PLUGIN_BASE' ) ) { define( 'JETPACK_BOOST_PLUGIN_BASE', plugin_basename( __FILE__ ) ); } if ( ! defined( 'JETPACK_BOOST_PLUGIN_FILENAME' ) ) { define( 'JETPACK_BOOST_PLUGIN_FILENAME', basename( __FILE__ ) ); } if ( ! defined( 'JETPACK_BOOST_REST_NAMESPACE' ) ) { define( 'JETPACK_BOOST_REST_NAMESPACE', 'jetpack-boost/v1' ); } // For use in situations where you want additional namespacing. if ( ! defined( 'JETPACK_BOOST_REST_PREFIX' ) ) { define( 'JETPACK_BOOST_REST_PREFIX', '' ); } if ( ! defined( 'JETPACK__WPCOM_JSON_API_BASE' ) ) { define( 'JETPACK__WPCOM_JSON_API_BASE', 'https://public-api.wordpress.com' ); } if ( ! defined( 'JETPACK_BOOST_PLUGINS_DIR_URL' ) ) { define( 'JETPACK_BOOST_PLUGINS_DIR_URL', plugin_dir_url( __FILE__ ) ); } /** * Setup autoloading */ $boost_packages_path = JETPACK_BOOST_DIR_PATH . '/vendor/autoload_packages.php'; if ( is_readable( $boost_packages_path ) ) { require_once $boost_packages_path; if ( method_exists( \Automattic\Jetpack\Assets::class, 'alias_textdomains_from_file' ) ) { \Automattic\Jetpack\Assets::alias_textdomains_from_file( JETPACK_BOOST_DIR_PATH . '/jetpack_vendor/i18n-map.php' ); } } else { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { /** @noinspection ForgottenDebugOutputInspection */ 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 Boost is incomplete. If you installed Jetpack Boost from GitHub, please refer to this document to set up your development environment: %1$s', 'jetpack-boost' ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md' ) ); } /** * Outputs an admin notice for folks running Jetpack Boost without having run composer install. * * @since 1.2.0 */ function jetpack_boost_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 Boost is incomplete. If you installed Jetpack Boost from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. Jetpack Boost must have Composer dependencies installed and built via the build command.', 'jetpack-boost' ), array( 'a' => array( 'href' => array(), 'target' => array(), 'rel' => array(), ), ) ), 'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project' ); ?> </p> </div> <?php } add_action( 'admin_notices', __NAMESPACE__ . '\\jetpack_boost_admin_missing_files' ); return; } /** * Setup Minify service. */ // Potential improvement: Make concat URL dir configurable // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if ( isset( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $request_path = explode( '?', wp_unslash( $_SERVER['REQUEST_URI'] ) )[0]; // Handling JETPACK_BOOST_STATIC_PREFIX constant inline to avoid loading the minify module until we know we want it. $static_prefix = defined( 'JETPACK_BOOST_STATIC_PREFIX' ) ? JETPACK_BOOST_STATIC_PREFIX : '/_jb_static/'; if ( $static_prefix === substr( $request_path, -strlen( $static_prefix ) ) ) { define( 'JETPACK_BOOST_CONCAT_USE_WP', true ); require_once JETPACK_BOOST_DIR_PATH . '/serve-minified-content.php'; exit; } } require plugin_dir_path( __FILE__ ) . 'app/class-jetpack-boost.php'; /** * Begins execution of the plugin. * * @since 0.1.0 */ function run_jetpack_boost() { new Jetpack_Boost(); } add_action( 'plugins_loaded', '\Automattic\Jetpack_Boost\run_jetpack_boost', 1 ); register_activation_hook( __FILE__, array( 'Automattic\Jetpack_Boost\Jetpack_Boost', 'activate' ) ); // Redirect to plugin page when the plugin is activated. add_action( 'activated_plugin', __NAMESPACE__ . '\jetpack_boost_plugin_activation' ); /** * Redirects to plugin page when the plugin is activated * * @access public * @static * * @param string $plugin Path to the plugin file relative to the plugins directory. */ function jetpack_boost_plugin_activation( $plugin ) { if ( JETPACK_BOOST_PLUGIN_BASE === $plugin && \Automattic\Jetpack\Plugins_Installer::is_current_request_activating_plugin_from_plugins_screen( JETPACK_BOOST_PLUGIN_BASE ) ) { wp_safe_redirect( esc_url( admin_url( 'admin.php?page=jetpack-boost' ) ) ); exit; } } /** * Extra tweaks to make Jetpack Boost work better with others, that need to be loaded early. */ function include_compatibility_files_early() { // Since Page Optimize allows its functionality to be disabled on plugins_loaded (10) // we need to do this earlier. if ( function_exists( 'page_optimize_init' ) ) { require_once __DIR__ . '/compatibility/page-optimize.php'; } } add_action( 'plugins_loaded', __NAMESPACE__ . '\include_compatibility_files_early', 1 ); /** * Extra tweaks to make Jetpack Boost work better with others. */ function include_compatibility_files() { if ( class_exists( 'Jetpack' ) ) { require_once __DIR__ . '/compatibility/jetpack.php'; } if ( class_exists( 'WooCommerce' ) ) { require_once __DIR__ . '/compatibility/woocommerce.php'; } if ( class_exists( '\Google\Web_Stories\Plugin' ) ) { require_once __DIR__ . '/compatibility/web-stories.php'; } if ( class_exists( '\Elementor\TemplateLibrary\Source_Local' ) ) { require_once __DIR__ . '/compatibility/elementor.php'; } if ( function_exists( 'amp_is_request' ) ) { require_once __DIR__ . '/compatibility/amp.php'; } if ( function_exists( 'wp_cache_is_enabled' ) ) { require_once __DIR__ . '/compatibility/wp-super-cache.php'; } if ( class_exists( '\Yoast\WP\SEO\Main' ) ) { require_once __DIR__ . '/compatibility/yoast.php'; } if ( function_exists( 'aioseo' ) ) { require_once __DIR__ . '/compatibility/aioseo.php'; } } add_action( 'plugins_loaded', __NAMESPACE__ . '\include_compatibility_files' ); register_uninstall_hook( __FILE__, 'Automattic\Jetpack_Boost\jetpack_boost_uninstall' ); /** * Clean up when uninstalling Jetpack Boost */ function jetpack_boost_uninstall() { $boost = new Jetpack_Boost(); $boost->uninstall(); } /** * Previous version compatibility files */ require_once __DIR__ . '/compatibility/boost-1.3.1.php'; require_once __DIR__ . '/compatibility/score-prompt.php'; require_once __DIR__ . '/wp-js-data-sync.php';
projects/plugins/boost/compatibility/yoast.php
<?php /** * Yoast SEO compatibility for Boost * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Yoast; // Add the Critical CSS generation query arg to Yoast's allowed query args list. // This prevents Yoast from removing the query arg, which breaks Critical CSS generation. add_filter( 'Yoast\WP\SEO\allowlist_permalink_vars', array( '\Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator', 'add_generate_query_action_to_list' ) );
projects/plugins/boost/compatibility/web-stories.php
<?php /** * Compatibility for Web Stories * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Web_Stories; /** * Exclude Web Stories pages to be processed by the Render Blocking JS module. * * @param bool $should_defer_js default filter value. */ function web_stories_should_defer_js( $should_defer_js ) { if ( class_exists( '\Google\Web_Stories\Story_Post_Type' ) && defined( '\Google\Web_Stories\Story_Post_Type::POST_TYPE_SLUG' ) && is_singular( \Google\Web_Stories\Story_Post_Type::POST_TYPE_SLUG ) ) { return false; } return $should_defer_js; } add_filter( 'jetpack_boost_should_defer_js', __NAMESPACE__ . '\web_stories_should_defer_js' );
projects/plugins/boost/compatibility/page-optimize.php
<?php /** * Compatibility file for Page Optimize. * * This will synchronize the settings from Page Optimize to Jetpack Boost. * It will also disable the Page Optimize functionality. * * @package automattic/jetpack-boost */ if ( function_exists( 'page_optimize_js_default' ) ) { $page_optimize_js_concatenate = (bool) get_option( 'page_optimize-js', page_optimize_js_default() ); $boost_js_concatenate = get_option( 'jetpack_boost_status_minify-js' ); // Only migrate JS Concatenation if Page Optimize has it enabled // and if Boost's equivalent hasn't been used at all. if ( $page_optimize_js_concatenate && false === $boost_js_concatenate ) { add_option( 'jetpack_boost_status_minify-js', true ); } } if ( function_exists( 'page_optimize_js_exclude_list' ) ) { $boost_js_excludes = get_option( 'jetpack_boost_ds_minify_js_excludes' ); // Only migrate this setting if Boost's equivalent hasn't been used. if ( false === $boost_js_excludes ) { $page_optimize_js_excludes = page_optimize_js_exclude_list(); add_option( 'jetpack_boost_ds_minify_js_excludes', $page_optimize_js_excludes ); } } if ( function_exists( 'page_optimize_css_default' ) ) { $css_concatenate = (bool) get_option( 'page_optimize-css', page_optimize_css_default() ); $boost_css_concatenate = get_option( 'jetpack_boost_status_minify-css' ); // Only migrate CSS Concatenation if Page Optimize has it enabled // and if Boost's equivalent hasn't been used at all. if ( $css_concatenate && false === $boost_css_concatenate ) { add_option( 'jetpack_boost_status_minify-css', true ); } } if ( function_exists( 'page_optimize_css_exclude_list' ) ) { $boost_css_excludes = get_option( 'jetpack_boost_ds_minify_css_excludes' ); // Only migrate this setting if Boost's equivalent hasn't been used. if ( false === $boost_css_excludes ) { $page_optimize_css_excludes = page_optimize_css_exclude_list(); add_option( 'jetpack_boost_ds_minify_css_excludes', $page_optimize_css_excludes ); } } // Disable Page Optimize functionality. remove_action( 'plugins_loaded', 'page_optimize_init' );
projects/plugins/boost/compatibility/woocommerce.php
<?php /** * Compatibility functions for WooCommerce * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Woocommerce; /** * Exclude special Woocommerce pages from standard "single page" Critical CSS. * * @param object $args the query args. */ function exclude_woocommerce_pages_from_query( $args ) { // Only do this for page post type. if ( 'page' !== $args['post_type'] ) { return $args; } $woocommerce_pages = get_woocommerce_page_ids(); if ( empty( $woocommerce_pages ) ) { return $args; } if ( ! isset( $args['post__not_in'] ) ) { $args['post__not_in'] = array(); } $args['post__not_in'] = array_merge( $woocommerce_pages, $args['post__not_in'] ); return $args; } /** * Get those ol' WooCommerce page IDs */ function get_woocommerce_page_ids() { if ( ! function_exists( 'wc_get_page_id' ) ) { return array(); } $page_slugs = array( 'myaccount', 'shop', 'cart', 'checkout', 'view_order', 'terms' ); $ids = array_map( 'wc_get_page_id', $page_slugs ); $ids = array_filter( $ids, function ( $value ) { return $value > 0; } ); return $ids; } add_filter( 'jetpack_boost_critical_css_post_type_query', __NAMESPACE__ . '\exclude_woocommerce_pages_from_query' );
projects/plugins/boost/compatibility/wp-super-cache.php
<?php /** * Super Cache compatibility for Boost * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Super_Cache; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Modules\Modules_Index; /** * Add WP Super Cache bypass query param to the URL. * * @param string $url The URL. */ function add_bypass_query_param( $url ) { global $cache_page_secret; return add_query_arg( 'donotcachepage', $cache_page_secret, $url ); } /** * Add WP Super Cache bypass query params to Critical CSS URLs. * * @param array $urls list of URLs to generate Critical CSS for. */ function critical_css_bypass_super_cache( $urls ) { return array_map( __NAMESPACE__ . '\add_bypass_query_param', $urls ); } add_filter( 'jetpack_boost_critical_css_urls', __NAMESPACE__ . '\critical_css_bypass_super_cache' ); /** * Clear Super Cache's cache. Called when Critical CSS finishes generating, or * when a module is enabled or disabled. */ function clear_cache() { global $wpdb; if ( function_exists( 'wp_cache_clear_cache' ) ) { wp_cache_clear_cache( $wpdb->blogid ); } } add_action( 'jetpack_boost_critical_css_generated', __NAMESPACE__ . '\clear_cache' ); add_action( 'jetpack_boost_critical_css_invalidated', __NAMESPACE__ . '\clear_cache' ); /** * Clear Super Cache's cache when a module is enabled or disabled. * * @param string $module_slug The module slug. * @param bool $status The new status. */ function module_status_updated( $module_slug, $status ) { // Get a list of modules that can change the HTML output. $output_changing_modules = Modules_Index::get_modules_implementing( Changes_Page_Output::class ); // Special case: don't clear when enabling Critical or Cloud CSS, as they will // be handled after generation. if ( $status ) { unset( $output_changing_modules['critical_css'] ); unset( $output_changing_modules['cloud_css'] ); } $slugs = array_keys( $output_changing_modules ); if ( ! in_array( $module_slug, $slugs, true ) ) { return; } clear_cache(); } add_action( 'jetpack_boost_module_status_updated', __NAMESPACE__ . '\module_status_updated', 10, 2 );
projects/plugins/boost/compatibility/amp.php
<?php /** * Compatibility for AMP. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Amp; use Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS\CriticalCSS; /** * Class AMP. */ class Amp { /** * CriticalCSS module instance. * * @var CriticalCSS */ private static $critical_css; /** * Init AMP compatibility actions after modules are initialized. * * @param CriticalCSS $module CriticalCSS Module instance. */ public static function init_compatibility( $module ) { self::$critical_css = $module; add_action( 'wp', array( __CLASS__, 'disable_critical_css' ), 0 ); } /** * Disable Critical CSS display. */ public static function disable_critical_css() { if ( amp_is_request() ) { remove_action( 'wp', array( self::$critical_css, 'display_critical_css' ) ); } } } add_action( 'jetpack_boost_critical-css_initialized', array( __NAMESPACE__ . '\Amp', 'init_compatibility' ) );
projects/plugins/boost/compatibility/boost-1.3.1.php
<?php /** * Seamlessly migrate to the new options format. Even if no admin hooks are fired as the plugin is updated, * the visitor will never notice a difference, because we'll use the old options in the background. */ function jetpack_boost_131_option_fallback( $default, $option ) { $old_config = get_option( 'jetpack_boost_config' ); if ( ! $old_config ) { return $default; } $key = str_replace( 'jetpack_boost_state_', '', $option ); if ( ! isset( $old_config[ $key ] ) || ! isset( $old_config[ $key ]['enabled'] ) ) { return $default; } return (string) $old_config[ $key ]['enabled']; } add_filter( 'default_option_jetpack_boost_state_critical-css', 'jetpack_boost_131_option_fallback', 10, 2 ); add_filter( 'default_option_jetpack_boost_state_render-blocking-js', 'jetpack_boost_131_option_fallback', 10, 2 ); /** * When something interacts with boost option toggles, * silently migrate the options to the new format, * that way the code above is never run. */ function jetpack_boost_131_option_migration() { /** * This function is hooked into add_option * and also is using add_option * * That can cause quite a bit of recursion. * Use static variables to guard that. */ static $has_run = false; if ( false !== $has_run ) { return; } $has_run = true; $old_config = get_option( 'jetpack_boost_config' ); if ( ! $old_config ) { return; } $migration_keys = array( 'critical-css', 'render-blocking-js' ); foreach ( $migration_keys as $migration_key ) { if ( ! isset( $old_config[ $migration_key ] ) || ! isset( $old_config[ $migration_key ]['enabled'] ) ) { continue; } add_option( "jetpack_boost_state_{$migration_key}", $old_config[ $migration_key ]['enabled'] ); } delete_option( 'jetpack_boost_config' ); } add_action( 'add_option_jetpack_boost_state_critical-css', 'jetpack_boost_131_option_migration', 10, 0 ); add_action( 'add_option_jetpack_boost_state_render-blocking-js', 'jetpack_boost_131_option_migration', 10, 0 );
projects/plugins/boost/compatibility/aioseo.php
<?php /** * All in One SEO compatibility for Boost * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\AIOSEO; // Add the Critical CSS generation query arg to the list of allowed query args of All in One SEO. // This prevents All in One SEO from removing the query arg, which breaks Critical CSS generation. add_filter( 'aioseo_unrecognized_allowed_query_args', array( '\Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator', 'add_generate_query_action_to_list' ) );
projects/plugins/boost/compatibility/jetpack.php
<?php /** * Jetpack compatibility for Boost * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Jetpack; require_once __DIR__ . '/lib/class-sync-jetpack-module-status.php'; ( new Sync_Jetpack_Module_Status( 'image_cdn', 'photon' ) )->init(); /** * Exclude Jetpack likes scripts from deferred JS. They are already in the footer, * and are sensitive to having their order changed relative to their companion iframe. * * @param array $exclusions The default array of scripts to exclude from deferral. */ function exclude_jetpack_likes_scripts_defer( $exclusions ) { static $likes_enabled = null; if ( null === $likes_enabled ) { $likes_enabled = \Jetpack::is_module_active( 'likes' ); } if ( $likes_enabled ) { return array_merge( $exclusions, array( 'jquery-core', 'postmessage', 'jetpack_likes_queuehandler', ) ); } return $exclusions; } add_filter( 'jetpack_boost_render_blocking_js_exclude_handles', __NAMESPACE__ . '\exclude_jetpack_likes_scripts_defer', 10, 1 );
projects/plugins/boost/compatibility/elementor.php
<?php /** * Compatibility functions for Elementor * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Compatibility\Elementor; use Elementor\TemplateLibrary\Source_Local; /** * Exclude Elementor Library custom post type from the list of post types to get urls from. * * @param array $post_types Post types. */ function exclude_elementor_library_custom_post_type( $post_types ) { if ( isset( $post_types[ Source_Local::CPT ] ) ) { unset( $post_types[ Source_Local::CPT ] ); } return $post_types; } add_filter( 'jetpack_boost_critical_css_post_types', __NAMESPACE__ . '\exclude_elementor_library_custom_post_type' );
projects/plugins/boost/compatibility/score-prompt.php
<?php /** * Compatibility file for old way of storing dismissed score prompt. * * @package automattic/jetpack-boost */ // Old value is the previous DS key, fallback to even older non-ds value. $old_value = (array) get_option( 'jetpack_boost_ds_dismissed_score_prompt', get_option( 'jb_show_score_prompt' ) ); if ( false !== $old_value ) { $new_value = (array) get_option( 'jetpack_boost_ds_dismissed_alerts', array() ); if ( in_array( 'score-increase', $old_value, true ) ) { $new_value['score_increase'] = true; } if ( in_array( 'score-decrease', $old_value, true ) ) { $new_value['score_decrease'] = true; } update_option( 'jetpack_boost_ds_dismissed_alerts', $new_value, false ); delete_option( 'jetpack_boost_ds_dismissed_score_prompt' ); delete_option( 'jb_show_score_prompt' ); }
projects/plugins/boost/compatibility/lib/class-sync-jetpack-module-status.php
<?php namespace Automattic\Jetpack_Boost\Compatibility\Jetpack; /** * Class that handles the sync of Jetpack module status to Boost module status. */ class Sync_Jetpack_Module_Status { /** Slug of the Jetpack module */ public $jetpack_module_slug; /** Slug of the Boost module */ public $boost_module_slug; public function __construct( $boost_module_slug, $jetpack_module_slug ) { $this->boost_module_slug = str_replace( '_', '-', $boost_module_slug ); $this->jetpack_module_slug = $jetpack_module_slug; } public function init() { // Use Jetpack as the source of truth for the module status add_filter( "default_option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'get_jetpack_module_status' ) ); add_filter( "option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'get_jetpack_module_status' ) ); $this->add_sync_to_jetpack_action(); $this->add_sync_from_jetpack_action(); /** * Update the Jetpack Boost option to match the Jetpack option, * in case the options are out of sync when the page is loaded. */ add_action( 'load-jetpack_page_jetpack-boost', array( $this, 'sync_from_jetpack' ) ); } /** * Get the status of the Jetpack module * * @return string */ public function get_jetpack_module_status() { return (string) \Jetpack::is_module_active( $this->jetpack_module_slug ); } /** * Forward all module status changes to Jetpack * when interacting with Jetpack Boost dashboard. */ public function sync_to_jetpack( $_unused, $new_value ) { $this->remove_sync_from_jetpack_action(); if ( $new_value ) { \Jetpack::activate_module( $this->jetpack_module_slug, false, false ); } else { \Jetpack::deactivate_module( $this->jetpack_module_slug ); } $this->add_sync_from_jetpack_action(); return $new_value; } /** * The compatibility layer uses Jetpack as the single source of truth for shared modules. * As a fallback, Boost still keeps track of the value in the database, * This ensures that the value is still present when Jetpack is deactivated. * * This filter is going to track changes to the modules shared between Jetpack and Boost * and make sure that both plugins are in in sync. * Example: image_cdn */ public function sync_from_jetpack() { $this->remove_sync_to_jetpack_action(); update_option( "jetpack_boost_status_{$this->boost_module_slug}", \Jetpack::is_module_active( $this->jetpack_module_slug ) ); $this->add_sync_to_jetpack_action(); } /** * Sync the status to Boost when interacting with the Jetpack dashboard. */ public function add_sync_from_jetpack_action() { add_action( "jetpack_deactivate_module_{$this->jetpack_module_slug}", array( $this, 'sync_from_jetpack' ), 10, 2 ); add_action( "jetpack_activate_module_{$this->jetpack_module_slug}", array( $this, 'sync_from_jetpack' ), 10, 2 ); } public function remove_sync_from_jetpack_action() { remove_action( "jetpack_deactivate_module_{$this->jetpack_module_slug}", array( $this, 'sync_from_jetpack' ), 10, 2 ); remove_action( "jetpack_activate_module_{$this->jetpack_module_slug}", array( $this, 'sync_from_jetpack' ), 10, 2 ); } /** * Sync the status to Jetpack when interacting with the Boost dashboard */ public function add_sync_to_jetpack_action() { add_action( "add_option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'sync_to_jetpack' ), 10, 2 ); add_action( "update_option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'sync_to_jetpack' ), 10, 2 ); } public function remove_sync_to_jetpack_action() { remove_action( "add_option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'sync_to_jetpack' ), 10, 2 ); remove_action( "update_option_jetpack_boost_status_{$this->boost_module_slug}", array( $this, 'sync_to_jetpack' ), 10, 2 ); } }
projects/plugins/boost/app/class-jetpack-boost.php
<?php /** * The file that defines the core plugin class * * A class definition that includes attributes and functions used across both the * public-facing side of the site and the admin area. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost; use Automattic\Jetpack\Boost_Core\Lib\Transient; use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History; use Automattic\Jetpack\Config as Jetpack_Config; use Automattic\Jetpack\Image_CDN\Image_CDN_Core; use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer; use Automattic\Jetpack\Plugin_Deactivation\Deactivation_Handler; use Automattic\Jetpack_Boost\Admin\Admin; use Automattic\Jetpack_Boost\Admin\Regenerate_Admin_Notice; use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry; use Automattic\Jetpack_Boost\Lib\Analytics; use Automattic\Jetpack_Boost\Lib\CLI; use Automattic\Jetpack_Boost\Lib\Connection; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; use Automattic\Jetpack_Boost\Lib\Setup; use Automattic\Jetpack_Boost\Lib\Site_Health; use Automattic\Jetpack_Boost\Lib\Status; use Automattic\Jetpack_Boost\Modules\Modules_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings; use Automattic\Jetpack_Boost\REST_API\Endpoints\List_Site_Urls; use Automattic\Jetpack_Boost\REST_API\REST_API; /** * The core plugin class. * * This is used to define internationalization, admin-specific hooks, and * public-facing site hooks. * * Also maintains the unique identifier of this plugin as well as the current * version of the plugin. * * @since 1.0.0 * @author Automattic <support@jetpack.com> */ class Jetpack_Boost { /** * The unique identifier of this plugin. * * @since 1.0.0 * @var string The string used to uniquely identify this plugin. */ private $plugin_name; /** * The current version of the plugin. * * @since 1.0.0 * @var string The current version of the plugin. */ private $version; /** * The Jetpack Boost Connection manager instance. * * @since 1.0.0 * @access public * @var Connection The Jetpack Boost Connection manager instance. */ public $connection; /** * Define the core functionality of the plugin. * * Set the plugin name and the plugin version that can be used throughout the plugin. * Load the dependencies, define the locale, and set the hooks for the admin area and * the public-facing side of the site. * * @since 1.0.0 */ public function __construct() { $this->version = JETPACK_BOOST_VERSION; $this->plugin_name = 'jetpack-boost'; $this->connection = new Connection(); $this->connection->init(); // Require plugin features. $this->init_textdomain(); $this->register_deactivation_hook(); if ( defined( 'WP_CLI' ) && WP_CLI ) { $cli_instance = new CLI( $this ); \WP_CLI::add_command( 'jetpack-boost', $cli_instance ); } $modules_setup = new Modules_Setup(); Setup::add( $modules_setup ); // Initialize the Admin experience. $this->init_admin( $modules_setup ); // Initiate jetpack sync. $this->init_sync(); add_action( 'init', array( $this, 'init_textdomain' ) ); add_action( 'handle_environment_change', array( $this, 'handle_environment_change' ), 10, 2 ); // Fired when plugin ready. do_action( 'jetpack_boost_loaded', $this ); My_Jetpack_Initializer::init(); Deactivation_Handler::init( $this->plugin_name, __DIR__ . '/admin/deactivation-dialog.php' ); // Register the core Image CDN hooks. Image_CDN_Core::setup(); // Setup Site Health panel functionality. Site_Health::init(); } /** * Register deactivation hook. */ private function register_deactivation_hook() { $plugin_file = trailingslashit( dirname( __DIR__ ) ) . 'jetpack-boost.php'; register_deactivation_hook( $plugin_file, array( $this, 'deactivate' ) ); } /** * Plugin activation handler. */ public static function activate() { // Make sure user sees the "Get Started" when first time opening. ( new Getting_Started_Entry() )->set( true ); Analytics::record_user_event( 'activate_plugin' ); $page_cache_status = new Status( Page_Cache::get_slug() ); if ( $page_cache_status->is_enabled() && Boost_Cache_Settings::get_instance()->get_enabled() ) { Page_Cache_Setup::run_setup(); } } /** * Plugin deactivation handler. Clear cache, and reset admin notices. */ public function deactivate() { do_action( 'jetpack_boost_deactivate' ); Regenerate_Admin_Notice::dismiss(); Analytics::record_user_event( 'deactivate_plugin' ); Page_Cache_Setup::deactivate(); } /** * Initialize the admin experience. */ public function init_admin( $modules_setup ) { REST_API::register( List_Site_Urls::class ); $this->connection->ensure_connection(); ( new Admin() )->init( $modules_setup ); } public function init_sync() { $jetpack_config = new Jetpack_Config(); $jetpack_config->ensure( 'sync', array( 'jetpack_sync_callable_whitelist' => array( 'boost_modules' => array( new Modules_Setup(), 'get_status' ), 'boost_latest_scores' => array( new Speed_Score_History( get_home_url() ), 'latest' ), 'boost_latest_no_boost_scores' => array( new Speed_Score_History( add_query_arg( 'jb-disable-modules', 'all', get_home_url() ) ), 'latest' ), 'critical_css_state' => array( new Critical_CSS_State(), 'get' ), ), ) ); } /** * Loads the textdomain. */ public function init_textdomain() { load_plugin_textdomain( 'jetpack-boost', false, JETPACK_BOOST_DIR_PATH . '/languages/' ); } /** * The name of the plugin used to uniquely identify it within the context of * WordPress and to define internationalization functionality. * * @return string The name of the plugin. * @since 1.0.0 */ public function get_plugin_name() { return $this->plugin_name; } /** * Retrieve the version number of the plugin. * * @return string The version number of the plugin. * @since 1.0.0 */ public function get_version() { return $this->version; } /** * Handle an environment change to set the correct status to the Critical CSS request. * This is done here so even if the Critical CSS module is switched off we can * still capture the change of environment event and flag Critical CSS for a rebuild. */ public function handle_environment_change( $is_major_change, $change_type ) { if ( $is_major_change ) { Regenerate_Admin_Notice::enable(); } jetpack_boost_ds_set( 'critical_css_suggest_regenerate', $change_type ); } /** * Plugin uninstallation handler. Delete all settings and cache. */ public function uninstall() { global $wpdb; // When uninstalling, make sure all deactivation cleanups have run as well. $this->deactivate(); // Delete all Jetpack Boost options. //phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $option_names = $wpdb->get_col( " SELECT `option_name` FROM `$wpdb->options` WHERE `option_name` LIKE 'jetpack_boost_%'; " ); //phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching foreach ( $option_names as $option_name ) { delete_option( $option_name ); } // Delete stored Critical CSS. ( new Critical_CSS_Storage() )->clear(); // Delete all transients created by boost. Transient::delete_by_prefix( '' ); // Clear getting started value ( new Getting_Started_Entry() )->set( false ); Page_Cache_Setup::uninstall(); } }
projects/plugins/boost/app/contracts/Has_Slug.php
<?php namespace Automattic\Jetpack_Boost\Contracts; interface Has_Slug { public static function get_slug(); }
projects/plugins/boost/app/contracts/Has_Activate.php
<?php namespace Automattic\Jetpack_Boost\Contracts; interface Has_Activate { public static function activate(); }
projects/plugins/boost/app/contracts/Changes_Output.php
<?php namespace Automattic\Jetpack_Boost\Contracts; /** * Modules can implement this interface to indicate that they change the HTML output for the site visitor. */ interface Changes_Page_Output {}
projects/plugins/boost/app/contracts/Is_Always_On.php
<?php namespace Automattic\Jetpack_Boost\Contracts; /** * Modules can implement this interface to indicate that they are always on if available. */ interface Is_Always_On {}
projects/plugins/boost/app/contracts/Pluggable.php
<?php namespace Automattic\Jetpack_Boost\Contracts; /** * Every plugin feature that's large enough * to need setup also needs a slug */ interface Pluggable extends Has_Setup, Has_Slug { /** * Whether the feature is available for use. * Use this to check for feature flags, etc. * @return bool */ public static function is_available(); }
projects/plugins/boost/app/contracts/Has_Setup.php
<?php namespace Automattic\Jetpack_Boost\Contracts; /** * A class that has a setup step that's supposed to be executed only once. */ interface Has_Setup { /** * This class has a setup method that should be * run only once per the request lifecycle. * * This is a good place to attach hooks * or perform other tasks that need * to be performed once. * * @return mixed */ public function setup(); }
projects/plugins/boost/app/contracts/Has_Deactivate.php
<?php namespace Automattic\Jetpack_Boost\Contracts; interface Has_Deactivate { public static function deactivate(); }
projects/plugins/boost/app/features/setup-prompt/Setup_Prompt.php
<?php /** * Prompt the user to setup Jetpack Boost. * DEPRECATED in v2.3.1 */ namespace Automattic\Jetpack_Boost\Features\Setup_Prompt; use Automattic\Jetpack_Boost\Contracts\Has_Setup; use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry; class Setup_Prompt implements Has_Setup { const NONCE_ACTION = 'jetpack_boost_setup_banner'; const OPTION_KEY = 'jb_setup_banner_dismissed'; const AJAX_ACTION = 'jb_dismiss_setup_banner'; public function setup() { // The ajax endpoint may not trigger the setup_trigger hook, so we need to add it here. add_action( 'wp_ajax_' . self::AJAX_ACTION, array( $this, 'dismiss_setup_banner' ) ); add_action( 'load-plugins.php', array( $this, 'load_banner' ) ); } public function load_banner() { if ( ( new Getting_Started_Entry() )->get() === false || $this->is_banner_dismissed() ) { return; } add_action( 'admin_notices', array( $this, 'connection_prompt' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'admin_footer', array( $this, 'add_dismiss_script' ) ); } public function enqueue_scripts() { wp_enqueue_style( 'jetpack-boost-admin-banner', plugins_url( '../../assets/dist/admin-banner.css', __FILE__ ), array(), JETPACK_BOOST_VERSION ); } public function connection_prompt() { include __DIR__ . '/_inc/banner.php'; } public function add_dismiss_script() { include __DIR__ . '/_inc/dismiss-script.php'; } private function is_banner_dismissed() { return get_option( self::OPTION_KEY, false ); } // hides the boost promo banner on dismiss public function dismiss_setup_banner() { check_ajax_referer( self::NONCE_ACTION, 'nonce' ); update_option( self::OPTION_KEY, true, 'no' ); exit(); } }