feat: upgrade the update-checker component version

pull/620/head
Seaton Jiang 2023-08-25 15:24:45 +08:00
parent a6027fe4a3
commit 07a1d92cf4
No known key found for this signature in database
GPG Key ID: B79682F6FE8D30E3
50 changed files with 1391 additions and 2236 deletions

View File

@ -7,6 +7,8 @@
* @version 2023.04.04 * @version 2023.04.04
*/ */
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
// CDN 资源地址 // CDN 资源地址
if (kratos_option('g_cdn', false)) { if (kratos_option('g_cdn', false)) {
$asset_path = 'https://cdn.jsdelivr.net/gh/seatonjiang/kratos@v' . THEME_VERSION; $asset_path = 'https://cdn.jsdelivr.net/gh/seatonjiang/kratos@v' . THEME_VERSION;
@ -222,7 +224,7 @@ if (kratos_option('g_replace_gravatar_url_fieldset')['g_replace_gravatar_url'] ?
} }
// 主题更新检测 // 主题更新检测
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker( $myUpdateChecker = PucFactory::buildUpdateChecker(
'https://cdn.jsdelivr.net/gh/seatonjiang/kratos/inc/update-checker/update.json', 'https://cdn.jsdelivr.net/gh/seatonjiang/kratos/inc/update-checker/update.json',
get_template_directory() . '/functions.php', get_template_directory() . '/functions.php',
'Kratos' 'Kratos'

View File

@ -1,6 +0,0 @@
<?php
if ( !class_exists('Puc_v4_Factory', false) ):
class Puc_v4_Factory extends Puc_v4p10_Factory { }
endif;

View File

@ -1,63 +0,0 @@
<?php
if ( !class_exists('Puc_v4p10_Autoloader', false) ):
class Puc_v4p10_Autoloader {
private $prefix = '';
private $rootDir = '';
private $libraryDir = '';
private $staticMap;
public function __construct() {
$this->rootDir = dirname(__FILE__) . '/';
$nameParts = explode('_', __CLASS__, 3);
$this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
$this->libraryDir = $this->rootDir . '../..';
if ( !self::isPhar() ) {
$this->libraryDir = realpath($this->libraryDir);
}
$this->libraryDir = $this->libraryDir . '/';
$this->staticMap = array(
'PucReadmeParser' => 'vendor/PucReadmeParser.php',
'Parsedown' => 'vendor/Parsedown.php',
'Puc_v4_Factory' => 'Puc/v4/Factory.php',
);
spl_autoload_register(array($this, 'autoload'));
}
/**
* Determine if this file is running as part of a Phar archive.
*
* @return bool
*/
private static function isPhar() {
//Check if the current file path starts with "phar://".
static $pharProtocol = 'phar://';
return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol);
}
public function autoload($className) {
if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
/** @noinspection PhpIncludeInspection */
include ($this->libraryDir . $this->staticMap[$className]);
return;
}
if (strpos($className, $this->prefix) === 0) {
$path = substr($className, strlen($this->prefix));
$path = str_replace('_', '/', $path);
$path = $this->rootDir . $path . '.php';
if (file_exists($path)) {
/** @noinspection PhpIncludeInspection */
include $path;
}
}
}
}
endif;

View File

@ -1,33 +0,0 @@
<?php
if ( !class_exists('Puc_v4p10_DebugBar_PluginExtension', false) ):
class Puc_v4p10_DebugBar_PluginExtension extends Puc_v4p10_DebugBar_Extension {
/** @var Puc_v4p10_Plugin_UpdateChecker */
protected $updateChecker;
public function __construct($updateChecker) {
parent::__construct($updateChecker, 'Puc_v4p10_DebugBar_PluginPanel');
add_action('wp_ajax_puc_v4_debug_request_info', array($this, 'ajaxRequestInfo'));
}
/**
* Request plugin info and output it.
*/
public function ajaxRequestInfo() {
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
return;
}
$this->preAjaxRequest();
$info = $this->updateChecker->requestInfo();
if ( $info !== null ) {
echo 'Successfully retrieved plugin info from the metadata URL:';
echo '<pre>', htmlentities(print_r($info, true)), '</pre>';
} else {
echo 'Failed to retrieve plugin info from the metadata URL.';
}
exit;
}
}
endif;

View File

@ -0,0 +1,10 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5;
if ( !class_exists(PucFactory::class, false) ):
class PucFactory extends \YahnisElsts\PluginUpdateChecker\v5p2\PucFactory {
}
endif;

View File

@ -0,0 +1,86 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists(Autoloader::class, false) ):
class Autoloader {
const DEFAULT_NS_PREFIX = 'YahnisElsts\\PluginUpdateChecker\\';
private $prefix;
private $rootDir;
private $libraryDir;
private $staticMap;
public function __construct() {
$this->rootDir = dirname(__FILE__) . '/';
$namespaceWithSlash = __NAMESPACE__ . '\\';
$this->prefix = $namespaceWithSlash;
$this->libraryDir = $this->rootDir . '../..';
if ( !self::isPhar() ) {
$this->libraryDir = realpath($this->libraryDir);
}
$this->libraryDir = $this->libraryDir . '/';
//Usually, dependencies like Parsedown are in the global namespace,
//but if someone adds a custom namespace to the entire library, they
//will be in the same namespace as this class.
$isCustomNamespace = (
substr($namespaceWithSlash, 0, strlen(self::DEFAULT_NS_PREFIX)) !== self::DEFAULT_NS_PREFIX
);
$libraryPrefix = $isCustomNamespace ? $namespaceWithSlash : '';
$this->staticMap = array(
$libraryPrefix . 'PucReadmeParser' => 'vendor/PucReadmeParser.php',
$libraryPrefix . 'Parsedown' => 'vendor/Parsedown.php',
);
//Add the generic, major-version-only factory class to the static map.
$versionSeparatorPos = strrpos(__NAMESPACE__, '\\v');
if ( $versionSeparatorPos !== false ) {
$versionSegment = substr(__NAMESPACE__, $versionSeparatorPos + 1);
$pointPos = strpos($versionSegment, 'p');
if ( ($pointPos !== false) && ($pointPos > 1) ) {
$majorVersionSegment = substr($versionSegment, 0, $pointPos);
$majorVersionNs = __NAMESPACE__ . '\\' . $majorVersionSegment;
$this->staticMap[$majorVersionNs . '\\PucFactory'] =
'Puc/' . $majorVersionSegment . '/Factory.php';
}
}
spl_autoload_register(array($this, 'autoload'));
}
/**
* Determine if this file is running as part of a Phar archive.
*
* @return bool
*/
private static function isPhar() {
//Check if the current file path starts with "phar://".
static $pharProtocol = 'phar://';
return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol);
}
public function autoload($className) {
if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
include($this->libraryDir . $this->staticMap[$className]);
return;
}
if ( strpos($className, $this->prefix) === 0 ) {
$path = substr($className, strlen($this->prefix));
$path = str_replace(array('_', '\\'), '/', $path);
$path = $this->rootDir . $path . '.php';
if ( file_exists($path) ) {
include $path;
}
}
}
}
endif;

View File

@ -1,12 +1,17 @@
<?php <?php
if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
class Puc_v4p10_DebugBar_Extension { use YahnisElsts\PluginUpdateChecker\v5p2\PucFactory;
use YahnisElsts\PluginUpdateChecker\v5p2\UpdateChecker;
if ( !class_exists(Extension::class, false) ):
class Extension {
const RESPONSE_BODY_LENGTH_LIMIT = 4000; const RESPONSE_BODY_LENGTH_LIMIT = 4000;
/** @var Puc_v4p10_UpdateChecker */ /** @var UpdateChecker */
protected $updateChecker; protected $updateChecker;
protected $panelClass = 'Puc_v4p10_DebugBar_Panel'; protected $panelClass = Panel::class;
public function __construct($updateChecker, $panelClass = null) { public function __construct($updateChecker, $panelClass = null) {
$this->updateChecker = $updateChecker; $this->updateChecker = $updateChecker;
@ -14,10 +19,14 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
$this->panelClass = $panelClass; $this->panelClass = $panelClass;
} }
if ( (strpos($this->panelClass, '\\') === false) ) {
$this->panelClass = __NAMESPACE__ . '\\' . $this->panelClass;
}
add_filter('debug_bar_panels', array($this, 'addDebugBarPanel')); add_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies')); add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
add_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow')); add_action('wp_ajax_puc_v5_debug_check_now', array($this, 'ajaxCheckNow'));
} }
/** /**
@ -38,17 +47,17 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
*/ */
public function enqueuePanelDependencies() { public function enqueuePanelDependencies() {
wp_enqueue_style( wp_enqueue_style(
'puc-debug-bar-style-v4', 'puc-debug-bar-style-v5',
$this->getLibraryUrl("/css/puc-debug-bar.css"), $this->getLibraryUrl("/css/puc-debug-bar.css"),
array('debug-bar'), array('debug-bar'),
'20171124' '20221008'
); );
wp_enqueue_script( wp_enqueue_script(
'puc-debug-bar-js-v4', 'puc-debug-bar-js-v5',
$this->getLibraryUrl("/js/debug-bar.js"), $this->getLibraryUrl("/js/debug-bar.js"),
array('jquery'), array('jquery'),
'20170516' '20221008'
); );
} }
@ -57,14 +66,16 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
* the update checking process works as expected. * the update checking process works as expected.
*/ */
public function ajaxCheckNow() { public function ajaxCheckNow() {
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is checked in preAjaxRequest().
if ( !isset($_POST['uid']) || ($_POST['uid'] !== $this->updateChecker->getUniqueName('uid')) ) {
return; return;
} }
$this->preAjaxRequest(); $this->preAjaxRequest();
$update = $this->updateChecker->checkForUpdates(); $update = $this->updateChecker->checkForUpdates();
if ( $update !== null ) { if ( $update !== null ) {
echo "An update is available:"; echo "An update is available:";
echo '<pre>', htmlentities(print_r($update, true)), '</pre>'; //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- For debugging output.
echo '<pre>', esc_html(print_r($update, true)), '</pre>';
} else { } else {
echo 'No updates found.'; echo 'No updates found.';
} }
@ -75,8 +86,8 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
foreach (array_values($errors) as $num => $item) { foreach (array_values($errors) as $num => $item) {
$wpError = $item['error']; $wpError = $item['error'];
/** @var WP_Error $wpError */ /** @var \WP_Error $wpError */
printf('<h4>%d) %s</h4>', $num + 1, esc_html($wpError->get_error_message())); printf('<h4>%d) %s</h4>', intval($num + 1), esc_html($wpError->get_error_message()));
echo '<dl>'; echo '<dl>';
printf('<dt>Error code:</dt><dd><code>%s</code></dd>', esc_html($wpError->get_error_code())); printf('<dt>Error code:</dt><dd><code>%s</code></dd>', esc_html($wpError->get_error_code()));
@ -88,7 +99,7 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
if ( isset($item['httpResponse']) ) { if ( isset($item['httpResponse']) ) {
if ( is_wp_error($item['httpResponse']) ) { if ( is_wp_error($item['httpResponse']) ) {
$httpError = $item['httpResponse']; $httpError = $item['httpResponse'];
/** @var WP_Error $httpError */ /** @var \WP_Error $httpError */
printf( printf(
'<dt>WordPress HTTP API error:</dt><dd>%s (<code>%s</code>)</dd>', '<dt>WordPress HTTP API error:</dt><dd>%s (<code>%s</code>)</dd>',
esc_html($httpError->get_error_message()), esc_html($httpError->get_error_message()),
@ -98,8 +109,8 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
//Status code. //Status code.
printf( printf(
'<dt>HTTP status:</dt><dd><code>%d %s</code></dd>', '<dt>HTTP status:</dt><dd><code>%d %s</code></dd>',
wp_remote_retrieve_response_code($item['httpResponse']), esc_html(wp_remote_retrieve_response_code($item['httpResponse'])),
wp_remote_retrieve_response_message($item['httpResponse']) esc_html(wp_remote_retrieve_response_message($item['httpResponse']))
); );
//Headers. //Headers.
@ -138,7 +149,9 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
} }
check_ajax_referer('puc-ajax'); check_ajax_referer('puc-ajax');
//phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_error_reporting -- Part of a debugging feature.
error_reporting(E_ALL); error_reporting(E_ALL);
//phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted
@ini_set('display_errors', 'On'); @ini_set('display_errors', 'On');
} }
@ -148,7 +161,7 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
public function removeHooks() { public function removeHooks() {
remove_filter('debug_bar_panels', array($this, 'addDebugBarPanel')); remove_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
remove_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies')); remove_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
remove_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow')); remove_action('wp_ajax_puc_v5_debug_check_now', array($this, 'ajaxCheckNow'));
} }
/** /**
@ -159,11 +172,11 @@ if ( !class_exists('Puc_v4p10_DebugBar_Extension', false) ):
$absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/')); $absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/'));
//Where is the library located inside the WordPress directory structure? //Where is the library located inside the WordPress directory structure?
$absolutePath = Puc_v4p10_Factory::normalizePath($absolutePath); $absolutePath = PucFactory::normalizePath($absolutePath);
$pluginDir = Puc_v4p10_Factory::normalizePath(WP_PLUGIN_DIR); $pluginDir = PucFactory::normalizePath(WP_PLUGIN_DIR);
$muPluginDir = Puc_v4p10_Factory::normalizePath(WPMU_PLUGIN_DIR); $muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
$themeDir = Puc_v4p10_Factory::normalizePath(get_theme_root()); $themeDir = PucFactory::normalizePath(get_theme_root());
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) { if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
//It's part of a plugin. //It's part of a plugin.

View File

@ -1,9 +1,12 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
if ( !class_exists('Puc_v4p10_DebugBar_Panel', false) && class_exists('Debug_Bar_Panel', false) ): use YahnisElsts\PluginUpdateChecker\v5p2\UpdateChecker;
class Puc_v4p10_DebugBar_Panel extends Debug_Bar_Panel { if ( !class_exists(Panel::class, false) && class_exists('Debug_Bar_Panel', false) ):
/** @var Puc_v4p10_UpdateChecker */
class Panel extends \Debug_Bar_Panel {
/** @var UpdateChecker */
protected $updateChecker; protected $updateChecker;
private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>'; private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
@ -20,7 +23,7 @@ if ( !class_exists('Puc_v4p10_DebugBar_Panel', false) && class_exists('Debug_Bar
public function render() { public function render() {
printf( printf(
'<div class="puc-debug-bar-panel-v4" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">', '<div class="puc-debug-bar-panel-v5" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">',
esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')), esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')),
esc_attr($this->updateChecker->slug), esc_attr($this->updateChecker->slug),
esc_attr($this->updateChecker->getUniqueName('uid')), esc_attr($this->updateChecker->getUniqueName('uid')),
@ -119,7 +122,10 @@ if ( !class_exists('Puc_v4p10_DebugBar_Panel', false) && class_exists('Debug_Bar
$fields = $this->getUpdateFields(); $fields = $this->getUpdateFields();
foreach($fields as $field) { foreach($fields as $field) {
if ( property_exists($update, $field) ) { if ( property_exists($update, $field) ) {
$this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field)); $this->row(
ucwords(str_replace('_', ' ', $field)),
isset($update->$field) ? htmlentities($update->$field) : null
);
} }
} }
echo '</table>'; echo '</table>';
@ -154,11 +160,18 @@ if ( !class_exists('Puc_v4p10_DebugBar_Panel', false) && class_exists('Debug_Bar
public function row($name, $value) { public function row($name, $value) {
if ( is_object($value) || is_array($value) ) { if ( is_object($value) || is_array($value) ) {
//This is specifically for debugging, so print_r() is fine.
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
$value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>'; $value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
} else if ($value === null) { } else if ($value === null) {
$value = '<code>null</code>'; $value = '<code>null</code>';
} }
printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value); printf(
'<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>',
esc_html($name),
//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above.
$value
);
} }
} }

View File

@ -0,0 +1,40 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
use YahnisElsts\PluginUpdateChecker\v5p2\Plugin\UpdateChecker;
if ( !class_exists(PluginExtension::class, false) ):
class PluginExtension extends Extension {
/** @var UpdateChecker */
protected $updateChecker;
public function __construct($updateChecker) {
parent::__construct($updateChecker, PluginPanel::class);
add_action('wp_ajax_puc_v5_debug_request_info', array($this, 'ajaxRequestInfo'));
}
/**
* Request plugin info and output it.
*/
public function ajaxRequestInfo() {
//phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce is checked in preAjaxRequest().
if ( !isset($_POST['uid']) || ($_POST['uid'] !== $this->updateChecker->getUniqueName('uid')) ) {
return;
}
$this->preAjaxRequest();
$info = $this->updateChecker->requestInfo();
if ( $info !== null ) {
echo 'Successfully retrieved plugin info from the metadata URL:';
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- For debugging output.
echo '<pre>', esc_html(print_r($info, true)), '</pre>';
} else {
echo 'Failed to retrieve plugin info from the metadata URL.';
}
exit;
}
}
endif;

View File

@ -1,10 +1,13 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
if ( !class_exists('Puc_v4p10_DebugBar_PluginPanel', false) ): use YahnisElsts\PluginUpdateChecker\v5p2\Plugin\UpdateChecker;
class Puc_v4p10_DebugBar_PluginPanel extends Puc_v4p10_DebugBar_Panel { if ( !class_exists(PluginPanel::class, false) ):
class PluginPanel extends Panel {
/** /**
* @var Puc_v4p10_Plugin_UpdateChecker * @var UpdateChecker
*/ */
protected $updateChecker; protected $updateChecker;

View File

@ -1,10 +1,14 @@
<?php <?php
if ( !class_exists('Puc_v4p10_DebugBar_ThemePanel', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
class Puc_v4p10_DebugBar_ThemePanel extends Puc_v4p10_DebugBar_Panel { use YahnisElsts\PluginUpdateChecker\v5p2\Theme\UpdateChecker;
if ( !class_exists(ThemePanel::class, false) ):
class ThemePanel extends Panel {
/** /**
* @var Puc_v4p10_Theme_UpdateChecker * @var UpdateChecker
*/ */
protected $updateChecker; protected $updateChecker;

View File

@ -1,5 +1,7 @@
<?php <?php
if ( !class_exists('Puc_v4p10_InstalledPackage', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists(InstalledPackage::class, false) ):
/** /**
* This class represents a currently installed plugin or theme. * This class represents a currently installed plugin or theme.
@ -7,9 +9,9 @@ if ( !class_exists('Puc_v4p10_InstalledPackage', false) ):
* Not to be confused with the "package" field in WP update API responses that contains * Not to be confused with the "package" field in WP update API responses that contains
* the download URL of a the new version. * the download URL of a the new version.
*/ */
abstract class Puc_v4p10_InstalledPackage { abstract class InstalledPackage {
/** /**
* @var Puc_v4p10_UpdateChecker * @var UpdateChecker
*/ */
protected $updateChecker; protected $updateChecker;

View File

@ -1,5 +1,11 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Metadata', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2;
use LogicException;
use stdClass;
use WP_Error;
if ( !class_exists(Metadata::class, false) ):
/** /**
* A base container for holding information about updates and plugin metadata. * A base container for holding information about updates and plugin metadata.
@ -8,7 +14,13 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* @copyright 2016 * @copyright 2016
* @access public * @access public
*/ */
abstract class Puc_v4p10_Metadata { abstract class Metadata {
/**
* Additional dynamic properties, usually copied from the API response.
*
* @var array<string,mixed>
*/
protected $extraProperties = array();
/** /**
* Create an instance of this class from a JSON document. * Create an instance of this class from a JSON document.
@ -17,7 +29,7 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* @param string $json * @param string $json
* @return self * @return self
*/ */
public static function fromJson(/** @noinspection PhpUnusedParameterInspection */ $json) { public static function fromJson($json) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses'); throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
} }
@ -27,19 +39,21 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* @return bool * @return bool
*/ */
protected static function createFromJson($json, $target) { protected static function createFromJson($json, $target) {
/** @var StdClass $apiResponse */ /** @var \StdClass $apiResponse */
$apiResponse = json_decode($json); $apiResponse = json_decode($json);
if ( empty($apiResponse) || !is_object($apiResponse) ){ if ( empty($apiResponse) || !is_object($apiResponse) ){
$errorMessage = "Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/"; $errorMessage = "Failed to parse update metadata. Try validating your .json file with https://jsonlint.com/";
do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage)); do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage));
trigger_error($errorMessage, E_USER_NOTICE); //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- For plugin developers.
trigger_error(esc_html($errorMessage), E_USER_NOTICE);
return false; return false;
} }
$valid = $target->validateMetadata($apiResponse); $valid = $target->validateMetadata($apiResponse);
if ( is_wp_error($valid) ){ if ( is_wp_error($valid) ){
do_action('puc_api_error', $valid); do_action('puc_api_error', $valid);
trigger_error($valid->get_error_message(), E_USER_NOTICE); //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- For plugin developers.
trigger_error(esc_html($valid->get_error_message()), E_USER_NOTICE);
return false; return false;
} }
@ -53,10 +67,10 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
/** /**
* No validation by default! Subclasses should check that the required fields are present. * No validation by default! Subclasses should check that the required fields are present.
* *
* @param StdClass $apiResponse * @param \StdClass $apiResponse
* @return bool|WP_Error * @return bool|\WP_Error
*/ */
protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) { protected function validateMetadata($apiResponse) {
return true; return true;
} }
@ -64,10 +78,10 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* Create a new instance by copying the necessary fields from another object. * Create a new instance by copying the necessary fields from another object.
* *
* @abstract * @abstract
* @param StdClass|self $object The source object. * @param \StdClass|self $object The source object.
* @return self The new copy. * @return self The new copy.
*/ */
public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) { public static function fromObject($object) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses'); throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
} }
@ -77,7 +91,7 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* avoids the "incomplete object" problem if the cached value is loaded * avoids the "incomplete object" problem if the cached value is loaded
* before this class. * before this class.
* *
* @return StdClass * @return \StdClass
*/ */
public function toStdClass() { public function toStdClass() {
$object = new stdClass(); $object = new stdClass();
@ -95,8 +109,8 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
/** /**
* Copy known fields from one object to another. * Copy known fields from one object to another.
* *
* @param StdClass|self $from * @param \StdClass|self $from
* @param StdClass|self $to * @param \StdClass|self $to
*/ */
protected function copyFields($from, $to) { protected function copyFields($from, $to) {
$fields = $this->getFieldNames(); $fields = $this->getFieldNames();
@ -127,6 +141,22 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
protected function getPrefixedFilter($tag) { protected function getPrefixedFilter($tag) {
return 'puc_' . $tag; return 'puc_' . $tag;
} }
public function __set($name, $value) {
$this->extraProperties[$name] = $value;
}
public function __get($name) {
return isset($this->extraProperties[$name]) ? $this->extraProperties[$name] : null;
}
public function __isset($name) {
return isset($this->extraProperties[$name]);
}
public function __unset($name) {
unset($this->extraProperties[$name]);
}
} }
endif; endif;

View File

@ -1,11 +1,12 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists('Puc_v4p10_OAuthSignature', false) ): if ( !class_exists(OAuthSignature::class, false) ):
/** /**
* A basic signature generator for zero-legged OAuth 1.0. * A basic signature generator for zero-legged OAuth 1.0.
*/ */
class Puc_v4p10_OAuthSignature { class OAuthSignature {
private $consumerKey = ''; private $consumerKey = '';
private $consumerSecret = ''; private $consumerSecret = '';
@ -25,10 +26,10 @@ if ( !class_exists('Puc_v4p10_OAuthSignature', false) ):
$parameters = array(); $parameters = array();
//Parse query parameters. //Parse query parameters.
$query = parse_url($url, PHP_URL_QUERY); $query = wp_parse_url($url, PHP_URL_QUERY);
if ( !empty($query) ) { if ( !empty($query) ) {
parse_str($query, $parsedParams); parse_str($query, $parsedParams);
if ( is_array($parameters) ) { if ( is_array($parsedParams) ) {
$parameters = $parsedParams; $parameters = $parsedParams;
} }
//Remove the query string from the URL. We'll replace it later. //Remove the query string from the URL. We'll replace it later.
@ -85,12 +86,13 @@ if ( !class_exists('Puc_v4p10_OAuthSignature', false) ):
if ( is_callable('random_bytes') ) { if ( is_callable('random_bytes') ) {
try { try {
$rand = random_bytes(16); $rand = random_bytes(16);
} catch (Exception $ex) { } catch (\Exception $ex) {
//Fall back to mt_rand (below). //Fall back to mt_rand (below).
} }
} }
if ( $rand === null ) { if ( $rand === null ) {
$rand = mt_rand(); //phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand
$rand = function_exists('wp_rand') ? wp_rand() : mt_rand();
} }
return md5($mt . '_' . $rand); return md5($mt . '_' . $rand);

View File

@ -1,9 +1,14 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Plugin_Package', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
class Puc_v4p10_Plugin_Package extends Puc_v4p10_InstalledPackage { use YahnisElsts\PluginUpdateChecker\v5p2\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p2\PucFactory;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/** /**
* @var Puc_v4p10_Plugin_UpdateChecker * @var UpdateChecker
*/ */
protected $updateChecker; protected $updateChecker;
@ -46,7 +51,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Package', false) ):
//This can happen if the filename points to something that is not a plugin. //This can happen if the filename points to something that is not a plugin.
$this->updateChecker->triggerError( $this->updateChecker->triggerError(
sprintf( sprintf(
"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", "Cannot read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->updateChecker->pluginFile $this->updateChecker->pluginFile
), ),
E_USER_WARNING E_USER_WARNING
@ -140,7 +145,6 @@ if ( !class_exists('Puc_v4p10_Plugin_Package', false) ):
} }
if ( !function_exists('get_plugin_data') ) { if ( !function_exists('get_plugin_data') ) {
/** @noinspection PhpIncludeInspection */
require_once(ABSPATH . '/wp-admin/includes/plugin.php'); require_once(ABSPATH . '/wp-admin/includes/plugin.php');
} }
return get_plugin_data($this->pluginAbsolutePath, false, false); return get_plugin_data($this->pluginAbsolutePath, false, false);
@ -170,8 +174,8 @@ if ( !class_exists('Puc_v4p10_Plugin_Package', false) ):
$pluginPath = realpath($this->pluginAbsolutePath); $pluginPath = realpath($this->pluginAbsolutePath);
//If realpath() fails, just normalize the syntax instead. //If realpath() fails, just normalize the syntax instead.
if (($muPluginDir === false) || ($pluginPath === false)) { if (($muPluginDir === false) || ($pluginPath === false)) {
$muPluginDir = Puc_v4p10_Factory::normalizePath(WPMU_PLUGIN_DIR); $muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
$pluginPath = Puc_v4p10_Factory::normalizePath($this->pluginAbsolutePath); $pluginPath = PucFactory::normalizePath($this->pluginAbsolutePath);
} }
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0); $cachedResult = (strpos($pluginPath, $muPluginDir) === 0);

View File

@ -1,5 +1,9 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Plugin_Info', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p2\Metadata;
if ( !class_exists(PluginInfo::class, false) ):
/** /**
* A container class for holding and transforming various plugin metadata. * A container class for holding and transforming various plugin metadata.
@ -8,7 +12,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Info', false) ):
* @copyright 2016 * @copyright 2016
* @access public * @access public
*/ */
class Puc_v4p10_Plugin_Info extends Puc_v4p10_Metadata { class PluginInfo extends Metadata {
//Most fields map directly to the contents of the plugin's info.json file. //Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning. //See the relevant docs for a description of their meaning.
public $name; public $name;
@ -64,8 +68,8 @@ if ( !class_exists('Puc_v4p10_Plugin_Info', false) ):
/** /**
* Very, very basic validation. * Very, very basic validation.
* *
* @param StdClass $apiResponse * @param \StdClass $apiResponse
* @return bool|WP_Error * @return bool|\WP_Error
*/ */
protected function validateMetadata($apiResponse) { protected function validateMetadata($apiResponse) {
if ( if (
@ -73,7 +77,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Info', false) ):
|| empty($apiResponse->name) || empty($apiResponse->name)
|| empty($apiResponse->version) || empty($apiResponse->version)
) { ) {
return new WP_Error( return new \WP_Error(
'puc-invalid-metadata', 'puc-invalid-metadata',
"The plugin metadata file does not contain the required 'name' and/or 'version' keys." "The plugin metadata file does not contain the required 'name' and/or 'version' keys."
); );
@ -88,7 +92,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Info', false) ):
* @return object * @return object
*/ */
public function toWpFormat(){ public function toWpFormat(){
$info = new stdClass; $info = new \stdClass;
//The custom update API is built so that many fields have the same name and format //The custom update API is built so that many fields have the same name and format
//as those returned by the native WordPress.org API. These can be assigned directly. //as those returned by the native WordPress.org API. These can be assigned directly.

View File

@ -1,14 +1,16 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
if ( !class_exists('Ui', false) ):
/** /**
* Additional UI elements for plugins. * Additional UI elements for plugins.
*/ */
class Puc_v4p10_Plugin_Ui { class Ui {
private $updateChecker; private $updateChecker;
private $manualCheckErrorTransient = ''; private $manualCheckErrorTransient = '';
/** /**
* @param Puc_v4p10_Plugin_UpdateChecker $updateChecker * @param UpdateChecker $updateChecker
*/ */
public function __construct($updateChecker) { public function __construct($updateChecker) {
$this->updateChecker = $updateChecker; $this->updateChecker = $updateChecker;
@ -156,8 +158,9 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
if ( $shouldCheck ) { if ( $shouldCheck ) {
$update = $this->updateChecker->checkForUpdates(); $update = $this->updateChecker->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available'; $status = ($update === null) ? 'no_update' : 'update_available';
$lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors();
if ( ($update === null) && !empty($this->lastRequestApiErrors) ) { if ( ($update === null) && !empty($lastRequestApiErrors) ) {
//Some errors are not critical. For example, if PUC tries to retrieve the readme.txt //Some errors are not critical. For example, if PUC tries to retrieve the readme.txt
//file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates //file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates
//from working. Maybe the plugin simply doesn't have a readme. //from working. Maybe the plugin simply doesn't have a readme.
@ -169,9 +172,9 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
'puc-bitbucket-http-error', 'puc-bitbucket-http-error',
); );
foreach ($this->lastRequestApiErrors as $item) { foreach ($lastRequestApiErrors as $item) {
$wpError = $item['error']; $wpError = $item['error'];
/** @var WP_Error $wpError */ /** @var \WP_Error $wpError */
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) { if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
$foundCriticalErrors = true; $foundCriticalErrors = true;
break; break;
@ -180,7 +183,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
if ( $foundCriticalErrors ) { if ( $foundCriticalErrors ) {
$status = 'error'; $status = 'error';
set_site_transient($this->manualCheckErrorTransient, $this->lastRequestApiErrors, 60); set_site_transient($this->manualCheckErrorTransient, $lastRequestApiErrors, 60);
} }
} }
@ -203,8 +206,9 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
* You can change the result message by using the "puc_manual_check_message-$slug" filter. * You can change the result message by using the "puc_manual_check_message-$slug" filter.
*/ */
public function displayManualCheckResult() { public function displayManualCheckResult() {
//phpcs:disable WordPress.Security.NonceVerification.Recommended -- Just displaying a message.
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) { if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) {
$status = strval($_GET['puc_update_check_result']); $status = sanitize_key($_GET['puc_update_check_result']);
$title = $this->updateChecker->getInstalledPackage()->getPluginTitle(); $title = $this->updateChecker->getInstalledPackage()->getPluginTitle();
$noticeClass = 'updated notice-success'; $noticeClass = 'updated notice-success';
$details = ''; $details = '';
@ -220,16 +224,29 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient)); $details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
delete_site_transient($this->manualCheckErrorTransient); delete_site_transient($this->manualCheckErrorTransient);
} else { } else {
$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status)); $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), $status);
$noticeClass = 'error notice-error'; $noticeClass = 'error notice-error';
} }
$message = esc_html($message);
//Plugins can replace the message with their own, including adding HTML.
$message = apply_filters(
$this->updateChecker->getUniqueName('manual_check_message'),
$message,
$status
);
printf( printf(
'<div class="notice %s is-dismissible"><p>%s</p>%s</div>', '<div class="notice %s is-dismissible"><p>%s</p>%s</div>',
$noticeClass, esc_attr($noticeClass),
apply_filters($this->updateChecker->getUniqueName('manual_check_message'), $message, $status), //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Was escaped above, and plugins can add HTML.
$message,
//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Contains HTML. Content should already be escaped.
$details $details
); );
} }
//phpcs:enable
} }
/** /**
@ -253,11 +270,11 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
} }
foreach ($errors as $item) { foreach ($errors as $item) {
$wpError = $item['error']; $wpError = $item['error'];
/** @var WP_Error $wpError */ /** @var \WP_Error $wpError */
$output .= sprintf( $output .= sprintf(
$formatString, $formatString,
$wpError->get_error_message(), esc_html($wpError->get_error_message()),
$wpError->get_error_code() esc_html($wpError->get_error_code())
); );
} }
if ( $showAsList ) { if ( $showAsList ) {

View File

@ -1,5 +1,9 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Plugin_Update', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p2\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
/** /**
* A simple container class for holding information about an available update. * A simple container class for holding information about an available update.
@ -8,7 +12,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Update', false) ):
* @copyright 2016 * @copyright 2016
* @access public * @access public
*/ */
class Puc_v4p10_Plugin_Update extends Puc_v4p10_Update { class Update extends BaseUpdate {
public $id = 0; public $id = 0;
public $homepage; public $homepage;
public $upgrade_notice; public $upgrade_notice;
@ -25,13 +29,13 @@ if ( !class_exists('Puc_v4p10_Plugin_Update', false) ):
* Create a new instance of PluginUpdate from its JSON-encoded representation. * Create a new instance of PluginUpdate from its JSON-encoded representation.
* *
* @param string $json * @param string $json
* @return Puc_v4p10_Plugin_Update|null * @return self|null
*/ */
public static function fromJson($json){ public static function fromJson($json){
//Since update-related information is simply a subset of the full plugin info, //Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over //we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about. //the parts that we care about.
$pluginInfo = Puc_v4p10_Plugin_Info::fromJson($json); $pluginInfo = PluginInfo::fromJson($json);
if ( $pluginInfo !== null ) { if ( $pluginInfo !== null ) {
return self::fromPluginInfo($pluginInfo); return self::fromPluginInfo($pluginInfo);
} else { } else {
@ -43,18 +47,18 @@ if ( !class_exists('Puc_v4p10_Plugin_Update', false) ):
* Create a new instance of PluginUpdate based on an instance of PluginInfo. * Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another. * Basically, this just copies a subset of fields from one object to another.
* *
* @param Puc_v4p10_Plugin_Info $info * @param PluginInfo $info
* @return Puc_v4p10_Plugin_Update * @return static
*/ */
public static function fromPluginInfo($info){ public static function fromPluginInfo($info){
return self::fromObject($info); return static::fromObject($info);
} }
/** /**
* Create a new instance by copying the necessary fields from another object. * Create a new instance by copying the necessary fields from another object.
* *
* @param StdClass|Puc_v4p10_Plugin_Info|Puc_v4p10_Plugin_Update $object The source object. * @param \StdClass|PluginInfo|self $object The source object.
* @return Puc_v4p10_Plugin_Update The new copy. * @return self The new copy.
*/ */
public static function fromObject($object) { public static function fromObject($object) {
$update = new self(); $update = new self();

View File

@ -1,5 +1,12 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p2\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p2\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p2\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
/** /**
* A custom plugin update checker. * A custom plugin update checker.
@ -8,7 +15,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* @copyright 2018 * @copyright 2018
* @access public * @access public
*/ */
class Puc_v4p10_Plugin_UpdateChecker extends Puc_v4p10_UpdateChecker { class UpdateChecker extends BaseUpdateChecker {
protected $updateTransient = 'update_plugins'; protected $updateTransient = 'update_plugins';
protected $translationType = 'plugin'; protected $translationType = 'plugin';
@ -17,7 +24,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory. public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
/** /**
* @var Puc_v4p10_Plugin_Package * @var Package
*/ */
protected $package; protected $package;
@ -50,8 +57,8 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
if ( $slugUsedBy ) { if ( $slugUsedBy ) {
$this->triggerError(sprintf( $this->triggerError(sprintf(
'Plugin slug "%s" is already in use by %s. Slugs must be unique.', 'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
htmlentities($slug), $slug,
htmlentities($slugUsedBy) $slugUsedBy
), E_USER_ERROR); ), E_USER_ERROR);
} }
add_filter($slugCheckFilter, array($this, 'getAbsolutePath')); add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
@ -68,17 +75,17 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
//Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964 //Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964
add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks')); add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks'));
$this->extraUi = new Puc_v4p10_Plugin_Ui($this); $this->extraUi = new Ui($this);
} }
/** /**
* Create an instance of the scheduler. * Create an instance of the scheduler.
* *
* @param int $checkPeriod * @param int $checkPeriod
* @return Puc_v4p10_Scheduler * @return Scheduler
*/ */
protected function createScheduler($checkPeriod) { protected function createScheduler($checkPeriod) {
$scheduler = new Puc_v4p10_Scheduler($this, $checkPeriod, array('load-plugins.php')); $scheduler = new Scheduler($this, $checkPeriod, array('load-plugins.php'));
register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron')); register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron'));
return $scheduler; return $scheduler;
} }
@ -124,13 +131,17 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* @uses wp_remote_get() * @uses wp_remote_get()
* *
* @param array $queryArgs Additional query arguments to append to the request. Optional. * @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return Puc_v4p10_Plugin_Info * @return PluginInfo
*/ */
public function requestInfo($queryArgs = array()) { public function requestInfo($queryArgs = array()) {
list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p10_Plugin_Info', 'request_info', $queryArgs); list($pluginInfo, $result) = $this->requestMetadata(
PluginInfo::class,
'request_info',
$queryArgs
);
if ( $pluginInfo !== null ) { if ( $pluginInfo !== null ) {
/** @var Puc_v4p10_Plugin_Info $pluginInfo */ /** @var PluginInfo $pluginInfo */
$pluginInfo->filename = $this->pluginFile; $pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug; $pluginInfo->slug = $this->slug;
} }
@ -142,9 +153,9 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
/** /**
* Retrieve the latest update (if any) from the configured API endpoint. * Retrieve the latest update (if any) from the configured API endpoint.
* *
* @uses PluginUpdateChecker::requestInfo() * @uses UpdateChecker::requestInfo()
* *
* @return Puc_v4p10_Update|null An instance of Plugin_Update, or NULL when no updates are available. * @return Update|null An instance of Plugin Update, or NULL when no updates are available.
*/ */
public function requestUpdate() { public function requestUpdate() {
//For the sake of simplicity, this function just calls requestInfo() //For the sake of simplicity, this function just calls requestInfo()
@ -153,7 +164,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
if ( $pluginInfo === null ){ if ( $pluginInfo === null ){
return null; return null;
} }
$update = Puc_v4p10_Plugin_Update::fromPluginInfo($pluginInfo); $update = Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update); $update = $this->filterUpdateResult($update);
@ -197,9 +208,9 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
} }
/** /**
* @param stdClass|null $updates * @param \stdClass|null $updates
* @param stdClass $updateToAdd * @param \stdClass $updateToAdd
* @return stdClass * @return \stdClass
*/ */
protected function addUpdateToList($updates, $updateToAdd) { protected function addUpdateToList($updates, $updateToAdd) {
if ( $this->package->isMuPlugin() ) { if ( $this->package->isMuPlugin() ) {
@ -211,8 +222,8 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
} }
/** /**
* @param stdClass|null $updates * @param \stdClass|null $updates
* @return stdClass|null * @return \stdClass|null
*/ */
protected function removeUpdateFromList($updates) { protected function removeUpdateFromList($updates) {
$updates = parent::removeUpdateFromList($updates); $updates = parent::removeUpdateFromList($updates);
@ -246,7 +257,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
'banners' => array(), 'banners' => array(),
'banners_rtl' => array(), 'banners_rtl' => array(),
'tested' => '', 'tested' => '',
'compatibility' => new stdClass(), 'compatibility' => new \stdClass(),
) )
); );
} }
@ -255,7 +266,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* Alias for isBeingUpgraded(). * Alias for isBeingUpgraded().
* *
* @deprecated * @deprecated
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool * @return bool
*/ */
public function isPluginBeingUpgraded($upgrader = null) { public function isPluginBeingUpgraded($upgrader = null) {
@ -265,7 +276,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
/** /**
* Is there an update being installed for this plugin, right now? * Is there an update being installed for this plugin, right now?
* *
* @param WP_Upgrader|null $upgrader * @param \WP_Upgrader|null $upgrader
* @return bool * @return bool
*/ */
public function isBeingUpgraded($upgrader = null) { public function isBeingUpgraded($upgrader = null) {
@ -281,12 +292,12 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from * Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead. * the metadata URL, call requestUpdate() instead.
* *
* @return Puc_v4p10_Plugin_Update|null * @return Update|null
*/ */
public function getUpdate() { public function getUpdate() {
$update = parent::getUpdate(); $update = parent::getUpdate();
if ( isset($update) ) { if ( isset($update) ) {
/** @var Puc_v4p10_Plugin_Update $update */ /** @var Update $update */
$update->filename = $this->pluginFile; $update->filename = $this->pluginFile;
} }
return $update; return $update;
@ -391,20 +402,20 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
} }
protected function createDebugBarExtension() { protected function createDebugBarExtension() {
return new Puc_v4p10_DebugBar_PluginExtension($this); return new DebugBar\PluginExtension($this);
} }
/** /**
* Create a package instance that represents this plugin or theme. * Create a package instance that represents this plugin or theme.
* *
* @return Puc_v4p10_InstalledPackage * @return InstalledPackage
*/ */
protected function createInstalledPackage() { protected function createInstalledPackage() {
return new Puc_v4p10_Plugin_Package($this->pluginAbsolutePath, $this); return new Package($this->pluginAbsolutePath, $this);
} }
/** /**
* @return Puc_v4p10_Plugin_Package * @return Package
*/ */
public function getInstalledPackage() { public function getInstalledPackage() {
return $this->package; return $this->package;

View File

@ -1,5 +1,12 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Factory', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p2;
use YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p2\Theme;
use YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !class_exists(PucFactory::class, false) ):
/** /**
* A factory that builds update checker instances. * A factory that builds update checker instances.
@ -11,7 +18,7 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
* At the moment it can only build instances of the UpdateChecker class. Other classes are * At the moment it can only build instances of the UpdateChecker class. Other classes are
* intended mainly for internal use and refer directly to specific implementations. * intended mainly for internal use and refer directly to specific implementations.
*/ */
class Puc_v4p10_Factory { class PucFactory {
protected static $classVersions = array(); protected static $classVersions = array();
protected static $sorted = false; protected static $sorted = false;
@ -23,7 +30,7 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
* *
* @param string $fullPath Full path to the main plugin file or the theme's style.css. * @param string $fullPath Full path to the main plugin file or the theme's style.css.
* @param array $args Optional arguments. Keys should match the argument names of the buildUpdateChecker() method. * @param array $args Optional arguments. Keys should match the argument names of the buildUpdateChecker() method.
* @return Puc_v4p10_Plugin_UpdateChecker|Puc_v4p10_Theme_UpdateChecker|Puc_v4p10_Vcs_BaseChecker * @return Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/ */
public static function buildFromHeader($fullPath, $args = array()) { public static function buildFromHeader($fullPath, $args = array()) {
$fullPath = self::normalizePath($fullPath); $fullPath = self::normalizePath($fullPath);
@ -44,7 +51,6 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
$metadataUrl = self::getServiceURI($fullPath); $metadataUrl = self::getServiceURI($fullPath);
} }
/** @noinspection PhpUndefinedVariableInspection These variables are created by extract(), above. */
return self::buildUpdateChecker($metadataUrl, $fullPath, $slug, $checkPeriod, $optionName, $muPluginFile); return self::buildUpdateChecker($metadataUrl, $fullPath, $slug, $checkPeriod, $optionName, $muPluginFile);
} }
@ -54,15 +60,15 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
* This method automatically detects if you're using it for a plugin or a theme and chooses * This method automatically detects if you're using it for a plugin or a theme and chooses
* the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc). * the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc).
* *
* @see Puc_v4p10_UpdateChecker::__construct * @see UpdateChecker::__construct
* *
* @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source. * @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source.
* @param string $fullPath Full path to the main plugin file or to the theme directory. * @param string $fullPath Full path to the main plugin file or to the theme directory.
* @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory. * @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory.
* @param int $checkPeriod How often to check for updates (in hours). * @param int $checkPeriod How often to check for updates (in hours).
* @param string $optionName Where to store book-keeping info about update checks. * @param string $optionName Where to store bookkeeping info about update checks.
* @param string $muPluginFile The plugin filename relative to the mu-plugins directory. * @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
* @return Puc_v4p10_Plugin_UpdateChecker|Puc_v4p10_Theme_UpdateChecker|Puc_v4p10_Vcs_BaseChecker * @return Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/ */
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') { public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$fullPath = self::normalizePath($fullPath); $fullPath = self::normalizePath($fullPath);
@ -77,7 +83,7 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
$type = 'Theme'; $type = 'Theme';
$id = $themeDirectory; $id = $themeDirectory;
} else { } else {
throw new RuntimeException(sprintf( throw new \RuntimeException(sprintf(
'The update checker cannot determine if "%s" is a plugin or a theme. ' . 'The update checker cannot determine if "%s" is a plugin or a theme. ' .
'This is a bug. Please contact the PUC developer.', 'This is a bug. Please contact the PUC developer.',
htmlentities($fullPath) htmlentities($fullPath)
@ -90,25 +96,25 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
$apiClass = null; $apiClass = null;
if ( empty($service) ) { if ( empty($service) ) {
//The default is to get update information from a remote JSON file. //The default is to get update information from a remote JSON file.
$checkerClass = $type . '_UpdateChecker'; $checkerClass = $type . '\\UpdateChecker';
} else { } else {
//You can also use a VCS repository like GitHub. //You can also use a VCS repository like GitHub.
$checkerClass = 'Vcs_' . $type . 'UpdateChecker'; $checkerClass = 'Vcs\\' . $type . 'UpdateChecker';
$apiClass = $service . 'Api'; $apiClass = $service . 'Api';
} }
$checkerClass = self::getCompatibleClassVersion($checkerClass); $checkerClass = self::getCompatibleClassVersion($checkerClass);
if ( $checkerClass === null ) { if ( $checkerClass === null ) {
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error( trigger_error(
sprintf( esc_html(sprintf(
'PUC %s does not support updates for %ss %s', 'PUC %s does not support updates for %ss %s',
htmlentities(self::$latestCompatibleVersion), self::$latestCompatibleVersion,
strtolower($type), strtolower($type),
$service ? ('hosted on ' . htmlentities($service)) : 'using JSON metadata' $service ? ('hosted on ' . $service) : 'using JSON metadata'
), )),
E_USER_ERROR E_USER_ERROR
); );
return null;
} }
if ( !isset($apiClass) ) { if ( !isset($apiClass) ) {
@ -118,12 +124,12 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
//VCS checker + an API client. //VCS checker + an API client.
$apiClass = self::getCompatibleClassVersion($apiClass); $apiClass = self::getCompatibleClassVersion($apiClass);
if ( $apiClass === null ) { if ( $apiClass === null ) {
trigger_error(sprintf( //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(esc_html(sprintf(
'PUC %s does not support %s', 'PUC %s does not support %s',
htmlentities(self::$latestCompatibleVersion), self::$latestCompatibleVersion,
htmlentities($service) $service
), E_USER_ERROR); )), E_USER_ERROR);
return null;
} }
return new $checkerClass( return new $checkerClass(
@ -141,7 +147,7 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
* *
* Normalize a filesystem path. Introduced in WP 3.9. * Normalize a filesystem path. Introduced in WP 3.9.
* Copying here allows use of the class on earlier versions. * Copying here allows use of the class on earlier versions.
* This version adapted from WP 4.8.2 (unchanged since 4.5.0) * This version adapted from WP 4.8.2 (unchanged since 4.5.2)
* *
* @param string $path Path to normalize. * @param string $path Path to normalize.
* @return string Normalized path. * @return string Normalized path.
@ -232,7 +238,7 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
} }
//URI was not found so throw an error. //URI was not found so throw an error.
throw new RuntimeException( throw new \RuntimeException(
sprintf('Unable to locate URI in header of "%s"', htmlentities($fullPath)) sprintf('Unable to locate URI in header of "%s"', htmlentities($fullPath))
); );
} }
@ -247,8 +253,8 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
$service = null; $service = null;
//Which hosting service does the URL point to? //Which hosting service does the URL point to?
$host = parse_url($metadataUrl, PHP_URL_HOST); $host = (string)(wp_parse_url($metadataUrl, PHP_URL_HOST));
$path = parse_url($metadataUrl, PHP_URL_PATH); $path = (string)(wp_parse_url($metadataUrl, PHP_URL_PATH));
//Check if the path looks like "/user-name/repository". //Check if the path looks like "/user-name/repository".
//For GitLab.com it can also be "/user/group1/group2/.../repository". //For GitLab.com it can also be "/user/group1/group2/.../repository".
@ -328,8 +334,8 @@ if ( !class_exists('Puc_v4p10_Factory', false) ):
*/ */
public static function addVersion($generalClass, $versionedClass, $version) { public static function addVersion($generalClass, $versionedClass, $version) {
if ( empty(self::$myMajorVersion) ) { if ( empty(self::$myMajorVersion) ) {
$nameParts = explode('_', __CLASS__, 3); $lastNamespaceSegment = substr(__NAMESPACE__, strrpos(__NAMESPACE__, '\\') + 1);
self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1); self::$myMajorVersion = substr(ltrim($lastNamespaceSegment, 'v'), 0, 1);
} }
//Store the greatest version number that matches our major version. //Store the greatest version number that matches our major version.

View File

@ -1,11 +1,13 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Scheduler', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists(Scheduler::class, false) ):
/** /**
* The scheduler decides when and how often to check for updates. * The scheduler decides when and how often to check for updates.
* It calls @see Puc_v4p10_UpdateChecker::checkForUpdates() to perform the actual checks. * It calls @see UpdateChecker::checkForUpdates() to perform the actual checks.
*/ */
class Puc_v4p10_Scheduler { class Scheduler {
public $checkPeriod = 12; //How often to check for updates (in hours). public $checkPeriod = 12; //How often to check for updates (in hours).
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available. public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
public $throttledCheckPeriod = 72; public $throttledCheckPeriod = 72;
@ -13,7 +15,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
protected $hourlyCheckHooks = array('load-update.php'); protected $hourlyCheckHooks = array('load-update.php');
/** /**
* @var Puc_v4p10_UpdateChecker * @var UpdateChecker
*/ */
protected $updateChecker; protected $updateChecker;
@ -22,7 +24,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
/** /**
* Scheduler constructor. * Scheduler constructor.
* *
* @param Puc_v4p10_UpdateChecker $updateChecker * @param UpdateChecker $updateChecker
* @param int $checkPeriod How often to check for updates (in hours). * @param int $checkPeriod How often to check for updates (in hours).
* @param array $hourlyHooks * @param array $hourlyHooks
*/ */
@ -47,13 +49,22 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
} else { } else {
//Use a custom cron schedule. //Use a custom cron schedule.
$scheduleName = 'every' . $this->checkPeriod . 'hours'; $scheduleName = 'every' . $this->checkPeriod . 'hours';
//phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- WPCS fails to parse the callback.
add_filter('cron_schedules', array($this, '_addCustomSchedule')); add_filter('cron_schedules', array($this, '_addCustomSchedule'));
} }
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
//Randomly offset the schedule to help prevent update server traffic spikes. Without this //Randomly offset the schedule to help prevent update server traffic spikes. Without this
//most checks may happen during times of day when people are most likely to install new plugins. //most checks may happen during times of day when people are most likely to install new plugins.
$firstCheckTime = time() - rand(0, max($this->checkPeriod * 3600 - 15 * 60, 1)); $upperLimit = max($this->checkPeriod * 3600 - 15 * 60, 1);
if ( function_exists('wp_rand') ) {
$randomOffset = wp_rand(0, $upperLimit);
} else {
//This constructor may be called before wp_rand() is available.
//phpcs:ignore WordPress.WP.AlternativeFunctions.rand_rand
$randomOffset = rand(0, $upperLimit);
}
$firstCheckTime = time() - $randomOffset;
$firstCheckTime = apply_filters( $firstCheckTime = apply_filters(
$this->updateChecker->getUniqueName('first_check_time'), $this->updateChecker->getUniqueName('first_check_time'),
$firstCheckTime $firstCheckTime
@ -69,6 +80,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
//Like WordPress itself, we check more often on certain pages. //Like WordPress itself, we check more often on certain pages.
/** @see wp_update_plugins */ /** @see wp_update_plugins */
add_action('load-update-core.php', array($this, 'maybeCheckForUpdates')); add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
//phpcs:ignore Squiz.PHP.CommentedOutCode.Found -- Not actually code, just file names.
//"load-update.php" and "load-plugins.php" or "load-themes.php". //"load-update.php" and "load-plugins.php" or "load-themes.php".
$this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks); $this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
foreach($this->hourlyCheckHooks as $hook) { foreach($this->hourlyCheckHooks as $hook) {
@ -89,7 +101,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
* We look at the parameters to decide whether to call maybeCheckForUpdates() or not. * We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
* We also check if the update checker has been removed by the update. * We also check if the update checker has been removed by the update.
* *
* @param WP_Upgrader $upgrader WP_Upgrader instance * @param \WP_Upgrader $upgrader WP_Upgrader instance
* @param array $upgradeInfo extra information about the upgrade * @param array $upgradeInfo extra information about the upgrade
*/ */
public function upgraderProcessComplete( public function upgraderProcessComplete(
@ -116,7 +128,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
//Filter out notifications of upgrades that should have no bearing upon whether or not our //Filter out notifications of upgrades that should have no bearing upon whether or not our
//current info is up-to-date. //current info is up-to-date.
if ( is_a($this->updateChecker, 'Puc_v4p10_Theme_UpdateChecker') ) { if ( is_a($this->updateChecker, Theme\UpdateChecker::class) ) {
if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) { if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
return; return;
} }
@ -130,7 +142,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
} }
} }
if ( is_a($this->updateChecker, 'Puc_v4p10_Plugin_UpdateChecker') ) { if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) { if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
return; return;
} }

View File

@ -1,8 +1,9 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists('Puc_v4p10_StateStore', false) ): if ( !class_exists(StateStore::class, false) ):
class Puc_v4p10_StateStore { class StateStore {
/** /**
* @var int Last update check timestamp. * @var int Last update check timestamp.
*/ */
@ -14,7 +15,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
protected $checkedVersion = ''; protected $checkedVersion = '';
/** /**
* @var Puc_v4p10_Update|null Cached update. * @var Update|null Cached update.
*/ */
protected $update = null; protected $update = null;
@ -65,7 +66,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
} }
/** /**
* @return null|Puc_v4p10_Update * @return null|Update
*/ */
public function getUpdate() { public function getUpdate() {
$this->lazyLoad(); $this->lazyLoad();
@ -73,10 +74,10 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
} }
/** /**
* @param Puc_v4p10_Update|null $update * @param Update|null $update
* @return $this * @return $this
*/ */
public function setUpdate(Puc_v4p10_Update $update = null) { public function setUpdate(Update $update = null) {
$this->lazyLoad(); $this->lazyLoad();
$this->update = $update; $this->update = $update;
return $this; return $this;
@ -127,7 +128,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
} }
public function save() { public function save() {
$state = new stdClass(); $state = new \stdClass();
$state->lastCheck = $this->lastCheck; $state->lastCheck = $this->lastCheck;
$state->checkedVersion = $this->checkedVersion; $state->checkedVersion = $this->checkedVersion;
@ -138,7 +139,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
$updateClass = get_class($this->update); $updateClass = get_class($this->update);
$state->updateClass = $updateClass; $state->updateClass = $updateClass;
$prefix = $this->getLibPrefix(); $prefix = $this->getLibPrefix();
if ( Puc_v4p10_Utils::startsWith($updateClass, $prefix) ) { if ( Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix)); $state->updateBaseClass = substr($updateClass, strlen($prefix));
} }
} }
@ -169,8 +170,8 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
return; return;
} }
$this->lastCheck = intval(Puc_v4p10_Utils::get($state, 'lastCheck', 0)); $this->lastCheck = intval(Utils::get($state, 'lastCheck', 0));
$this->checkedVersion = Puc_v4p10_Utils::get($state, 'checkedVersion', ''); $this->checkedVersion = Utils::get($state, 'checkedVersion', '');
$this->update = null; $this->update = null;
if ( isset($state->update) ) { if ( isset($state->update) ) {
@ -180,12 +181,13 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
$updateClass = null; $updateClass = null;
if ( isset($state->updateBaseClass) ) { if ( isset($state->updateBaseClass) ) {
$updateClass = $this->getLibPrefix() . $state->updateBaseClass; $updateClass = $this->getLibPrefix() . $state->updateBaseClass;
} else if ( isset($state->updateClass) && class_exists($state->updateClass) ) { } else if ( isset($state->updateClass) ) {
$updateClass = $state->updateClass; $updateClass = $state->updateClass;
} }
if ( $updateClass !== null ) { $factory = array($updateClass, 'fromObject');
$this->update = call_user_func(array($updateClass, 'fromObject'), $state->update); if ( ($updateClass !== null) && is_callable($factory) ) {
$this->update = call_user_func($factory, $state->update);
} }
} }
} }
@ -199,8 +201,8 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
} }
private function getLibPrefix() { private function getLibPrefix() {
$parts = explode('_', __CLASS__, 3); //This assumes that the current class is at the top of the versioned namespace.
return $parts[0] . '_' . $parts[1] . '_'; return __NAMESPACE__ . '\\';
} }
} }

View File

@ -1,14 +1,18 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Theme_Package', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Theme;
class Puc_v4p10_Theme_Package extends Puc_v4p10_InstalledPackage { use YahnisElsts\PluginUpdateChecker\v5p2\InstalledPackage;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/** /**
* @var string Theme directory name. * @var string Theme directory name.
*/ */
protected $stylesheet; protected $stylesheet;
/** /**
* @var WP_Theme Theme object. * @var \WP_Theme Theme object.
*/ */
protected $theme; protected $theme;

View File

@ -1,8 +1,12 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Theme_Update', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Theme;
class Puc_v4p10_Theme_Update extends Puc_v4p10_Update { use YahnisElsts\PluginUpdateChecker\v5p2\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
class Update extends BaseUpdate {
public $details_url = ''; public $details_url = '';
protected static $extraFields = array('details_url'); protected static $extraFields = array('details_url');
@ -44,8 +48,8 @@ if ( !class_exists('Puc_v4p10_Theme_Update', false) ):
/** /**
* Create a new instance by copying the necessary fields from another object. * Create a new instance by copying the necessary fields from another object.
* *
* @param StdClass|Puc_v4p10_Theme_Update $object The source object. * @param \StdClass|self $object The source object.
* @return Puc_v4p10_Theme_Update The new copy. * @return self The new copy.
*/ */
public static function fromObject($object) { public static function fromObject($object) {
$update = new self(); $update = new self();
@ -56,14 +60,14 @@ if ( !class_exists('Puc_v4p10_Theme_Update', false) ):
/** /**
* Basic validation. * Basic validation.
* *
* @param StdClass $apiResponse * @param \StdClass $apiResponse
* @return bool|WP_Error * @return bool|\WP_Error
*/ */
protected function validateMetadata($apiResponse) { protected function validateMetadata($apiResponse) {
$required = array('version', 'details_url'); $required = array('version', 'details_url');
foreach($required as $key) { foreach($required as $key) {
if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) { if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) {
return new WP_Error( return new \WP_Error(
'tuc-invalid-metadata', 'tuc-invalid-metadata',
sprintf('The theme metadata is missing the required "%s" key.', $key) sprintf('The theme metadata is missing the required "%s" key.', $key)
); );

View File

@ -1,8 +1,15 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Theme;
class Puc_v4p10_Theme_UpdateChecker extends Puc_v4p10_UpdateChecker { use YahnisElsts\PluginUpdateChecker\v5p2\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p2\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p2\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p2\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
class UpdateChecker extends BaseUpdateChecker {
protected $filterSuffix = 'theme'; protected $filterSuffix = 'theme';
protected $updateTransient = 'update_themes'; protected $updateTransient = 'update_themes';
protected $translationType = 'theme'; protected $translationType = 'theme';
@ -39,13 +46,13 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
/** /**
* Retrieve the latest update (if any) from the configured API endpoint. * Retrieve the latest update (if any) from the configured API endpoint.
* *
* @return Puc_v4p10_Update|null An instance of Update, or NULL when no updates are available. * @return Update|null An instance of Update, or NULL when no updates are available.
*/ */
public function requestUpdate() { public function requestUpdate() {
list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p10_Theme_Update', 'request_update'); list($themeUpdate, $result) = $this->requestMetadata(Update::class, 'request_update');
if ( $themeUpdate !== null ) { if ( $themeUpdate !== null ) {
/** @var Puc_v4p10_Theme_Update $themeUpdate */ /** @var Update $themeUpdate */
$themeUpdate->slug = $this->slug; $themeUpdate->slug = $this->slug;
} }
@ -71,16 +78,16 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
* Create an instance of the scheduler. * Create an instance of the scheduler.
* *
* @param int $checkPeriod * @param int $checkPeriod
* @return Puc_v4p10_Scheduler * @return Scheduler
*/ */
protected function createScheduler($checkPeriod) { protected function createScheduler($checkPeriod) {
return new Puc_v4p10_Scheduler($this, $checkPeriod, array('load-themes.php')); return new Scheduler($this, $checkPeriod, array('load-themes.php'));
} }
/** /**
* Is there an update being installed right now for this theme? * Is there an update being installed right now for this theme?
* *
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool * @return bool
*/ */
public function isBeingUpgraded($upgrader = null) { public function isBeingUpgraded($upgrader = null) {
@ -88,7 +95,7 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
} }
protected function createDebugBarExtension() { protected function createDebugBarExtension() {
return new Puc_v4p10_DebugBar_Extension($this, 'Puc_v4p10_DebugBar_ThemePanel'); return new DebugBar\Extension($this, DebugBar\ThemePanel::class);
} }
/** /**
@ -142,10 +149,10 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
/** /**
* Create a package instance that represents this plugin or theme. * Create a package instance that represents this plugin or theme.
* *
* @return Puc_v4p10_InstalledPackage * @return InstalledPackage
*/ */
protected function createInstalledPackage() { protected function createInstalledPackage() {
return new Puc_v4p10_Theme_Package($this->stylesheet, $this); return new Package($this->stylesheet, $this);
} }
} }

View File

@ -1,5 +1,9 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Update', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2;
use stdClass;
if ( !class_exists(Update::class, false) ):
/** /**
* A simple container class for holding information about an available update. * A simple container class for holding information about an available update.
@ -7,7 +11,7 @@ if ( !class_exists('Puc_v4p10_Update', false) ):
* @author Janis Elsts * @author Janis Elsts
* @access public * @access public
*/ */
abstract class Puc_v4p10_Update extends Puc_v4p10_Metadata { abstract class Update extends Metadata {
public $slug; public $slug;
public $version; public $version;
public $download_url; public $download_url;

View File

@ -1,11 +1,15 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists('Puc_v4p10_UpdateChecker', false) ): use stdClass;
use WP_Error;
abstract class Puc_v4p10_UpdateChecker { if ( !class_exists(UpdateChecker::class, false) ):
abstract class UpdateChecker {
protected $filterSuffix = ''; protected $filterSuffix = '';
protected $updateTransient = ''; protected $updateTransient = '';
protected $translationType = ''; //"plugin" or "theme". protected $translationType = ''; //This can be "plugin" or "theme".
/** /**
* Set to TRUE to enable error reporting. Errors are raised using trigger_error() * Set to TRUE to enable error reporting. Errors are raised using trigger_error()
@ -36,22 +40,22 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
public $slug = ''; public $slug = '';
/** /**
* @var Puc_v4p10_InstalledPackage * @var InstalledPackage
*/ */
protected $package; protected $package;
/** /**
* @var Puc_v4p10_Scheduler * @var Scheduler
*/ */
public $scheduler; public $scheduler;
/** /**
* @var Puc_v4p10_UpgraderStatus * @var UpgraderStatus
*/ */
protected $upgraderStatus; protected $upgraderStatus;
/** /**
* @var Puc_v4p10_StateStore * @var StateStore
*/ */
protected $updateState; protected $updateState;
@ -66,7 +70,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
protected $cachedMetadataHost = 0; protected $cachedMetadataHost = 0;
/** /**
* @var Puc_v4p10_DebugBar_Extension|null * @var DebugBar\Extension|null
*/ */
protected $debugBarExtension = null; protected $debugBarExtension = null;
@ -89,8 +93,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
$this->package = $this->createInstalledPackage(); $this->package = $this->createInstalledPackage();
$this->scheduler = $this->createScheduler($checkPeriod); $this->scheduler = $this->createScheduler($checkPeriod);
$this->upgraderStatus = new Puc_v4p10_UpgraderStatus(); $this->upgraderStatus = new UpgraderStatus();
$this->updateState = new Puc_v4p10_StateStore($this->optionName); $this->updateState = new StateStore($this->optionName);
if ( did_action('init') ) { if ( did_action('init') ) {
$this->loadTextDomain(); $this->loadTextDomain();
@ -206,7 +210,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/ */
public function allowMetadataHost($allow, $host) { public function allowMetadataHost($allow, $host) {
if ( $this->cachedMetadataHost === 0 ) { if ( $this->cachedMetadataHost === 0 ) {
$this->cachedMetadataHost = parse_url($this->metadataUrl, PHP_URL_HOST); $this->cachedMetadataHost = wp_parse_url($this->metadataUrl, PHP_URL_HOST);
} }
if ( is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost)) ) { if ( is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost)) ) {
@ -218,12 +222,12 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/** /**
* Create a package instance that represents this plugin or theme. * Create a package instance that represents this plugin or theme.
* *
* @return Puc_v4p10_InstalledPackage * @return InstalledPackage
*/ */
abstract protected function createInstalledPackage(); abstract protected function createInstalledPackage();
/** /**
* @return Puc_v4p10_InstalledPackage * @return InstalledPackage
*/ */
public function getInstalledPackage() { public function getInstalledPackage() {
return $this->package; return $this->package;
@ -236,14 +240,14 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* and substitute their own scheduler. * and substitute their own scheduler.
* *
* @param int $checkPeriod * @param int $checkPeriod
* @return Puc_v4p10_Scheduler * @return Scheduler
*/ */
abstract protected function createScheduler($checkPeriod); abstract protected function createScheduler($checkPeriod);
/** /**
* Check for updates. The results are stored in the DB option specified in $optionName. * Check for updates. The results are stored in the DB option specified in $optionName.
* *
* @return Puc_v4p10_Update|null * @return Update|null
*/ */
public function checkForUpdates() { public function checkForUpdates() {
$installedVersion = $this->getInstalledVersion(); $installedVersion = $this->getInstalledVersion();
@ -277,7 +281,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/** /**
* Load the update checker state from the DB. * Load the update checker state from the DB.
* *
* @return Puc_v4p10_StateStore * @return StateStore
*/ */
public function getUpdateState() { public function getUpdateState() {
return $this->updateState->lazyLoad(); return $this->updateState->lazyLoad();
@ -302,7 +306,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from * Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead. * the metadata URL, call requestUpdate() instead.
* *
* @return Puc_v4p10_Update|null * @return Update|null
*/ */
public function getUpdate() { public function getUpdate() {
$update = $this->updateState->getUpdate(); $update = $this->updateState->getUpdate();
@ -323,16 +327,17 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* *
* Subclasses should run the update through filterUpdateResult before returning it. * Subclasses should run the update through filterUpdateResult before returning it.
* *
* @return Puc_v4p10_Update An instance of Update, or NULL when no updates are available. * @return Update An instance of Update, or NULL when no updates are available.
*/ */
abstract public function requestUpdate(); abstract public function requestUpdate();
/** /**
* Filter the result of a requestUpdate() call. * Filter the result of a requestUpdate() call.
* *
* @param Puc_v4p10_Update|null $update * @template T of Update
* @param T|null $update
* @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any. * @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
* @return Puc_v4p10_Update * @return T
*/ */
protected function filterUpdateResult($update, $httpResult = null) { protected function filterUpdateResult($update, $httpResult = null) {
//Let plugins/themes modify the update. //Let plugins/themes modify the update.
@ -355,9 +360,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* "Compatibility: Unknown". * "Compatibility: Unknown".
* The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to". * The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to".
* *
* @param Puc_v4p10_Metadata|null $update * @param Metadata|null $update
*/ */
protected function fixSupportedWordpressVersion(Puc_v4p10_Metadata $update = null) { protected function fixSupportedWordpressVersion(Metadata $update = null) {
if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) { if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) {
return; return;
} }
@ -427,7 +432,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/ */
public function triggerError($message, $errorType) { public function triggerError($message, $errorType) {
if ( $this->isDebugModeEnabled() ) { if ( $this->isDebugModeEnabled() ) {
trigger_error($message, $errorType); //phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- Only happens in debug mode.
trigger_error(esc_html($message), $errorType);
} }
} }
@ -462,7 +468,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* Store API errors that are generated when checking for updates. * Store API errors that are generated when checking for updates.
* *
* @internal * @internal
* @param WP_Error $error * @param \WP_Error $error
* @param array|null $httpResponse * @param array|null $httpResponse
* @param string|null $url * @param string|null $url
* @param string|null $slug * @param string|null $slug
@ -515,8 +521,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/** /**
* Insert the latest update (if any) into the update list maintained by WP. * Insert the latest update (if any) into the update list maintained by WP.
* *
* @param stdClass $updates Update list. * @param \stdClass $updates Update list.
* @return stdClass Modified update list. * @return \stdClass Modified update list.
*/ */
public function injectUpdate($updates) { public function injectUpdate($updates) {
//Is there an update to insert? //Is there an update to insert?
@ -543,9 +549,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
} }
/** /**
* @param stdClass|null $updates * @param \stdClass|null $updates
* @param stdClass|array $updateToAdd * @param \stdClass|array $updateToAdd
* @return stdClass * @return \stdClass
*/ */
protected function addUpdateToList($updates, $updateToAdd) { protected function addUpdateToList($updates, $updateToAdd) {
if ( !is_object($updates) ) { if ( !is_object($updates) ) {
@ -558,8 +564,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
} }
/** /**
* @param stdClass|null $updates * @param \stdClass|null $updates
* @return stdClass|null * @return \stdClass|null
*/ */
protected function removeUpdateFromList($updates) { protected function removeUpdateFromList($updates) {
if ( isset($updates, $updates->response) ) { if ( isset($updates, $updates->response) ) {
@ -572,8 +578,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* See this post for more information: * See this post for more information:
* @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/ * @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/
* *
* @param stdClass|null $updates * @param \stdClass|null $updates
* @return stdClass * @return \stdClass
*/ */
protected function addNoUpdateItem($updates) { protected function addNoUpdateItem($updates) {
if ( !is_object($updates) ) { if ( !is_object($updates) ) {
@ -635,10 +641,10 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/** /**
* Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl. * Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl.
* *
* @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method. * @param class-string<Update> $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
* @param string $filterRoot * @param string $filterRoot
* @param array $queryArgs Additional query arguments. * @param array $queryArgs Additional query arguments.
* @return array [Puc_v4p10_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get(). * @return array<Metadata|null, array|WP_Error> A metadata instance and the value returned by wp_remote_get().
*/ */
protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) { protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) {
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
@ -654,7 +660,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
//Various options for the wp_remote_get() call. Plugins can filter these, too. //Various options for the wp_remote_get() call. Plugins can filter these, too.
$options = array( $options = array(
'timeout' => 10, //seconds 'timeout' => wp_doing_cron() ? 10 : 3,
'headers' => array( 'headers' => array(
'Accept' => 'application/json', 'Accept' => 'application/json',
), ),
@ -675,6 +681,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
$status = $this->validateApiResponse($result); $status = $this->validateApiResponse($result);
$metadata = null; $metadata = null;
if ( !is_wp_error($status) ){ if ( !is_wp_error($status) ){
if ( (strpos($metaClass, '\\') === false) ) {
$metaClass = __NAMESPACE__ . '\\' . $metaClass;
}
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']); $metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
} else { } else {
do_action('puc_api_error', $status, $result, $url, $this->slug); do_action('puc_api_error', $status, $result, $url, $this->slug);
@ -876,12 +885,12 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* *
* @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource. * @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource.
* @param string $remoteSource WordPress has extracted the update to this directory. * @param string $remoteSource WordPress has extracted the update to this directory.
* @param WP_Upgrader $upgrader * @param \WP_Upgrader $upgrader
* @return string|WP_Error * @return string|WP_Error
*/ */
public function fixDirectoryName($source, $remoteSource, $upgrader) { public function fixDirectoryName($source, $remoteSource, $upgrader) {
global $wp_filesystem; global $wp_filesystem;
/** @var WP_Filesystem_Base $wp_filesystem */ /** @var \WP_Filesystem_Base $wp_filesystem */
//Basic sanity checks. //Basic sanity checks.
if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
@ -911,7 +920,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
); );
} }
/** @var WP_Upgrader_Skin $upgrader ->skin */ /** @var \WP_Upgrader_Skin $upgrader ->skin */
$upgrader->skin->feedback(sprintf( $upgrader->skin->feedback(sprintf(
'Renaming %s to %s&#8230;', 'Renaming %s to %s&#8230;',
'<span class="code">' . basename($source) . '</span>', '<span class="code">' . basename($source) . '</span>',
@ -935,7 +944,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/** /**
* Is there an update being installed right now, for this plugin or theme? * Is there an update being installed right now, for this plugin or theme?
* *
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool * @return bool
*/ */
abstract public function isBeingUpgraded($upgrader = null); abstract public function isBeingUpgraded($upgrader = null);
@ -949,7 +958,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/ */
protected function isBadDirectoryStructure($remoteSource) { protected function isBadDirectoryStructure($remoteSource) {
global $wp_filesystem; global $wp_filesystem;
/** @var WP_Filesystem_Base $wp_filesystem */ /** @var \WP_Filesystem_Base $wp_filesystem */
$sourceFiles = $wp_filesystem->dirlist($remoteSource); $sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) { if ( is_array($sourceFiles) ) {
@ -977,13 +986,13 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
} }
protected function createDebugBarExtension() { protected function createDebugBarExtension() {
return new Puc_v4p10_DebugBar_Extension($this); return new DebugBar\Extension($this);
} }
/** /**
* Display additional configuration details in the Debug Bar panel. * Display additional configuration details in the Debug Bar panel.
* *
* @param Puc_v4p10_DebugBar_Panel $panel * @param DebugBar\Panel $panel
*/ */
public function onDisplayConfiguration($panel) { public function onDisplayConfiguration($panel) {
//Do nothing. Subclasses can use this to add additional info to the panel. //Do nothing. Subclasses can use this to add additional info to the panel.

View File

@ -1,5 +1,7 @@
<?php <?php
if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists(UpgraderStatus::class, false) ):
/** /**
* A utility class that helps figure out which plugin or theme WordPress is upgrading. * A utility class that helps figure out which plugin or theme WordPress is upgrading.
@ -8,8 +10,8 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
* Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT). * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
* This class uses a few workarounds and heuristics to get the file name. * This class uses a few workarounds and heuristics to get the file name.
*/ */
class Puc_v4p10_UpgraderStatus { class UpgraderStatus {
private $currentType = null; //"plugin" or "theme". private $currentType = null; //This must be either "plugin" or "theme".
private $currentId = null; //Plugin basename or theme directory name. private $currentId = null; //Plugin basename or theme directory name.
public function __construct() { public function __construct() {
@ -27,7 +29,7 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
* and upgrader implementations are liable to change without notice. * and upgrader implementations are liable to change without notice.
* *
* @param string $pluginFile The plugin to check. * @param string $pluginFile The plugin to check.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool True if the plugin identified by $pluginFile is being upgraded. * @return bool True if the plugin identified by $pluginFile is being upgraded.
*/ */
public function isPluginBeingUpgraded($pluginFile, $upgrader = null) { public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
@ -38,7 +40,7 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
* Is there an update being installed for a specific theme? * Is there an update being installed for a specific theme?
* *
* @param string $stylesheet Theme directory name. * @param string $stylesheet Theme directory name.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool * @return bool
*/ */
public function isThemeBeingUpgraded($stylesheet, $upgrader = null) { public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
@ -50,7 +52,7 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
* *
* @param string $type * @param string $type
* @param string $id * @param string $id
* @param Plugin_Upgrader|WP_Upgrader|null $upgrader * @param \Plugin_Upgrader|\WP_Upgrader|null $upgrader
* @return bool * @return bool
*/ */
protected function isBeingUpgraded($type, $id, $upgrader = null) { protected function isBeingUpgraded($type, $id, $upgrader = null) {
@ -76,7 +78,7 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
* ['plugin', 'plugin-dir-name/plugin.php'] * ['plugin', 'plugin-dir-name/plugin.php']
* ['theme', 'theme-dir-name'] * ['theme', 'theme-dir-name']
* *
* @param Plugin_Upgrader|WP_Upgrader $upgrader * @param \Plugin_Upgrader|\WP_Upgrader $upgrader
* @return array * @return array
*/ */
private function getThingBeingUpgradedBy($upgrader) { private function getThingBeingUpgradedBy($upgrader) {
@ -89,13 +91,13 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
$themeDirectoryName = null; $themeDirectoryName = null;
$skin = $upgrader->skin; $skin = $upgrader->skin;
if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) { if ( isset($skin->theme_info) && ($skin->theme_info instanceof \WP_Theme) ) {
$themeDirectoryName = $skin->theme_info->get_stylesheet(); $themeDirectoryName = $skin->theme_info->get_stylesheet();
} elseif ( $skin instanceof Plugin_Upgrader_Skin ) { } elseif ( $skin instanceof \Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
$pluginFile = $skin->plugin; $pluginFile = $skin->plugin;
} }
} elseif ( $skin instanceof Theme_Upgrader_Skin ) { } elseif ( $skin instanceof \Theme_Upgrader_Skin ) {
if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) { if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
$themeDirectoryName = $skin->theme; $themeDirectoryName = $skin->theme;
} }
@ -122,7 +124,6 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
*/ */
private function identifyPluginByHeaders($searchHeaders) { private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){ if ( !function_exists('get_plugins') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
} }

View File

@ -1,8 +1,9 @@
<?php <?php
namespace YahnisElsts\PluginUpdateChecker\v5p2;
if ( !class_exists('Puc_v4p10_Utils', false) ): if ( !class_exists(Utils::class, false) ):
class Puc_v4p10_Utils { class Utils {
/** /**
* Get a value from a nested array or object based on a path. * Get a value from a nested array or object based on a path.
* *

View File

@ -1,7 +1,43 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_Api') ):
abstract class Puc_v4p10_Vcs_Api { namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
use Parsedown;
use PucReadmeParser;
if ( !class_exists(Api::class, false) ):
abstract class Api {
const STRATEGY_LATEST_RELEASE = 'latest_release';
const STRATEGY_LATEST_TAG = 'latest_tag';
const STRATEGY_STABLE_TAG = 'stable_tag';
const STRATEGY_BRANCH = 'branch';
/**
* Consider all releases regardless of their version number or prerelease/upcoming
* release status.
*/
const RELEASE_FILTER_ALL = 3;
/**
* Exclude releases that have the "prerelease" or "upcoming release" flag.
*
* This does *not* look for prerelease keywords like "beta" in the version number.
* It only uses the data provided by the API. For example, on GitHub, you can
* manually mark a release as a prerelease.
*/
const RELEASE_FILTER_SKIP_PRERELEASE = 1;
/**
* If there are no release assets or none of them match the configured filter,
* fall back to the automatically generated source code archive.
*/
const PREFER_RELEASE_ASSETS = 1;
/**
* Skip releases that don't have any matching release assets.
*/
const REQUIRE_RELEASE_ASSETS = 2;
protected $tagNameProperty = 'name'; protected $tagNameProperty = 'name';
protected $slug = ''; protected $slug = '';
@ -21,13 +57,19 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
*/ */
protected $httpFilterName = ''; protected $httpFilterName = '';
/**
* @var string The filter applied to the list of update detection strategies that
* are used to find the latest version.
*/
protected $strategyFilterName = '';
/** /**
* @var string|null * @var string|null
*/ */
protected $localDirectory = null; protected $localDirectory = null;
/** /**
* Puc_v4p10_Vcs_Api constructor. * Api constructor.
* *
* @param string $repositoryUrl * @param string $repositoryUrl
* @param array|string|null $credentials * @param array|string|null $credentials
@ -45,12 +87,41 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
} }
/** /**
* Figure out which reference (i.e tag or branch) contains the latest version. * Figure out which reference (i.e. tag or branch) contains the latest version.
* *
* @param string $configBranch Start looking in this branch. * @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p10_Vcs_Reference * @return null|Reference
*/ */
abstract public function chooseReference($configBranch); public function chooseReference($configBranch) {
$strategies = $this->getUpdateDetectionStrategies($configBranch);
if ( !empty($this->strategyFilterName) ) {
$strategies = apply_filters(
$this->strategyFilterName,
$strategies,
$this->slug
);
}
foreach ($strategies as $strategy) {
$reference = call_user_func($strategy);
if ( !empty($reference) ) {
return $reference;
}
}
return null;
}
/**
* Get an ordered list of strategies that can be used to find the latest version.
*
* The update checker will try each strategy in order until one of them
* returns a valid reference.
*
* @param string $configBranch
* @return array<callable> Array of callables that return Vcs_Reference objects.
*/
abstract protected function getUpdateDetectionStrategies($configBranch);
/** /**
* Get the readme.txt file from the remote repository and parse it * Get the readme.txt file from the remote repository and parse it
@ -105,7 +176,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Get a branch. * Get a branch.
* *
* @param string $branchName * @param string $branchName
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
abstract public function getBranch($branchName); abstract public function getBranch($branchName);
@ -113,7 +184,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Get a specific tag. * Get a specific tag.
* *
* @param string $tagName * @param string $tagName
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
abstract public function getTag($tagName); abstract public function getTag($tagName);
@ -121,7 +192,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Get the tag that looks like the highest version number. * Get the tag that looks like the highest version number.
* (Implementations should skip pre-release versions if possible.) * (Implementations should skip pre-release versions if possible.)
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
abstract public function getLatestTag(); abstract public function getLatestTag();
@ -147,7 +218,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
/** /**
* Check if a tag appears to be named like a version number. * Check if a tag appears to be named like a version number.
* *
* @param stdClass $tag * @param \stdClass $tag
* @return bool * @return bool
*/ */
protected function isVersionTag($tag) { protected function isVersionTag($tag) {
@ -159,8 +230,8 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Sort a list of tags as if they were version numbers. * Sort a list of tags as if they were version numbers.
* Tags that don't look like version number will be removed. * Tags that don't look like version number will be removed.
* *
* @param stdClass[] $tags Array of tag objects. * @param \stdClass[] $tags Array of tag objects.
* @return stdClass[] Filtered array of tags sorted in descending order. * @return \stdClass[] Filtered array of tags sorted in descending order.
*/ */
protected function sortTagsByVersion($tags) { protected function sortTagsByVersion($tags) {
//Keep only those tags that look like version numbers. //Keep only those tags that look like version numbers.
@ -174,8 +245,8 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
/** /**
* Compare two tags as if they were version number. * Compare two tags as if they were version number.
* *
* @param stdClass $tag1 Tag object. * @param \stdClass $tag1 Tag object.
* @param stdClass $tag2 Another tag object. * @param \stdClass $tag2 Another tag object.
* @return int * @return int
*/ */
protected function compareTagNames($tag1, $tag2) { protected function compareTagNames($tag1, $tag2) {
@ -224,7 +295,6 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
return null; return null;
} }
/** @noinspection PhpUndefinedClassInspection */
return Parsedown::instance()->text($changelog); return Parsedown::instance()->text($changelog);
} }
@ -280,6 +350,13 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
$this->httpFilterName = $filterName; $this->httpFilterName = $filterName;
} }
/**
* @param string $filterName
*/
public function setStrategyFilterName($filterName) {
$this->strategyFilterName = $filterName;
}
/** /**
* @param string $directory * @param string $directory
*/ */

View File

@ -1,7 +1,9 @@
<?php <?php
if ( !interface_exists('Puc_v4p10_Vcs_BaseChecker', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
interface Puc_v4p10_Vcs_BaseChecker { if ( !interface_exists(BaseChecker::class, false) ):
interface BaseChecker {
/** /**
* Set the repository branch to use for updates. Defaults to 'master'. * Set the repository branch to use for updates. Defaults to 'master'.
* *
@ -19,7 +21,7 @@ if ( !interface_exists('Puc_v4p10_Vcs_BaseChecker', false) ):
public function setAuthentication($credentials); public function setAuthentication($credentials);
/** /**
* @return Puc_v4p10_Vcs_Api * @return Api
*/ */
public function getVcsApi(); public function getVcsApi();
} }

View File

@ -1,9 +1,15 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
class Puc_v4p10_Vcs_BitBucketApi extends Puc_v4p10_Vcs_Api { namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p2\OAuthSignature;
use YahnisElsts\PluginUpdateChecker\v5p2\Utils;
if ( !class_exists(BitBucketApi::class, false) ):
class BitBucketApi extends Api {
/** /**
* @var Puc_v4p10_OAuthSignature * @var OAuthSignature
*/ */
private $oauth = null; private $oauth = null;
@ -18,39 +24,32 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
private $repository; private $repository;
public function __construct($repositoryUrl, $credentials = array()) { public function __construct($repositoryUrl, $credentials = array()) {
$path = parse_url($repositoryUrl, PHP_URL_PATH); $path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) { if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->username = $matches['username']; $this->username = $matches['username'];
$this->repository = $matches['repository']; $this->repository = $matches['repository'];
} else { } else {
throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"'); throw new \InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
} }
parent::__construct($repositoryUrl, $credentials); parent::__construct($repositoryUrl, $credentials);
} }
/** protected function getUpdateDetectionStrategies($configBranch) {
* Figure out which reference (i.e tag or branch) contains the latest version. $strategies = array(
* self::STRATEGY_STABLE_TAG => function () use ($configBranch) {
* @param string $configBranch Start looking in this branch. return $this->getStableTag($configBranch);
* @return null|Puc_v4p10_Vcs_Reference },
*/ );
public function chooseReference($configBranch) {
$updateSource = null;
//Check if there's a "Stable tag: 1.2.3" header that points to a valid tag. if ( ($configBranch === 'master' || $configBranch === 'main') ) {
$updateSource = $this->getStableTag($configBranch); $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
//Look for version-like tags.
if ( !$updateSource && ($configBranch === 'master') ) {
$updateSource = $this->getLatestTag();
}
//If all else fails, use the specified branch itself.
if ( !$updateSource ) {
$updateSource = $this->getBranch($configBranch);
} }
return $updateSource; $strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
} }
public function getBranch($branchName) { public function getBranch($branchName) {
@ -59,8 +58,16 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return null; return null;
} }
return new Puc_v4p10_Vcs_Reference(array( //The "/src/{stuff}/{path}" endpoint doesn't seem to handle branch names that contain slashes.
'name' => $branch->name, //If we don't encode the slash, we get a 404. If we encode it as "%2F", we get a 401.
//To avoid issues, if the branch name is not URL-safe, let's use the commit hash instead.
$ref = $branch->name;
if ((urlencode($ref) !== $ref) && isset($branch->target->hash)) {
$ref = $branch->target->hash;
}
return new Reference(array(
'name' => $ref,
'updated' => $branch->target->date, 'updated' => $branch->target->date,
'downloadUrl' => $this->getDownloadUrl($branch->name), 'downloadUrl' => $this->getDownloadUrl($branch->name),
)); ));
@ -70,7 +77,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
* Get a specific tag. * Get a specific tag.
* *
* @param string $tagName * @param string $tagName
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getTag($tagName) { public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName); $tag = $this->api('/refs/tags/' . $tagName);
@ -78,7 +85,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return null; return null;
} }
return new Puc_v4p10_Vcs_Reference(array( return new Reference(array(
'name' => $tag->name, 'name' => $tag->name,
'version' => ltrim($tag->name, 'v'), 'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date, 'updated' => $tag->target->date,
@ -89,7 +96,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
/** /**
* Get the tag that looks like the highest version number. * Get the tag that looks like the highest version number.
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getLatestTag() { public function getLatestTag() {
$tags = $this->api('/refs/tags?sort=-target.date'); $tags = $this->api('/refs/tags?sort=-target.date');
@ -103,7 +110,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
//Return the first result. //Return the first result.
if ( !empty($versionTags) ) { if ( !empty($versionTags) ) {
$tag = $versionTags[0]; $tag = $versionTags[0];
return new Puc_v4p10_Vcs_Reference(array( return new Reference(array(
'name' => $tag->name, 'name' => $tag->name,
'version' => ltrim($tag->name, 'v'), 'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date, 'updated' => $tag->target->date,
@ -117,7 +124,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
* Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch. * Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
* *
* @param string $branch * @param string $branch
* @return null|Puc_v4p10_Vcs_Reference * @return null|Reference
*/ */
protected function getStableTag($branch) { protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch); $remoteReadme = $this->getRemoteReadme($branch);
@ -183,11 +190,11 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
* *
* @param string $url * @param string $url
* @param string $version * @param string $version
* @return mixed|WP_Error * @return mixed|\WP_Error
*/ */
public function api($url, $version = '2.0') { public function api($url, $version = '2.0') {
$url = ltrim($url, '/'); $url = ltrim($url, '/');
$isSrcResource = Puc_v4p10_Utils::startsWith($url, 'src/'); $isSrcResource = Utils::startsWith($url, 'src/');
$url = implode('/', array( $url = implode('/', array(
'https://api.bitbucket.org', 'https://api.bitbucket.org',
@ -203,7 +210,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
$url = $this->oauth->sign($url,'GET'); $url = $this->oauth->sign($url,'GET');
} }
$options = array('timeout' => 10); $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) { if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options); $options = apply_filters($this->httpFilterName, $options);
} }
@ -226,7 +233,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return $document; return $document;
} }
$error = new WP_Error( $error = new \WP_Error(
'puc-bitbucket-http-error', 'puc-bitbucket-http-error',
sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code) sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
); );
@ -242,7 +249,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
parent::setAuthentication($credentials); parent::setAuthentication($credentials);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) { if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
$this->oauth = new Puc_v4p10_OAuthSignature( $this->oauth = new OAuthSignature(
$credentials['consumer_key'], $credentials['consumer_key'],
$credentials['consumer_secret'] $credentials['consumer_secret']
); );
@ -253,7 +260,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
public function signDownloadUrl($url) { public function signDownloadUrl($url) {
//Add authentication data to download URLs. Since OAuth signatures incorporate //Add authentication data to download URLs. Since OAuth signatures incorporate
//timestamps, we have to do this immediately before inserting the update. Otherwise //timestamps, we have to do this immediately before inserting the update. Otherwise,
//authentication could fail due to a stale timestamp. //authentication could fail due to a stale timestamp.
if ( $this->oauth ) { if ( $this->oauth ) {
$url = $this->oauth->sign($url); $url = $this->oauth->sign($url);

View File

@ -1,8 +1,15 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
use Parsedown;
if ( !class_exists(GitHubApi::class, false) ):
class GitHubApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
class Puc_v4p10_Vcs_GitHubApi extends Puc_v4p10_Vcs_Api {
/** /**
* @var string GitHub username. * @var string GitHub username.
*/ */
@ -22,33 +29,18 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
*/ */
protected $accessToken; protected $accessToken;
/**
* @var bool Whether to download release assets instead of the auto-generated source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var string|null Regular expression that's used to filter release assets by name. Optional.
*/
protected $assetFilterRegex = null;
/**
* @var string|null The unchanging part of a release asset URL. Used to identify download attempts.
*/
protected $assetApiBaseUrl = null;
/** /**
* @var bool * @var bool
*/ */
private $downloadFilterAdded = false; private $downloadFilterAdded = false;
public function __construct($repositoryUrl, $accessToken = null) { public function __construct($repositoryUrl, $accessToken = null) {
$path = parse_url($repositoryUrl, PHP_URL_PATH); $path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) { if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username']; $this->userName = $matches['username'];
$this->repositoryName = $matches['repository']; $this->repositoryName = $matches['repository'];
} else { } else {
throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"'); throw new \InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
} }
parent::__construct($repositoryUrl, $accessToken); parent::__construct($repositoryUrl, $accessToken);
@ -57,17 +49,59 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
/** /**
* Get the latest release from GitHub. * Get the latest release from GitHub.
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getLatestRelease() { public function getLatestRelease() {
//The "latest release" endpoint returns one release and always skips pre-releases,
//so we can only use it if that's compatible with the current filter settings.
if (
$this->shouldSkipPreReleases()
&& (
($this->releaseFilterMaxReleases === 1) || !$this->hasCustomReleaseFilter()
)
) {
//Just get the latest release.
$release = $this->api('/repos/:user/:repo/releases/latest'); $release = $this->api('/repos/:user/:repo/releases/latest');
if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) { if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
return null; return null;
} }
$foundReleases = array($release);
} else {
//Get a list of the most recent releases.
$foundReleases = $this->api(
'/repos/:user/:repo/releases',
array('per_page' => $this->releaseFilterMaxReleases)
);
if ( is_wp_error($foundReleases) || !is_array($foundReleases) ) {
return null;
}
}
$reference = new Puc_v4p10_Vcs_Reference(array( foreach ($foundReleases as $release) {
//Always skip drafts.
if ( isset($release->draft) && !empty($release->draft) ) {
continue;
}
//Skip pre-releases unless specifically included.
if (
$this->shouldSkipPreReleases()
&& isset($release->prerelease)
&& !empty($release->prerelease)
) {
continue;
}
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
//Custom release filtering.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
$reference = new Reference(array(
'name' => $release->tag_name, 'name' => $release->tag_name,
'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3". 'version' => $versionNumber,
'downloadUrl' => $release->zipball_url, 'downloadUrl' => $release->zipball_url,
'updated' => $release->created_at, 'updated' => $release->created_at,
'apiResponse' => $release, 'apiResponse' => $release,
@ -77,9 +111,14 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
$reference->downloadCount = $release->assets[0]->download_count; $reference->downloadCount = $release->assets[0]->download_count;
} }
if ( $this->releaseAssetsEnabled && isset($release->assets, $release->assets[0]) ) { if ( $this->releaseAssetsEnabled ) {
//Use the first release asset that matches the specified regular expression. //Use the first release asset that matches the specified regular expression.
$matchingAssets = array_filter($release->assets, array($this, 'matchesAssetFilter')); if ( isset($release->assets, $release->assets[0]) ) {
$matchingAssets = array_values(array_filter($release->assets, array($this, 'matchesAssetFilter')));
} else {
$matchingAssets = array();
}
if ( !empty($matchingAssets) ) { if ( !empty($matchingAssets) ) {
if ( $this->isAuthenticationEnabled() ) { if ( $this->isAuthenticationEnabled() ) {
/** /**
@ -95,21 +134,27 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
} }
$reference->downloadCount = $matchingAssets[0]->download_count; $reference->downloadCount = $matchingAssets[0]->download_count;
} else if ( $this->releaseAssetPreference === Api::REQUIRE_RELEASE_ASSETS ) {
//None of the assets match the filter, and we're not allowed
//to fall back to the auto-generated source ZIP.
return null;
} }
} }
if ( !empty($release->body) ) { if ( !empty($release->body) ) {
/** @noinspection PhpUndefinedClassInspection */
$reference->changelog = Parsedown::instance()->text($release->body); $reference->changelog = Parsedown::instance()->text($release->body);
} }
return $reference; return $reference;
} }
return null;
}
/** /**
* Get the tag that looks like the highest version number. * Get the tag that looks like the highest version number.
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getLatestTag() { public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags'); $tags = $this->api('/repos/:user/:repo/tags');
@ -124,7 +169,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
} }
$tag = $versionTags[0]; $tag = $versionTags[0];
return new Puc_v4p10_Vcs_Reference(array( return new Reference(array(
'name' => $tag->name, 'name' => $tag->name,
'version' => ltrim($tag->name, 'v'), 'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $tag->zipball_url, 'downloadUrl' => $tag->zipball_url,
@ -136,7 +181,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* Get a branch by name. * Get a branch by name.
* *
* @param string $branchName * @param string $branchName
* @return null|Puc_v4p10_Vcs_Reference * @return null|Reference
*/ */
public function getBranch($branchName) { public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName); $branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
@ -144,7 +189,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
return null; return null;
} }
$reference = new Puc_v4p10_Vcs_Reference(array( $reference = new Reference(array(
'name' => $branch->name, 'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name), 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch, 'apiResponse' => $branch,
@ -162,7 +207,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* *
* @param string $filename * @param string $filename
* @param string $ref Reference name (e.g. branch or tag). * @param string $ref Reference name (e.g. branch or tag).
* @return StdClass|null * @return \StdClass|null
*/ */
public function getLatestCommit($filename, $ref = 'master') { public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api( $commits = $this->api(
@ -197,13 +242,13 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* *
* @param string $url * @param string $url
* @param array $queryParams * @param array $queryParams
* @return mixed|WP_Error * @return mixed|\WP_Error
*/ */
protected function api($url, $queryParams = array()) { protected function api($url, $queryParams = array()) {
$baseUrl = $url; $baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams); $url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => 10); $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( $this->isAuthenticationEnabled() ) { if ( $this->isAuthenticationEnabled() ) {
$options['headers'] = array('Authorization' => $this->getAuthorizationHeader()); $options['headers'] = array('Authorization' => $this->getAuthorizationHeader());
} }
@ -224,7 +269,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
return $document; return $document;
} }
$error = new WP_Error( $error = new \WP_Error(
'puc-github-http-error', 'puc-github-http-error',
sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code) sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
); );
@ -298,7 +343,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
*/ */
public function getTag($tagName) { public function getTag($tagName) {
//The current GitHub update checker doesn't use getTag, so I didn't bother to implement it. //The current GitHub update checker doesn't use getTag, so I didn't bother to implement it.
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.'); throw new \LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
} }
public function setAuthentication($credentials) { public function setAuthentication($credentials) {
@ -310,72 +355,52 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+ add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+
} }
/** protected function getUpdateDetectionStrategies($configBranch) {
* Figure out which reference (i.e tag or branch) contains the latest version. $strategies = array();
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p10_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
if ( $configBranch === 'master' ) { if ( $configBranch === 'master' || $configBranch === 'main') {
//Use the latest release. //Use the latest release.
$updateSource = $this->getLatestRelease(); $strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
if ( $updateSource === null ) {
//Failing that, use the tag with the highest version number. //Failing that, use the tag with the highest version number.
$updateSource = $this->getLatestTag(); $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
}
//Alternatively, just use the branch itself.
if ( empty($updateSource) ) {
$updateSource = $this->getBranch($configBranch);
} }
return $updateSource; //Alternatively, just use the branch itself.
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
} }
/** /**
* Enable updating via release assets. * Get the unchanging part of a release asset URL. Used to identify download attempts.
* *
* If the latest release contains no usable assets, the update checker * @return string
* will fall back to using the automatically generated ZIP archive.
*
* Private repositories will only work with WordPress 3.7 or later.
*
* @param string|null $fileNameRegex Optional. Use only those assets where the file name matches this regex.
*/ */
public function enableReleaseAssets($fileNameRegex = null) { protected function getAssetApiBaseUrl() {
$this->releaseAssetsEnabled = true; return sprintf(
$this->assetFilterRegex = $fileNameRegex;
$this->assetApiBaseUrl = sprintf(
'//api.github.com/repos/%1$s/%2$s/releases/assets/', '//api.github.com/repos/%1$s/%2$s/releases/assets/',
$this->userName, $this->userName,
$this->repositoryName $this->repositoryName
); );
} }
/** protected function getFilterableAssetName($releaseAsset) {
* Does this asset match the file name regex? if ( isset($releaseAsset->name) ) {
* return $releaseAsset->name;
* @param stdClass $releaseAsset
* @return bool
*/
protected function matchesAssetFilter($releaseAsset) {
if ( $this->assetFilterRegex === null ) {
//The default is to accept all assets.
return true;
} }
return isset($releaseAsset->name) && preg_match($this->assetFilterRegex, $releaseAsset->name); return null;
} }
/** /**
* @internal
* @param bool $result * @param bool $result
* @return bool * @return bool
* @internal
*/ */
public function addHttpRequestFilter($result) { public function addHttpRequestFilter($result) {
if ( !$this->downloadFilterAdded && $this->isAuthenticationEnabled() ) { if ( !$this->downloadFilterAdded && $this->isAuthenticationEnabled() ) {
//phpcs:ignore WordPressVIPMinimum.Hooks.RestrictedHooks.http_request_args -- The callback doesn't change the timeout.
add_filter('http_request_args', array($this, 'setUpdateDownloadHeaders'), 10, 2); add_filter('http_request_args', array($this, 'setUpdateDownloadHeaders'), 10, 2);
add_action('requests-requests.before_redirect', array($this, 'removeAuthHeaderFromRedirects'), 10, 4); add_action('requests-requests.before_redirect', array($this, 'removeAuthHeaderFromRedirects'), 10, 4);
$this->downloadFilterAdded = true; $this->downloadFilterAdded = true;
@ -387,6 +412,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* Set the HTTP headers that are necessary to download updates from private repositories. * Set the HTTP headers that are necessary to download updates from private repositories.
* *
* See GitHub docs: * See GitHub docs:
*
* @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset * @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset
* @link https://developer.github.com/v3/auth/#basic-authentication * @link https://developer.github.com/v3/auth/#basic-authentication
* *
@ -397,7 +423,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
*/ */
public function setUpdateDownloadHeaders($requestArgs, $url = '') { public function setUpdateDownloadHeaders($requestArgs, $url = '') {
//Is WordPress trying to download one of our release assets? //Is WordPress trying to download one of our release assets?
if ( $this->releaseAssetsEnabled && (strpos($url, $this->assetApiBaseUrl) !== false) ) { if ( $this->releaseAssetsEnabled && (strpos($url, $this->getAssetApiBaseUrl()) !== false) ) {
$requestArgs['headers']['Accept'] = 'application/octet-stream'; $requestArgs['headers']['Accept'] = 'application/octet-stream';
} }
//Use Basic authentication, but only if the download is from our repository. //Use Basic authentication, but only if the download is from our repository.
@ -413,9 +439,9 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* the authorization header to other hosts. We don't want that because it breaks * the authorization header to other hosts. We don't want that because it breaks
* AWS downloads and can leak authorization information. * AWS downloads and can leak authorization information.
* *
* @internal
* @param string $location * @param string $location
* @param array $headers * @param array $headers
* @internal
*/ */
public function removeAuthHeaderFromRedirects(&$location, &$headers) { public function removeAuthHeaderFromRedirects(&$location, &$headers) {
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array()); $repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());

View File

@ -1,8 +1,13 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !class_exists(GitLabApi::class, false) ):
class GitLabApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
class Puc_v4p10_Vcs_GitLabApi extends Puc_v4p10_Vcs_Api {
/** /**
* @var string GitLab username. * @var string GitLab username.
*/ */
@ -28,20 +33,26 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
*/ */
protected $accessToken; protected $accessToken;
/**
* @deprecated
* @var bool No longer used.
*/
protected $releasePackageEnabled = false;
public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) { public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) {
//Parse the repository host to support custom hosts. //Parse the repository host to support custom hosts.
$port = parse_url($repositoryUrl, PHP_URL_PORT); $port = wp_parse_url($repositoryUrl, PHP_URL_PORT);
if ( !empty($port) ) { if ( !empty($port) ) {
$port = ':' . $port; $port = ':' . $port;
} }
$this->repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port; $this->repositoryHost = wp_parse_url($repositoryUrl, PHP_URL_HOST) . $port;
if ( $this->repositoryHost !== 'gitlab.com' ) { if ( $this->repositoryHost !== 'gitlab.com' ) {
$this->repositoryProtocol = parse_url($repositoryUrl, PHP_URL_SCHEME); $this->repositoryProtocol = wp_parse_url($repositoryUrl, PHP_URL_SCHEME);
} }
//Find the repository information //Find the repository information
$path = parse_url($repositoryUrl, PHP_URL_PATH); $path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) { if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username']; $this->userName = $matches['username'];
$this->repositoryName = $matches['repository']; $this->repositoryName = $matches['repository'];
@ -49,7 +60,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
//This is probably a repository in a subgroup, e.g. "/organization/category/repo". //This is probably a repository in a subgroup, e.g. "/organization/category/repo".
$parts = explode('/', trim($path, '/')); $parts = explode('/', trim($path, '/'));
if ( count($parts) < 3 ) { if ( count($parts) < 3 ) {
throw new InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"'); throw new \InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"');
} }
$lastPart = array_pop($parts); $lastPart = array_pop($parts);
$this->userName = implode('/', $parts); $this->userName = implode('/', $parts);
@ -66,7 +77,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
//We need at least /user-name/repository-name/ //We need at least /user-name/repository-name/
if ( count($segments) < 2 ) { if ( count($segments) < 2 ) {
throw new InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"'); throw new \InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
} }
//Get the username and repository name. //Get the username and repository name.
@ -91,16 +102,92 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
/** /**
* Get the latest release from GitLab. * Get the latest release from GitLab.
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getLatestRelease() { public function getLatestRelease() {
return $this->getLatestTag(); $releases = $this->api('/:id/releases', array('per_page' => $this->releaseFilterMaxReleases));
if ( is_wp_error($releases) || empty($releases) || !is_array($releases) ) {
return null;
}
foreach ($releases as $release) {
if (
//Skip invalid/unsupported releases.
!is_object($release)
|| !isset($release->tag_name)
//Skip upcoming releases.
|| (
!empty($release->upcoming_release)
&& $this->shouldSkipPreReleases()
)
) {
continue;
}
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
//Apply custom filters.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
$downloadUrl = $this->findReleaseDownloadUrl($release);
if ( empty($downloadUrl) ) {
//The latest release doesn't have valid download URL.
return null;
}
if ( !empty($this->accessToken) ) {
$downloadUrl = add_query_arg('private_token', $this->accessToken, $downloadUrl);
}
return new Reference(array(
'name' => $release->tag_name,
'version' => $versionNumber,
'downloadUrl' => $downloadUrl,
'updated' => $release->released_at,
'apiResponse' => $release,
));
}
return null;
}
/**
* @param object $release
* @return string|null
*/
protected function findReleaseDownloadUrl($release) {
if ( $this->releaseAssetsEnabled ) {
if ( isset($release->assets, $release->assets->links) ) {
//Use the first asset link where the URL matches the filter.
foreach ($release->assets->links as $link) {
if ( $this->matchesAssetFilter($link) ) {
return $link->url;
}
}
}
if ( $this->releaseAssetPreference === Api::REQUIRE_RELEASE_ASSETS ) {
//Falling back to source archives is not allowed, so give up.
return null;
}
}
//Use the first source code archive that's in ZIP format.
foreach ($release->assets->sources as $source) {
if ( isset($source->format) && ($source->format === 'zip') ) {
return $source->url;
}
}
return null;
} }
/** /**
* Get the tag that looks like the highest version number. * Get the tag that looks like the highest version number.
* *
* @return Puc_v4p10_Vcs_Reference|null * @return Reference|null
*/ */
public function getLatestTag() { public function getLatestTag() {
$tags = $this->api('/:id/repository/tags'); $tags = $this->api('/:id/repository/tags');
@ -114,7 +201,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
} }
$tag = $versionTags[0]; $tag = $versionTags[0];
return new Puc_v4p10_Vcs_Reference(array( return new Reference(array(
'name' => $tag->name, 'name' => $tag->name,
'version' => ltrim($tag->name, 'v'), 'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name), 'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
@ -126,7 +213,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
* Get a branch by name. * Get a branch by name.
* *
* @param string $branchName * @param string $branchName
* @return null|Puc_v4p10_Vcs_Reference * @return null|Reference
*/ */
public function getBranch($branchName) { public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName); $branch = $this->api('/:id/repository/branches/' . $branchName);
@ -134,7 +221,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
return null; return null;
} }
$reference = new Puc_v4p10_Vcs_Reference(array( $reference = new Reference(array(
'name' => $branch->name, 'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name), 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch, 'apiResponse' => $branch,
@ -167,13 +254,13 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
* *
* @param string $url * @param string $url
* @param array $queryParams * @param array $queryParams
* @return mixed|WP_Error * @return mixed|\WP_Error
*/ */
protected function api($url, $queryParams = array()) { protected function api($url, $queryParams = array()) {
$baseUrl = $url; $baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams); $url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => 10); $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) { if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options); $options = apply_filters($this->httpFilterName, $options);
} }
@ -190,7 +277,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
return json_decode($body); return json_decode($body);
} }
$error = new WP_Error( $error = new \WP_Error(
'puc-gitlab-http-error', 'puc-gitlab-http-error',
sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code) sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
); );
@ -276,34 +363,52 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
* @return void * @return void
*/ */
public function getTag($tagName) { public function getTag($tagName) {
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.'); throw new \LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
} }
/** protected function getUpdateDetectionStrategies($configBranch) {
* Figure out which reference (i.e tag or branch) contains the latest version. $strategies = array();
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p10_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
// GitLab doesn't handle releases the same as GitHub so just use the latest tag if ( ($configBranch === 'main') || ($configBranch === 'master') ) {
if ( $configBranch === 'master' ) { $strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
$updateSource = $this->getLatestTag(); $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
} }
if ( empty($updateSource) ) { $strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
$updateSource = $this->getBranch($configBranch); return $this->getBranch($configBranch);
} };
return $updateSource; return $strategies;
} }
public function setAuthentication($credentials) { public function setAuthentication($credentials) {
parent::setAuthentication($credentials); parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null; $this->accessToken = is_string($credentials) ? $credentials : null;
} }
/**
* Use release assets that link to GitLab generic packages (e.g. .zip files)
* instead of automatically generated source archives.
*
* This is included for backwards compatibility with older versions of PUC.
*
* @return void
* @deprecated Use enableReleaseAssets() instead.
* @noinspection PhpUnused -- Public API
*/
public function enableReleasePackages() {
$this->enableReleaseAssets(
/** @lang RegExp */ '/\.zip($|[?&#])/i',
Api::REQUIRE_RELEASE_ASSETS
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->url) ) {
return $releaseAsset->url;
}
return null;
}
} }
endif; endif;

View File

@ -1,21 +1,18 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
class Puc_v4p10_Vcs_PluginUpdateChecker extends Puc_v4p10_Plugin_UpdateChecker implements Puc_v4p10_Vcs_BaseChecker { namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
/**
* @var string The branch where to look for updates. Defaults to "master". use YahnisElsts\PluginUpdateChecker\v5p2\Plugin;
*/
protected $branch = 'master'; if ( !class_exists(PluginUpdateChecker::class, false) ):
class PluginUpdateChecker extends Plugin\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/** /**
* @var Puc_v4p10_Vcs_Api Repository API client. * PluginUpdateChecker constructor.
*/
protected $api = null;
/**
* Puc_v4p10_Vcs_PluginUpdateChecker constructor.
* *
* @param Puc_v4p10_Vcs_Api $api * @param Api $api
* @param string $pluginFile * @param string $pluginFile
* @param string $slug * @param string $slug
* @param int $checkPeriod * @param int $checkPeriod
@ -24,10 +21,11 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
*/ */
public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') { public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$this->api = $api; $this->api = $api;
$this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile); parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
$this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
$this->api->setStrategyFilterName($this->getUniqueName('vcs_update_detection_strategies'));
$this->api->setSlug($this->slug); $this->api->setSlug($this->slug);
} }
@ -41,11 +39,13 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
$api = $this->api; $api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath()); $api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$info = new Puc_v4p10_Plugin_Info(); $info = new Plugin\PluginInfo();
$info->filename = $this->pluginFile; $info->filename = $this->pluginFile;
$info->slug = $this->slug; $info->slug = $this->slug;
$this->setInfoFromHeader($this->package->getPluginHeader(), $info); $this->setInfoFromHeader($this->package->getPluginHeader(), $info);
$this->setIconsFromLocalAssets($info);
$this->setBannersFromLocalAssets($info);
//Pick a branch or tag. //Pick a branch or tag.
$updateSource = $api->chooseReference($this->branch); $updateSource = $api->chooseReference($this->branch);
@ -65,7 +65,7 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
//There's probably a network problem or an authentication error. //There's probably a network problem or an authentication error.
do_action( do_action(
'puc_api_error', 'puc_api_error',
new WP_Error( new \WP_Error(
'puc-no-update-source', 'puc-no-update-source',
'Could not retrieve version information from the repository. ' 'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect ' . 'This usually means that the update checker either can\'t connect '
@ -124,7 +124,7 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
* Copy plugin metadata from a file header to a Plugin Info object. * Copy plugin metadata from a file header to a Plugin Info object.
* *
* @param array $fileHeader * @param array $fileHeader
* @param Puc_v4p10_Plugin_Info $pluginInfo * @param Plugin\PluginInfo $pluginInfo
*/ */
protected function setInfoFromHeader($fileHeader, $pluginInfo) { protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array( $headerToPropertyMap = array(
@ -157,7 +157,7 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
* Copy plugin metadata from the remote readme.txt file. * Copy plugin metadata from the remote readme.txt file.
* *
* @param string $ref GitHub tag or branch where to look for the readme. * @param string $ref GitHub tag or branch where to look for the readme.
* @param Puc_v4p10_Plugin_Info $pluginInfo * @param Plugin\PluginInfo $pluginInfo
*/ */
protected function setInfoFromRemoteReadme($ref, $pluginInfo) { protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
$readme = $this->api->getRemoteReadme($ref); $readme = $this->api->getRemoteReadme($ref);
@ -183,35 +183,77 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
} }
} }
public function setBranch($branch) { /**
$this->branch = $branch; * Add icons from the currently installed version to a Plugin Info object.
return $this; *
* The icons should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setIconsFromLocalAssets($pluginInfo) {
$icons = $this->getLocalAssetUrls(array(
'icon.svg' => 'svg',
'icon-256x256.png' => '2x',
'icon-256x256.jpg' => '2x',
'icon-128x128.png' => '1x',
'icon-128x128.jpg' => '1x',
));
if ( !empty($icons) ) {
//The "default" key seems to be used only as last-resort fallback in WP core (5.8/5.9),
//but we'll set it anyway in case some code somewhere needs it.
reset($icons);
$firstKey = key($icons);
$icons['default'] = $icons[$firstKey];
$pluginInfo->icons = $icons;
}
} }
public function setAuthentication($credentials) { /**
$this->api->setAuthentication($credentials); * Add banners from the currently installed version to a Plugin Info object.
return $this; *
* The banners should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-headers
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setBannersFromLocalAssets($pluginInfo) {
$banners = $this->getLocalAssetUrls(array(
'banner-772x250.png' => 'high',
'banner-772x250.jpg' => 'high',
'banner-1544x500.png' => 'low',
'banner-1544x500.jpg' => 'low',
));
if ( !empty($banners) ) {
$pluginInfo->banners = $banners;
}
} }
public function getVcsApi() { /**
return $this->api; * @param array<string, string> $filesToKeys
* @return array<string, string>
*/
protected function getLocalAssetUrls($filesToKeys) {
$assetDirectory = $this->package->getAbsoluteDirectoryPath() . DIRECTORY_SEPARATOR . 'assets';
if ( !is_dir($assetDirectory) ) {
return array();
}
$assetBaseUrl = trailingslashit(plugins_url('', $assetDirectory . '/imaginary.file'));
$foundAssets = array();
foreach ($filesToKeys as $fileName => $key) {
$fullBannerPath = $assetDirectory . DIRECTORY_SEPARATOR . $fileName;
if ( !isset($icons[$key]) && is_file($fullBannerPath) ) {
$foundAssets[$key] = $assetBaseUrl . $fileName;
}
} }
public function getUpdate() { return $foundAssets;
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
} }
} }

View File

@ -1,5 +1,7 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_Reference', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !class_exists(Reference::class, false) ):
/** /**
* This class represents a VCS branch or tag. It's intended as a read only, short-lived container * This class represents a VCS branch or tag. It's intended as a read only, short-lived container
@ -13,7 +15,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Reference', false) ):
* @property string|null $changelog * @property string|null $changelog
* @property int|null $downloadCount * @property int|null $downloadCount
*/ */
class Puc_v4p10_Vcs_Reference { class Reference {
private $properties = array(); private $properties = array();
public function __construct($properties = array()) { public function __construct($properties = array()) {

View File

@ -0,0 +1,83 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !trait_exists(ReleaseAssetSupport::class, false) ) :
trait ReleaseAssetSupport {
/**
* @var bool Whether to download release assets instead of the auto-generated
* source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var string|null Regular expression that's used to filter release assets
* by file name or URL. Optional.
*/
protected $assetFilterRegex = null;
/**
* How to handle releases that don't have any matching release assets.
*
* @var int
*/
protected $releaseAssetPreference = Api::PREFER_RELEASE_ASSETS;
/**
* Enable updating via release assets.
*
* If the latest release contains no usable assets, the update checker
* will fall back to using the automatically generated ZIP archive.
*
* @param string|null $nameRegex Optional. Use only those assets where
* the file name or URL matches this regex.
* @param int $preference Optional. How to handle releases that don't have
* any matching release assets.
*/
public function enableReleaseAssets($nameRegex = null, $preference = Api::PREFER_RELEASE_ASSETS) {
$this->releaseAssetsEnabled = true;
$this->assetFilterRegex = $nameRegex;
$this->releaseAssetPreference = $preference;
}
/**
* Disable release assets.
*
* @return void
* @noinspection PhpUnused -- Public API
*/
public function disableReleaseAssets() {
$this->releaseAssetsEnabled = false;
$this->assetFilterRegex = null;
}
/**
* Does the specified asset match the name regex?
*
* @param mixed $releaseAsset Data type and structure depend on the host/API.
* @return bool
*/
protected function matchesAssetFilter($releaseAsset) {
if ( $this->assetFilterRegex === null ) {
//The default is to accept all assets.
return true;
}
$name = $this->getFilterableAssetName($releaseAsset);
if ( !is_string($name) ) {
return false;
}
return (bool)preg_match($this->assetFilterRegex, $releaseAsset->name);
}
/**
* Get the part of asset data that will be checked against the filter regex.
*
* @param mixed $releaseAsset
* @return string|null
*/
abstract protected function getFilterableAssetName($releaseAsset);
}
endif;

View File

@ -0,0 +1,108 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !trait_exists(ReleaseFilteringFeature::class, false) ) :
trait ReleaseFilteringFeature {
/**
* @var callable|null
*/
protected $releaseFilterCallback = null;
/**
* @var int
*/
protected $releaseFilterMaxReleases = 1;
/**
* @var string One of the Api::RELEASE_FILTER_* constants.
*/
protected $releaseFilterByType = Api::RELEASE_FILTER_SKIP_PRERELEASE;
/**
* Set a custom release filter.
*
* Setting a new filter will override the old filter, if any.
*
* @param callable $callback A callback that accepts a version number and a release
* object, and returns a boolean.
* @param int $releaseTypes One of the Api::RELEASE_FILTER_* constants.
* @param int $maxReleases Optional. The maximum number of recent releases to examine
* when trying to find a release that matches the filter. 1 to 100.
* @return $this
*/
public function setReleaseFilter(
$callback,
$releaseTypes = Api::RELEASE_FILTER_SKIP_PRERELEASE,
$maxReleases = 20
) {
if ( $maxReleases > 100 ) {
throw new \InvalidArgumentException(sprintf(
'The max number of releases is too high (%d). It must be 100 or less.',
$maxReleases
));
} else if ( $maxReleases < 1 ) {
throw new \InvalidArgumentException(sprintf(
'The max number of releases is too low (%d). It must be at least 1.',
$maxReleases
));
}
$this->releaseFilterCallback = $callback;
$this->releaseFilterByType = $releaseTypes;
$this->releaseFilterMaxReleases = $maxReleases;
return $this;
}
/**
* Filter releases by their version number.
*
* @param string $regex A regular expression. The release version number must match this regex.
* @param int $releaseTypes
* @param int $maxReleasesToExamine
* @return $this
* @noinspection PhpUnused -- Public API
*/
public function setReleaseVersionFilter(
$regex,
$releaseTypes = Api::RELEASE_FILTER_SKIP_PRERELEASE,
$maxReleasesToExamine = 20
) {
return $this->setReleaseFilter(
function ($versionNumber) use ($regex) {
return (preg_match($regex, $versionNumber) === 1);
},
$releaseTypes,
$maxReleasesToExamine
);
}
/**
* @param string $versionNumber The detected release version number.
* @param object $releaseObject Varies depending on the host/API.
* @return bool
*/
protected function matchesCustomReleaseFilter($versionNumber, $releaseObject) {
if ( !is_callable($this->releaseFilterCallback) ) {
return true; //No custom filter.
}
return call_user_func($this->releaseFilterCallback, $versionNumber, $releaseObject);
}
/**
* @return bool
*/
protected function shouldSkipPreReleases() {
//Maybe this could be a bitfield in the future, if we need to support
//more release types.
return ($this->releaseFilterByType !== Api::RELEASE_FILTER_ALL);
}
/**
* @return bool
*/
protected function hasCustomReleaseFilter() {
return isset($this->releaseFilterCallback) && is_callable($this->releaseFilterCallback);
}
}
endif;

View File

@ -1,22 +1,19 @@
<?php <?php
if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ): namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
class Puc_v4p10_Vcs_ThemeUpdateChecker extends Puc_v4p10_Theme_UpdateChecker implements Puc_v4p10_Vcs_BaseChecker { use YahnisElsts\PluginUpdateChecker\v5p2\Theme;
/** use YahnisElsts\PluginUpdateChecker\v5p2\Utils;
* @var string The branch where to look for updates. Defaults to "master".
*/ if ( !class_exists(ThemeUpdateChecker::class, false) ):
protected $branch = 'master';
class ThemeUpdateChecker extends Theme\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/** /**
* @var Puc_v4p10_Vcs_Api Repository API client. * ThemeUpdateChecker constructor.
*/
protected $api = null;
/**
* Puc_v4p10_Vcs_ThemeUpdateChecker constructor.
* *
* @param Puc_v4p10_Vcs_Api $api * @param Api $api
* @param null $stylesheet * @param null $stylesheet
* @param null $customSlug * @param null $customSlug
* @param int $checkPeriod * @param int $checkPeriod
@ -24,10 +21,11 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
*/ */
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') { public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
$this->api = $api; $this->api = $api;
$this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName); parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName);
$this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
$this->api->setStrategyFilterName($this->getUniqueName('vcs_update_detection_strategies'));
$this->api->setSlug($this->slug); $this->api->setSlug($this->slug);
} }
@ -35,7 +33,7 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
$api = $this->api; $api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath()); $api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$update = new Puc_v4p10_Theme_Update(); $update = new Theme\Update();
$update->slug = $this->slug; $update->slug = $this->slug;
//Figure out which reference (tag or branch) we'll use to get the latest version of the theme. //Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
@ -46,7 +44,7 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
} else { } else {
do_action( do_action(
'puc_api_error', 'puc_api_error',
new WP_Error( new \WP_Error(
'puc-no-update-source', 'puc-no-update-source',
'Could not retrieve version information from the repository. ' 'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect ' . 'This usually means that the update checker either can\'t connect '
@ -60,13 +58,13 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
//Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata //Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags. //are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
$remoteHeader = $this->package->getFileHeader($api->getRemoteFile('style.css', $ref)); $remoteHeader = $this->package->getFileHeader($api->getRemoteFile('style.css', $ref));
$update->version = Puc_v4p10_Utils::findNotEmpty(array( $update->version = Utils::findNotEmpty(array(
$remoteHeader['Version'], $remoteHeader['Version'],
Puc_v4p10_Utils::get($updateSource, 'version'), Utils::get($updateSource, 'version'),
)); ));
//The details URL defaults to the Theme URI header or the repository URL. //The details URL defaults to the Theme URI header or the repository URL.
$update->details_url = Puc_v4p10_Utils::findNotEmpty(array( $update->details_url = Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'], $remoteHeader['ThemeURI'],
$this->package->getHeaderValue('ThemeURI'), $this->package->getHeaderValue('ThemeURI'),
$this->metadataUrl, $this->metadataUrl,
@ -80,39 +78,6 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
$update = $this->filterUpdateResult($update); $update = $this->filterUpdateResult($update);
return $update; return $update;
} }
//FIXME: This is duplicated code. Both theme and plugin subclasses that use VCS share these methods.
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
}
public function getVcsApi() {
return $this->api;
}
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
}
} }
endif; endif;

View File

@ -0,0 +1,59 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p2\Vcs;
if ( !trait_exists(VcsCheckerMethods::class, false) ) :
trait VcsCheckerMethods {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
/**
* @var Api Repository API client.
*/
protected $api = null;
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
/**
* Set authentication credentials.
*
* @param array|string $credentials
* @return $this
*/
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
}
/**
* @return Api
*/
public function getVcsApi() {
return $this->api;
}
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
}
}
endif;

42
inc/update-checker/autoload.php Normal file → Executable file
View File

@ -1,35 +1,39 @@
<?php <?php
/** /**
* Plugin Update Checker Library 4.10 * Plugin Update Checker Library 5.2
* http://w-shadow.com/ * http://w-shadow.com/
* *
* Copyright 2020 Janis Elsts * Copyright 2022 Janis Elsts
* Released under the MIT license. See license.txt for details. * Released under the MIT license. See license.txt for details.
*/ */
require dirname(__FILE__) . '/Puc/v4p10/Autoloader.php'; namespace YahnisElsts\PluginUpdateChecker\v5p2;
new Puc_v4p10_Autoloader();
require dirname(__FILE__) . '/Puc/v4p10/Factory.php'; use YahnisElsts\PluginUpdateChecker\v5\PucFactory as MajorFactory;
require dirname(__FILE__) . '/Puc/v4/Factory.php'; use YahnisElsts\PluginUpdateChecker\v5p2\PucFactory as MinorFactory;
require __DIR__ . '/Puc/v5p2/Autoloader.php';
new Autoloader();
require __DIR__ . '/Puc/v5p2/PucFactory.php';
require __DIR__ . '/Puc/v5/PucFactory.php';
//Register classes defined in this version with the factory. //Register classes defined in this version with the factory.
foreach ( foreach (array(
array( 'Plugin\\UpdateChecker' => Plugin\UpdateChecker::class,
'Plugin_UpdateChecker' => 'Puc_v4p10_Plugin_UpdateChecker', 'Theme\\UpdateChecker' => Theme\UpdateChecker::class,
'Theme_UpdateChecker' => 'Puc_v4p10_Theme_UpdateChecker',
'Vcs_PluginUpdateChecker' => 'Puc_v4p10_Vcs_PluginUpdateChecker', 'Vcs\\PluginUpdateChecker' => Vcs\PluginUpdateChecker::class,
'Vcs_ThemeUpdateChecker' => 'Puc_v4p10_Vcs_ThemeUpdateChecker', 'Vcs\\ThemeUpdateChecker' => Vcs\ThemeUpdateChecker::class,
'GitHubApi' => 'Puc_v4p10_Vcs_GitHubApi', 'GitHubApi' => Vcs\GitHubApi::class,
'BitBucketApi' => 'Puc_v4p10_Vcs_BitBucketApi', 'BitBucketApi' => Vcs\BitBucketApi::class,
'GitLabApi' => 'Puc_v4p10_Vcs_GitLabApi', 'GitLabApi' => Vcs\GitLabApi::class,
) )
as $pucGeneralClass => $pucVersionedClass as $pucGeneralClass => $pucVersionedClass) {
) { MajorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.2');
Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.10');
//Also add it to the minor-version factory in case the major-version factory //Also add it to the minor-version factory in case the major-version factory
//was already defined by another, older version of the update checker. //was already defined by another, older version of the update checker.
Puc_v4p10_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.10'); MinorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.2');
} }

View File

@ -1,4 +1,4 @@
.puc-debug-bar-panel-v4 pre { .puc-debug-bar-panel-v5 pre {
margin-top: 0; margin-top: 0;
} }

View File

@ -2,7 +2,7 @@ jQuery(function($) {
function runAjaxAction(button, action) { function runAjaxAction(button, action) {
button = $(button); button = $(button);
var panel = button.closest('.puc-debug-bar-panel-v4'); var panel = button.closest('.puc-debug-bar-panel-v5');
var responseBox = button.closest('td').find('.puc-ajax-response'); var responseBox = button.closest('td').find('.puc-ajax-response');
responseBox.text('Processing...').show(); responseBox.text('Processing...').show();
@ -14,19 +14,21 @@ jQuery(function($) {
_wpnonce: panel.data('nonce') _wpnonce: panel.data('nonce')
}, },
function(data) { function(data) {
//The response contains HTML that should already be escaped in server-side code.
//phpcs:ignore WordPressVIPMinimum.JS.HTMLExecutingFunctions.html
responseBox.html(data); responseBox.html(data);
}, },
'html' 'html'
); );
} }
$('.puc-debug-bar-panel-v4 input[name="puc-check-now-button"]').click(function() { $('.puc-debug-bar-panel-v5 input[name="puc-check-now-button"]').on('click', function() {
runAjaxAction(this, 'puc_v4_debug_check_now'); runAjaxAction(this, 'puc_v5_debug_check_now');
return false; return false;
}); });
$('.puc-debug-bar-panel-v4 input[name="puc-request-info-button"]').click(function() { $('.puc-debug-bar-panel-v5 input[name="puc-request-info-button"]').on('click', function() {
runAjaxAction(this, 'puc_v4_debug_request_info'); runAjaxAction(this, 'puc_v5_debug_request_info');
return false; return false;
}); });
@ -34,7 +36,7 @@ jQuery(function($) {
// Debug Bar uses the panel class name as part of its link and container IDs. This means we can // Debug Bar uses the panel class name as part of its link and container IDs. This means we can
// end up with multiple identical IDs if more than one plugin uses the update checker library. // end up with multiple identical IDs if more than one plugin uses the update checker library.
// Fix it by replacing the class name with the plugin slug. // Fix it by replacing the class name with the plugin slug.
var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v4'); var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v5');
panels.each(function() { panels.each(function() {
var panel = $(this); var panel = $(this);
var uid = panel.data('uid'); var uid = panel.data('uid');

View File

@ -1,48 +1,57 @@
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: plugin-update-checker\n" "Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n" "POT-Creation-Date: 2022-01-29 12:09+0800\n"
"PO-Revision-Date: 2020-08-04 08:10+0800\n" "PO-Revision-Date: 2022-01-29 12:10+0800\n"
"Last-Translator: Seaton Jiang <hi@seatonjiang.com>\n"
"Language-Team: \n" "Language-Team: \n"
"Language: zh_CN\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.4\n" "X-Generator: Poedit 2.4.3\n"
"X-Poedit-Basepath: ..\n" "X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=1; plural=0;\n" "Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-SourceCharset: UTF-8\n" "X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" "X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Seaton Jiang <seaton@vtrois.com>\n"
"Language: zh_CN\n"
"X-Poedit-SearchPath-0: .\n" "X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395 #: Puc/v4p11/Plugin/Ui.php:54
msgid "View details"
msgstr "查看详情"
#: Puc/v4p11/Plugin/Ui.php:77
#, php-format
msgid "More information about %s"
msgstr "%s 的更多信息"
#: Puc/v4p11/Plugin/Ui.php:128
msgid "Check for updates" msgid "Check for updates"
msgstr "检查更新" msgstr "检查更新"
#: Puc/v4p3/Plugin/UpdateChecker.php:548 #: Puc/v4p11/Plugin/Ui.php:214
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "The %s plugin is up to date." msgid "The %s plugin is up to date."
msgstr "%s 目前是最新版本。" msgstr "%s 目前是最新版本。"
#: Puc/v4p3/Plugin/UpdateChecker.php:550 #: Puc/v4p11/Plugin/Ui.php:216
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "A new version of the %s plugin is available." msgid "A new version of the %s plugin is available."
msgstr "%s 当前有可用的更新。" msgstr "%s 当前有可用的更新。"
#: Puc/v4p3/Plugin/UpdateChecker.php:552 #: Puc/v4p11/Plugin/Ui.php:218
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s." msgid "Could not determine if updates are available for %s."
msgstr "%s 无法确定是否有可用的更新。" msgstr "%s 无法确定是否有可用的更新。"
#: Puc/v4p3/Plugin/UpdateChecker.php:558 #: Puc/v4p11/Plugin/Ui.php:224
#, php-format #, php-format
msgid "Unknown update checker status \"%s\"" msgid "Unknown update checker status \"%s\""
msgstr "未知的更新检查状态:%s" msgstr "未知的更新检查状态:%s"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 #: Puc/v4p11/Vcs/PluginUpdateChecker.php:100
msgid "There is no changelog available." msgid "There is no changelog available."
msgstr "没有可用的更新日志。" msgstr "没有可用的更新日志。"

View File

@ -2,48 +2,48 @@
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: plugin-update-checker\n" "Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2020-08-08 14:36+0300\n" "POT-Creation-Date: 2022-07-29 15:34+0300\n"
"PO-Revision-Date: 2016-01-10 20:59+0100\n" "PO-Revision-Date: 2016-01-10 20:59+0100\n"
"Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n" "Last-Translator: \n"
"Language-Team: \n" "Language-Team: \n"
"Language: en_US\n" "Language: en_US\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: Poedit 3.1.1\n"
"X-Poedit-Basepath: ..\n"
"X-Poedit-SourceCharset: UTF-8\n" "X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" "X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"X-Poedit-SearchPath-0: .\n" "X-Poedit-SearchPath-0: .\n"
#: Puc/v4p10/Plugin/Ui.php:128 #: Puc/v5p2/Plugin/Ui.php:128
msgid "Check for updates" msgid "Check for updates"
msgstr "" msgstr ""
#: Puc/v4p10/Plugin/Ui.php:213 #: Puc/v5p2/Plugin/Ui.php:214
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "The %s plugin is up to date." msgid "The %s plugin is up to date."
msgstr "" msgstr ""
#: Puc/v4p10/Plugin/Ui.php:215 #: Puc/v5p2/Plugin/Ui.php:216
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "A new version of the %s plugin is available." msgid "A new version of the %s plugin is available."
msgstr "" msgstr ""
#: Puc/v4p10/Plugin/Ui.php:217 #: Puc/v5p2/Plugin/Ui.php:218
#, php-format #, php-format
msgctxt "the plugin title" msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s." msgid "Could not determine if updates are available for %s."
msgstr "" msgstr ""
#: Puc/v4p10/Plugin/Ui.php:223 #: Puc/v5p2/Plugin/Ui.php:224
#, php-format #, php-format
msgid "Unknown update checker status \"%s\"" msgid "Unknown update checker status \"%s\""
msgstr "" msgstr ""
#: Puc/v4p10/Vcs/PluginUpdateChecker.php:98 #: Puc/v5p2/Vcs/PluginUpdateChecker.php:100
msgid "There is no changelog available." msgid "There is no changelog available."
msgstr "" msgstr ""

7
inc/update-checker/license.txt Executable file
View File

@ -0,0 +1,7 @@
Copyright (c) 2023 Jānis Elsts
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,9 +1,4 @@
<?php <?php
if ( !class_exists('Parsedown', false) ) { if ( !class_exists('Parsedown', false) ) {
//Load the Parsedown version that's compatible with the current PHP version.
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
require __DIR__ . '/ParsedownModern.php'; require __DIR__ . '/ParsedownModern.php';
} else {
require __DIR__ . '/ParsedownLegacy.php';
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -241,7 +241,11 @@ class PucReadmeParser {
} }
function sanitize_text( $text ) { // not fancy function sanitize_text( $text ) { // not fancy
$text = strip_tags($text); $text = function_exists('wp_strip_all_tags')
? wp_strip_all_tags($text)
//phpcs:ignore WordPressVIPMinimum.Functions.StripTags.StripTagsOneParameter -- Using wp_strip_all_tags() if available
: strip_tags($text);
$text = esc_html($text); $text = esc_html($text);
$text = trim($text); $text = trim($text);
return $text; return $text;