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"> (%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> > <?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' );
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 32