Compare commits

..

104 Commits

Author SHA1 Message Date
Yahnis Elsts 68a70bf887
Merge pull request #602 from hisman/add-autoupdate-field-to-plugininfo
Add an optional `autoupdate` field to plugin update info that allows automatically installing updates
2026-01-09 16:38:05 +02:00
Hisman 36f3c2be5b Add default value to the autoupdate field 2026-01-03 18:45:10 +07:00
Hisman 4f87723b6a Add autoupdate field to plugin update info 2025-12-29 22:58:03 +07:00
Yahnis Elsts 07a4c2586f
Merge pull request #601 from seatonjiang/master
Update Simplified Chinese (zh_CN) translations
2025-11-21 16:33:49 +02:00
Seaton Jiang 572bfe0986
feat: update Simplified Chinese (zh_CN) translations 2025-11-21 10:58:21 +08:00
Yahnis Elsts 288f270d8e
Merge pull request #600 from alexclassroom/master
Add translations for zh_TW
2025-09-25 17:42:01 +03:00
Alex Lion 69d30a9c17
Add zh_TW Language Pack based on 5.6 2025-09-19 14:23:24 -07:00
Yahnis Elsts 8add8143a2 Merge branch 'master' of https://github.com/YahnisElsts/plugin-update-checker 2025-07-22 14:38:19 +03:00
Yahnis Elsts 5dfd5e5d1e Replace wp_redirect() with wp_safe_redirect()
This redirect always goes back to the "Plugins" page on the same site, so this should be fine.

Reported in #597
2025-07-22 14:27:13 +03:00
Yahnis Elsts e39f84488e Replace all htmlentities() calls with esc_html()
This avoids the need to explicitly specify the flags and the character set. WordPress will use predefined flags and detect the character set used by the site.

Prompted by #597
2025-07-22 14:23:12 +03:00
Yahnis Elsts dbe1a66274
Merge pull request #596 from aljvdi/upgrade-improve-persian-language
Update Persian translation
2025-06-13 17:57:13 +03:00
Alex Javadi b2cbbd98dd
feat: update and improve Persian translations after 9 years 2025-06-12 23:54:49 +01:00
Yahnis Elsts 60ec73fddc Minor: Update year in license block. 2025-05-22 16:13:04 +03:00
Yahnis Elsts a2db6871de Minor: Update POT file
No new translations, just making sure the file names and line numbers are still correct.
2025-05-20 15:29:01 +03:00
Yahnis Elsts dc93f32388 Bump version number to 5.6 2025-05-20 15:20:21 +03:00
Yahnis Elsts 9f890f5cfd
Merge pull request #593 from todeveni/bc-php84-deprecations
Fix PHP 8.4 deprecation errors pt. 2
2025-04-30 15:48:27 +03:00
Toni Viemerö 46ee454f68 Fix PHP 8.4 deprecation errors
Remove type declarations for parameters that are nullable to get rid of
deprecation errors in a backwards compatible way.
2025-04-29 17:53:45 +03:00
Yahnis Elsts 73e6281e43
Merge pull request #584 from urosevic/master
Add Serbian (Cyrillic) (sr_RS) translation
2024-12-09 17:47:56 +02:00
Aleksandar Urosevic 8f54e73dea
Add Serbian (Cyrillic) language 2024-12-09 12:29:01 +01:00
Yahnis Elsts 845d65da93 Minor: Update POT file.
No new strings, just updated line numbers and such.
2024-10-16 17:25:00 +03:00
Yahnis Elsts c74a3bcde2 Bump version number to 5.5 2024-10-16 17:14:29 +03:00
Yahnis Elsts 70f3c80c81 Minor: Fix grammar in a comment 2024-10-16 17:12:01 +03:00
Yahnis Elsts 8d785d75ac Rename filter that removes plugin/theme from data sent to wp.org API
See #578
2024-10-16 16:35:25 +03:00
Yahnis Elsts dce70db088
Minor: Fix a couple of typos
One out by @robertdevore in #580, the other I noticed myself while fixing the first one.
2024-10-15 12:35:22 +03:00
Yahnis Elsts 93a17f984c Minor: Suppress phpcs warning about changing HTTP request timeouts.
This code doesn't actually modify timeouts.
2024-10-14 19:26:28 +03:00
Yahnis Elsts 7c907e7629 Polish #579 for #578 and improve theme compatibility
Probably needs testing, especially for themes.
2024-10-14 19:23:53 +03:00
Yahnis Elsts ea8de31ebd
Merge pull request #579 from DavidAnderson684/patch-1
Remove plugin/theme data from update requests to api.wordpress.org
2024-10-14 18:08:29 +03:00
David Anderson a622b0047a
Update UpdateChecker.php - add check 2024-10-12 18:21:50 +00:00
David Anderson cc5c8d9eca
Update UpdateChecker.php - filter unwanted data to api.wordpress.org 2024-10-12 15:47:10 +00:00
Yahnis Elsts dfc396c011 Minor: Remove unnecessary doc comment
It seems PhpStorm no longer complains about the "skin" property.
2024-07-06 19:56:43 +03:00
Yahnis Elsts 432e7d5f1a Minor: Fix code style 2024-07-06 19:55:40 +03:00
Yahnis Elsts 668e416c98
Merge pull request #574 from MehbubRashid/master
Fix the remote source directory structure if files are at the archive root instead in a subdirectory
2024-07-06 19:50:07 +03:00
Mehbub Rashid 1dd70e99f0
Fix the remote source folder structure if necessary.
It re-structures and corrects the folder/zip structure of the extracted remote zip folder - if not correct already.
2024-07-06 13:46:47 +06:00
Yahnis Elsts 3b1becb956
Merge pull request #573 from seatonjiang/master
Update Simplified Chinese (zh_CN) translation
2024-05-21 18:36:47 +03:00
Seaton Jiang 1a040ee4bb
feat: update Simplified Chinese (zh_CN) translations 2024-05-18 00:12:19 +08:00
Yahnis Elsts 040a2ef658 Add Greek translation by @theo-gk 2024-05-10 18:24:45 +03:00
Yahnis Elsts 97dfe23d15 Debug Bar: Display "Check Now" and "Request Info" in front end
By default, these buttons are generated using the get_submit_button() API function, but that function is only available in the admin dashboard (unless explicitly loaded). Previously, the buttons were not shown in the front end.

This patch adds a fallback that generates the buttons directly. These won't look exactly the same as admin buttons due to admin styles not being loaded, and WP may change submit button HTML at some point, but the fallback buttons should still work.

Fixes #568
2024-03-20 18:33:33 +02:00
Yahnis Elsts e8e53e6d98 Minor: Update copyright year 2024-02-24 11:56:49 +02:00
Yahnis Elsts 1ee425c37b Bump version number to 5.4 2024-02-24 11:54:53 +02:00
Yahnis Elsts a1445bb8dc Minor: Fix misleading doc-comment and argument name.
Previously, triggerUpdateCheckOnce() was attached to a transient filter, but that's no longer the case. Now it's passed directly to WP_CLI::add_hook().

However, it still takes and returns a value. WP-CLI documentation says that the `before_invoke:<command>` hook takes one argument and acts as a filter.
2024-02-02 16:07:07 +02:00
Yahnis Elsts 36efab0022 Minor: Fix method name in a comment 2024-02-02 15:59:22 +02:00
Yahnis Elsts a211943884 WP-CLI: Maybe check for updates when certain WP-CLI commands run
See #558. Needs testing.
2024-02-02 15:58:59 +02:00
Yahnis Elsts c1bf33e770 Fix a potential autoloading failure due to not using a FQN in class_exists()
Fixes #557
2024-01-20 21:07:24 +02:00
Yahnis Elsts 0a8fd4ad3a
Merge pull request #546 from szepeviktor/fix-exports
Stop exporting development files
2024-01-19 15:40:36 +02:00
Yahnis Elsts 5f251be064 Add more sanity checks to prevent PUC from inadvertently triggering a fatal error if one of its hook callbacks is called while the containing plugin/theme is being deleted.
PUC already used `upgrader_process_complete` to remove hooks when  the plugin version it was part of was deleted during an update. However, that did not catch more obscure situations, such as apparently being called from an unrelated AJAX request while the host plugin version was being deleted (a user sent a stack trace where it seems that was what happened).
2023-11-15 18:49:00 +02:00
Yahnis Elsts 9c1bddcd46 Fix (probably) a conflict with the "WP Last Modified Info" plugin, version 1.8.8.
When a plugin update overwrites PUC with a different version of PUC, the hook callbacks registered by the old version can trigger fatal errors when they try to autoload now-deleted PHP files. Normally, PUC avoids this by using an `upgrader_process_complete` hook to check if one of its files still exists, and removing the hooks if the file is missing.  

However, it appears that WP Last Modified Info has its own `upgrader_process_complete` callback that runs earlier. That callback tries to download plugin metadata, which indirectly triggers some PUC hooks, and leads to the fatal error(s) mentioned earlier.

Fixed by extracting the relevant part of  `upgraderProcessComplete` to a separate method and registering that method as a callback for the same hook, but with an earlier priority (1 instead of 11). It appears that WP Last Modified Info uses the default priority: 10.
2023-11-14 11:52:30 +02:00
Yahnis Elsts 0b6bd7cd32 Bump version number to 5.3 2023-11-09 10:34:00 +02:00
Viktor Szépe 90e055ecd3 Stop exporting development files 2023-10-27 13:47:19 +00:00
Yahnis Elsts 00774ef3d9 Add an additional check to the Debug Bar integration to avoid triggering a fatal error in the unusual situation where `Debug_Bar` exists and `Debug_Bar_Panel` does not.
This should never happen with the Debug Bar plugin itself. However, it's apparently possible if Query Monitor is involved. See #543
2023-10-20 16:40:52 +03:00
Yahnis Elsts 0f7296123e Minor: Fix typo 2023-08-23 20:26:40 +03:00
Yahnis Elsts b9aa17be21 Add a sanity check to reject VCS updates that don't have a version number.
This can happen when PUC is configured to use a branch (as opposed to tags or releases) and it fails to retrieve the main plugin file from the repository, e.g. due to API rate limits. Then it can't get the "Version" header from the main plugin file.

See #526
2023-08-23 20:24:28 +03:00
Yahnis Elsts 5a270988c5 Minor: Update copyright year in the license 2023-08-17 15:44:32 +03:00
Yahnis Elsts 565a071b59 Bump version number to 5.2 2023-08-17 15:42:19 +03:00
Yahnis Elsts ad59ffe9a3 Add `__get`/`__set`/etc methods to the Metadata class.
Update metadata can include additional, arbitrary fields such as request statistics, licence information, and so on. This data was stored as dynamic properties on Metadata subclasses, which triggered a deprecation notice in PHP 8.2. Fixed by explicitly storing dynamic fields in a new protected property and adding magic methods to access/modify those fields.

Fixes #536
2023-06-16 14:11:14 +03:00
Yahnis Elsts 48b03e93c9 Bump version number to 5.1 2023-05-20 14:55:43 +03:00
Yahnis Elsts 98f17e4d14 Fix bad directory name 2023-05-20 14:49:27 +03:00
Yahnis Elsts 8e2e6a3b34 Minor: Quote file names passed to git 2023-05-20 14:47:06 +03:00
Yahnis Elsts fcf85abaec Fix version number not being updated in the main file 2023-05-20 14:45:30 +03:00
Yahnis Elsts ddce4cd388 Update the loader file name in composer.json 2023-05-20 14:40:30 +03:00
Yahnis Elsts 53535fd83a Fix version numbers (not) being changed in places
JSON files in the `examples` directory should not change, but the .pot file should,
2023-05-20 14:28:21 +03:00
Yahnis Elsts 10404db947 Minor: Line endings CRLF -> LF 2023-05-20 14:26:46 +03:00
Yahnis Elsts 345778385c Minor: Add a version bump completion message 2023-05-20 14:20:34 +03:00
Yahnis Elsts eddade3ebb Hopefully fix some cmd argument quoting bugs 2023-05-20 14:18:10 +03:00
Yahnis Elsts 01c1565344 Add a script for bumping the version number
WIP, needs more testing.
2023-05-20 14:13:43 +03:00
Yahnis Elsts 579d537926 Add a PHPCS configuration and fix or silence all current warnings/errors
The main functional change is that PUC will now use shorter HTTP request timeouts when not running inside a Cron task. This is to comply with the WP VIP coding standard that strongly recommends a maximum timeout of 3 seconds.

Prompted by #107
2023-05-01 12:28:55 +03:00
Yahnis Elsts a42e1e7346 Use wp_strip_all_tags() instead of strip_tags() when available
Supposedly, it's better at stripping the contents of <script> and <style> tags.
2023-05-01 12:22:04 +03:00
Yahnis Elsts ebf5bc21a0 Revert accidentally committed TODO
This reverts commit 573467a543.
2023-03-08 19:29:08 +02:00
Yahnis Elsts 573467a543 Use the same KO component for CheckBox and the toggle checkbox. 2023-03-08 19:23:53 +02:00
Yahnis Elsts c86ce6ef9f Better check to see if the update creation method exists.
Based on a user report, there are cases where just checking if the *class* exists is not sufficient.
2023-01-17 21:15:38 +02:00
Yahnis Elsts 7457e85680
Merge pull request #513 from liedekef/patch-1
Fix release asset filtering bug and treat `main` as a default branch.
2023-01-03 17:05:04 +02:00
Franky Van Liedekerke 75c05617ec
Also allow "main" as branch for github assets
When setting
$myUpdateChecker->setBranch('main');
the setting enableReleaseAssets was ignored. But since on newer versions "main" is the default (and not "master"), it should allow it.
2023-01-01 22:34:49 +01:00
Franky Van Liedekerke 2fb701089d
Fix GitHub assets
array_filter keeps the index, so if the asset matching has index 1, an array with key 1 is returned. However, further down, $matchingAssets[0] is always used. This will then fail. Using array_values after array_filter resets the indexes on the array from 0, solving the problem.
2023-01-01 22:26:25 +01:00
Yahnis Elsts 304020175d Minor: Fix grammar mistake in an error message 2022-12-01 17:38:30 +02:00
Yahnis Elsts c4bf64eca4 Add a way to filter GitHub and Gitlab releases.
The filter is applied when trying to get the latest release from a VCS repository. Inspired by #506.

Example of filtering releases by the version number: 
```php
//Allow only beta versions (e.g. for testing).
$updateChecker->getVcsApi()->setReleaseVersionFilter(
    '/beta/i', //Regex for the version number.
    Api::RELEASE_FILTER_ALL, //Disables the default filter(s).
    30 //Max number of recent releases to scan for matches.
);
```

Alternatively, you can use a callback to implement custom filtering rules. 
```php
//Set an arbitrary custom filter.
$updateChecker->getVcsApi()->setReleaseFilter(
    function($versionNumber, $releaseObject) {
        /* 
        Put your custom logic here. The $releaseObject variable contains
        the release data returned by the GitHub/GitLab API. The format
        will vary depending on which service you're using.
        */
        return true;
    },
    Api::RELEASE_FILTER_ALL
);
```

Setting a new filter will override any previous filters, so you can't add a regex-based version filter and a custom callback at the same time.
2022-11-17 18:26:23 +02:00
Yahnis Elsts affb44665f Refactor release asset support.
The GitLab release asset implementation was unnecessarily complex and did not match the coding style of the rest of the project (it was provided by an external contributor, and I didn't feel like rewriting it at the time). With the recent change of requiring PHP 5.6 as the minimum version, it's now possible to extract most of the asset logic into a new trait.

This also provided the opportunity to add an undocumented way to *require* that a release have assets:
`enableReleaseAssets('optional-regex', Vcs\Api::REQUIRE_RELEASE_ASSETS)`  

Prompted by #505
2022-11-08 18:29:37 +02:00
Yahnis Elsts 81be284da7 Fix inconsistent directory separators in the autoloader.
It looks like this was the cause of a version 5.0 bug reported in #378.
2022-10-28 20:46:32 +03:00
Yahnis Elsts 32f0079038 Minor: Fix incorrect class name in a doc comment 2022-10-28 14:01:49 +03:00
Yahnis Elsts 9bb19e44e2 Minor: Update ToC 2022-10-16 22:13:03 +03:00
Yahnis Elsts 594ea2012b Add basic migration instructions and fix incorrect class name in a couple of code samples. 2022-10-16 22:11:55 +03:00
Yahnis Elsts c5d9af3480 Minor: Switch multiple URLs to HTTPS 2022-10-15 21:00:58 +03:00
Yahnis Elsts b85b82f82d Fixed deprecation notice related to htmlentities.
The notice: "Passing null to parameter #1 ($string) of type string is deprecated". This could be triggered because some update fields can be null, like the upgrade notice field.
2022-10-15 20:58:18 +03:00
Yahnis Elsts a680a49789 Replace old class name with namespaced class name.
Also, we don't need the explicit "use" statement in this file because relative names work fine.
2022-10-15 00:27:46 +03:00
Yahnis Elsts e25b45339e Fix minor alignment issues with code sample 2022-10-15 00:18:00 +03:00
Yahnis Elsts 30f6fe7875 WIP: Update readme to use namespaces 2022-10-15 00:12:48 +03:00
Yahnis Elsts 3960de8391 Minor: Change URL to HTTPS 2022-10-14 19:48:52 +03:00
Yahnis Elsts 749f33c5c4 Fixed many WPCS warnings
This fixes or explicitly ignores most - but not all - coding standard issues that are reported when running PHP_CodeSniffer with the basic WordPress ruleset and the WordPress-VIP ruleset. 

Notably, one of the issues that remain is the request timeout for update requests and VCS API requests. The current default is 10 seconds, but the WordPress-VIP standards appear to require 3 seconds or less. Personally, I'm not sure if that low limit is appropriate for requests that are intended to mostly run in Cron jobs.
2022-10-14 19:37:00 +03:00
Yahnis Elsts 6c9fce0887 Minor: Remove unnecessary PHP version check.
PHP 5.6 is now the minimum supported version.
2022-10-13 20:12:41 +03:00
Yahnis Elsts 44baf224b8 When saving cached updates, set the library prefix to just the namespace.
This means that previously cached updates can't be loaded by this version, but that should be fine. The cache will just get updated the next time PUC checks for updates.
2022-10-13 20:07:00 +03:00
Yahnis Elsts bec5c00e89 Minor: Remove obsolete code that was originally added for PHP 5.3 compatibility 2022-10-13 17:50:14 +03:00
Yahnis Elsts 0784d3fff2 Fix non-napespaced class name in requestInfo 2022-10-13 17:49:29 +03:00
Yahnis Elsts ac3c24029c Fix own version detection 2022-10-13 17:48:49 +03:00
Yahnis Elsts d86f4f4b94 Minor: Remove some unreachable code.
trigger_error() should stop execution when the error type is E_USER_ERROR.
2022-10-09 18:52:41 +03:00
Yahnis Elsts 2b97a8f712 Extract common VCS update checker stuff into a new to reduce code duplication. 2022-10-09 18:46:36 +03:00
Yahnis Elsts 2dbb2baff1 Bump the version number in Debug Bar HTML.
Technically, this is not necessary because that part of the library hasn't really changed, but let's use the same version number everywhere for consistency.
2022-10-09 00:58:18 +03:00
Yahnis Elsts 4b6127f0f2 Put all^ PUC classes in namespaces.
^ Except dependencies like Parsedown.

The readme is now out of date. The legacy version of Parsedown was removed because we no longer need to support PHP versions older than 5.3. The stub file that loads ParsedownModern.php stays in place because it has the "class_exists" check.
2022-10-08 23:15:37 +03:00
Yahnis Elsts 90bee76fa9 Minor: Fix incorrect version number in class name 2022-10-08 20:09:29 +03:00
Yahnis Elsts 0d4d717cde Bump version number to 5.0 2022-10-08 20:07:42 +03:00
Yahnis Elsts 1372e6fa7d Increase minimum PHP version to 5.6.20
This matches the minimum requirements for WordPress 6.0.2, which is currently the latest WP release. WordPress usage stats say that less than 3% of users are on PHP versions older than this.
2022-10-08 19:56:29 +03:00
Yahnis Elsts 8a82397a6e Minor: Remove some redundant IDE notice suppressions. 2022-09-06 15:14:17 +03:00
Yahnis Elsts adbfa5dd3a Add a way to filter VCS update detection strategies
Example: 
```
$bitbucketPluginChecker->addFilter('vcs_update_detection_strategies', function($strategies) {
 	//Don't look for a "Stable tag" header in readme.txt.
 	unset($strategies['stable_tag']);
 	return $strategies;
});
```

To make this possible, the chooseReference() method was refactored into something that more closely resembles a "chain of responsibility" pattern. Instead of a tree of "if" conditions, it now gets an array of callables from another method, and it calls each of those in order until it gets a non-empty VCS reference.

You can filter this array to remove specific strategies, or even to add your own. Note that the item order matters.

Required PHP version was increased to 5.4 because some "strategies" take an argument and some don't, and I would rather just use closures for that than something more complex.

Coincidentally, testing this change revealed a bug where the HTTP filter name was not initialized correctly: it was missing the $slug. That should also be fixed now. 

Prompted by #378
2022-09-06 15:13:15 +03:00
Yahnis Elsts 5b863c26bd Fix a potential PHP notice when detecting a VCS service
In the (unlikely) case where the update metadata URL does not include a path, the getVcsService() method could previously trigger a deprecation notice like "preg_match(): Passing null to parameter #2 ($subject) of type string is deprecated". This is because parse_url() returns NULL when the specified component is not present.

Fixed by always casting the $path to string. The VCS detection code doesn't care about the difference between "empty path" and "no path" - it should correctly return NULL (= no VCS host found) anyway.

Also, let's cast $host to a string as well to avoid another potential notice if the URL somehow has a path but no domain name.

Initially reported in #499.
2022-08-06 17:29:44 +03:00
Yahnis Elsts 6eb27a6911 Bump version to 4.13
Also updated the POT file. No new strings, but some of the source code references were out of date.
2022-07-29 15:36:25 +03:00
Yahnis Elsts 3347254e0d Fail-safe when update class cannot be correctly reconstructed or loaded.
Previously, if the wrong base class name was written to the database, attempts to load update information could trigger a warning because there was no class_exists() check in the "updateBaseClass is set" branch. To fix that, I've moved the class_exists() closer to the place where the class name is actually used.

StateStore will still fail to load a stored update if the class name is invalid, but without a PHP warning this time. The invalid stored update information should be overwritten the next time PUC checks for updates.
2022-07-28 16:01:14 +03:00
Yahnis Elsts b4c5a82cc8 Fix (hopefully) a warning when loading update details stored by a different version of PUC that was also using a custom namespace.
Reported in #498.
2022-07-28 14:57:21 +03:00
70 changed files with 2204 additions and 2590 deletions

6
.gitattributes vendored Normal file
View File

@ -0,0 +1,6 @@
/.editorconfig export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/build/ export-ignore
/examples/ export-ignore
/phpcs.xml export-ignore

View File

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

View File

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

View File

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

View File

@ -1,38 +0,0 @@
<?php
if ( !class_exists('Puc_v4p12_DebugBar_PluginPanel', false) ):
class Puc_v4p12_DebugBar_PluginPanel extends Puc_v4p12_DebugBar_Panel {
/**
* @var Puc_v4p12_Plugin_UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Plugin file', htmlentities($this->updateChecker->pluginFile));
parent::displayConfigHeader();
}
protected function getMetadataButton() {
$requestInfoButton = '';
if ( function_exists('get_submit_button') ) {
$requestInfoButton = get_submit_button(
'Request Info',
'secondary',
'puc-request-info-button',
false,
array('id' => $this->updateChecker->getUniqueName('request-info-button'))
);
}
return $requestInfoButton;
}
protected function getUpdateFields() {
return array_merge(
parent::getUpdateFields(),
array('homepage', 'upgrade_notice', 'tested',)
);
}
}
endif;

View File

@ -1,21 +0,0 @@
<?php
if ( !class_exists('Puc_v4p12_DebugBar_ThemePanel', false) ):
class Puc_v4p12_DebugBar_ThemePanel extends Puc_v4p12_DebugBar_Panel {
/**
* @var Puc_v4p12_Theme_UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Theme directory', htmlentities($this->updateChecker->directoryName));
parent::displayConfigHeader();
}
protected function getUpdateFields() {
return array_merge(parent::getUpdateFields(), array('details_url'));
}
}
endif;

10
Puc/v5/PucFactory.php Normal file
View File

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

86
Puc/v5p6/Autoloader.php Normal file
View File

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

View File

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

View File

@ -1,9 +1,12 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar_Panel', false) ):
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker;
class Puc_v4p12_DebugBar_Panel extends Debug_Bar_Panel {
/** @var Puc_v4p12_UpdateChecker */
if ( !class_exists(Panel::class, false) && class_exists('Debug_Bar_Panel', false) ):
class Panel extends \Debug_Bar_Panel {
/** @var UpdateChecker */
protected $updateChecker;
private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
@ -20,7 +23,7 @@ if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar
public function render() {
printf(
'<div class="puc-debug-bar-panel-v4" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">',
'<div class="puc-debug-bar-panel-v5" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">',
esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')),
esc_attr($this->updateChecker->slug),
esc_attr($this->updateChecker->getUniqueName('uid')),
@ -38,11 +41,11 @@ if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar
echo '<h3>Configuration</h3>';
echo '<table class="puc-debug-data">';
$this->displayConfigHeader();
$this->row('Slug', htmlentities($this->updateChecker->slug));
$this->row('DB option', htmlentities($this->updateChecker->optionName));
$this->row('Slug', esc_html($this->updateChecker->slug));
$this->row('DB option', esc_html($this->updateChecker->optionName));
$requestInfoButton = $this->getMetadataButton();
$this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
$this->row('Metadata URL', esc_html($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
$scheduler = $this->updateChecker->scheduler;
if ( $scheduler->checkPeriod > 0 ) {
@ -83,14 +86,22 @@ if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar
echo '<h3>Status</h3>';
echo '<table class="puc-debug-data">';
$state = $this->updateChecker->getUpdateState();
$checkNowButton = '';
$checkButtonId = $this->updateChecker->getUniqueName('check-now-button');
if ( function_exists('get_submit_button') ) {
$checkNowButton = get_submit_button(
'Check Now',
'secondary',
'puc-check-now-button',
false,
array('id' => $this->updateChecker->getUniqueName('check-now-button'))
array('id' => $checkButtonId)
);
} else {
//get_submit_button() is not available in the frontend. Make a button directly.
//It won't look the same without admin styles, but it should still work.
$checkNowButton = sprintf(
'<input type="button" id="%1$s" name="puc-check-now-button" value="%2$s" class="button button-secondary" />',
esc_attr($checkButtonId),
esc_attr('Check Now')
);
}
@ -104,10 +115,10 @@ if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar
$this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck));
if ( $state->getCheckedVersion() !== '' ) {
$this->row('Checked version', htmlentities($state->getCheckedVersion()));
$this->row('Checked version', esc_html($state->getCheckedVersion()));
$this->row('Cached update', $state->getUpdate());
}
$this->row('Update checker class', htmlentities(get_class($this->updateChecker)));
$this->row('Update checker class', esc_html(get_class($this->updateChecker)));
echo '</table>';
}
@ -119,7 +130,10 @@ if ( !class_exists('Puc_v4p12_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) ? esc_html($update->$field) : null
);
}
}
echo '</table>';
@ -154,11 +168,18 @@ if ( !class_exists('Puc_v4p12_DebugBar_Panel', false) && class_exists('Debug_Bar
public function row($name, $value) {
if ( is_object($value) || is_array($value) ) {
$value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
//This is specifically for debugging, so print_r() is fine.
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
$value = '<pre>' . esc_html(print_r($value, true)) . '</pre>';
} else if ($value === null) {
$value = '<code>null</code>';
}
printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value);
printf(
'<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>',
esc_html($name),
//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped above.
$value
);
}
}

View File

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

View File

@ -0,0 +1,47 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
use YahnisElsts\PluginUpdateChecker\v5p6\Plugin\UpdateChecker;
if ( !class_exists(PluginPanel::class, false) ):
class PluginPanel extends Panel {
/**
* @var UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Plugin file', esc_html($this->updateChecker->pluginFile));
parent::displayConfigHeader();
}
protected function getMetadataButton() {
$buttonId = $this->updateChecker->getUniqueName('request-info-button');
if ( function_exists('get_submit_button') ) {
$requestInfoButton = get_submit_button(
'Request Info',
'secondary',
'puc-request-info-button',
false,
array('id' => $buttonId)
);
} else {
$requestInfoButton = sprintf(
'<input type="button" name="puc-request-info-button" id="%1$s" value="%2$s" class="button button-secondary" />',
esc_attr($buttonId),
esc_attr('Request Info')
);
}
return $requestInfoButton;
}
protected function getUpdateFields() {
return array_merge(
parent::getUpdateFields(),
array('homepage', 'upgrade_notice', 'tested',)
);
}
}
endif;

View File

@ -0,0 +1,25 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
use YahnisElsts\PluginUpdateChecker\v5p6\Theme\UpdateChecker;
if ( !class_exists(ThemePanel::class, false) ):
class ThemePanel extends Panel {
/**
* @var UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Theme directory', esc_html($this->updateChecker->directoryName));
parent::displayConfigHeader();
}
protected function getUpdateFields() {
return array_merge(parent::getUpdateFields(), array('details_url'));
}
}
endif;

View File

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

View File

@ -1,5 +1,11 @@
<?php
if ( !class_exists('Puc_v4p12_Metadata', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use LogicException;
use stdClass;
use WP_Error;
if ( !class_exists(Metadata::class, false) ):
/**
* A base container for holding information about updates and plugin metadata.
@ -8,7 +14,13 @@ if ( !class_exists('Puc_v4p12_Metadata', false) ):
* @copyright 2016
* @access public
*/
abstract class Puc_v4p12_Metadata {
abstract class Metadata {
/**
* Additional dynamic properties, usually copied from the API response.
*
* @var array<string,mixed>
*/
protected $extraProperties = array();
/**
* Create an instance of this class from a JSON document.
@ -17,7 +29,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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;

View File

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

View File

@ -1,9 +1,14 @@
<?php
if ( !class_exists('Puc_v4p12_Plugin_Package', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
class Puc_v4p12_Plugin_Package extends Puc_v4p12_InstalledPackage {
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\PucFactory;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/**
* @var Puc_v4p12_Plugin_UpdateChecker
* @var UpdateChecker
*/
protected $updateChecker;
@ -46,7 +51,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Package', false) ):
//This can happen if the filename points to something that is not a plugin.
$this->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_v4p12_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_v4p12_Plugin_Package', false) ):
$pluginPath = realpath($this->pluginAbsolutePath);
//If realpath() fails, just normalize the syntax instead.
if (($muPluginDir === false) || ($pluginPath === false)) {
$muPluginDir = Puc_v4p12_Factory::normalizePath(WPMU_PLUGIN_DIR);
$pluginPath = Puc_v4p12_Factory::normalizePath($this->pluginAbsolutePath);
$muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
$pluginPath = PucFactory::normalizePath($this->pluginAbsolutePath);
}
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);

View File

@ -1,5 +1,9 @@
<?php
if ( !class_exists('Puc_v4p12_Plugin_Info', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\Metadata;
if ( !class_exists(PluginInfo::class, false) ):
/**
* A container class for holding and transforming various plugin metadata.
@ -8,7 +12,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Info', false) ):
* @copyright 2016
* @access public
*/
class Puc_v4p12_Plugin_Info extends Puc_v4p12_Metadata {
class PluginInfo extends Metadata {
//Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning.
public $name;
@ -35,6 +39,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Info', false) ):
public $downloaded;
public $active_installs;
public $last_updated;
public $autoupdate = false;
public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
@ -64,8 +69,8 @@ if ( !class_exists('Puc_v4p12_Plugin_Info', false) ):
/**
* Very, very basic validation.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
* @param \StdClass $apiResponse
* @return bool|\WP_Error
*/
protected function validateMetadata($apiResponse) {
if (
@ -73,7 +78,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Info', false) ):
|| empty($apiResponse->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 +93,7 @@ if ( !class_exists('Puc_v4p12_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.

View File

@ -1,14 +1,16 @@
<?php
if ( !class_exists('Puc_v4p12_Plugin_Ui', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
if ( !class_exists(Ui::class, false) ):
/**
* Additional UI elements for plugins.
*/
class Puc_v4p12_Plugin_Ui {
class Ui {
private $updateChecker;
private $manualCheckErrorTransient = '';
/**
* @param Puc_v4p12_Plugin_UpdateChecker $updateChecker
* @param UpdateChecker $updateChecker
*/
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
@ -172,7 +174,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Ui', false) ):
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;
@ -185,7 +187,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Ui', false) ):
}
}
wp_redirect(add_query_arg(
wp_safe_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->updateChecker->slug,
@ -204,8 +206,9 @@ if ( !class_exists('Puc_v4p12_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 = '';
@ -221,16 +224,29 @@ if ( !class_exists('Puc_v4p12_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(
'<div class="notice %s is-dismissible"><p>%s</p>%s</div>',
$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
}
/**
@ -254,11 +270,11 @@ if ( !class_exists('Puc_v4p12_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 ) {

View File

@ -1,5 +1,9 @@
<?php
if ( !class_exists('Puc_v4p12_Plugin_Update', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
/**
* A simple container class for holding information about an available update.
@ -8,7 +12,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Update', false) ):
* @copyright 2016
* @access public
*/
class Puc_v4p12_Plugin_Update extends Puc_v4p12_Update {
class Update extends BaseUpdate {
public $id = 0;
public $homepage;
public $upgrade_notice;
@ -16,22 +20,23 @@ if ( !class_exists('Puc_v4p12_Plugin_Update', false) ):
public $requires_php = false;
public $icons = array();
public $filename; //Plugin filename relative to the plugins directory.
public $autoupdate = false;
protected static $extraFields = array(
'id', 'homepage', 'tested', 'requires_php', 'upgrade_notice', 'icons', 'filename',
'id', 'homepage', 'tested', 'requires_php', 'upgrade_notice', 'icons', 'filename', 'autoupdate',
);
/**
* Create a new instance of PluginUpdate from its JSON-encoded representation.
*
* @param string $json
* @return Puc_v4p12_Plugin_Update|null
* @return self|null
*/
public static function fromJson($json){
//Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about.
$pluginInfo = Puc_v4p12_Plugin_Info::fromJson($json);
$pluginInfo = PluginInfo::fromJson($json);
if ( $pluginInfo !== null ) {
return self::fromPluginInfo($pluginInfo);
} else {
@ -43,18 +48,18 @@ if ( !class_exists('Puc_v4p12_Plugin_Update', false) ):
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another.
*
* @param Puc_v4p12_Plugin_Info $info
* @return Puc_v4p12_Plugin_Update
* @param PluginInfo $info
* @return static
*/
public static function fromPluginInfo($info){
return self::fromObject($info);
return static::fromObject($info);
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param StdClass|Puc_v4p12_Plugin_Info|Puc_v4p12_Plugin_Update $object The source object.
* @return Puc_v4p12_Plugin_Update The new copy.
* @param \StdClass|PluginInfo|self $object The source object.
* @return self The new copy.
*/
public static function fromObject($object) {
$update = new self();
@ -82,6 +87,7 @@ if ( !class_exists('Puc_v4p12_Plugin_Update', false) ):
$update->tested = $this->tested;
$update->requires_php = $this->requires_php;
$update->plugin = $this->filename;
$update->autoupdate = $this->autoupdate;
if ( !empty($this->upgrade_notice) ) {
$update->upgrade_notice = $this->upgrade_notice;

View File

@ -1,5 +1,12 @@
<?php
if ( !class_exists('Puc_v4p12_Plugin_UpdateChecker', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
/**
* A custom plugin update checker.
@ -8,16 +15,16 @@ if ( !class_exists('Puc_v4p12_Plugin_UpdateChecker', false) ):
* @copyright 2018
* @access public
*/
class Puc_v4p12_Plugin_UpdateChecker extends Puc_v4p12_UpdateChecker {
class UpdateChecker extends BaseUpdateChecker {
protected $updateTransient = 'update_plugins';
protected $translationType = 'plugin';
protected $componentType = 'plugin';
public $pluginAbsolutePath = ''; //Full path of the main plugin file.
public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
/**
* @var Puc_v4p12_Plugin_Package
* @var Package
*/
protected $package;
@ -50,8 +57,8 @@ if ( !class_exists('Puc_v4p12_Plugin_UpdateChecker', false) ):
if ( $slugUsedBy ) {
$this->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_v4p12_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_v4p12_Plugin_Ui($this);
$this->extraUi = new Ui($this);
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p12_Scheduler
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
$scheduler = new Puc_v4p12_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_v4p12_Plugin_UpdateChecker', false) ):
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return Puc_v4p12_Plugin_Info
* @return PluginInfo
*/
public function requestInfo($queryArgs = array()) {
list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p12_Plugin_Info', 'request_info', $queryArgs);
list($pluginInfo, $result) = $this->requestMetadata(
PluginInfo::class,
'request_info',
$queryArgs
);
if ( $pluginInfo !== null ) {
/** @var Puc_v4p12_Plugin_Info $pluginInfo */
/** @var PluginInfo $pluginInfo */
$pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug;
}
@ -142,9 +153,9 @@ if ( !class_exists('Puc_v4p12_Plugin_UpdateChecker', false) ):
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses PluginUpdateChecker::requestInfo()
* @uses UpdateChecker::requestInfo()
*
* @return Puc_v4p12_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_v4p12_Plugin_UpdateChecker', false) ):
if ( $pluginInfo === null ){
return null;
}
$update = Puc_v4p12_Plugin_Update::fromPluginInfo($pluginInfo);
$update = Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update);
@ -197,9 +208,9 @@ if ( !class_exists('Puc_v4p12_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_v4p12_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_v4p12_Plugin_UpdateChecker', false) ):
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'compatibility' => new stdClass(),
'compatibility' => new \stdClass(),
)
);
}
@ -255,7 +266,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_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_v4p12_Plugin_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4p12_Plugin_Update|null
* @return Update|null
*/
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) ) {
/** @var Puc_v4p12_Plugin_Update $update */
/** @var Update $update */
$update->filename = $this->pluginFile;
}
return $update;
@ -391,20 +402,20 @@ if ( !class_exists('Puc_v4p12_Plugin_UpdateChecker', false) ):
}
protected function createDebugBarExtension() {
return new Puc_v4p12_DebugBar_PluginExtension($this);
return new DebugBar\PluginExtension($this);
}
/**
* Create a package instance that represents this plugin or theme.
*
* @return Puc_v4p12_InstalledPackage
* @return InstalledPackage
*/
protected function createInstalledPackage() {
return new Puc_v4p12_Plugin_Package($this->pluginAbsolutePath, $this);
return new Package($this->pluginAbsolutePath, $this);
}
/**
* @return Puc_v4p12_Plugin_Package
* @return Package
*/
public function getInstalledPackage() {
return $this->package;

View File

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

View File

@ -1,11 +1,13 @@
<?php
if ( !class_exists('Puc_v4p12_Scheduler', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(Scheduler::class, false) ):
/**
* The scheduler decides when and how often to check for updates.
* It calls @see Puc_v4p12_UpdateChecker::checkForUpdates() to perform the actual checks.
* It calls @see UpdateChecker::checkForUpdates() to perform the actual checks.
*/
class Puc_v4p12_Scheduler {
class Scheduler {
public $checkPeriod = 12; //How often to check for updates (in hours).
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
public $throttledCheckPeriod = 72;
@ -13,7 +15,7 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
protected $hourlyCheckHooks = array('load-update.php');
/**
* @var Puc_v4p12_UpdateChecker
* @var UpdateChecker
*/
protected $updateChecker;
@ -22,7 +24,7 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
/**
* Scheduler constructor.
*
* @param Puc_v4p12_UpdateChecker $updateChecker
* @param UpdateChecker $updateChecker
* @param int $checkPeriod How often to check for updates (in hours).
* @param array $hourlyHooks
*/
@ -47,13 +49,22 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
} else {
//Use a custom cron schedule.
$scheduleName = 'every' . $this->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,12 +80,14 @@ if ( !class_exists('Puc_v4p12_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) {
add_action($hook, array($this, 'maybeCheckForUpdates'));
}
//This hook fires after a bulk update is complete.
add_action('upgrader_process_complete', array($this, 'removeHooksIfLibraryGone'), 1, 0);
add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2);
} else {
@ -84,18 +97,11 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
}
/**
* Runs upon the WP action upgrader_process_complete.
* Remove all hooks if this version of PUC has been deleted or overwritten.
*
* 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 array $upgradeInfo extra information about the upgrade
* Callback for the "upgrader_process_complete" action.
*/
public function upgraderProcessComplete(
/** @noinspection PhpUnusedParameterInspection */
$upgrader, $upgradeInfo
) {
public function removeHooksIfLibraryGone() {
//Cancel all further actions if the current version of PUC has been deleted or overwritten
//by a different version during the upgrade. If we try to do anything more in that situation,
//we could trigger a fatal error by trying to autoload a deleted class.
@ -103,9 +109,22 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
if ( !file_exists(__FILE__) ) {
$this->removeHooks();
$this->updateChecker->removeHooks();
return;
}
}
/**
* Runs upon the WP action upgrader_process_complete.
*
* 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 array $upgradeInfo extra information about the upgrade
*/
public function upgraderProcessComplete(
/** @noinspection PhpUnusedParameterInspection */
$upgrader, $upgradeInfo
) {
//Sanity check and limitation to relevant types.
if (
!is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
@ -116,7 +135,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_Theme_UpdateChecker') ) {
if ( is_a($this->updateChecker, Theme\UpdateChecker::class) ) {
if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
return;
}
@ -130,7 +149,7 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
}
}
if ( is_a($this->updateChecker, 'Puc_v4p12_Plugin_UpdateChecker') ) {
if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
return;
}
@ -168,6 +187,21 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
$state = $this->updateChecker->getUpdateState();
$shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
if ( $shouldCheck ) {
//Sanity check: Do not proceed if one of the critical classes is missing.
//That can happen - theoretically and extremely rarely - if maybeCheckForUpdates()
//is called before the old version of our plugin has been fully deleted, or
//called from an independent AJAX request during deletion.
if ( !(
class_exists(Utils::class)
&& class_exists(Metadata::class)
&& class_exists(Plugin\Update::class)
&& class_exists(Theme\Update::class)
) ) {
return;
}
}
//Let plugin authors substitute their own algorithm.
$shouldCheck = apply_filters(
$this->updateChecker->getUniqueName('check_now'),
@ -198,7 +232,7 @@ if ( !class_exists('Puc_v4p12_Scheduler', false) ):
//Check less frequently if it's already known that an update is available.
$period = $this->throttledCheckPeriod * 3600;
} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
//WordPress cron schedules are not exact, so lets do an update check even
//WordPress cron schedules are not exact, so let's do an update check even
//if slightly less than $checkPeriod hours have elapsed since the last check.
$cronFuzziness = 20 * 60;
$period = $this->checkPeriod * 3600 - $cronFuzziness;

View File

@ -1,8 +1,9 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4p12_StateStore', false) ):
if ( !class_exists(StateStore::class, false) ):
class Puc_v4p12_StateStore {
class StateStore {
/**
* @var int Last update check timestamp.
*/
@ -14,7 +15,7 @@ if ( !class_exists('Puc_v4p12_StateStore', false) ):
protected $checkedVersion = '';
/**
* @var Puc_v4p12_Update|null Cached update.
* @var Update|null Cached update.
*/
protected $update = null;
@ -65,7 +66,7 @@ if ( !class_exists('Puc_v4p12_StateStore', false) ):
}
/**
* @return null|Puc_v4p12_Update
* @return null|Update
*/
public function getUpdate() {
$this->lazyLoad();
@ -73,10 +74,10 @@ if ( !class_exists('Puc_v4p12_StateStore', false) ):
}
/**
* @param Puc_v4p12_Update|null $update
* @param Update|null $update
* @return $this
*/
public function setUpdate(Puc_v4p12_Update $update = null) {
public function setUpdate($update = null) {
$this->lazyLoad();
$this->update = $update;
return $this;
@ -127,7 +128,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_StateStore', false) ):
$updateClass = get_class($this->update);
$state->updateClass = $updateClass;
$prefix = $this->getLibPrefix();
if ( Puc_v4p12_Utils::startsWith($updateClass, $prefix) ) {
if ( Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix));
}
}
@ -162,15 +163,20 @@ if ( !class_exists('Puc_v4p12_StateStore', false) ):
$state = get_site_option($this->optionName, null);
if ( !is_object($state) ) {
if (
!is_object($state)
//Sanity check: If the Utils class is missing, the plugin is probably in the process
//of being deleted (e.g. the old version gets deleted during an update).
|| !class_exists(Utils::class)
) {
$this->lastCheck = 0;
$this->checkedVersion = '';
$this->update = null;
return;
}
$this->lastCheck = intval(Puc_v4p12_Utils::get($state, 'lastCheck', 0));
$this->checkedVersion = Puc_v4p12_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 +186,13 @@ if ( !class_exists('Puc_v4p12_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 +206,8 @@ if ( !class_exists('Puc_v4p12_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__ . '\\';
}
}

View File

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

View File

@ -1,8 +1,12 @@
<?php
if ( !class_exists('Puc_v4p12_Theme_Update', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
class Puc_v4p12_Theme_Update extends Puc_v4p12_Update {
use YahnisElsts\PluginUpdateChecker\v5p6\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
class Update extends BaseUpdate {
public $details_url = '';
protected static $extraFields = array('details_url');
@ -44,8 +48,8 @@ if ( !class_exists('Puc_v4p12_Theme_Update', false) ):
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param StdClass|Puc_v4p12_Theme_Update $object The source object.
* @return Puc_v4p12_Theme_Update The new copy.
* @param \StdClass|self $object The source object.
* @return self The new copy.
*/
public static function fromObject($object) {
$update = new self();
@ -56,14 +60,14 @@ if ( !class_exists('Puc_v4p12_Theme_Update', false) ):
/**
* Basic validation.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
* @param \StdClass $apiResponse
* @return bool|\WP_Error
*/
protected function validateMetadata($apiResponse) {
$required = array('version', 'details_url');
foreach($required as $key) {
if ( !isset($apiResponse->$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)
);

View File

@ -1,11 +1,18 @@
<?php
if ( !class_exists('Puc_v4p12_Theme_UpdateChecker', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
class Puc_v4p12_Theme_UpdateChecker extends Puc_v4p12_UpdateChecker {
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
class UpdateChecker extends BaseUpdateChecker {
protected $filterSuffix = 'theme';
protected $updateTransient = 'update_themes';
protected $translationType = 'theme';
protected $componentType = 'theme';
/**
* @var string Theme directory name.
@ -39,13 +46,13 @@ if ( !class_exists('Puc_v4p12_Theme_UpdateChecker', false) ):
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @return Puc_v4p12_Update|null An instance of Update, or NULL when no updates are available.
* @return Update|null An instance of Update, or NULL when no updates are available.
*/
public function requestUpdate() {
list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p12_Theme_Update', 'request_update');
list($themeUpdate, $result) = $this->requestMetadata(Update::class, 'request_update');
if ( $themeUpdate !== null ) {
/** @var Puc_v4p12_Theme_Update $themeUpdate */
/** @var Update $themeUpdate */
$themeUpdate->slug = $this->slug;
}
@ -71,16 +78,16 @@ if ( !class_exists('Puc_v4p12_Theme_UpdateChecker', false) ):
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p12_Scheduler
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
return new Puc_v4p12_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_v4p12_Theme_UpdateChecker', false) ):
}
protected function createDebugBarExtension() {
return new Puc_v4p12_DebugBar_Extension($this, 'Puc_v4p12_DebugBar_ThemePanel');
return new DebugBar\Extension($this, DebugBar\ThemePanel::class);
}
/**
@ -142,10 +149,10 @@ if ( !class_exists('Puc_v4p12_Theme_UpdateChecker', false) ):
/**
* Create a package instance that represents this plugin or theme.
*
* @return Puc_v4p12_InstalledPackage
* @return InstalledPackage
*/
protected function createInstalledPackage() {
return new Puc_v4p12_Theme_Package($this->stylesheet, $this);
return new Package($this->stylesheet, $this);
}
}

View File

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

View File

@ -1,11 +1,24 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
use stdClass;
use WP_Error;
abstract class Puc_v4p12_UpdateChecker {
if ( !class_exists(UpdateChecker::class, false) ):
abstract class UpdateChecker {
protected $filterSuffix = '';
protected $updateTransient = '';
protected $translationType = ''; //"plugin" or "theme".
/**
* @var string This can be "plugin" or "theme".
*/
protected $componentType = '';
/**
* @var string Currently the same as $componentType, but this is an implementation detail that
* depends on how WP works internally, and could therefore change.
*/
protected $translationType = '';
/**
* Set to TRUE to enable error reporting. Errors are raised using trigger_error()
@ -36,22 +49,22 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
public $slug = '';
/**
* @var Puc_v4p12_InstalledPackage
* @var InstalledPackage
*/
protected $package;
/**
* @var Puc_v4p12_Scheduler
* @var Scheduler
*/
public $scheduler;
/**
* @var Puc_v4p12_UpgraderStatus
* @var UpgraderStatus
*/
protected $upgraderStatus;
/**
* @var Puc_v4p12_StateStore
* @var StateStore
*/
protected $updateState;
@ -66,10 +79,15 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
protected $cachedMetadataHost = 0;
/**
* @var Puc_v4p12_DebugBar_Extension|null
* @var DebugBar\Extension|null
*/
protected $debugBarExtension = null;
/**
* @var WpCliCheckTrigger|null
*/
protected $wpCliCheckTrigger = null;
public function __construct($metadataUrl, $directoryName, $slug = null, $checkPeriod = 12, $optionName = '') {
$this->debugMode = (bool)(constant('WP_DEBUG'));
$this->metadataUrl = $metadataUrl;
@ -87,10 +105,14 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
}
}
if ( empty($this->translationType) ) {
$this->translationType = $this->componentType;
}
$this->package = $this->createInstalledPackage();
$this->scheduler = $this->createScheduler($checkPeriod);
$this->upgraderStatus = new Puc_v4p12_UpgraderStatus();
$this->updateState = new Puc_v4p12_StateStore($this->optionName);
$this->upgraderStatus = new UpgraderStatus();
$this->updateState = new StateStore($this->optionName);
if ( did_action('init') ) {
$this->loadTextDomain();
@ -99,6 +121,10 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
}
$this->installHooks();
if ( ($this->wpCliCheckTrigger === null) && defined('WP_CLI') ) {
$this->wpCliCheckTrigger = new WpCliCheckTrigger($this->componentType, $this->scheduler);
}
}
/**
@ -145,6 +171,10 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
//Allow HTTP requests to the metadata URL even if it's on a local host.
add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
//Potentially exclude information about this entity from core update check requests to api.wordpress.org.
//phpcs:ignore WordPressVIPMinimum.Hooks.RestrictedHooks.http_request_args -- Doesn't modify timeouts.
add_filter('http_request_args', array($this, 'excludeEntityFromWordPressAPI'), 10, 2);
//DebugBar integration.
if ( did_action('plugins_loaded') ) {
$this->maybeInitDebugBar();
@ -166,6 +196,7 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
remove_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10);
remove_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10);
remove_filter('http_request_args', array($this, 'excludeEntityFromWordPressAPI'));
remove_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
remove_action('init', array($this, 'loadTextDomain'));
@ -206,7 +237,7 @@ if ( !class_exists('Puc_v4p12_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 +249,12 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
/**
* Create a package instance that represents this plugin or theme.
*
* @return Puc_v4p12_InstalledPackage
* @return InstalledPackage
*/
abstract protected function createInstalledPackage();
/**
* @return Puc_v4p12_InstalledPackage
* @return InstalledPackage
*/
public function getInstalledPackage() {
return $this->package;
@ -236,14 +267,84 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
* and substitute their own scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p12_Scheduler
* @return Scheduler
*/
abstract protected function createScheduler($checkPeriod);
/**
* Remove information about this plugin or theme from the requests that WordPress core sends
* to api.wordpress.org when checking for updates.
*
* @param array $args
* @param string $url
* @return array
*/
public function excludeEntityFromWordPressAPI($args, $url) {
//Is this an api.wordpress.org update check request?
$parsedUrl = wp_parse_url($url);
if ( !isset($parsedUrl['host']) || (strtolower($parsedUrl['host']) !== 'api.wordpress.org') ) {
return $args;
}
$typePluralised = $this->componentType . 's';
$expectedPathPrefix = '/' . $typePluralised . '/update-check/1.'; //e.g. "/plugins/update-check/1.1/"
if ( !isset($parsedUrl['path']) || !Utils::startsWith($parsedUrl['path'], $expectedPathPrefix) ) {
return $args;
}
//Plugins and themes can disable this feature by using the filter below.
if ( !apply_filters(
$this->getUniqueName('remove_from_default_update_checks'),
true, $this, $args, $url
) ) {
return $args;
}
if ( empty($args['body'][$typePluralised]) ) {
return $args;
}
$reportingItems = json_decode($args['body'][$typePluralised], true);
if ( $reportingItems === null ) {
return $args;
}
//The list of installed items uses different key formats for plugins and themes.
//Luckily, we can reuse the getUpdateListKey() method here.
$updateListKey = $this->getUpdateListKey();
if ( isset($reportingItems[$typePluralised][$updateListKey]) ) {
unset($reportingItems[$typePluralised][$updateListKey]);
}
if ( !empty($reportingItems['active']) ) {
if ( is_array($reportingItems['active']) ) {
foreach ($reportingItems['active'] as $index => $relativePath) {
if ( $relativePath === $updateListKey ) {
unset($reportingItems['active'][$index]);
}
}
//Re-index the array.
$reportingItems['active'] = array_values($reportingItems['active']);
} else if ( $reportingItems['active'] === $updateListKey ) {
//For themes, the "active" field is a string that contains the theme's directory name.
//Pretend that the default theme is active so that we don't reveal the actual theme.
if ( defined('WP_DEFAULT_THEME') ) {
$reportingItems['active'] = WP_DEFAULT_THEME;
}
//Unfortunately, it doesn't seem to be documented if we can safely remove the "active"
//key. So when we don't know the default theme, we'll just leave it as is.
}
}
$args['body'][$typePluralised] = wp_json_encode($reportingItems);
return $args;
}
/**
* Check for updates. The results are stored in the DB option specified in $optionName.
*
* @return Puc_v4p12_Update|null
* @return Update|null
*/
public function checkForUpdates() {
$installedVersion = $this->getInstalledVersion();
@ -277,7 +378,7 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
/**
* Load the update checker state from the DB.
*
* @return Puc_v4p12_StateStore
* @return StateStore
*/
public function getUpdateState() {
return $this->updateState->lazyLoad();
@ -302,7 +403,7 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4p12_Update|null
* @return Update|null
*/
public function getUpdate() {
$update = $this->updateState->getUpdate();
@ -323,16 +424,17 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
*
* Subclasses should run the update through filterUpdateResult before returning it.
*
* @return Puc_v4p12_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_v4p12_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_v4p12_Update
* @return T
*/
protected function filterUpdateResult($update, $httpResult = null) {
//Let plugins/themes modify the update.
@ -355,9 +457,9 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
* "Compatibility: Unknown".
* The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to".
*
* @param Puc_v4p12_Metadata|null $update
* @param Metadata|null $update
*/
protected function fixSupportedWordpressVersion(Puc_v4p12_Metadata $update = null) {
protected function fixSupportedWordpressVersion($update = null) {
if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) {
return;
}
@ -427,7 +529,8 @@ if ( !class_exists('Puc_v4p12_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 +565,7 @@ if ( !class_exists('Puc_v4p12_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 +618,8 @@ if ( !class_exists('Puc_v4p12_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 +646,9 @@ if ( !class_exists('Puc_v4p12_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 +661,8 @@ if ( !class_exists('Puc_v4p12_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 +675,8 @@ if ( !class_exists('Puc_v4p12_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 +738,10 @@ if ( !class_exists('Puc_v4p12_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<Update> $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_v4p12_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get().
* @return array<Metadata|null, array|WP_Error> A metadata instance and the value returned by wp_remote_get().
*/
protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) {
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
@ -654,7 +757,7 @@ if ( !class_exists('Puc_v4p12_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',
),
@ -670,12 +773,12 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
$result = wp_remote_get($url, $options);
$result = apply_filters($this->getUniqueName('request_metadata_http_result'), $result, $url, $options);
//Try to parse the response
$status = $this->validateApiResponse($result);
$metadata = null;
if ( !is_wp_error($status) ){
if ( version_compare(PHP_VERSION, '5.3', '>=') && (strpos($metaClass, '\\') === false) ) {
if ( (strpos($metaClass, '\\') === false) ) {
$metaClass = __NAMESPACE__ . '\\' . $metaClass;
}
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
@ -879,12 +982,12 @@ if ( !class_exists('Puc_v4p12_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) ) {
@ -896,25 +999,62 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
return $source;
}
//Fix the remote source structure if necessary.
//The update archive should contain a single directory that contains the rest of plugin/theme files.
//Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource).
//We can't rename $remoteSource because that would break WordPress code that cleans up temporary files
//after update.
if ( $this->isBadDirectoryStructure($remoteSource) ) {
//Create a new directory using the plugin slug.
$newDirectory = trailingslashit($remoteSource) . $this->slug . '/';
if ( !$wp_filesystem->is_dir($newDirectory) ) {
$wp_filesystem->mkdir($newDirectory);
//Move all files to the newly created directory.
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) {
$sourceFiles = array_keys($sourceFiles);
$allMoved = true;
foreach ($sourceFiles as $filename) {
//Skip our newly created folder.
if ( $filename === $this->slug ) {
continue;
}
$previousSource = trailingslashit($remoteSource) . $filename;
$newSource = trailingslashit($newDirectory) . $filename;
if ( !$wp_filesystem->move($previousSource, $newSource, true) ) {
$allMoved = false;
break;
}
}
if ( $allMoved ) {
//Rename source.
$source = $newDirectory;
} else {
//Delete our newly created folder including all files in it.
$wp_filesystem->rmdir($newDirectory, true);
//And return a relevant error.
return new WP_Error(
'puc-incorrect-directory-structure',
sprintf(
'The directory structure of the update was incorrect. All files should be inside ' .
'a directory named <span class="code">%s</span>, not at the root of the ZIP archive. Plugin Update Checker tried to fix the directory structure, but failed.',
esc_html($this->slug)
)
);
}
}
}
}
//Rename the source to match the existing directory.
$correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/';
if ( $source !== $correctedSource ) {
//The update archive should contain a single directory that contains the rest of plugin/theme files.
//Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource).
//We can't rename $remoteSource because that would break WordPress code that cleans up temporary files
//after update.
if ( $this->isBadDirectoryStructure($remoteSource) ) {
return new WP_Error(
'puc-incorrect-directory-structure',
sprintf(
'The directory structure of the update is incorrect. All files should be inside ' .
'a directory named <span class="code">%s</span>, not at the root of the ZIP archive.',
htmlentities($this->slug)
)
);
}
/** @var WP_Upgrader_Skin $upgrader ->skin */
$upgrader->skin->feedback(sprintf(
'Renaming %s to %s&#8230;',
'<span class="code">' . basename($source) . '</span>',
@ -938,7 +1078,7 @@ if ( !class_exists('Puc_v4p12_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);
@ -952,7 +1092,7 @@ if ( !class_exists('Puc_v4p12_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) ) {
@ -974,19 +1114,23 @@ if ( !class_exists('Puc_v4p12_UpdateChecker', false) ):
* Initialize the update checker Debug Bar plugin/add-on thingy.
*/
public function maybeInitDebugBar() {
if ( class_exists('Debug_Bar', false) && file_exists(dirname(__FILE__) . '/DebugBar') ) {
if (
class_exists('Debug_Bar', false)
&& class_exists('Debug_Bar_Panel', false)
&& file_exists(dirname(__FILE__) . '/DebugBar')
) {
$this->debugBarExtension = $this->createDebugBarExtension();
}
}
protected function createDebugBarExtension() {
return new Puc_v4p12_DebugBar_Extension($this);
return new DebugBar\Extension($this);
}
/**
* Display additional configuration details in the Debug Bar panel.
*
* @param Puc_v4p12_DebugBar_Panel $panel
* @param DebugBar\Panel $panel
*/
public function onDisplayConfiguration($panel) {
//Do nothing. Subclasses can use this to add additional info to the panel.

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,15 @@
<?php
if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
class Puc_v4p12_Vcs_BitBucketApi extends Puc_v4p12_Vcs_Api {
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p6\OAuthSignature;
use YahnisElsts\PluginUpdateChecker\v5p6\Utils;
if ( !class_exists(BitBucketApi::class, false) ):
class BitBucketApi extends Api {
/**
* @var Puc_v4p12_OAuthSignature
* @var OAuthSignature
*/
private $oauth = null;
@ -18,39 +24,32 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
private $repository;
public function __construct($repositoryUrl, $credentials = array()) {
$path = parse_url($repositoryUrl, PHP_URL_PATH);
$path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$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_v4p12_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' || $configBranch === 'main') ) {
$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) {
@ -67,7 +66,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
$ref = $branch->target->hash;
}
return new Puc_v4p12_Vcs_Reference(array(
return new Reference(array(
'name' => $ref,
'updated' => $branch->target->date,
'downloadUrl' => $this->getDownloadUrl($branch->name),
@ -78,7 +77,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4p12_Vcs_Reference|null
* @return Reference|null
*/
public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName);
@ -86,7 +85,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
return null;
}
return new Puc_v4p12_Vcs_Reference(array(
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
@ -97,7 +96,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4p12_Vcs_Reference|null
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/refs/tags?sort=-target.date');
@ -111,7 +110,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
//Return the first result.
if ( !empty($versionTags) ) {
$tag = $versionTags[0];
return new Puc_v4p12_Vcs_Reference(array(
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
@ -125,7 +124,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_Vcs_Reference
* @return null|Reference
*/
protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch);
@ -191,11 +190,11 @@ if ( !class_exists('Puc_v4p12_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_v4p12_Utils::startsWith($url, 'src/');
$isSrcResource = Utils::startsWith($url, 'src/');
$url = implode('/', array(
'https://api.bitbucket.org',
@ -211,7 +210,7 @@ if ( !class_exists('Puc_v4p12_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);
}
@ -234,7 +233,7 @@ if ( !class_exists('Puc_v4p12_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)
);
@ -250,7 +249,7 @@ if ( !class_exists('Puc_v4p12_Vcs_BitBucketApi', false) ):
parent::setAuthentication($credentials);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
$this->oauth = new Puc_v4p12_OAuthSignature(
$this->oauth = new OAuthSignature(
$credentials['consumer_key'],
$credentials['consumer_secret']
);
@ -261,7 +260,7 @@ if ( !class_exists('Puc_v4p12_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);

View File

@ -1,8 +1,15 @@
<?php
if ( !class_exists('Puc_v4p12_Vcs_GitHubApi', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use Parsedown;
if ( !class_exists(GitHubApi::class, false) ):
class GitHubApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
class Puc_v4p12_Vcs_GitHubApi extends Puc_v4p12_Vcs_Api {
/**
* @var string GitHub username.
*/
@ -22,33 +29,18 @@ if ( !class_exists('Puc_v4p12_Vcs_GitHubApi', false) ):
*/
protected $accessToken;
/**
* @var bool Whether to download release assets instead of the auto-generated source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var string|null Regular expression that's used to filter release assets by name. Optional.
*/
protected $assetFilterRegex = null;
/**
* @var string|null The unchanging part of a release asset URL. Used to identify download attempts.
*/
protected $assetApiBaseUrl = null;
/**
* @var bool
*/
private $downloadFilterAdded = false;
public function __construct($repositoryUrl, $accessToken = null) {
$path = parse_url($repositoryUrl, PHP_URL_PATH);
$path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$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_v4p12_Vcs_GitHubApi', false) ):
/**
* Get the latest release from GitHub.
*
* @return Puc_v4p12_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_v4p12_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_v4p12_Vcs_Reference|null
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
@ -124,7 +169,7 @@ if ( !class_exists('Puc_v4p12_Vcs_GitHubApi', false) ):
}
$tag = $versionTags[0];
return new Puc_v4p12_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_v4p12_Vcs_GitHubApi', false) ):
* Get a branch by name.
*
* @param string $branchName
* @return null|Puc_v4p12_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_v4p12_Vcs_GitHubApi', false) ):
return null;
}
$reference = new Puc_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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_v4p12_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());

View File

@ -1,8 +1,13 @@
<?php
if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !class_exists(GitLabApi::class, false) ):
class GitLabApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
class Puc_v4p12_Vcs_GitLabApi extends Puc_v4p12_Vcs_Api {
/**
* @var string GitLab username.
*/
@ -29,29 +34,25 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
protected $accessToken;
/**
* @var bool Whether to download release assets instead of the auto-generated source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var bool Whether to download release asset package rather than release asset source.
* @deprecated
* @var bool No longer used.
*/
protected $releasePackageEnabled = false;
public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) {
//Parse the repository host to support custom hosts.
$port = parse_url($repositoryUrl, PHP_URL_PORT);
$port = wp_parse_url($repositoryUrl, PHP_URL_PORT);
if ( !empty($port) ) {
$port = ':' . $port;
}
$this->repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port;
$this->repositoryHost = wp_parse_url($repositoryUrl, PHP_URL_HOST) . $port;
if ( $this->repositoryHost !== 'gitlab.com' ) {
$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<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
@ -59,7 +60,7 @@ if ( !class_exists('Puc_v4p12_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);
@ -76,7 +77,7 @@ if ( !class_exists('Puc_v4p12_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.
@ -101,83 +102,92 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
/**
* Get the latest release from GitLab.
*
* @return Puc_v4p12_Vcs_Reference|null
* @return Reference|null
*/
public function getLatestRelease() {
$releases = $this->api('/:id/releases');
$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 ( true !== $release->upcoming_release ) {
break 1; //Break the loop on the first release we find that isn't an upcoming release
if (
//Skip invalid/unsupported releases.
!is_object($release)
|| !isset($release->tag_name)
//Skip upcoming releases.
|| (
!empty($release->upcoming_release)
&& $this->shouldSkipPreReleases()
)
) {
continue;
}
}
if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
return null;
}
$reference = new Puc_v4p12_Vcs_Reference(array(
'name' => $release->tag_name,
'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
'downloadUrl' => '',
'updated' => $release->released_at,
'apiResponse' => $release,
));
$download_url = false;
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
if ( $this->releasePackageEnabled && isset($release->assets, $release->assets->links) ) {
/**
* Use the first asset LINK that is a zip format file generated by a Gitlab Release Pipeline
*
* @link https://gist.github.com/timwiel/9dfd3526c768efad4973254085e065ce
*/
foreach ($release->assets->links as $link) {
//TODO: Check the "format" property instead of the URL suffix.
if ( 'zip' === substr($link->url, -3) ) {
$download_url = $link->url;
break 1;
}
//Apply custom filters.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
if ( empty( $download_url ) ) {
$downloadUrl = $this->findReleaseDownloadUrl($release);
if ( empty($downloadUrl) ) {
//The latest release doesn't have valid download URL.
return null;
}
if ( ! empty( $this->accessToken ) ) {
$download_url = add_query_arg('private_token', $this->accessToken, $download_url);
}
$reference->downloadUrl = $download_url;
return $reference;
} elseif ( isset($release->assets) ) {
/**
* Use the first asset SOURCE file that is a zip format from a Gitlab Release which should be a zip file
*/
foreach ($release->assets->sources as $source) {
if ( 'zip' === $source->format ) {
$download_url = $source->url;
break 1;
}
if ( !empty($this->accessToken) ) {
$downloadUrl = add_query_arg('private_token', $this->accessToken, $downloadUrl);
}
if ( empty( $download_url ) ) {
return null;
}
if ( ! empty( $this->accessToken ) ) {
$download_url = add_query_arg('private_token', $this->accessToken, $download_url);
}
$reference->downloadUrl = $download_url;
return $reference;
return new Reference(array(
'name' => $release->tag_name,
'version' => $versionNumber,
'downloadUrl' => $downloadUrl,
'updated' => $release->released_at,
'apiResponse' => $release,
));
}
//If we get this far without a return then obviosuly noi release download urls were found
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_v4p12_Vcs_Reference|null
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/:id/repository/tags');
@ -191,7 +201,7 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
}
$tag = $versionTags[0];
return new Puc_v4p12_Vcs_Reference(array(
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
@ -203,7 +213,7 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
* Get a branch by name.
*
* @param string $branchName
* @return null|Puc_v4p12_Vcs_Reference
* @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName);
@ -211,7 +221,7 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
return null;
}
$reference = new Puc_v4p12_Vcs_Reference(array(
$reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
@ -244,13 +254,13 @@ if ( !class_exists('Puc_v4p12_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);
}
@ -267,7 +277,7 @@ if ( !class_exists('Puc_v4p12_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)
);
@ -353,31 +363,22 @@ if ( !class_exists('Puc_v4p12_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_v4p12_Vcs_Reference
*/
public function chooseReference($configBranch) {
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array();
if ( $configBranch === 'main' || $configBranch === 'master' ) {
//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);
if ( ($configBranch === 'main') || ($configBranch === 'master') ) {
$strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
$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 setAuthentication($credentials) {
@ -385,16 +386,29 @@ if ( !class_exists('Puc_v4p12_Vcs_GitLabApi', false) ):
$this->accessToken = is_string($credentials) ? $credentials : null;
}
public function enableReleaseAssets() {
$this->releaseAssetsEnabled = true;
$this->releasePackageEnabled = false;
}
/**
* 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->releaseAssetsEnabled = false;
$this->releasePackageEnabled = true;
$this->enableReleaseAssets(
/** @lang RegExp */ '/\.zip($|[?&#])/i',
Api::REQUIRE_RELEASE_ASSETS
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->url) ) {
return $releaseAsset->url;
}
return null;
}
}
endif;

View File

@ -1,21 +1,18 @@
<?php
if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
class Puc_v4p12_Vcs_PluginUpdateChecker extends Puc_v4p12_Plugin_UpdateChecker implements Puc_v4p12_Vcs_BaseChecker {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
if ( !class_exists(PluginUpdateChecker::class, false) ):
class PluginUpdateChecker extends Plugin\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/**
* @var Puc_v4p12_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4p12_Vcs_PluginUpdateChecker constructor.
* PluginUpdateChecker constructor.
*
* @param Puc_v4p12_Vcs_Api $api
* @param Api $api
* @param string $pluginFile
* @param string $slug
* @param int $checkPeriod
@ -24,10 +21,11 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
*/
public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$this->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,7 +39,7 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$info = new Puc_v4p12_Plugin_Info();
$info = new Plugin\PluginInfo();
$info->filename = $this->pluginFile;
$info->slug = $this->slug;
@ -67,7 +65,7 @@ if ( !class_exists('Puc_v4p12_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 '
@ -87,6 +85,21 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
$this->setInfoFromHeader($remoteHeader, $info);
}
//Sanity check: Reject updates that don't have a version number.
//This can happen when we're using a branch, and we either fail to retrieve the main plugin
//file or the file doesn't have a "Version" header.
if ( empty($info->version) ) {
do_action(
'puc_api_error',
new \WP_Error(
'puc-no-plugin-version',
'Could not find the version number in the repository.'
),
null, null, $this->slug
);
return null;
}
//Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
//a lot of useful information like the required/tested WP version, changelog, and so on.
if ( $this->readmeTxtExistsLocally() ) {
@ -126,7 +139,7 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
* Copy plugin metadata from a file header to a Plugin Info object.
*
* @param array $fileHeader
* @param Puc_v4p12_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array(
@ -159,7 +172,7 @@ if ( !class_exists('Puc_v4p12_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_v4p12_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
$readme = $this->api->getRemoteReadme($ref);
@ -192,7 +205,7 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
*
* @param Puc_v4p12_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setIconsFromLocalAssets($pluginInfo) {
$icons = $this->getLocalAssetUrls(array(
@ -221,7 +234,7 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-headers
*
* @param Puc_v4p12_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setBannersFromLocalAssets($pluginInfo) {
$banners = $this->getLocalAssetUrls(array(
@ -257,37 +270,6 @@ if ( !class_exists('Puc_v4p12_Vcs_PluginUpdateChecker') ):
return $foundAssets;
}
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;

View File

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

View File

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

View File

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

View File

@ -1,22 +1,19 @@
<?php
if ( !class_exists('Puc_v4p12_Vcs_ThemeUpdateChecker', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
class Puc_v4p12_Vcs_ThemeUpdateChecker extends Puc_v4p12_Theme_UpdateChecker implements Puc_v4p12_Vcs_BaseChecker {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
use YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\Utils;
if ( !class_exists(ThemeUpdateChecker::class, false) ):
class ThemeUpdateChecker extends Theme\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/**
* @var Puc_v4p12_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4p12_Vcs_ThemeUpdateChecker constructor.
* ThemeUpdateChecker constructor.
*
* @param Puc_v4p12_Vcs_Api $api
* @param Api $api
* @param null $stylesheet
* @param null $customSlug
* @param int $checkPeriod
@ -24,10 +21,11 @@ if ( !class_exists('Puc_v4p12_Vcs_ThemeUpdateChecker', false) ):
*/
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
$this->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_v4p12_Vcs_ThemeUpdateChecker', false) ):
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$update = new Puc_v4p12_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_v4p12_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_v4p12_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_v4p12_Utils::findNotEmpty(array(
$update->version = Utils::findNotEmpty(array(
$remoteHeader['Version'],
Puc_v4p12_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_v4p12_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_v4p12_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;

View File

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

View File

@ -0,0 +1,84 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use WP_CLI;
/**
* Triggers an update check when relevant WP-CLI commands are executed.
*
* When WP-CLI runs certain commands like "wp plugin status" or "wp theme list", it calls
* wp_update_plugins() and wp_update_themes() to refresh update information. This class hooks into
* the same commands and triggers an update check when they are executed.
*
* Note that wp_update_plugins() and wp_update_themes() do not perform an update check *every* time
* they are called. They use a context-dependent delay between update checks. Similarly, this class
* calls Scheduler::maybeCheckForUpdates(), which also dynamically decides whether to actually
* run a check. If you want to force an update check, call UpdateChecker::checkForUpdates() instead.
*/
class WpCliCheckTrigger {
/**
* @var Scheduler
*/
private $scheduler;
/**
* @var string 'plugin' or 'theme'
*/
private $componentType;
/**
* @var bool Whether an update check was already triggered during the current request
* or script execution.
*/
private $wasCheckTriggered = false;
public function __construct($componentType, Scheduler $scheduler) {
if ( !in_array($componentType, ['plugin', 'theme']) ) {
throw new \InvalidArgumentException('Invalid component type. Must be "plugin" or "theme".');
}
$this->componentType = $componentType;
$this->scheduler = $scheduler;
if ( !defined('WP_CLI') || !class_exists(WP_CLI::class, false) ) {
return; //Nothing to do if WP-CLI is not available.
}
/*
* We can't hook directly into wp_update_plugins(), but we can hook into the WP-CLI
* commands that call it. We'll use the "before_invoke:xyz" hook to trigger update checks.
*/
foreach ($this->getRelevantCommands() as $command) {
WP_CLI::add_hook('before_invoke:' . $command, [$this, 'triggerUpdateCheckOnce']);
}
}
private function getRelevantCommands() {
$result = [];
foreach (['status', 'list', 'update'] as $subcommand) {
$result[] = $this->componentType . ' ' . $subcommand;
}
return $result;
}
/**
* Trigger a potential update check once.
*
* @param mixed $input
* @return mixed The input value, unchanged.
* @internal This method is public so that it can be used as a WP-CLI hook callback.
* It should not be called directly.
*
*/
public function triggerUpdateCheckOnce($input = null) {
if ( $this->wasCheckTriggered ) {
return $input;
}
$this->wasCheckTriggered = true;
$this->scheduler->maybeCheckForUpdates();
return $input;
}
}

182
README.md
View File

@ -20,6 +20,7 @@ From the users' perspective, it works just like with plugins and themes hosted o
- [How to Release an Update](#how-to-release-an-update-2)
- [GitLab Integration](#gitlab-integration)
- [How to Release a GitLab Update](#how-to-release-a-gitlab-update)
- [Migrating from 4.x](#migrating-from-4x)
- [License Management](#license-management)
- [Resources](#resources)
@ -28,7 +29,7 @@ From the users' perspective, it works just like with plugins and themes hosted o
Getting Started
---------------
*Note:* In each of the below examples, part of the instructions are to create an instance of the update checker class. It's recommended to do this either during the `plugins_loaded` action or outside of any hooks. If you do it only during an `admin_*` action, then updates will not be visible to a wide variety of WordPress maanagement tools; they will only be visible to logged-in users on dashboard pages.
*Note:* In each of the below examples, part of the instructions is to create an instance of the update checker class. It's recommended to do this either during the `plugins_loaded` action or outside of any hooks. If you do it only during an `admin_*` action, then updates will not be visible to a wide variety of WordPress management tools; they will only be visible to logged-in users on dashboard pages.
### Self-hosted Plugins and Themes
@ -40,7 +41,7 @@ Getting Started
{
"name" : "Plugin Name",
"version" : "2.0",
"download_url" : "http://example.com/plugin-name-2.0.zip",
"download_url" : "https://example.com/plugin-name-2.0.zip",
"sections" : {
"description" : "Plugin description here. You can use HTML."
}
@ -53,8 +54,8 @@ Getting Started
```json
{
"version": "2.0",
"details_url": "http://example.com/version-2.0-details.html",
"download_url": "http://example.com/example-theme-2.0.zip"
"details_url": "https://example.com/version-2.0-details.html",
"download_url": "https://example.com/example-theme-2.0.zip"
}
```
@ -64,8 +65,10 @@ Getting Started
```php
require 'path/to/plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'http://example.com/path/to/details.json',
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://example.com/path/to/details.json',
__FILE__, //Full path to the main plugin file or functions.php.
'unique-plugin-or-theme-slug'
);
@ -96,7 +99,9 @@ By default, the library will check the specified URL for changes every 12 hours.
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://github.com/user-name/repo-name/',
__FILE__,
'unique-plugin-or-theme-slug'
@ -127,7 +132,7 @@ This library supports a couple of different ways to release updates on GitHub. P
To release version 1.2.3, create a new Git tag named `v1.2.3` or `1.2.3`. That's it.
PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitHub releases or branches instead.
PUC doesn't require strict adherence to [SemVer](https://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitHub releases or branches instead.
- **Stable branch**
@ -175,7 +180,9 @@ The library will pull update details from the following parts of a release/tag/b
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://bitbucket.org/user-name/repo-name',
__FILE__,
'unique-plugin-or-theme-slug'
@ -214,7 +221,7 @@ BitBucket doesn't have an equivalent to GitHub's releases, so the process is sli
You can skip the "stable tag" bit and just create a new Git tag named `v1.2.3` or `1.2.3`. The update checker will look at the most recent tags and pick the one that looks like the highest version number.
PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions.
PUC doesn't require strict adherence to [SemVer](https://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions.
- **Stable branch**
@ -231,7 +238,9 @@ BitBucket doesn't have an equivalent to GitHub's releases, so the process is sli
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://gitlab.com/user-name/repo-name/',
__FILE__,
'unique-plugin-or-theme-slug'
@ -243,72 +252,109 @@ BitBucket doesn't have an equivalent to GitHub's releases, so the process is sli
Alternatively, if you're using a self-hosted GitLab instance, initialize the update checker like this:
```php
$myUpdateChecker = new Puc_v4p12_Vcs_PluginUpdateChecker(
new Puc_v4p12_Vcs_GitLabApi('https://myserver.com/user-name/repo-name/'),
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: Add setAuthentication(...) and setBranch(...) as shown above.
```
If you're using a self-hosted GitLab instance and [subgroups or nested groups](https://docs.gitlab.com/ce/user/group/subgroups/index.html), you have to tell the update checker which parts of the URL are subgroups:
```php
$myUpdateChecker = new Puc_v4p12_Vcs_PluginUpdateChecker(
new Puc_v4p12_Vcs_GitLabApi('https://myserver.com/group-name/subgroup-level1/subgroup-level2/subgroup-level3/repo-name/', null, 'subgroup-level1/subgroup-level2/subgroup-level3'),
__FILE__,
'unique-plugin-or-theme-slug'
);
```
use YahnisElsts\PluginUpdateChecker\v5p6\Vcs\PluginUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\Vcs\GitLabApi;
$myUpdateChecker = new PluginUpdateChecker(
new GitLabApi('https://myserver.com/user-name/repo-name/'),
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: Add setAuthentication(...) and setBranch(...) as shown above.
```
If you're using a self-hosted GitLab instance and [subgroups or nested groups](https://docs.gitlab.com/ce/user/group/subgroups/index.html), you have to tell the update checker which parts of the URL are subgroups:
```php
use YahnisElsts\PluginUpdateChecker\v5p6\Vcs\PluginUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\Vcs\GitLabApi;
$myUpdateChecker = new PluginUpdateChecker(
new GitLabApi(
'https://myserver.com/group-name/subgroup-level1/subgroup-level2/subgroup-level3/repo-name/',
null,
'subgroup-level1/subgroup-level2/subgroup-level3'
),
__FILE__,
'unique-plugin-or-theme-slug'
);
```
3. Plugins only: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/readme.txt) to your repository. The contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
#### How to Release a GitLab Update
A Gitlab repository can be checked for updates in 4 different ways.
1. **Stable branch** (other than `master` or `main`):
- Point the update checker at any stable, production-ready branch and PUC will periodically check the `Version` header in the main plugin file or `style.css` and display a notification if it's greater than the installed version.
- Add the following code:
```php
//Add the following code to your main plugin file or `functions.php` file to check for updates from a custom branch
$myUpdateChecker->setBranch('stable-branch-name');
```
- Caveats:
- If you set the branch to `main` (the default) or `master` (the historical default), the update checker will look for recent releases and tags first. It'll only use the `main` or `master` branch if it doesn't find anything else suitable.
A GitLab repository can be checked for updates in 3 different ways.
2. **GitLab Releases using Generic Packages**:
- Use a Gitlab CI/CD Pipeline to automatically generate your update on release using a Generic Package. The benefit of using Generic Package assets over the Source Code assets is that the code can already be built and production ready.
- Add the following code:
```php
//Add the following code to your main plugin file or `functions.php` file to check for a new update from releases using generic packages
$myUpdateChecker->getVcsApi()->enableReleasePackages();
```
- PUC will periodically check the release version (i.e. the tag name of the release) and will display a notification if the release is a greater version than the installed version.
- The release tag name should loosely follow [SemVer](http://semver.org/) but these are all valid release names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5` However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitLab branches instead.
- For more information about *Gitlab Release Generic Packages* refer to the following links:
- **GitLab releases**
Create a new release using the "Releases" feature on GitLab. The tag name should match the version number. You can add a `v` prefix to the tag, like `v1.2.3`. Releases that are marked as ["Upcoming Release"](https://docs.gitlab.com/ee/user/project/releases/index.html#upcoming-releases) will be automatically ignored.
If you want to use custom release assets, call the `enableReleaseAssets()` method after creating the update checker instance:
```php
$myUpdateChecker->getVcsApi()->enableReleaseAssets();
```
By default, PUC will use the first available asset link, regardless of type. You can pass a regular expression to `enableReleaseAssets()` to make it pick the first link where the URL matches the regex. For example:
```php
$myUpdateChecker->getVcsApi()->enableReleaseAssets('/\.zip($|[?&#])/i');
```
**Tip:** You can use a Gitlab CI/CD Pipeline to automatically generate your update on release using a Generic Package. For more information about generic packages, refer to the following links:
- [Gitlab CI/CD Release Documentation](https://docs.gitlab.com/ee/user/project/releases/#create-release-from-gitlab-ci)
- [Gitlab Release Assets as Generic Package Documentation](https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs/examples/release-assets-as-generic-package/)
- [Example .gitlab-ci.yml file using Release Generic Packages for generating a update package from the Sensei-LMS wordpress plugin](https://gist.github.com/timwiel/9dfd3526c768efad4973254085e065ce)
- **Tags**
3. **GitLab Releases using Source Code Assets**:
- Create a new release using the "Releases" feature on Gitlab.
- Add the following code:
```php
//Add the following code to your main plugin file or `functions.php` file to check for a new update from releases using release assets
$myUpdateChecker->getVcsApi()->enableReleaseAssets();
```
- PUC will periodically check the release version (based on release tag name) and display a notification if the release version is greater than the installed version.
- The release name should loosely follow [SemVer](http://semver.org/) but these are all valid release names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5` However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitLab branches instead.
To release version 1.2.3, create a new Git tag named `v1.2.3` or `1.2.3`. The update checker will look at recent tags and use the one that looks like the highest version number.
PUC doesn't require strict adherence to [SemVer](https://semver.org/). However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitLab branches instead.
- **Stable branch**
4. **Tags** (this is the default option):
- To release version 1.2.3, create a new Git tag named `v1.2.3` or `1.2.3`.
- Optionally, add the following code:
```php
//Add the following code to your main plugin file or `functions.php` file to check for updates from the default branch
$myUpdateChecker->setBranch('master'); //or 'main'
```
- PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitLab branches instead.
Point the update checker at any stable, production-ready branch:
```php
$myUpdateChecker->setBranch('stable-branch-name');
```
PUC will periodically check the `Version` header in the main plugin file or `style.css` and display a notification if it's greater than the installed version. Caveat: Even if you set the branch to `main` (the default) or `master` (the historical default), the update checker will still look for recent releases and tags first.
Migrating from 4.x
------------------
Older versions of the library didn't use namespaces. Code that was written for those versions will need to be updated to work with the current version. At a minimum, you'll need to change the factory class name.
Old code:
```php
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'https://example.com/info.json',
__FILE__,
'my-slug'
);
```
New code:
```php
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://example.com/info.json',
__FILE__,
'my-slug'
);
```
Other classes have also been renamed, usually by simply removing the `Puc_vXpY_` prefix and converting `Category_Thing` to `Category\Thing`. Here's a table of the most commonly used classes and their new names:
| Old class name | New class name |
|-------------------------------------|----------------------------------------------------------------|
| `Puc_v4_Factory` | `YahnisElsts\PluginUpdateChecker\v5\PucFactory` |
| `Puc_v4p13_Factory` | `YahnisElsts\PluginUpdateChecker\v5p6\PucFactory` |
| `Puc_v4p13_Plugin_UpdateChecker` | `YahnisElsts\PluginUpdateChecker\v5p6\Plugin\UpdateChecker` |
| `Puc_v4p13_Theme_UpdateChecker` | `YahnisElsts\PluginUpdateChecker\v5p6\Theme\UpdateChecker` |
| `Puc_v4p13_Vcs_PluginUpdateChecker` | `YahnisElsts\PluginUpdateChecker\v5p6\Vcs\PluginUpdateChecker` |
| `Puc_v4p13_Vcs_ThemeUpdateChecker` | `YahnisElsts\PluginUpdateChecker\v5p6\Vcs\ThemeUpdateChecker` |
| `Puc_v4p13_Vcs_GitHubApi` | `YahnisElsts\PluginUpdateChecker\v5p6\Vcs\GitHubApi` |
| `Puc_v4p13_Vcs_GitLabApi` | `YahnisElsts\PluginUpdateChecker\v5p6\Vcs\GitLabApi` |
| `Puc_v4p13_Vcs_BitBucketApi` | `YahnisElsts\PluginUpdateChecker\v5p6\Vcs\BitBucketApi` |
License Management
------------------
@ -318,9 +364,9 @@ Currently, the update checker doesn't have any built-in license management featu
Resources
---------
- [This blog post](http://w-shadow.com/blog/2010/09/02/automatic-updates-for-any-plugin/) has more information about the update checker API. *Slightly out of date.*
- [This blog post](https://w-shadow.com/blog/2010/09/02/automatic-updates-for-any-plugin/) has more information about the update checker API. *Slightly out of date.*
- [Debug Bar](https://wordpress.org/plugins/debug-bar/) - useful for testing and debugging the update checker.
- [Update format reference](https://docs.google.com/spreadsheets/d/1eOBbW7Go2qEQXReOOCdidMTf_tDYRq4JfegcO1CBPIs/edit?usp=sharing) - describes all fields supported by the JSON-based update information format used by the update checker. Only covers plugins. Themes use a similar but more limited format.
- [Securing download links](http://w-shadow.com/blog/2013/03/19/plugin-updates-securing-download-links/) - a general overview.
- [A GUI for entering download credentials](http://open-tools.net/documentation/tutorial-automatic-updates.html#wordpress)
- [Theme Update Checker](http://w-shadow.com/blog/2011/06/02/automatic-updates-for-commercial-themes/) - an older, theme-only variant of this update checker.
- [Securing download links](https://w-shadow.com/blog/2013/03/19/plugin-updates-securing-download-links/) - a general overview.
- [A GUI for entering download credentials](https://open-tools.net/documentation/tutorial-automatic-updates.html#wordpress)
- [Theme Update Checker](https://w-shadow.com/blog/2011/06/02/automatic-updates-for-commercial-themes/) - an older, theme-only variant of this update checker.

136
build/bump-version.php Normal file
View File

@ -0,0 +1,136 @@
<?php
function versionToInfix($versionNumber) {
if ( !isValidVersion($versionNumber) ) {
throw new InvalidArgumentException("Invalid version number: $versionNumber");
}
$parts = explode('.', $versionNumber);
return 'v' . $parts[0] . 'p' . $parts[1];
}
function infixToVersion($infix) {
$parts = explode('p', substr($infix, 1));
$version = $parts[0] . '.' . $parts[1];
if ( !isValidVersion($version) ) {
throw new InvalidArgumentException("Invalid version infix: $infix");
}
return $version;
}
function isValidVersion($version) {
return preg_match('/^\d+\.\d+$/', $version);
}
//Switch to the parent directory so that we can use relative paths where needed.
$oldDir = getcwd();
$repositoryRoot = __DIR__ . '/..';
chdir($repositoryRoot);
function updateVersionNumbers($filePath, $oldVersion, $newVersion) {
$content = file_get_contents($filePath);
if ( $content === false ) {
echo "Failed to read file: $filePath\n";
exit(1);
}
$content = preg_replace("/\b" . preg_quote($oldVersion, '/') . "\b/", $newVersion, $content);
$content = preg_replace(
"/\b" . preg_quote(versionToInfix($oldVersion), '/') . "\b/",
versionToInfix($newVersion),
$content
);
file_put_contents($filePath, $content);
}
//Check for uncommitted changes.
exec('git status --porcelain', $output, $returnCode);
if ( $returnCode !== 0 ) {
echo "Failed to check for uncommitted changes. Git not installed or not in a Git repository?\n";
chdir($oldDir);
exit(1);
}
if ( !empty($output) ) {
echo "You have uncommitted changes. Please commit or stash them before running this script.\n";
chdir($oldDir);
exit(1);
}
//Get the current version.
$currentVersionDir = glob($repositoryRoot . '/Puc/v*p*')[0];
if ( !is_dir($currentVersionDir) ) {
echo "Failed to find the current version's subdirectory.\n";
chdir($oldDir);
exit(1);
}
$currentVersion = infixToVersion(basename($currentVersionDir));
//Ask the user for the new version number
echo "Current version is $currentVersion. Enter new version number: ";
$newVersion = trim(fgets(STDIN));
if ( !isValidVersion($newVersion) ) {
echo "Invalid version number: $newVersion\n";
chdir($oldDir);
exit(1);
}
//Get the old and new version in vXpY and X.Y formats.
$oldVersionInfix = basename($currentVersionDir);
$newVersionInfix = versionToInfix($newVersion);
$oldVersion = $currentVersion;
//Create a new branch for the version update.
exec("git checkout -b \"version-bump-$newVersion\"");
//Rename the Puc/vXpY directory using Git.
exec("git mv \"Puc/$oldVersionInfix\" \"Puc/$newVersionInfix\"");
//Define the list of directories to search
$directoriesToSearch = ['css', 'js', 'Puc'];
//Replace old version infix and old version number in the source code
foreach ($directoriesToSearch as $dir) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $file) {
if ( $file->isFile() ) {
updateVersionNumbers($file->getPathname(), $oldVersion, $newVersion);
}
}
}
//Update version numbers in certain files that are not in the above subdirectories.
$standaloneFiles = [
'plugin-update-checker.php',
'README.md',
'languages/plugin-update-checker.pot',
];
foreach ($standaloneFiles as $standaloneFile) {
updateVersionNumbers($repositoryRoot . '/' . $standaloneFile, $oldVersion, $newVersion);
}
//Rename the loader file and update the version numbers.
$oldLoaderFileName = "load-$oldVersionInfix.php";
$newLoaderFileName = "load-$newVersionInfix.php";
exec("git mv \"$oldLoaderFileName\" \"$newLoaderFileName\"");
updateVersionNumbers($repositoryRoot . '/' . $newLoaderFileName, $oldVersion, $newVersion);
//Replace the old loader file name with new one in files that use it.
//plugin-update-checker.php was already updated by the previous step, but we'll
//include it here anyway in case the code order or loader naming scheme changes.
$filesUsingLoader = ['plugin-update-checker.php', 'composer.json'];
foreach ($filesUsingLoader as $fileName) {
$fullFileName = $repositoryRoot . '/' . $fileName;
$content = file_get_contents($fullFileName);
$content = str_replace($oldLoaderFileName, $newLoaderFileName, $content);
file_put_contents($fullFileName, $content);
}
//Commit the changes.
exec('git add .');
exec("git commit -m \"Bump version number to $newVersion\"");
echo "Version number bumped to $newVersion.\n";
//Switch back to the original directory.
chdir($oldDir);

View File

@ -9,15 +9,15 @@
{
"name": "Yahnis Elsts",
"email": "whiteshadow@w-shadow.com",
"homepage": "http://w-shadow.com/",
"homepage": "https://w-shadow.com/",
"role": "Developer"
}
],
"require": {
"php": ">=5.2.0",
"php": ">=5.6.20",
"ext-json": "*"
},
"autoload": {
"files": ["load-v4p12.php"]
"files": ["load-v5p6.php"]
}
}

View File

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

View File

@ -1,52 +1,52 @@
{
"name": "My Example Plugin",
"version": "2.0",
"download_url": "http://example.com/updates/example-plugin.zip",
"homepage": "http://example.com/",
"requires": "4.5",
"tested": "4.8",
"last_updated": "2017-01-01 16:17:00",
"upgrade_notice": "Here's why you should upgrade...",
"author": "Janis Elsts",
"author_homepage": "http://example.com/",
"sections": {
"description": "(Required) Plugin description. Basic HTML can be used in all sections.",
"installation": "(Recommended) Installation instructions.",
"changelog": "(Recommended) Changelog. <p>This section will be displayed by default when the user clicks 'View version x.y.z details'.</p>",
"custom_section": "This is a custom section labeled 'Custom Section'."
},
"icons" : {
"1x" : "http://w-shadow.com/files/external-update-example/assets/icon-128x128.png",
"2x" : "http://w-shadow.com/files/external-update-example/assets/icon-256x256.png"
},
"banners": {
"low": "http://w-shadow.com/files/external-update-example/assets/banner-772x250.png",
"high": "http://w-shadow.com/files/external-update-example/assets/banner-1544x500.png"
},
"translations": [
{
"language": "fr_FR",
"version": "4.0",
"updated": "2016-04-22 23:22:42",
"package": "http://example.com/updates/translations/french-language-pack.zip"
},
{
"language": "de_DE",
"version": "5.0",
"updated": "2016-04-22 23:22:42",
"package": "http://example.com/updates/translations/german-language-pack.zip"
}
],
"rating": 90,
"num_ratings": 123,
"downloaded": 1234,
"active_installs": 12345
{
"name": "My Example Plugin",
"version": "2.0",
"download_url": "http://example.com/updates/example-plugin.zip",
"homepage": "http://example.com/",
"requires": "4.5",
"tested": "4.8",
"last_updated": "2017-01-01 16:17:00",
"upgrade_notice": "Here's why you should upgrade...",
"author": "Janis Elsts",
"author_homepage": "http://example.com/",
"sections": {
"description": "(Required) Plugin description. Basic HTML can be used in all sections.",
"installation": "(Recommended) Installation instructions.",
"changelog": "(Recommended) Changelog. <p>This section will be displayed by default when the user clicks 'View version x.y.z details'.</p>",
"custom_section": "This is a custom section labeled 'Custom Section'."
},
"icons" : {
"1x" : "http://w-shadow.com/files/external-update-example/assets/icon-128x128.png",
"2x" : "http://w-shadow.com/files/external-update-example/assets/icon-256x256.png"
},
"banners": {
"low": "http://w-shadow.com/files/external-update-example/assets/banner-772x250.png",
"high": "http://w-shadow.com/files/external-update-example/assets/banner-1544x500.png"
},
"translations": [
{
"language": "fr_FR",
"version": "4.0",
"updated": "2016-04-22 23:22:42",
"package": "http://example.com/updates/translations/french-language-pack.zip"
},
{
"language": "de_DE",
"version": "5.0",
"updated": "2016-04-22 23:22:42",
"package": "http://example.com/updates/translations/german-language-pack.zip"
}
],
"rating": 90,
"num_ratings": 123,
"downloaded": 1234,
"active_installs": 12345
}

View File

@ -1,5 +1,5 @@
{
"version": "2.0",
"details_url": "http://example.com/version-2.0-details.html",
"download_url": "http://example.com/example-theme-2.0.zip"
{
"version": "2.0",
"details_url": "http://example.com/version-2.0-details.html",
"download_url": "http://example.com/example-theme-2.0.zip"
}

View File

@ -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"]').on('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"]').on('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');

Binary file not shown.

View File

@ -0,0 +1,52 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2022-07-29 15:34+0300\n"
"PO-Revision-Date: 2024-05-09 22:22+0000\n"
"Last-Translator: theogk\n"
"Language-Team: Ελληνικά\n"
"Language: el\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Loco https://localise.biz/\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"
"Report-Msgid-Bugs-To: \n"
"X-Loco-Version: 2.6.9; wp-6.5.3"
#: Puc/v5p4/Plugin/Ui.php:128
msgid "Check for updates"
msgstr "Έλεγχος για ενημερώσεις"
#: Puc/v5p4/Plugin/Ui.php:214
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Το πρόσθετο %s είναι ενημερωμένο."
#: Puc/v5p4/Plugin/Ui.php:216
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Μία νέα έκδοση είναι διαθέσιμη για το πρόσθετο %s."
#: Puc/v5p4/Plugin/Ui.php:218
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr ""
"Δεν ήταν εφικτό να εκτελεστεί ο έλεγχος για νέες ενημερώσεις για το πρόσθετο "
"%s."
#: Puc/v5p4/Plugin/Ui.php:224
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Άγνωστο πρόβλημα του ενημερωτή προσθέτων \"%s\""
#: Puc/v5p4/Vcs/PluginUpdateChecker.php:100
msgid "There is no changelog available."
msgstr "Δεν υπάρχει διαθέσιμο αρχείο αλλαγών."

View File

@ -1,38 +1,50 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-02-17 14:21+0100\n"
"PO-Revision-Date: 2016-10-28 14:30+0330\n"
"Last-Translator: studio RVOLA <hello@rvola.com>\n"
"Language-Team: Pro Style <info@prostyle.ir>\n"
"POT-Creation-Date: 2025-06-12 23:40+0100\n"
"PO-Revision-Date: 2025-06-12 23:49+0100\n"
"Last-Translator: Pro Style <info@prostyle.ir>\n"
"Language-Team: Alex Javadi <alex@aljm.org>\n"
"Language: fa_IR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.8\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Generator: Poedit 3.6\n"
"X-Poedit-Basepath: ..\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:120
msgid "There is no changelog available."
msgstr "شرحی برای تغییرات یافت نشد"
#: Puc/v5p6/Plugin/Ui.php:56
msgid "View details"
msgstr "مشاهده جزئیات"
#: plugin-update-checker.php:637
#: Puc/v5p6/Plugin/Ui.php:79
#, php-format
msgid "More information about %s"
msgstr "اطلاعات بیشتر درباره %s"
# It had some “potential” grammar issues and also didnt sound native.
# P.S. I know the current translation is literally “Checking for new updates”, however, I thought it might sound more natural and known to others.
#: Puc/v5p6/Plugin/Ui.php:130
msgid "Check for updates"
msgstr "بررسی برای بروزرسانی "
msgstr "بررسی بروزرسانی جدید"
#: plugin-update-checker.php:681
msgid "This plugin is up to date."
msgstr "شما از آخرین نسخه استفاده میکنید . به‌روز باشید"
#: plugin-update-checker.php:683
msgid "A new version of this plugin is available."
msgstr "نسخه جدیدی برای افزونه ارائه شده است ."
#: plugin-update-checker.php:685
# The word “ناشناخته” is seems to be translated directly from the word (Un-known), rather than checking for the context.
# I think “نامشخص” (unknown) might be a suitable version in this scenario.
#: Puc/v5p6/Plugin/Ui.php:227
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "وضعیت ناشناخته برای بروزرسانی \"%s\""
msgstr "وضعیت نامشخص برای بروزرسانی \"%s\""
# The previous translation was okay, however, it didnt sound native to me.
#: Puc/v5p6/Vcs/PluginUpdateChecker.php:113
msgid "There is no changelog available."
msgstr "آخرین تغییراتی یافت نشد."
#~ msgid "This plugin is up to date."
#~ msgstr "شما از آخرین نسخه استفاده میکنید . به‌روز باشید"
#~ msgid "A new version of this plugin is available."
#~ msgstr "نسخه جدیدی برای افزونه ارائه شده است ."

Binary file not shown.

View File

@ -0,0 +1,57 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2024-12-09 11:45+0100\n"
"PO-Revision-Date: 2024-12-09 12:20+0100\n"
"Last-Translator: Aleksandar Urošević <urke.kg@gmail.com>\n"
"Language-Team: \n"
"Language: sr_RS\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Generator: Poedit 2.4.3\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/v5p5/Plugin/Ui.php:56
msgid "View details"
msgstr "Види детаље"
#: Puc/v5p5/Plugin/Ui.php:79
#, php-format
msgid "More information about %s"
msgstr "Више информација о %s"
#: Puc/v5p5/Plugin/Ui.php:130
msgid "Check for updates"
msgstr "Провера ажурирања"
#: Puc/v5p5/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Додатак %s је у најновијем издању."
#: Puc/v5p5/Plugin/Ui.php:219
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Доступно је ново издање за %s."
#: Puc/v5p5/Plugin/Ui.php:221
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Није могуће утврдити да ли су доступне исправке за %s."
#: Puc/v5p5/Plugin/Ui.php:227
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Непознат статус провере ажурирања \"%s\""
#: Puc/v5p5/Vcs/PluginUpdateChecker.php:113
msgid "There is no changelog available."
msgstr "Белешке о изменама нису доступне."

View File

@ -1,57 +1,57 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2022-01-29 12:09+0800\n"
"PO-Revision-Date: 2022-01-29 12:10+0800\n"
"POT-Creation-Date: 2025-11-21 10:40+0800\n"
"PO-Revision-Date: 2025-11-21 10:40+0800\n"
"Last-Translator: Seaton Jiang <hi@seatonjiang.com>\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.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Poedit 3.8\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/v4p11/Plugin/Ui.php:54
#: Puc/v5p6/Plugin/Ui.php:56
msgid "View details"
msgstr "查看详情"
#: Puc/v4p11/Plugin/Ui.php:77
#: Puc/v5p6/Plugin/Ui.php:79
#, php-format
msgid "More information about %s"
msgstr "%s 的更多信息"
#: Puc/v4p11/Plugin/Ui.php:128
#: Puc/v5p6/Plugin/Ui.php:130
msgid "Check for updates"
msgstr "检查更新"
#: Puc/v4p11/Plugin/Ui.php:214
#: Puc/v5p6/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "%s 目前是最新版本。"
#: Puc/v4p11/Plugin/Ui.php:216
#: Puc/v5p6/Plugin/Ui.php:219
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "%s 当前有可用的更新。"
#: Puc/v4p11/Plugin/Ui.php:218
#: Puc/v5p6/Plugin/Ui.php:221
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "%s 无法确定是否有可用的更新。"
#: Puc/v4p11/Plugin/Ui.php:224
#: Puc/v5p6/Plugin/Ui.php:227
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "未知的更新检查状态:%s"
#: Puc/v4p11/Vcs/PluginUpdateChecker.php:100
#: Puc/v5p6/Vcs/PluginUpdateChecker.php:113
msgid "There is no changelog available."
msgstr "没有可用的更新日志。"

Binary file not shown.

View File

@ -0,0 +1,66 @@
# Blank Plugin POT Template
# Copyright 2025 ...
# This file is distributed under the GNU General Public License v3 or later.
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Plugin Update Checker\n"
"Report-Msgid-Bugs-To: Alex Lion <learnwithalex@gmail.com>\n"
"POT-Creation-Date: 2025-09-19 14:05-0700\n"
"PO-Revision-Date: \n"
"Last-Translator: Alex Lion <learnwithalex@gmail.com>\n"
"Language-Team: Alex Lion <learnwithalex@gmail.com>\n"
"Language: zh_TW\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-WPHeader: plugin-update-checker.php\n"
"X-Textdomain-Support: yesX-Generator: Poedit 1.6.4\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: "
"__;_e;esc_html_e;esc_html_x:1,2c;esc_html__;esc_attr_e;esc_attr_x:1,2c;esc_attr__;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2;_x:1,2c;_n:1,2;_n_noop:1,2;__ngettext:1,2;__ngettext_noop:1,2;_c,_nc:4c,1,2\n"
"X-Poedit-Basepath: ..\n"
"X-Poedit-Bookmarks: \n"
"X-Generator: Poedit 3.7\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v5p6/Plugin/Ui.php:56
msgid "View details"
msgstr "檢視詳細資料"
#: Puc/v5p6/Plugin/Ui.php:79
#, php-format
msgid "More information about %s"
msgstr "進一步了解 %s 的相關資訊"
#: Puc/v5p6/Plugin/Ui.php:130
msgid "Check for updates"
msgstr "檢查更新"
#: Puc/v5p6/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "%s 外掛已為最新版本。"
#: Puc/v5p6/Plugin/Ui.php:219
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "%s 外掛已有新版本可供更新。"
#: Puc/v5p6/Plugin/Ui.php:221
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "無法確定 %s 是否有可用的更新。"
#: Puc/v5p6/Plugin/Ui.php:227
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "未知的更新檢查程式狀態: %s"
#: Puc/v5p6/Vcs/PluginUpdateChecker.php:113
msgid "There is no changelog available."
msgstr "目前沒有可供檢閱的變更記錄。"

View File

@ -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: 2025-05-20 15:27+0300\n"
"PO-Revision-Date: 2016-01-10 20:59+0100\n"
"Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: 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.6\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/v4p11/Plugin/Ui.php:128
#: Puc/v5p6/Plugin/Ui.php:130
msgid "Check for updates"
msgstr ""
#: Puc/v4p11/Plugin/Ui.php:213
#: Puc/v5p6/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr ""
#: Puc/v4p11/Plugin/Ui.php:215
#: Puc/v5p6/Plugin/Ui.php:219
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr ""
#: Puc/v4p11/Plugin/Ui.php:217
#: Puc/v5p6/Plugin/Ui.php:221
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr ""
#: Puc/v4p11/Plugin/Ui.php:223
#: Puc/v5p6/Plugin/Ui.php:227
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr ""
#: Puc/v4p11/Vcs/PluginUpdateChecker.php:98
#: Puc/v5p6/Vcs/PluginUpdateChecker.php:113
msgid "There is no changelog available."
msgstr ""

View File

@ -1,4 +1,4 @@
Copyright (c) 2017 Jānis Elsts
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:

View File

@ -1,28 +0,0 @@
<?php
require dirname(__FILE__) . '/Puc/v4p12/Autoloader.php';
new Puc_v4p12_Autoloader();
require dirname(__FILE__) . '/Puc/v4p12/Factory.php';
require dirname(__FILE__) . '/Puc/v4/Factory.php';
//Register classes defined in this version with the factory.
foreach (
array(
'Plugin_UpdateChecker' => 'Puc_v4p12_Plugin_UpdateChecker',
'Theme_UpdateChecker' => 'Puc_v4p12_Theme_UpdateChecker',
'Vcs_PluginUpdateChecker' => 'Puc_v4p12_Vcs_PluginUpdateChecker',
'Vcs_ThemeUpdateChecker' => 'Puc_v4p12_Vcs_ThemeUpdateChecker',
'GitHubApi' => 'Puc_v4p12_Vcs_GitHubApi',
'BitBucketApi' => 'Puc_v4p12_Vcs_BitBucketApi',
'GitLabApi' => 'Puc_v4p12_Vcs_GitLabApi',
)
as $pucGeneralClass => $pucVersionedClass
) {
Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.12');
//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_v4p12_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.12');
}

34
load-v5p6.php Normal file
View File

@ -0,0 +1,34 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use YahnisElsts\PluginUpdateChecker\v5\PucFactory as MajorFactory;
use YahnisElsts\PluginUpdateChecker\v5p6\PucFactory as MinorFactory;
require __DIR__ . '/Puc/v5p6/Autoloader.php';
new Autoloader();
require __DIR__ . '/Puc/v5p6/PucFactory.php';
require __DIR__ . '/Puc/v5/PucFactory.php';
//Register classes defined in this version with the factory.
foreach (
array(
'Plugin\\UpdateChecker' => Plugin\UpdateChecker::class,
'Theme\\UpdateChecker' => Theme\UpdateChecker::class,
'Vcs\\PluginUpdateChecker' => Vcs\PluginUpdateChecker::class,
'Vcs\\ThemeUpdateChecker' => Vcs\ThemeUpdateChecker::class,
'GitHubApi' => Vcs\GitHubApi::class,
'BitBucketApi' => Vcs\BitBucketApi::class,
'GitLabApi' => Vcs\GitLabApi::class,
)
as $pucGeneralClass => $pucVersionedClass
) {
MajorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.6');
//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.
MinorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.6');
}

21
phpcs.xml Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0"?>
<ruleset name="PUC_PHPCS_Settings">
<description>PHPCS settings for Plugin Update Checker</description>
<arg name="basepath" value="."/>
<arg name="warning-severity" value="5"/>
<arg name="error-severity" value="5"/>
<arg value="sp"/>
<!-- Check the current directory by default -->
<file>./</file>
<!-- Include the WordPress-VIP-Go standard -->
<rule ref="WordPress-VIP-Go">
<!-- This library is not exclusive to WP VIP, so it doesn't use vip_safe_wp_remote_get() and such. -->
<exclude name="WordPressVIPMinimum.Functions.RestrictedFunctions.wp_remote_get_wp_remote_get" />
</rule>
<!-- Exclude external and third-party libraries -->
<exclude-pattern type="relative">^vendor/*</exclude-pattern>
</ruleset>

View File

@ -1,10 +1,10 @@
<?php
/**
* Plugin Update Checker Library 4.12
* Plugin Update Checker Library 5.6
* http://w-shadow.com/
*
* Copyright 2022 Janis Elsts
* Copyright 2025 Janis Elsts
* Released under the MIT license. See license.txt for details.
*/
require dirname(__FILE__) . '/load-v4p12.php';
require dirname(__FILE__) . '/load-v5p6.php';

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -648,7 +648,7 @@ class Parsedown
#
# Setext
protected function blockSetextHeader($Line, array $Block = null)
protected function blockSetextHeader($Line, $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{
@ -786,7 +786,7 @@ class Parsedown
#
# Table
protected function blockTable($Line, array $Block = null)
protected function blockTable($Line, $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{

View File

@ -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;