',
esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')),
esc_attr($this->updateChecker->slug),
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();
foreach($fields as $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 '';
@@ -154,11 +160,18 @@ if ( !class_exists('Puc_v4p10_DebugBar_Panel', false) && class_exists('Debug_Bar
public function row($name, $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 = '
' . htmlentities(print_r($value, true)) . '
';
} else if ($value === null) {
$value = '
null';
}
- printf('
| %1$s | %2$s |
|---|
', $name, $value);
+ printf(
+ '
| %1$s | %2$s |
|---|
',
+ esc_html($name),
+ //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above.
+ $value
+ );
}
}
diff --git a/inc/update-checker/Puc/v5p2/DebugBar/PluginExtension.php b/inc/update-checker/Puc/v5p2/DebugBar/PluginExtension.php
new file mode 100755
index 0000000..801e28f
--- /dev/null
+++ b/inc/update-checker/Puc/v5p2/DebugBar/PluginExtension.php
@@ -0,0 +1,40 @@
+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 '
', esc_html(print_r($info, true)), '
';
+ } else {
+ echo 'Failed to retrieve plugin info from the metadata URL.';
+ }
+ exit;
+ }
+ }
+
+endif;
diff --git a/inc/update-checker/Puc/v4p10/DebugBar/PluginPanel.php b/inc/update-checker/Puc/v5p2/DebugBar/PluginPanel.php
similarity index 76%
rename from inc/update-checker/Puc/v4p10/DebugBar/PluginPanel.php
rename to inc/update-checker/Puc/v5p2/DebugBar/PluginPanel.php
index ef2096b..c5d371a 100755
--- a/inc/update-checker/Puc/v4p10/DebugBar/PluginPanel.php
+++ b/inc/update-checker/Puc/v5p2/DebugBar/PluginPanel.php
@@ -1,10 +1,13 @@
+ */
+ protected $extraProperties = array();
/**
* Create an instance of this class from a JSON document.
@@ -17,7 +29,7 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* @param string $json
* @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');
}
@@ -27,19 +39,21 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* @return bool
*/
protected static function createFromJson($json, $target) {
- /** @var StdClass $apiResponse */
+ /** @var \StdClass $apiResponse */
$apiResponse = json_decode($json);
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));
- 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;
}
$valid = $target->validateMetadata($apiResponse);
if ( is_wp_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;
}
@@ -53,10 +67,10 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
/**
* No validation by default! Subclasses should check that the required fields are present.
*
- * @param StdClass $apiResponse
- * @return bool|WP_Error
+ * @param \StdClass $apiResponse
+ * @return bool|\WP_Error
*/
- protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) {
+ protected function validateMetadata($apiResponse) {
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.
*
* @abstract
- * @param StdClass|self $object The source object.
+ * @param \StdClass|self $object The source object.
* @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');
}
@@ -77,7 +91,7 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
* avoids the "incomplete object" problem if the cached value is loaded
* before this class.
*
- * @return StdClass
+ * @return \StdClass
*/
public function toStdClass() {
$object = new stdClass();
@@ -95,8 +109,8 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
/**
* Copy known fields from one object to another.
*
- * @param StdClass|self $from
- * @param StdClass|self $to
+ * @param \StdClass|self $from
+ * @param \StdClass|self $to
*/
protected function copyFields($from, $to) {
$fields = $this->getFieldNames();
@@ -127,6 +141,22 @@ if ( !class_exists('Puc_v4p10_Metadata', false) ):
protected function getPrefixedFilter($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;
diff --git a/inc/update-checker/Puc/v4p10/OAuthSignature.php b/inc/update-checker/Puc/v5p2/OAuthSignature.php
similarity index 87%
rename from inc/update-checker/Puc/v4p10/OAuthSignature.php
rename to inc/update-checker/Puc/v5p2/OAuthSignature.php
index 5127e0a..b92eb15 100755
--- a/inc/update-checker/Puc/v4p10/OAuthSignature.php
+++ b/inc/update-checker/Puc/v5p2/OAuthSignature.php
@@ -1,11 +1,12 @@
updateChecker->triggerError(
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
),
E_USER_WARNING
@@ -140,7 +145,6 @@ if ( !class_exists('Puc_v4p10_Plugin_Package', false) ):
}
if ( !function_exists('get_plugin_data') ) {
- /** @noinspection PhpIncludeInspection */
require_once(ABSPATH . '/wp-admin/includes/plugin.php');
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
@@ -170,8 +174,8 @@ if ( !class_exists('Puc_v4p10_Plugin_Package', false) ):
$pluginPath = realpath($this->pluginAbsolutePath);
//If realpath() fails, just normalize the syntax instead.
if (($muPluginDir === false) || ($pluginPath === false)) {
- $muPluginDir = Puc_v4p10_Factory::normalizePath(WPMU_PLUGIN_DIR);
- $pluginPath = Puc_v4p10_Factory::normalizePath($this->pluginAbsolutePath);
+ $muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
+ $pluginPath = PucFactory::normalizePath($this->pluginAbsolutePath);
}
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
diff --git a/inc/update-checker/Puc/v4p10/Plugin/Info.php b/inc/update-checker/Puc/v5p2/Plugin/PluginInfo.php
similarity index 91%
rename from inc/update-checker/Puc/v4p10/Plugin/Info.php
rename to inc/update-checker/Puc/v5p2/Plugin/PluginInfo.php
index c18959c..433db9b 100755
--- a/inc/update-checker/Puc/v4p10/Plugin/Info.php
+++ b/inc/update-checker/Puc/v5p2/Plugin/PluginInfo.php
@@ -1,5 +1,9 @@
name)
|| empty($apiResponse->version)
) {
- return new WP_Error(
+ return new \WP_Error(
'puc-invalid-metadata',
"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
*/
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
//as those returned by the native WordPress.org API. These can be assigned directly.
diff --git a/inc/update-checker/Puc/v4p10/Plugin/Ui.php b/inc/update-checker/Puc/v5p2/Plugin/Ui.php
similarity index 87%
rename from inc/update-checker/Puc/v4p10/Plugin/Ui.php
rename to inc/update-checker/Puc/v5p2/Plugin/Ui.php
index 1ff18d6..79033bf 100755
--- a/inc/update-checker/Puc/v4p10/Plugin/Ui.php
+++ b/inc/update-checker/Puc/v5p2/Plugin/Ui.php
@@ -1,14 +1,16 @@
updateChecker = $updateChecker;
@@ -156,8 +158,9 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
if ( $shouldCheck ) {
$update = $this->updateChecker->checkForUpdates();
$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
//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.
@@ -169,9 +172,9 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
'puc-bitbucket-http-error',
);
- foreach ($this->lastRequestApiErrors as $item) {
+ foreach ($lastRequestApiErrors as $item) {
$wpError = $item['error'];
- /** @var WP_Error $wpError */
+ /** @var \WP_Error $wpError */
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
$foundCriticalErrors = true;
break;
@@ -180,7 +183,7 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
if ( $foundCriticalErrors ) {
$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.
*/
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) ) {
- $status = strval($_GET['puc_update_check_result']);
+ $status = sanitize_key($_GET['puc_update_check_result']);
$title = $this->updateChecker->getInstalledPackage()->getPluginTitle();
$noticeClass = 'updated notice-success';
$details = '';
@@ -220,16 +224,29 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
delete_site_transient($this->manualCheckErrorTransient);
} 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';
}
+
+ $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(
'
',
- $noticeClass,
- apply_filters($this->updateChecker->getUniqueName('manual_check_message'), $message, $status),
+ esc_attr($noticeClass),
+ //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
);
}
+ //phpcs:enable
}
/**
@@ -253,11 +270,11 @@ if ( !class_exists('Puc_v4p10_Plugin_Ui', false) ):
}
foreach ($errors as $item) {
$wpError = $item['error'];
- /** @var WP_Error $wpError */
+ /** @var \WP_Error $wpError */
$output .= sprintf(
$formatString,
- $wpError->get_error_message(),
- $wpError->get_error_code()
+ esc_html($wpError->get_error_message()),
+ esc_html($wpError->get_error_code())
);
}
if ( $showAsList ) {
diff --git a/inc/update-checker/Puc/v4p10/Plugin/Update.php b/inc/update-checker/Puc/v5p2/Plugin/Update.php
similarity index 85%
rename from inc/update-checker/Puc/v4p10/Plugin/Update.php
rename to inc/update-checker/Puc/v5p2/Plugin/Update.php
index 89293c5..178f215 100755
--- a/inc/update-checker/Puc/v4p10/Plugin/Update.php
+++ b/inc/update-checker/Puc/v5p2/Plugin/Update.php
@@ -1,5 +1,9 @@
triggerError(sprintf(
'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
- htmlentities($slug),
- htmlentities($slugUsedBy)
+ $slug,
+ $slugUsedBy
), E_USER_ERROR);
}
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
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.
*
* @param int $checkPeriod
- * @return Puc_v4p10_Scheduler
+ * @return Scheduler
*/
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'));
return $scheduler;
}
@@ -124,13 +131,17 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
- * @return Puc_v4p10_Plugin_Info
+ * @return PluginInfo
*/
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 ) {
- /** @var Puc_v4p10_Plugin_Info $pluginInfo */
+ /** @var PluginInfo $pluginInfo */
$pluginInfo->filename = $this->pluginFile;
$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.
*
- * @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() {
//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 ){
return null;
}
- $update = Puc_v4p10_Plugin_Update::fromPluginInfo($pluginInfo);
+ $update = Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update);
@@ -197,9 +208,9 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
}
/**
- * @param stdClass|null $updates
- * @param stdClass $updateToAdd
- * @return stdClass
+ * @param \stdClass|null $updates
+ * @param \stdClass $updateToAdd
+ * @return \stdClass
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( $this->package->isMuPlugin() ) {
@@ -211,8 +222,8 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
}
/**
- * @param stdClass|null $updates
- * @return stdClass|null
+ * @param \stdClass|null $updates
+ * @return \stdClass|null
*/
protected function removeUpdateFromList($updates) {
$updates = parent::removeUpdateFromList($updates);
@@ -246,7 +257,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
- 'compatibility' => new stdClass(),
+ 'compatibility' => new \stdClass(),
)
);
}
@@ -255,7 +266,7 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
* Alias for isBeingUpgraded().
*
* @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
*/
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?
*
- * @param WP_Upgrader|null $upgrader
+ * @param \WP_Upgrader|null $upgrader
* @return bool
*/
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
* the metadata URL, call requestUpdate() instead.
*
- * @return Puc_v4p10_Plugin_Update|null
+ * @return Update|null
*/
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) ) {
- /** @var Puc_v4p10_Plugin_Update $update */
+ /** @var Update $update */
$update->filename = $this->pluginFile;
}
return $update;
@@ -391,20 +402,20 @@ if ( !class_exists('Puc_v4p10_Plugin_UpdateChecker', false) ):
}
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.
*
- * @return Puc_v4p10_InstalledPackage
+ * @return InstalledPackage
*/
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() {
return $this->package;
diff --git a/inc/update-checker/Puc/v4p10/Factory.php b/inc/update-checker/Puc/v5p2/PucFactory.php
similarity index 87%
rename from inc/update-checker/Puc/v4p10/Factory.php
rename to inc/update-checker/Puc/v5p2/PucFactory.php
index 28d69ee..d370ad6 100755
--- a/inc/update-checker/Puc/v4p10/Factory.php
+++ b/inc/update-checker/Puc/v5p2/PucFactory.php
@@ -1,5 +1,12 @@
checkPeriod . 'hours';
+ //phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- WPCS fails to parse the callback.
add_filter('cron_schedules', array($this, '_addCustomSchedule'));
}
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
//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.
- $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(
$this->updateChecker->getUniqueName('first_check_time'),
$firstCheckTime
@@ -69,6 +80,7 @@ if ( !class_exists('Puc_v4p10_Scheduler', false) ):
//Like WordPress itself, we check more often on certain pages.
/** @see wp_update_plugins */
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".
$this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
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 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
*/
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
//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']) ) {
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']) ) {
return;
}
diff --git a/inc/update-checker/Puc/v4p10/StateStore.php b/inc/update-checker/Puc/v5p2/StateStore.php
similarity index 82%
rename from inc/update-checker/Puc/v4p10/StateStore.php
rename to inc/update-checker/Puc/v5p2/StateStore.php
index 903fee1..0228195 100755
--- a/inc/update-checker/Puc/v4p10/StateStore.php
+++ b/inc/update-checker/Puc/v5p2/StateStore.php
@@ -1,8 +1,9 @@
lazyLoad();
@@ -73,10 +74,10 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
}
/**
- * @param Puc_v4p10_Update|null $update
+ * @param Update|null $update
* @return $this
*/
- public function setUpdate(Puc_v4p10_Update $update = null) {
+ public function setUpdate(Update $update = null) {
$this->lazyLoad();
$this->update = $update;
return $this;
@@ -127,7 +128,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
}
public function save() {
- $state = new stdClass();
+ $state = new \stdClass();
$state->lastCheck = $this->lastCheck;
$state->checkedVersion = $this->checkedVersion;
@@ -138,7 +139,7 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
$updateClass = get_class($this->update);
$state->updateClass = $updateClass;
$prefix = $this->getLibPrefix();
- if ( Puc_v4p10_Utils::startsWith($updateClass, $prefix) ) {
+ if ( Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix));
}
}
@@ -169,8 +170,8 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
return;
}
- $this->lastCheck = intval(Puc_v4p10_Utils::get($state, 'lastCheck', 0));
- $this->checkedVersion = Puc_v4p10_Utils::get($state, 'checkedVersion', '');
+ $this->lastCheck = intval(Utils::get($state, 'lastCheck', 0));
+ $this->checkedVersion = Utils::get($state, 'checkedVersion', '');
$this->update = null;
if ( isset($state->update) ) {
@@ -180,12 +181,13 @@ if ( !class_exists('Puc_v4p10_StateStore', false) ):
$updateClass = null;
if ( isset($state->updateBaseClass) ) {
$updateClass = $this->getLibPrefix() . $state->updateBaseClass;
- } else if ( isset($state->updateClass) && class_exists($state->updateClass) ) {
+ } else if ( isset($state->updateClass) ) {
$updateClass = $state->updateClass;
}
- if ( $updateClass !== null ) {
- $this->update = call_user_func(array($updateClass, 'fromObject'), $state->update);
+ $factory = array($updateClass, 'fromObject');
+ 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() {
- $parts = explode('_', __CLASS__, 3);
- return $parts[0] . '_' . $parts[1] . '_';
+ //This assumes that the current class is at the top of the versioned namespace.
+ return __NAMESPACE__ . '\\';
}
}
diff --git a/inc/update-checker/Puc/v4p10/Theme/Package.php b/inc/update-checker/Puc/v5p2/Theme/Package.php
similarity index 87%
rename from inc/update-checker/Puc/v4p10/Theme/Package.php
rename to inc/update-checker/Puc/v5p2/Theme/Package.php
index 5d9243b..36d1711 100755
--- a/inc/update-checker/Puc/v4p10/Theme/Package.php
+++ b/inc/update-checker/Puc/v5p2/Theme/Package.php
@@ -1,14 +1,18 @@
$key) || empty($apiResponse->$key) ) {
- return new WP_Error(
+ return new \WP_Error(
'tuc-invalid-metadata',
sprintf('The theme metadata is missing the required "%s" key.', $key)
);
diff --git a/inc/update-checker/Puc/v4p10/Theme/UpdateChecker.php b/inc/update-checker/Puc/v5p2/Theme/UpdateChecker.php
similarity index 79%
rename from inc/update-checker/Puc/v4p10/Theme/UpdateChecker.php
rename to inc/update-checker/Puc/v5p2/Theme/UpdateChecker.php
index cd894cd..66c5348 100755
--- a/inc/update-checker/Puc/v4p10/Theme/UpdateChecker.php
+++ b/inc/update-checker/Puc/v5p2/Theme/UpdateChecker.php
@@ -1,8 +1,15 @@
requestMetadata('Puc_v4p10_Theme_Update', 'request_update');
+ list($themeUpdate, $result) = $this->requestMetadata(Update::class, 'request_update');
if ( $themeUpdate !== null ) {
- /** @var Puc_v4p10_Theme_Update $themeUpdate */
+ /** @var Update $themeUpdate */
$themeUpdate->slug = $this->slug;
}
@@ -71,16 +78,16 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
* Create an instance of the scheduler.
*
* @param int $checkPeriod
- * @return Puc_v4p10_Scheduler
+ * @return Scheduler
*/
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?
*
- * @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
*/
public function isBeingUpgraded($upgrader = null) {
@@ -88,7 +95,7 @@ if ( !class_exists('Puc_v4p10_Theme_UpdateChecker', false) ):
}
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.
*
- * @return Puc_v4p10_InstalledPackage
+ * @return InstalledPackage
*/
protected function createInstalledPackage() {
- return new Puc_v4p10_Theme_Package($this->stylesheet, $this);
+ return new Package($this->stylesheet, $this);
}
}
diff --git a/inc/update-checker/Puc/v4p10/Update.php b/inc/update-checker/Puc/v5p2/Update.php
similarity index 79%
rename from inc/update-checker/Puc/v4p10/Update.php
rename to inc/update-checker/Puc/v5p2/Update.php
index b36b18b..8f5de5d 100755
--- a/inc/update-checker/Puc/v4p10/Update.php
+++ b/inc/update-checker/Puc/v5p2/Update.php
@@ -1,5 +1,9 @@
package = $this->createInstalledPackage();
$this->scheduler = $this->createScheduler($checkPeriod);
- $this->upgraderStatus = new Puc_v4p10_UpgraderStatus();
- $this->updateState = new Puc_v4p10_StateStore($this->optionName);
+ $this->upgraderStatus = new UpgraderStatus();
+ $this->updateState = new StateStore($this->optionName);
if ( did_action('init') ) {
$this->loadTextDomain();
@@ -206,7 +210,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/
public function allowMetadataHost($allow, $host) {
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)) ) {
@@ -218,12 +222,12 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/**
* Create a package instance that represents this plugin or theme.
*
- * @return Puc_v4p10_InstalledPackage
+ * @return InstalledPackage
*/
abstract protected function createInstalledPackage();
/**
- * @return Puc_v4p10_InstalledPackage
+ * @return InstalledPackage
*/
public function getInstalledPackage() {
return $this->package;
@@ -236,14 +240,14 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* and substitute their own scheduler.
*
* @param int $checkPeriod
- * @return Puc_v4p10_Scheduler
+ * @return Scheduler
*/
abstract protected function createScheduler($checkPeriod);
/**
* 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() {
$installedVersion = $this->getInstalledVersion();
@@ -277,7 +281,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/**
* Load the update checker state from the DB.
*
- * @return Puc_v4p10_StateStore
+ * @return StateStore
*/
public function getUpdateState() {
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
* the metadata URL, call requestUpdate() instead.
*
- * @return Puc_v4p10_Update|null
+ * @return Update|null
*/
public function 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.
*
- * @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();
/**
* 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.
- * @return Puc_v4p10_Update
+ * @return T
*/
protected function filterUpdateResult($update, $httpResult = null) {
//Let plugins/themes modify the update.
@@ -355,9 +360,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* "Compatibility: Unknown".
* 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) ) {
return;
}
@@ -427,7 +432,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/
public function triggerError($message, $errorType) {
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.
*
* @internal
- * @param WP_Error $error
+ * @param \WP_Error $error
* @param array|null $httpResponse
* @param string|null $url
* @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.
*
- * @param stdClass $updates Update list.
- * @return stdClass Modified update list.
+ * @param \stdClass $updates Update list.
+ * @return \stdClass Modified update list.
*/
public function injectUpdate($updates) {
//Is there an update to insert?
@@ -543,9 +549,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
}
/**
- * @param stdClass|null $updates
- * @param stdClass|array $updateToAdd
- * @return stdClass
+ * @param \stdClass|null $updates
+ * @param \stdClass|array $updateToAdd
+ * @return \stdClass
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( !is_object($updates) ) {
@@ -558,8 +564,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
}
/**
- * @param stdClass|null $updates
- * @return stdClass|null
+ * @param \stdClass|null $updates
+ * @return \stdClass|null
*/
protected function removeUpdateFromList($updates) {
if ( isset($updates, $updates->response) ) {
@@ -572,8 +578,8 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
* 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/
*
- * @param stdClass|null $updates
- * @return stdClass
+ * @param \stdClass|null $updates
+ * @return \stdClass
*/
protected function addNoUpdateItem($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.
*
- * @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
+ * @param class-string
$metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
* @param string $filterRoot
* @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 A metadata instance and the value returned by wp_remote_get().
*/
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()).
@@ -654,7 +660,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
//Various options for the wp_remote_get() call. Plugins can filter these, too.
$options = array(
- 'timeout' => 10, //seconds
+ 'timeout' => wp_doing_cron() ? 10 : 3,
'headers' => array(
'Accept' => 'application/json',
),
@@ -675,6 +681,9 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
$status = $this->validateApiResponse($result);
$metadata = null;
if ( !is_wp_error($status) ){
+ if ( (strpos($metaClass, '\\') === false) ) {
+ $metaClass = __NAMESPACE__ . '\\' . $metaClass;
+ }
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
} else {
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 $remoteSource WordPress has extracted the update to this directory.
- * @param WP_Upgrader $upgrader
+ * @param \WP_Upgrader $upgrader
* @return string|WP_Error
*/
public function fixDirectoryName($source, $remoteSource, $upgrader) {
global $wp_filesystem;
- /** @var WP_Filesystem_Base $wp_filesystem */
+ /** @var \WP_Filesystem_Base $wp_filesystem */
//Basic sanity checks.
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(
'Renaming %s to %s…',
'' . basename($source) . '',
@@ -935,7 +944,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
/**
* 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
*/
abstract public function isBeingUpgraded($upgrader = null);
@@ -949,7 +958,7 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
*/
protected function isBadDirectoryStructure($remoteSource) {
global $wp_filesystem;
- /** @var WP_Filesystem_Base $wp_filesystem */
+ /** @var \WP_Filesystem_Base $wp_filesystem */
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) {
@@ -977,13 +986,13 @@ if ( !class_exists('Puc_v4p10_UpdateChecker', false) ):
}
protected function createDebugBarExtension() {
- return new Puc_v4p10_DebugBar_Extension($this);
+ return new DebugBar\Extension($this);
}
/**
* Display additional configuration details in the Debug Bar panel.
*
- * @param Puc_v4p10_DebugBar_Panel $panel
+ * @param DebugBar\Panel $panel
*/
public function onDisplayConfiguration($panel) {
//Do nothing. Subclasses can use this to add additional info to the panel.
diff --git a/inc/update-checker/Puc/v4p10/UpgraderStatus.php b/inc/update-checker/Puc/v5p2/UpgraderStatus.php
similarity index 91%
rename from inc/update-checker/Puc/v4p10/UpgraderStatus.php
rename to inc/update-checker/Puc/v5p2/UpgraderStatus.php
index 2c2a625..b65303d 100755
--- a/inc/update-checker/Puc/v4p10/UpgraderStatus.php
+++ b/inc/update-checker/Puc/v5p2/UpgraderStatus.php
@@ -1,5 +1,7 @@
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();
- } elseif ( $skin instanceof Plugin_Upgrader_Skin ) {
+ } elseif ( $skin instanceof \Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($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 !== '') ) {
$themeDirectoryName = $skin->theme;
}
@@ -122,7 +124,6 @@ if ( !class_exists('Puc_v4p10_UpgraderStatus', false) ):
*/
private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){
- /** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
diff --git a/inc/update-checker/Puc/v4p10/Utils.php b/inc/update-checker/Puc/v5p2/Utils.php
similarity index 94%
rename from inc/update-checker/Puc/v4p10/Utils.php
rename to inc/update-checker/Puc/v5p2/Utils.php
index b4cf82e..eeda33d 100755
--- a/inc/update-checker/Puc/v4p10/Utils.php
+++ b/inc/update-checker/Puc/v5p2/Utils.php
@@ -1,8 +1,9 @@
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 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
@@ -105,7 +176,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Get a branch.
*
* @param string $branchName
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
abstract public function getBranch($branchName);
@@ -113,7 +184,7 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
* Get a specific tag.
*
* @param string $tagName
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
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.
* (Implementations should skip pre-release versions if possible.)
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
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.
*
- * @param stdClass $tag
+ * @param \stdClass $tag
* @return bool
*/
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.
* Tags that don't look like version number will be removed.
*
- * @param stdClass[] $tags Array of tag objects.
- * @return stdClass[] Filtered array of tags sorted in descending order.
+ * @param \stdClass[] $tags Array of tag objects.
+ * @return \stdClass[] Filtered array of tags sorted in descending order.
*/
protected function sortTagsByVersion($tags) {
//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.
*
- * @param stdClass $tag1 Tag object.
- * @param stdClass $tag2 Another tag object.
+ * @param \stdClass $tag1 Tag object.
+ * @param \stdClass $tag2 Another tag object.
* @return int
*/
protected function compareTagNames($tag1, $tag2) {
@@ -224,7 +295,6 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
return null;
}
- /** @noinspection PhpUndefinedClassInspection */
return Parsedown::instance()->text($changelog);
}
@@ -280,6 +350,13 @@ if ( !class_exists('Puc_v4p10_Vcs_Api') ):
$this->httpFilterName = $filterName;
}
+ /**
+ * @param string $filterName
+ */
+ public function setStrategyFilterName($filterName) {
+ $this->strategyFilterName = $filterName;
+ }
+
/**
* @param string $directory
*/
diff --git a/inc/update-checker/Puc/v4p10/Vcs/BaseChecker.php b/inc/update-checker/Puc/v5p2/Vcs/BaseChecker.php
similarity index 72%
rename from inc/update-checker/Puc/v4p10/Vcs/BaseChecker.php
rename to inc/update-checker/Puc/v5p2/Vcs/BaseChecker.php
index a1e574a..013e8f3 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/BaseChecker.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/BaseChecker.php
@@ -1,7 +1,9 @@
[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) {
$this->username = $matches['username'];
$this->repository = $matches['repository'];
} else {
- throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
+ throw new \InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $credentials);
}
- /**
- * Figure out which reference (i.e tag or branch) contains the latest version.
- *
- * @param string $configBranch Start looking in this branch.
- * @return null|Puc_v4p10_Vcs_Reference
- */
- public function chooseReference($configBranch) {
- $updateSource = null;
+ protected function getUpdateDetectionStrategies($configBranch) {
+ $strategies = array(
+ self::STRATEGY_STABLE_TAG => function () use ($configBranch) {
+ return $this->getStableTag($configBranch);
+ },
+ );
- //Check if there's a "Stable tag: 1.2.3" header that points to a valid tag.
- $updateSource = $this->getStableTag($configBranch);
-
- //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);
+ if ( ($configBranch === 'master' || $configBranch === 'main') ) {
+ $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
- return $updateSource;
+ $strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
+ return $this->getBranch($configBranch);
+ };
+ return $strategies;
}
public function getBranch($branchName) {
@@ -59,8 +58,16 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return null;
}
- return new Puc_v4p10_Vcs_Reference(array(
- 'name' => $branch->name,
+ //The "/src/{stuff}/{path}" endpoint doesn't seem to handle branch names that contain slashes.
+ //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,
'downloadUrl' => $this->getDownloadUrl($branch->name),
));
@@ -70,7 +77,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
* Get a specific tag.
*
* @param string $tagName
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName);
@@ -78,7 +85,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return null;
}
- return new Puc_v4p10_Vcs_Reference(array(
+ return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'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.
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/refs/tags?sort=-target.date');
@@ -103,7 +110,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
//Return the first result.
if ( !empty($versionTags) ) {
$tag = $versionTags[0];
- return new Puc_v4p10_Vcs_Reference(array(
+ return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'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.
*
* @param string $branch
- * @return null|Puc_v4p10_Vcs_Reference
+ * @return null|Reference
*/
protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch);
@@ -183,11 +190,11 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
*
* @param string $url
* @param string $version
- * @return mixed|WP_Error
+ * @return mixed|\WP_Error
*/
public function api($url, $version = '2.0') {
$url = ltrim($url, '/');
- $isSrcResource = Puc_v4p10_Utils::startsWith($url, 'src/');
+ $isSrcResource = Utils::startsWith($url, 'src/');
$url = implode('/', array(
'https://api.bitbucket.org',
@@ -203,7 +210,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
$url = $this->oauth->sign($url,'GET');
}
- $options = array('timeout' => 10);
+ $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
@@ -226,7 +233,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
return $document;
}
- $error = new WP_Error(
+ $error = new \WP_Error(
'puc-bitbucket-http-error',
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);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
- $this->oauth = new Puc_v4p10_OAuthSignature(
+ $this->oauth = new OAuthSignature(
$credentials['consumer_key'],
$credentials['consumer_secret']
);
@@ -253,7 +260,7 @@ if ( !class_exists('Puc_v4p10_Vcs_BitBucketApi', false) ):
public function signDownloadUrl($url) {
//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.
if ( $this->oauth ) {
$url = $this->oauth->sign($url);
diff --git a/inc/update-checker/Puc/v4p10/Vcs/GitHubApi.php b/inc/update-checker/Puc/v5p2/Vcs/GitHubApi.php
similarity index 64%
rename from inc/update-checker/Puc/v4p10/Vcs/GitHubApi.php
rename to inc/update-checker/Puc/v5p2/Vcs/GitHubApi.php
index ada0d13..590072d 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/GitHubApi.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/GitHubApi.php
@@ -1,8 +1,15 @@
[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
} else {
- throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
+ throw new \InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $accessToken);
@@ -57,59 +49,112 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
/**
* Get the latest release from GitHub.
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
public function getLatestRelease() {
- $release = $this->api('/repos/:user/:repo/releases/latest');
- if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
- return null;
- }
-
- $reference = new Puc_v4p10_Vcs_Reference(array(
- 'name' => $release->tag_name,
- 'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
- 'downloadUrl' => $release->zipball_url,
- 'updated' => $release->created_at,
- 'apiResponse' => $release,
- ));
-
- if ( isset($release->assets[0]) ) {
- $reference->downloadCount = $release->assets[0]->download_count;
- }
-
- if ( $this->releaseAssetsEnabled && isset($release->assets, $release->assets[0]) ) {
- //Use the first release asset that matches the specified regular expression.
- $matchingAssets = array_filter($release->assets, array($this, 'matchesAssetFilter'));
- if ( !empty($matchingAssets) ) {
- if ( $this->isAuthenticationEnabled() ) {
- /**
- * Keep in mind that we'll need to add an "Accept" header to download this asset.
- *
- * @see setUpdateDownloadHeaders()
- */
- $reference->downloadUrl = $matchingAssets[0]->url;
- } else {
- //It seems that browser_download_url only works for public repositories.
- //Using an access_token doesn't help. Maybe OAuth would work?
- $reference->downloadUrl = $matchingAssets[0]->browser_download_url;
- }
-
- $reference->downloadCount = $matchingAssets[0]->download_count;
+ //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');
+ if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
+ 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;
}
}
- if ( !empty($release->body) ) {
- /** @noinspection PhpUndefinedClassInspection */
- $reference->changelog = Parsedown::instance()->text($release->body);
+ 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,
+ 'version' => $versionNumber,
+ 'downloadUrl' => $release->zipball_url,
+ 'updated' => $release->created_at,
+ 'apiResponse' => $release,
+ ));
+
+ if ( isset($release->assets[0]) ) {
+ $reference->downloadCount = $release->assets[0]->download_count;
+ }
+
+ if ( $this->releaseAssetsEnabled ) {
+ //Use the first release asset that matches the specified regular expression.
+ if ( isset($release->assets, $release->assets[0]) ) {
+ $matchingAssets = array_values(array_filter($release->assets, array($this, 'matchesAssetFilter')));
+ } else {
+ $matchingAssets = array();
+ }
+
+ if ( !empty($matchingAssets) ) {
+ if ( $this->isAuthenticationEnabled() ) {
+ /**
+ * Keep in mind that we'll need to add an "Accept" header to download this asset.
+ *
+ * @see setUpdateDownloadHeaders()
+ */
+ $reference->downloadUrl = $matchingAssets[0]->url;
+ } else {
+ //It seems that browser_download_url only works for public repositories.
+ //Using an access_token doesn't help. Maybe OAuth would work?
+ $reference->downloadUrl = $matchingAssets[0]->browser_download_url;
+ }
+
+ $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) ) {
+ $reference->changelog = Parsedown::instance()->text($release->body);
+ }
+
+ return $reference;
}
- return $reference;
+ return null;
}
/**
* Get the tag that looks like the highest version number.
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
@@ -124,7 +169,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
}
$tag = $versionTags[0];
- return new Puc_v4p10_Vcs_Reference(array(
+ return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $tag->zipball_url,
@@ -136,7 +181,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
* Get a branch by name.
*
* @param string $branchName
- * @return null|Puc_v4p10_Vcs_Reference
+ * @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
@@ -144,7 +189,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
return null;
}
- $reference = new Puc_v4p10_Vcs_Reference(array(
+ $reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
@@ -162,7 +207,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
*
* @param string $filename
* @param string $ref Reference name (e.g. branch or tag).
- * @return StdClass|null
+ * @return \StdClass|null
*/
public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api(
@@ -197,13 +242,13 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
*
* @param string $url
* @param array $queryParams
- * @return mixed|WP_Error
+ * @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
- $options = array('timeout' => 10);
+ $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( $this->isAuthenticationEnabled() ) {
$options['headers'] = array('Authorization' => $this->getAuthorizationHeader());
}
@@ -224,7 +269,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitHubApi', false) ):
return $document;
}
- $error = new WP_Error(
+ $error = new \WP_Error(
'puc-github-http-error',
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) {
//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) {
@@ -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+
}
- /**
- * Figure out which reference (i.e tag or branch) contains the latest version.
- *
- * @param string $configBranch Start looking in this branch.
- * @return null|Puc_v4p10_Vcs_Reference
- */
- public function chooseReference($configBranch) {
- $updateSource = null;
+ protected function getUpdateDetectionStrategies($configBranch) {
+ $strategies = array();
- if ( $configBranch === 'master' ) {
+ if ( $configBranch === 'master' || $configBranch === 'main') {
//Use the latest release.
- $updateSource = $this->getLatestRelease();
- if ( $updateSource === null ) {
- //Failing that, use the tag with the highest version number.
- $updateSource = $this->getLatestTag();
- }
- }
- //Alternatively, just use the branch itself.
- if ( empty($updateSource) ) {
- $updateSource = $this->getBranch($configBranch);
+ $strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
+ //Failing that, use the tag with the highest version number.
+ $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
- 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
- * 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.
+ * @return string
*/
- public function enableReleaseAssets($fileNameRegex = null) {
- $this->releaseAssetsEnabled = true;
- $this->assetFilterRegex = $fileNameRegex;
- $this->assetApiBaseUrl = sprintf(
+ protected function getAssetApiBaseUrl() {
+ return sprintf(
'//api.github.com/repos/%1$s/%2$s/releases/assets/',
$this->userName,
$this->repositoryName
);
}
- /**
- * Does this asset match the file name regex?
- *
- * @param stdClass $releaseAsset
- * @return bool
- */
- protected function matchesAssetFilter($releaseAsset) {
- if ( $this->assetFilterRegex === null ) {
- //The default is to accept all assets.
- return true;
+ protected function getFilterableAssetName($releaseAsset) {
+ if ( isset($releaseAsset->name) ) {
+ return $releaseAsset->name;
}
- return isset($releaseAsset->name) && preg_match($this->assetFilterRegex, $releaseAsset->name);
+ return null;
}
/**
- * @internal
* @param bool $result
* @return bool
+ * @internal
*/
public function addHttpRequestFilter($result) {
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_action('requests-requests.before_redirect', array($this, 'removeAuthHeaderFromRedirects'), 10, 4);
$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.
*
* See GitHub docs:
+ *
* @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset
* @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 = '') {
//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';
}
//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
* AWS downloads and can leak authorization information.
*
- * @internal
* @param string $location
* @param array $headers
+ * @internal
*/
public function removeAuthHeaderFromRedirects(&$location, &$headers) {
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
diff --git a/inc/update-checker/Puc/v4p10/Vcs/GitLabApi.php b/inc/update-checker/Puc/v5p2/Vcs/GitLabApi.php
similarity index 62%
rename from inc/update-checker/Puc/v4p10/Vcs/GitLabApi.php
rename to inc/update-checker/Puc/v5p2/Vcs/GitLabApi.php
index a1a313c..a4944c1 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/GitLabApi.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/GitLabApi.php
@@ -1,8 +1,13 @@
repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port;
+ $this->repositoryHost = wp_parse_url($repositoryUrl, PHP_URL_HOST) . $port;
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
- $path = parse_url($repositoryUrl, PHP_URL_PATH);
+ $path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P[^/]+?)/(?P[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$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".
$parts = explode('/', trim($path, '/'));
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);
$this->userName = implode('/', $parts);
@@ -66,7 +77,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
//We need at least /user-name/repository-name/
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.
@@ -91,16 +102,92 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
/**
* Get the latest release from GitLab.
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
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.
*
- * @return Puc_v4p10_Vcs_Reference|null
+ * @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/:id/repository/tags');
@@ -114,7 +201,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
}
$tag = $versionTags[0];
- return new Puc_v4p10_Vcs_Reference(array(
+ return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
@@ -126,7 +213,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
* Get a branch by name.
*
* @param string $branchName
- * @return null|Puc_v4p10_Vcs_Reference
+ * @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName);
@@ -134,7 +221,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
return null;
}
- $reference = new Puc_v4p10_Vcs_Reference(array(
+ $reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
@@ -167,13 +254,13 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
*
* @param string $url
* @param array $queryParams
- * @return mixed|WP_Error
+ * @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
- $options = array('timeout' => 10);
+ $options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
@@ -190,7 +277,7 @@ if ( !class_exists('Puc_v4p10_Vcs_GitLabApi', false) ):
return json_decode($body);
}
- $error = new WP_Error(
+ $error = new \WP_Error(
'puc-gitlab-http-error',
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
*/
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.');
}
- /**
- * Figure out which reference (i.e tag or branch) contains the latest version.
- *
- * @param string $configBranch Start looking in this branch.
- * @return null|Puc_v4p10_Vcs_Reference
- */
- public function chooseReference($configBranch) {
- $updateSource = null;
+ protected function getUpdateDetectionStrategies($configBranch) {
+ $strategies = array();
- // GitLab doesn't handle releases the same as GitHub so just use the latest tag
- if ( $configBranch === 'master' ) {
- $updateSource = $this->getLatestTag();
+ if ( ($configBranch === 'main') || ($configBranch === 'master') ) {
+ $strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
+ $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
- if ( empty($updateSource) ) {
- $updateSource = $this->getBranch($configBranch);
- }
+ $strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
+ return $this->getBranch($configBranch);
+ };
- return $updateSource;
+ return $strategies;
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$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;
diff --git a/inc/update-checker/Puc/v4p10/Vcs/PluginUpdateChecker.php b/inc/update-checker/Puc/v5p2/Vcs/PluginUpdateChecker.php
similarity index 65%
rename from inc/update-checker/Puc/v4p10/Vcs/PluginUpdateChecker.php
rename to inc/update-checker/Puc/v5p2/Vcs/PluginUpdateChecker.php
index aba4b32..7fcbb2c 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/PluginUpdateChecker.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/PluginUpdateChecker.php
@@ -1,21 +1,18 @@
api = $api;
- $this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
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);
}
@@ -41,11 +39,13 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
- $info = new Puc_v4p10_Plugin_Info();
+ $info = new Plugin\PluginInfo();
$info->filename = $this->pluginFile;
$info->slug = $this->slug;
$this->setInfoFromHeader($this->package->getPluginHeader(), $info);
+ $this->setIconsFromLocalAssets($info);
+ $this->setBannersFromLocalAssets($info);
//Pick a branch or tag.
$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.
do_action(
'puc_api_error',
- new WP_Error(
+ new \WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. '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.
*
* @param array $fileHeader
- * @param Puc_v4p10_Plugin_Info $pluginInfo
+ * @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array(
@@ -157,7 +157,7 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
* Copy plugin metadata from the remote readme.txt file.
*
* @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) {
$readme = $this->api->getRemoteReadme($ref);
@@ -183,35 +183,77 @@ if ( !class_exists('Puc_v4p10_Vcs_PluginUpdateChecker') ):
}
}
- public function setBranch($branch) {
- $this->branch = $branch;
- return $this;
+ /**
+ * Add icons from the currently installed version to a Plugin Info object.
+ *
+ * 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);
- return $this;
+ /**
+ * Add banners from the currently installed version to a Plugin Info object.
+ *
+ * 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 $filesToKeys
+ * @return array
+ */
+ protected function getLocalAssetUrls($filesToKeys) {
+ $assetDirectory = $this->package->getAbsoluteDirectoryPath() . DIRECTORY_SEPARATOR . 'assets';
+ if ( !is_dir($assetDirectory) ) {
+ return array();
+ }
+ $assetBaseUrl = trailingslashit(plugins_url('', $assetDirectory . '/imaginary.file'));
- public function getUpdate() {
- $update = parent::getUpdate();
-
- if ( isset($update) && !empty($update->download_url) ) {
- $update->download_url = $this->api->signDownloadUrl($update->download_url);
+ $foundAssets = array();
+ foreach ($filesToKeys as $fileName => $key) {
+ $fullBannerPath = $assetDirectory . DIRECTORY_SEPARATOR . $fileName;
+ if ( !isset($icons[$key]) && is_file($fullBannerPath) ) {
+ $foundAssets[$key] = $assetBaseUrl . $fileName;
+ }
}
- 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));
+ return $foundAssets;
}
}
diff --git a/inc/update-checker/Puc/v4p10/Vcs/Reference.php b/inc/update-checker/Puc/v5p2/Vcs/Reference.php
similarity index 89%
rename from inc/update-checker/Puc/v4p10/Vcs/Reference.php
rename to inc/update-checker/Puc/v5p2/Vcs/Reference.php
index 85250cd..3b00942 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/Reference.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/Reference.php
@@ -1,5 +1,7 @@
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;
\ No newline at end of file
diff --git a/inc/update-checker/Puc/v5p2/Vcs/ReleaseFilteringFeature.php b/inc/update-checker/Puc/v5p2/Vcs/ReleaseFilteringFeature.php
new file mode 100755
index 0000000..091b1ec
--- /dev/null
+++ b/inc/update-checker/Puc/v5p2/Vcs/ReleaseFilteringFeature.php
@@ -0,0 +1,108 @@
+ 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;
\ No newline at end of file
diff --git a/inc/update-checker/Puc/v4p10/Vcs/ThemeUpdateChecker.php b/inc/update-checker/Puc/v5p2/Vcs/ThemeUpdateChecker.php
similarity index 55%
rename from inc/update-checker/Puc/v4p10/Vcs/ThemeUpdateChecker.php
rename to inc/update-checker/Puc/v5p2/Vcs/ThemeUpdateChecker.php
index de62822..16c2da4 100755
--- a/inc/update-checker/Puc/v4p10/Vcs/ThemeUpdateChecker.php
+++ b/inc/update-checker/Puc/v5p2/Vcs/ThemeUpdateChecker.php
@@ -1,22 +1,19 @@
api = $api;
- $this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
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);
}
@@ -35,7 +33,7 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
- $update = new Puc_v4p10_Theme_Update();
+ $update = new Theme\Update();
$update->slug = $this->slug;
//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 {
do_action(
'puc_api_error',
- new WP_Error(
+ new \WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. '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
//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));
- $update->version = Puc_v4p10_Utils::findNotEmpty(array(
+ $update->version = Utils::findNotEmpty(array(
$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.
- $update->details_url = Puc_v4p10_Utils::findNotEmpty(array(
+ $update->details_url = Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'],
$this->package->getHeaderValue('ThemeURI'),
$this->metadataUrl,
@@ -80,39 +78,6 @@ if ( !class_exists('Puc_v4p10_Vcs_ThemeUpdateChecker', false) ):
$update = $this->filterUpdateResult($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;
diff --git a/inc/update-checker/Puc/v5p2/Vcs/VcsCheckerMethods.php b/inc/update-checker/Puc/v5p2/Vcs/VcsCheckerMethods.php
new file mode 100755
index 0000000..28b406d
--- /dev/null
+++ b/inc/update-checker/Puc/v5p2/Vcs/VcsCheckerMethods.php
@@ -0,0 +1,59 @@
+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;
\ No newline at end of file
diff --git a/inc/update-checker/autoload.php b/inc/update-checker/autoload.php
old mode 100644
new mode 100755
index 1949b3d..74d1de9
--- a/inc/update-checker/autoload.php
+++ b/inc/update-checker/autoload.php
@@ -1,35 +1,39 @@
'Puc_v4p10_Plugin_UpdateChecker',
- 'Theme_UpdateChecker' => 'Puc_v4p10_Theme_UpdateChecker',
+foreach (array(
+ 'Plugin\\UpdateChecker' => Plugin\UpdateChecker::class,
+ 'Theme\\UpdateChecker' => Theme\UpdateChecker::class,
- 'Vcs_PluginUpdateChecker' => 'Puc_v4p10_Vcs_PluginUpdateChecker',
- 'Vcs_ThemeUpdateChecker' => 'Puc_v4p10_Vcs_ThemeUpdateChecker',
+ 'Vcs\\PluginUpdateChecker' => Vcs\PluginUpdateChecker::class,
+ 'Vcs\\ThemeUpdateChecker' => Vcs\ThemeUpdateChecker::class,
- 'GitHubApi' => 'Puc_v4p10_Vcs_GitHubApi',
- 'BitBucketApi' => 'Puc_v4p10_Vcs_BitBucketApi',
- 'GitLabApi' => 'Puc_v4p10_Vcs_GitLabApi',
+ 'GitHubApi' => Vcs\GitHubApi::class,
+ 'BitBucketApi' => Vcs\BitBucketApi::class,
+ 'GitLabApi' => Vcs\GitLabApi::class,
)
- as $pucGeneralClass => $pucVersionedClass
-) {
- Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.10');
+ as $pucGeneralClass => $pucVersionedClass) {
+ MajorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.2');
//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.
- Puc_v4p10_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.10');
+ MinorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.2');
}
diff --git a/inc/update-checker/css/puc-debug-bar.css b/inc/update-checker/css/puc-debug-bar.css
index 2cb3f8e..649db4f 100755
--- a/inc/update-checker/css/puc-debug-bar.css
+++ b/inc/update-checker/css/puc-debug-bar.css
@@ -1,4 +1,4 @@
-.puc-debug-bar-panel-v4 pre {
+.puc-debug-bar-panel-v5 pre {
margin-top: 0;
}
diff --git a/inc/update-checker/js/debug-bar.js b/inc/update-checker/js/debug-bar.js
index b8435db..80f53f1 100755
--- a/inc/update-checker/js/debug-bar.js
+++ b/inc/update-checker/js/debug-bar.js
@@ -2,7 +2,7 @@ jQuery(function($) {
function runAjaxAction(button, action) {
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');
responseBox.text('Processing...').show();
@@ -14,19 +14,21 @@ jQuery(function($) {
_wpnonce: panel.data('nonce')
},
function(data) {
+ //The response contains HTML that should already be escaped in server-side code.
+ //phpcs:ignore WordPressVIPMinimum.JS.HTMLExecutingFunctions.html
responseBox.html(data);
},
'html'
);
}
- $('.puc-debug-bar-panel-v4 input[name="puc-check-now-button"]').click(function() {
- runAjaxAction(this, 'puc_v4_debug_check_now');
+ $('.puc-debug-bar-panel-v5 input[name="puc-check-now-button"]').on('click', function() {
+ runAjaxAction(this, 'puc_v5_debug_check_now');
return false;
});
- $('.puc-debug-bar-panel-v4 input[name="puc-request-info-button"]').click(function() {
- runAjaxAction(this, 'puc_v4_debug_request_info');
+ $('.puc-debug-bar-panel-v5 input[name="puc-request-info-button"]').on('click', function() {
+ runAjaxAction(this, 'puc_v5_debug_request_info');
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
// 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.
- 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() {
var panel = $(this);
var uid = panel.data('uid');
diff --git a/inc/update-checker/languages/plugin-update-checker-zh_CN.mo b/inc/update-checker/languages/plugin-update-checker-zh_CN.mo
index c0fc405..86d1144 100755
Binary files a/inc/update-checker/languages/plugin-update-checker-zh_CN.mo and b/inc/update-checker/languages/plugin-update-checker-zh_CN.mo differ
diff --git a/inc/update-checker/languages/plugin-update-checker-zh_CN.po b/inc/update-checker/languages/plugin-update-checker-zh_CN.po
index 005b4d0..d4f7056 100755
--- a/inc/update-checker/languages/plugin-update-checker-zh_CN.po
+++ b/inc/update-checker/languages/plugin-update-checker-zh_CN.po
@@ -1,48 +1,57 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
-"POT-Creation-Date: 2017-11-24 17:02+0200\n"
-"PO-Revision-Date: 2020-08-04 08:10+0800\n"
+"POT-Creation-Date: 2022-01-29 12:09+0800\n"
+"PO-Revision-Date: 2022-01-29 12:10+0800\n"
+"Last-Translator: Seaton Jiang \n"
"Language-Team: \n"
+"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"X-Generator: Poedit 2.4\n"
+"X-Generator: Poedit 2.4.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
-"Last-Translator: Seaton Jiang \n"
-"Language: zh_CN\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"
msgstr "检查更新"
-#: Puc/v4p3/Plugin/UpdateChecker.php:548
+#: Puc/v4p11/Plugin/Ui.php:214
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "%s 目前是最新版本。"
-#: Puc/v4p3/Plugin/UpdateChecker.php:550
+#: Puc/v4p11/Plugin/Ui.php:216
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "%s 当前有可用的更新。"
-#: Puc/v4p3/Plugin/UpdateChecker.php:552
+#: Puc/v4p11/Plugin/Ui.php:218
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "%s 无法确定是否有可用的更新。"
-#: Puc/v4p3/Plugin/UpdateChecker.php:558
+#: Puc/v4p11/Plugin/Ui.php:224
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "未知的更新检查状态:%s"
-#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
+#: Puc/v4p11/Vcs/PluginUpdateChecker.php:100
msgid "There is no changelog available."
msgstr "没有可用的更新日志。"
diff --git a/inc/update-checker/languages/plugin-update-checker.pot b/inc/update-checker/languages/plugin-update-checker.pot
index 29d1f40..3610299 100755
--- a/inc/update-checker/languages/plugin-update-checker.pot
+++ b/inc/update-checker/languages/plugin-update-checker.pot
@@ -2,48 +2,48 @@
msgid ""
msgstr ""
"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"
-"Last-Translator: Tamás András Horváth \n"
+"Last-Translator: \n"
"Language-Team: \n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"X-Generator: Poedit 2.4\n"
-"X-Poedit-Basepath: ..\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-KeywordsList: __;_e;_x:1,2c;_x\n"
"X-Poedit-SearchPath-0: .\n"
-#: Puc/v4p10/Plugin/Ui.php:128
+#: Puc/v5p2/Plugin/Ui.php:128
msgid "Check for updates"
msgstr ""
-#: Puc/v4p10/Plugin/Ui.php:213
+#: Puc/v5p2/Plugin/Ui.php:214
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr ""
-#: Puc/v4p10/Plugin/Ui.php:215
+#: Puc/v5p2/Plugin/Ui.php:216
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr ""
-#: Puc/v4p10/Plugin/Ui.php:217
+#: Puc/v5p2/Plugin/Ui.php:218
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr ""
-#: Puc/v4p10/Plugin/Ui.php:223
+#: Puc/v5p2/Plugin/Ui.php:224
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr ""
-#: Puc/v4p10/Vcs/PluginUpdateChecker.php:98
+#: Puc/v5p2/Vcs/PluginUpdateChecker.php:100
msgid "There is no changelog available."
msgstr ""
diff --git a/inc/update-checker/license.txt b/inc/update-checker/license.txt
new file mode 100755
index 0000000..7fff536
--- /dev/null
+++ b/inc/update-checker/license.txt
@@ -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.
diff --git a/inc/update-checker/vendor/Parsedown.php b/inc/update-checker/vendor/Parsedown.php
index 6a07497..11a212f 100755
--- a/inc/update-checker/vendor/Parsedown.php
+++ b/inc/update-checker/vendor/Parsedown.php
@@ -1,9 +1,4 @@
=') ) {
- require __DIR__ . '/ParsedownModern.php';
- } else {
- require __DIR__ . '/ParsedownLegacy.php';
- }
+ require __DIR__ . '/ParsedownModern.php';
}
diff --git a/inc/update-checker/vendor/ParsedownLegacy.php b/inc/update-checker/vendor/ParsedownLegacy.php
deleted file mode 100755
index bbc2d32..0000000
--- a/inc/update-checker/vendor/ParsedownLegacy.php
+++ /dev/null
@@ -1,1535 +0,0 @@
-DefinitionData = array();
-
- # standardize line breaks
- $text = str_replace(array("\r\n", "\r"), "\n", $text);
-
- # remove surrounding line breaks
- $text = trim($text, "\n");
-
- # split text into lines
- $lines = explode("\n", $text);
-
- # iterate through lines to identify blocks
- $markup = $this->lines($lines);
-
- # trim line breaks
- $markup = trim($markup, "\n");
-
- return $markup;
- }
-
- #
- # Setters
- #
-
- function setBreaksEnabled($breaksEnabled)
- {
- $this->breaksEnabled = $breaksEnabled;
-
- return $this;
- }
-
- protected $breaksEnabled;
-
- function setMarkupEscaped($markupEscaped)
- {
- $this->markupEscaped = $markupEscaped;
-
- return $this;
- }
-
- protected $markupEscaped;
-
- function setUrlsLinked($urlsLinked)
- {
- $this->urlsLinked = $urlsLinked;
-
- return $this;
- }
-
- protected $urlsLinked = true;
-
- #
- # Lines
- #
-
- protected $BlockTypes = array(
- '#' => array('Header'),
- '*' => array('Rule', 'List'),
- '+' => array('List'),
- '-' => array('SetextHeader', 'Table', 'Rule', 'List'),
- '0' => array('List'),
- '1' => array('List'),
- '2' => array('List'),
- '3' => array('List'),
- '4' => array('List'),
- '5' => array('List'),
- '6' => array('List'),
- '7' => array('List'),
- '8' => array('List'),
- '9' => array('List'),
- ':' => array('Table'),
- '<' => array('Comment', 'Markup'),
- '=' => array('SetextHeader'),
- '>' => array('Quote'),
- '[' => array('Reference'),
- '_' => array('Rule'),
- '`' => array('FencedCode'),
- '|' => array('Table'),
- '~' => array('FencedCode'),
- );
-
- # ~
-
- protected $DefinitionTypes = array(
- '[' => array('Reference'),
- );
-
- # ~
-
- protected $unmarkedBlockTypes = array(
- 'Code',
- );
-
- #
- # Blocks
- #
-
- private function lines(array $lines)
- {
- $CurrentBlock = null;
-
- foreach ($lines as $line)
- {
- if (chop($line) === '')
- {
- if (isset($CurrentBlock))
- {
- $CurrentBlock['interrupted'] = true;
- }
-
- continue;
- }
-
- if (strpos($line, "\t") !== false)
- {
- $parts = explode("\t", $line);
-
- $line = $parts[0];
-
- unset($parts[0]);
-
- foreach ($parts as $part)
- {
- $shortage = 4 - mb_strlen($line, 'utf-8') % 4;
-
- $line .= str_repeat(' ', $shortage);
- $line .= $part;
- }
- }
-
- $indent = 0;
-
- while (isset($line[$indent]) and $line[$indent] === ' ')
- {
- $indent ++;
- }
-
- $text = $indent > 0 ? substr($line, $indent) : $line;
-
- # ~
-
- $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
-
- # ~
-
- if (isset($CurrentBlock['incomplete']))
- {
- $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
-
- if (isset($Block))
- {
- $CurrentBlock = $Block;
-
- continue;
- }
- else
- {
- if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
- {
- $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
- }
-
- unset($CurrentBlock['incomplete']);
- }
- }
-
- # ~
-
- $marker = $text[0];
-
- # ~
-
- $blockTypes = $this->unmarkedBlockTypes;
-
- if (isset($this->BlockTypes[$marker]))
- {
- foreach ($this->BlockTypes[$marker] as $blockType)
- {
- $blockTypes []= $blockType;
- }
- }
-
- #
- # ~
-
- foreach ($blockTypes as $blockType)
- {
- $Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
-
- if (isset($Block))
- {
- $Block['type'] = $blockType;
-
- if ( ! isset($Block['identified']))
- {
- $Blocks []= $CurrentBlock;
-
- $Block['identified'] = true;
- }
-
- if (method_exists($this, 'block'.$blockType.'Continue'))
- {
- $Block['incomplete'] = true;
- }
-
- $CurrentBlock = $Block;
-
- continue 2;
- }
- }
-
- # ~
-
- if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
- {
- $CurrentBlock['element']['text'] .= "\n".$text;
- }
- else
- {
- $Blocks []= $CurrentBlock;
-
- $CurrentBlock = $this->paragraph($Line);
-
- $CurrentBlock['identified'] = true;
- }
- }
-
- # ~
-
- if (isset($CurrentBlock['incomplete']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
- {
- $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
- }
-
- # ~
-
- $Blocks []= $CurrentBlock;
-
- unset($Blocks[0]);
-
- # ~
-
- $markup = '';
-
- foreach ($Blocks as $Block)
- {
- if (isset($Block['hidden']))
- {
- continue;
- }
-
- $markup .= "\n";
- $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
- }
-
- $markup .= "\n";
-
- # ~
-
- return $markup;
- }
-
- #
- # Code
-
- protected function blockCode($Line, $Block = null)
- {
- if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
- {
- return;
- }
-
- if ($Line['indent'] >= 4)
- {
- $text = substr($Line['body'], 4);
-
- $Block = array(
- 'element' => array(
- 'name' => 'pre',
- 'handler' => 'element',
- 'text' => array(
- 'name' => 'code',
- 'text' => $text,
- ),
- ),
- );
-
- return $Block;
- }
- }
-
- protected function blockCodeContinue($Line, $Block)
- {
- if ($Line['indent'] >= 4)
- {
- if (isset($Block['interrupted']))
- {
- $Block['element']['text']['text'] .= "\n";
-
- unset($Block['interrupted']);
- }
-
- $Block['element']['text']['text'] .= "\n";
-
- $text = substr($Line['body'], 4);
-
- $Block['element']['text']['text'] .= $text;
-
- return $Block;
- }
- }
-
- protected function blockCodeComplete($Block)
- {
- $text = $Block['element']['text']['text'];
-
- $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
-
- $Block['element']['text']['text'] = $text;
-
- return $Block;
- }
-
- #
- # Comment
-
- protected function blockComment($Line)
- {
- if ($this->markupEscaped)
- {
- return;
- }
-
- if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
- {
- $Block = array(
- 'markup' => $Line['body'],
- );
-
- if (preg_match('/-->$/', $Line['text']))
- {
- $Block['closed'] = true;
- }
-
- return $Block;
- }
- }
-
- protected function blockCommentContinue($Line, array $Block)
- {
- if (isset($Block['closed']))
- {
- return;
- }
-
- $Block['markup'] .= "\n" . $Line['body'];
-
- if (preg_match('/-->$/', $Line['text']))
- {
- $Block['closed'] = true;
- }
-
- return $Block;
- }
-
- #
- # Fenced Code
-
- protected function blockFencedCode($Line)
- {
- if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
- {
- $Element = array(
- 'name' => 'code',
- 'text' => '',
- );
-
- if (isset($matches[2]))
- {
- $class = 'language-'.$matches[2];
-
- $Element['attributes'] = array(
- 'class' => $class,
- );
- }
-
- $Block = array(
- 'char' => $Line['text'][0],
- 'element' => array(
- 'name' => 'pre',
- 'handler' => 'element',
- 'text' => $Element,
- ),
- );
-
- return $Block;
- }
- }
-
- protected function blockFencedCodeContinue($Line, $Block)
- {
- if (isset($Block['complete']))
- {
- return;
- }
-
- if (isset($Block['interrupted']))
- {
- $Block['element']['text']['text'] .= "\n";
-
- unset($Block['interrupted']);
- }
-
- if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
- {
- $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
-
- $Block['complete'] = true;
-
- return $Block;
- }
-
- $Block['element']['text']['text'] .= "\n".$Line['body'];;
-
- return $Block;
- }
-
- protected function blockFencedCodeComplete($Block)
- {
- $text = $Block['element']['text']['text'];
-
- $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
-
- $Block['element']['text']['text'] = $text;
-
- return $Block;
- }
-
- #
- # Header
-
- protected function blockHeader($Line)
- {
- if (isset($Line['text'][1]))
- {
- $level = 1;
-
- while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
- {
- $level ++;
- }
-
- if ($level > 6)
- {
- return;
- }
-
- $text = trim($Line['text'], '# ');
-
- $Block = array(
- 'element' => array(
- 'name' => 'h' . min(6, $level),
- 'text' => $text,
- 'handler' => 'line',
- ),
- );
-
- return $Block;
- }
- }
-
- #
- # List
-
- protected function blockList($Line)
- {
- list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
-
- if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
- {
- $Block = array(
- 'indent' => $Line['indent'],
- 'pattern' => $pattern,
- 'element' => array(
- 'name' => $name,
- 'handler' => 'elements',
- ),
- );
-
- $Block['li'] = array(
- 'name' => 'li',
- 'handler' => 'li',
- 'text' => array(
- $matches[2],
- ),
- );
-
- $Block['element']['text'] []= & $Block['li'];
-
- return $Block;
- }
- }
-
- protected function blockListContinue($Line, array $Block)
- {
- if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
- {
- if (isset($Block['interrupted']))
- {
- $Block['li']['text'] []= '';
-
- unset($Block['interrupted']);
- }
-
- unset($Block['li']);
-
- $text = isset($matches[1]) ? $matches[1] : '';
-
- $Block['li'] = array(
- 'name' => 'li',
- 'handler' => 'li',
- 'text' => array(
- $text,
- ),
- );
-
- $Block['element']['text'] []= & $Block['li'];
-
- return $Block;
- }
-
- if ($Line['text'][0] === '[' and $this->blockReference($Line))
- {
- return $Block;
- }
-
- if ( ! isset($Block['interrupted']))
- {
- $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
-
- $Block['li']['text'] []= $text;
-
- return $Block;
- }
-
- if ($Line['indent'] > 0)
- {
- $Block['li']['text'] []= '';
-
- $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
-
- $Block['li']['text'] []= $text;
-
- unset($Block['interrupted']);
-
- return $Block;
- }
- }
-
- #
- # Quote
-
- protected function blockQuote($Line)
- {
- if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
- {
- $Block = array(
- 'element' => array(
- 'name' => 'blockquote',
- 'handler' => 'lines',
- 'text' => (array) $matches[1],
- ),
- );
-
- return $Block;
- }
- }
-
- protected function blockQuoteContinue($Line, array $Block)
- {
- if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
- {
- if (isset($Block['interrupted']))
- {
- $Block['element']['text'] []= '';
-
- unset($Block['interrupted']);
- }
-
- $Block['element']['text'] []= $matches[1];
-
- return $Block;
- }
-
- if ( ! isset($Block['interrupted']))
- {
- $Block['element']['text'] []= $Line['text'];
-
- return $Block;
- }
- }
-
- #
- # Rule
-
- protected function blockRule($Line)
- {
- if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
- {
- $Block = array(
- 'element' => array(
- 'name' => 'hr'
- ),
- );
-
- return $Block;
- }
- }
-
- #
- # Setext
-
- protected function blockSetextHeader($Line, array $Block = null)
- {
- if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
- {
- return;
- }
-
- if (chop($Line['text'], $Line['text'][0]) === '')
- {
- $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
-
- return $Block;
- }
- }
-
- #
- # Markup
-
- protected function blockMarkup($Line)
- {
- if ($this->markupEscaped)
- {
- return;
- }
-
- if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
- {
- if (in_array($matches[1], $this->textLevelElements))
- {
- return;
- }
-
- $Block = array(
- 'name' => $matches[1],
- 'depth' => 0,
- 'markup' => $Line['text'],
- );
-
- $length = strlen($matches[0]);
-
- $remainder = substr($Line['text'], $length);
-
- if (trim($remainder) === '')
- {
- if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
- {
- $Block['closed'] = true;
-
- $Block['void'] = true;
- }
- }
- else
- {
- if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
- {
- return;
- }
-
- if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
- {
- $Block['closed'] = true;
- }
- }
-
- return $Block;
- }
- }
-
- protected function blockMarkupContinue($Line, array $Block)
- {
- if (isset($Block['closed']))
- {
- return;
- }
-
- if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
- {
- $Block['depth'] ++;
- }
-
- if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
- {
- if ($Block['depth'] > 0)
- {
- $Block['depth'] --;
- }
- else
- {
- $Block['closed'] = true;
- }
-
- $Block['markup'] .= $matches[1];
- }
-
- if (isset($Block['interrupted']))
- {
- $Block['markup'] .= "\n";
-
- unset($Block['interrupted']);
- }
-
- $Block['markup'] .= "\n".$Line['body'];
-
- return $Block;
- }
-
- #
- # Reference
-
- protected function blockReference($Line)
- {
- if (preg_match('/^\[(.+?)\]:[ ]*(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
- {
- $id = strtolower($matches[1]);
-
- $Data = array(
- 'url' => $matches[2],
- 'title' => null,
- );
-
- if (isset($matches[3]))
- {
- $Data['title'] = $matches[3];
- }
-
- $this->DefinitionData['Reference'][$id] = $Data;
-
- $Block = array(
- 'hidden' => true,
- );
-
- return $Block;
- }
- }
-
- #
- # Table
-
- protected function blockTable($Line, array $Block = null)
- {
- if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
- {
- return;
- }
-
- if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
- {
- $alignments = array();
-
- $divider = $Line['text'];
-
- $divider = trim($divider);
- $divider = trim($divider, '|');
-
- $dividerCells = explode('|', $divider);
-
- foreach ($dividerCells as $dividerCell)
- {
- $dividerCell = trim($dividerCell);
-
- if ($dividerCell === '')
- {
- continue;
- }
-
- $alignment = null;
-
- if ($dividerCell[0] === ':')
- {
- $alignment = 'left';
- }
-
- if (substr($dividerCell, - 1) === ':')
- {
- $alignment = $alignment === 'left' ? 'center' : 'right';
- }
-
- $alignments []= $alignment;
- }
-
- # ~
-
- $HeaderElements = array();
-
- $header = $Block['element']['text'];
-
- $header = trim($header);
- $header = trim($header, '|');
-
- $headerCells = explode('|', $header);
-
- foreach ($headerCells as $index => $headerCell)
- {
- $headerCell = trim($headerCell);
-
- $HeaderElement = array(
- 'name' => 'th',
- 'text' => $headerCell,
- 'handler' => 'line',
- );
-
- if (isset($alignments[$index]))
- {
- $alignment = $alignments[$index];
-
- $HeaderElement['attributes'] = array(
- 'style' => 'text-align: '.$alignment.';',
- );
- }
-
- $HeaderElements []= $HeaderElement;
- }
-
- # ~
-
- $Block = array(
- 'alignments' => $alignments,
- 'identified' => true,
- 'element' => array(
- 'name' => 'table',
- 'handler' => 'elements',
- ),
- );
-
- $Block['element']['text'] []= array(
- 'name' => 'thead',
- 'handler' => 'elements',
- );
-
- $Block['element']['text'] []= array(
- 'name' => 'tbody',
- 'handler' => 'elements',
- 'text' => array(),
- );
-
- $Block['element']['text'][0]['text'] []= array(
- 'name' => 'tr',
- 'handler' => 'elements',
- 'text' => $HeaderElements,
- );
-
- return $Block;
- }
- }
-
- protected function blockTableContinue($Line, array $Block)
- {
- if (isset($Block['interrupted']))
- {
- return;
- }
-
- if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
- {
- $Elements = array();
-
- $row = $Line['text'];
-
- $row = trim($row);
- $row = trim($row, '|');
-
- preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
-
- foreach ($matches[0] as $index => $cell)
- {
- $cell = trim($cell);
-
- $Element = array(
- 'name' => 'td',
- 'handler' => 'line',
- 'text' => $cell,
- );
-
- if (isset($Block['alignments'][$index]))
- {
- $Element['attributes'] = array(
- 'style' => 'text-align: '.$Block['alignments'][$index].';',
- );
- }
-
- $Elements []= $Element;
- }
-
- $Element = array(
- 'name' => 'tr',
- 'handler' => 'elements',
- 'text' => $Elements,
- );
-
- $Block['element']['text'][1]['text'] []= $Element;
-
- return $Block;
- }
- }
-
- #
- # ~
- #
-
- protected function paragraph($Line)
- {
- $Block = array(
- 'element' => array(
- 'name' => 'p',
- 'text' => $Line['text'],
- 'handler' => 'line',
- ),
- );
-
- return $Block;
- }
-
- #
- # Inline Elements
- #
-
- protected $InlineTypes = array(
- '"' => array('SpecialCharacter'),
- '!' => array('Image'),
- '&' => array('SpecialCharacter'),
- '*' => array('Emphasis'),
- ':' => array('Url'),
- '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
- '>' => array('SpecialCharacter'),
- '[' => array('Link'),
- '_' => array('Emphasis'),
- '`' => array('Code'),
- '~' => array('Strikethrough'),
- '\\' => array('EscapeSequence'),
- );
-
- # ~
-
- protected $inlineMarkerList = '!"*_&[:<>`~\\';
-
- #
- # ~
- #
-
- public function line($text)
- {
- $markup = '';
-
- $unexaminedText = $text;
-
- $markerPosition = 0;
-
- while ($excerpt = strpbrk($unexaminedText, $this->inlineMarkerList))
- {
- $marker = $excerpt[0];
-
- $markerPosition += strpos($unexaminedText, $marker);
-
- $Excerpt = array('text' => $excerpt, 'context' => $text);
-
- foreach ($this->InlineTypes[$marker] as $inlineType)
- {
- $Inline = $this->{'inline'.$inlineType}($Excerpt);
-
- if ( ! isset($Inline))
- {
- continue;
- }
-
- if (isset($Inline['position']) and $Inline['position'] > $markerPosition) # position is ahead of marker
- {
- continue;
- }
-
- if ( ! isset($Inline['position']))
- {
- $Inline['position'] = $markerPosition;
- }
-
- $unmarkedText = substr($text, 0, $Inline['position']);
-
- $markup .= $this->unmarkedText($unmarkedText);
-
- $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
-
- $text = substr($text, $Inline['position'] + $Inline['extent']);
-
- $unexaminedText = $text;
-
- $markerPosition = 0;
-
- continue 2;
- }
-
- $unexaminedText = substr($excerpt, 1);
-
- $markerPosition ++;
- }
-
- $markup .= $this->unmarkedText($text);
-
- return $markup;
- }
-
- #
- # ~
- #
-
- protected function inlineCode($Excerpt)
- {
- $marker = $Excerpt['text'][0];
-
- if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(? strlen($matches[0]),
- 'element' => array(
- 'name' => 'code',
- 'text' => $text,
- ),
- );
- }
- }
-
- protected function inlineEmailTag($Excerpt)
- {
- if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
- {
- $url = $matches[1];
-
- if ( ! isset($matches[2]))
- {
- $url = 'mailto:' . $url;
- }
-
- return array(
- 'extent' => strlen($matches[0]),
- 'element' => array(
- 'name' => 'a',
- 'text' => $matches[1],
- 'attributes' => array(
- 'href' => $url,
- ),
- ),
- );
- }
- }
-
- protected function inlineEmphasis($Excerpt)
- {
- if ( ! isset($Excerpt['text'][1]))
- {
- return;
- }
-
- $marker = $Excerpt['text'][0];
-
- if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
- {
- $emphasis = 'strong';
- }
- elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
- {
- $emphasis = 'em';
- }
- else
- {
- return;
- }
-
- return array(
- 'extent' => strlen($matches[0]),
- 'element' => array(
- 'name' => $emphasis,
- 'handler' => 'line',
- 'text' => $matches[1],
- ),
- );
- }
-
- protected function inlineEscapeSequence($Excerpt)
- {
- if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
- {
- return array(
- 'markup' => $Excerpt['text'][1],
- 'extent' => 2,
- );
- }
- }
-
- protected function inlineImage($Excerpt)
- {
- if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
- {
- return;
- }
-
- $Excerpt['text']= substr($Excerpt['text'], 1);
-
- $Link = $this->inlineLink($Excerpt);
-
- if ($Link === null)
- {
- return;
- }
-
- $Inline = array(
- 'extent' => $Link['extent'] + 1,
- 'element' => array(
- 'name' => 'img',
- 'attributes' => array(
- 'src' => $Link['element']['attributes']['href'],
- 'alt' => $Link['element']['text'],
- ),
- ),
- );
-
- $Inline['element']['attributes'] += $Link['element']['attributes'];
-
- unset($Inline['element']['attributes']['href']);
-
- return $Inline;
- }
-
- protected function inlineLink($Excerpt)
- {
- $Element = array(
- 'name' => 'a',
- 'handler' => 'line',
- 'text' => null,
- 'attributes' => array(
- 'href' => null,
- 'title' => null,
- ),
- );
-
- $extent = 0;
-
- $remainder = $Excerpt['text'];
-
- if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
- {
- $Element['text'] = $matches[1];
-
- $extent += strlen($matches[0]);
-
- $remainder = substr($remainder, $extent);
- }
- else
- {
- return;
- }
-
- if (preg_match('/^[(]((?:[^ (]|[(][^ )]+[)])+)(?:[ ]+("[^"]+"|\'[^\']+\'))?[)]/', $remainder, $matches))
- {
- $Element['attributes']['href'] = $matches[1];
-
- if (isset($matches[2]))
- {
- $Element['attributes']['title'] = substr($matches[2], 1, - 1);
- }
-
- $extent += strlen($matches[0]);
- }
- else
- {
- if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
- {
- $definition = $matches[1] ? $matches[1] : $Element['text'];
- $definition = strtolower($definition);
-
- $extent += strlen($matches[0]);
- }
- else
- {
- $definition = strtolower($Element['text']);
- }
-
- if ( ! isset($this->DefinitionData['Reference'][$definition]))
- {
- return;
- }
-
- $Definition = $this->DefinitionData['Reference'][$definition];
-
- $Element['attributes']['href'] = $Definition['url'];
- $Element['attributes']['title'] = $Definition['title'];
- }
-
- $Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']);
-
- return array(
- 'extent' => $extent,
- 'element' => $Element,
- );
- }
-
- protected function inlineMarkup($Excerpt)
- {
- if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
- {
- return;
- }
-
- if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
- {
- return array(
- 'markup' => $matches[0],
- 'extent' => strlen($matches[0]),
- );
- }
-
- if ($Excerpt['text'][1] === '!' and preg_match('/^/s', $Excerpt['text'], $matches))
- {
- return array(
- 'markup' => $matches[0],
- 'extent' => strlen($matches[0]),
- );
- }
-
- if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
- {
- return array(
- 'markup' => $matches[0],
- 'extent' => strlen($matches[0]),
- );
- }
- }
-
- protected function inlineSpecialCharacter($Excerpt)
- {
- if ($Excerpt['text'][0] === '&' and ! preg_match('/^?\w+;/', $Excerpt['text']))
- {
- return array(
- 'markup' => '&',
- 'extent' => 1,
- );
- }
-
- $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
-
- if (isset($SpecialCharacter[$Excerpt['text'][0]]))
- {
- return array(
- 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
- 'extent' => 1,
- );
- }
- }
-
- protected function inlineStrikethrough($Excerpt)
- {
- if ( ! isset($Excerpt['text'][1]))
- {
- return;
- }
-
- if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
- {
- return array(
- 'extent' => strlen($matches[0]),
- 'element' => array(
- 'name' => 'del',
- 'text' => $matches[1],
- 'handler' => 'line',
- ),
- );
- }
- }
-
- protected function inlineUrl($Excerpt)
- {
- if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
- {
- return;
- }
-
- if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
- {
- $Inline = array(
- 'extent' => strlen($matches[0][0]),
- 'position' => $matches[0][1],
- 'element' => array(
- 'name' => 'a',
- 'text' => $matches[0][0],
- 'attributes' => array(
- 'href' => $matches[0][0],
- ),
- ),
- );
-
- return $Inline;
- }
- }
-
- protected function inlineUrlTag($Excerpt)
- {
- if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
- {
- $url = str_replace(array('&', '<'), array('&', '<'), $matches[1]);
-
- return array(
- 'extent' => strlen($matches[0]),
- 'element' => array(
- 'name' => 'a',
- 'text' => $url,
- 'attributes' => array(
- 'href' => $url,
- ),
- ),
- );
- }
- }
-
- #
- # ~
-
- protected $unmarkedInlineTypes = array("\n" => 'Break', '://' => 'Url');
-
- # ~
-
- protected function unmarkedText($text)
- {
- if ($this->breaksEnabled)
- {
- $text = preg_replace('/[ ]*\n/', "
\n", $text);
- }
- else
- {
- $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "
\n", $text);
- $text = str_replace(" \n", "\n", $text);
- }
-
- return $text;
- }
-
- #
- # Handlers
- #
-
- protected function element(array $Element)
- {
- $markup = '<'.$Element['name'];
-
- if (isset($Element['attributes']))
- {
- foreach ($Element['attributes'] as $name => $value)
- {
- if ($value === null)
- {
- continue;
- }
-
- $markup .= ' '.$name.'="'.$value.'"';
- }
- }
-
- if (isset($Element['text']))
- {
- $markup .= '>';
-
- if (isset($Element['handler']))
- {
- $markup .= $this->{$Element['handler']}($Element['text']);
- }
- else
- {
- $markup .= $Element['text'];
- }
-
- $markup .= ''.$Element['name'].'>';
- }
- else
- {
- $markup .= ' />';
- }
-
- return $markup;
- }
-
- protected function elements(array $Elements)
- {
- $markup = '';
-
- foreach ($Elements as $Element)
- {
- $markup .= "\n" . $this->element($Element);
- }
-
- $markup .= "\n";
-
- return $markup;
- }
-
- # ~
-
- protected function li($lines)
- {
- $markup = $this->lines($lines);
-
- $trimmedMarkup = trim($markup);
-
- if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '')
- {
- $markup = $trimmedMarkup;
- $markup = substr($markup, 3);
-
- $position = strpos($markup, "
");
-
- $markup = substr_replace($markup, '', $position, 4);
- }
-
- return $markup;
- }
-
- #
- # Deprecated Methods
- #
-
- function parse($text)
- {
- $markup = $this->text($text);
-
- return $markup;
- }
-
- #
- # Static Methods
- #
-
- static function instance($name = 'default')
- {
- if (isset(self::$instances[$name]))
- {
- return self::$instances[$name];
- }
-
- $instance = new self();
-
- self::$instances[$name] = $instance;
-
- return $instance;
- }
-
- private static $instances = array();
-
- #
- # Fields
- #
-
- protected $DefinitionData;
-
- #
- # Read-Only
-
- protected $specialCharacters = array(
- '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
- );
-
- protected $StrongRegex = array(
- '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
- '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
- );
-
- protected $EmRegex = array(
- '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
- '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
- );
-
- protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
-
- protected $voidElements = array(
- 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
- );
-
- protected $textLevelElements = array(
- 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
- 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
- 'i', 'rp', 'del', 'code', 'strike', 'marquee',
- 'q', 'rt', 'ins', 'font', 'strong',
- 's', 'tt', 'sub', 'mark',
- 'u', 'xm', 'sup', 'nobr',
- 'var', 'ruby',
- 'wbr', 'span',
- 'time',
- );
-}
diff --git a/inc/update-checker/vendor/PucReadmeParser.php b/inc/update-checker/vendor/PucReadmeParser.php
index 1f5cec9..a794c49 100755
--- a/inc/update-checker/vendor/PucReadmeParser.php
+++ b/inc/update-checker/vendor/PucReadmeParser.php
@@ -241,7 +241,11 @@ class PucReadmeParser {
}
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 = trim($text);
return $text;