Compare commits

...

369 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
Yahnis Elsts ae5789b5a7 Rename classes for 4.12 2022-07-25 00:33:05 +03:00
Yahnis Elsts 4525927a6b Rename loader file 2022-07-25 00:27:58 +03:00
Yahnis Elsts 568e845d89 Begin 4.12 version change
Rename versioned directory
2022-07-25 00:24:42 +03:00
Yahnis Elsts f478379ed7 Replace defined('__NAMESPACE__') conditions with PHP version checks. 2022-07-21 12:28:39 +03:00
Yahnis Elsts 3119408761 Attempt to fix some PHP Scoper compatibility issues. See #496 2022-07-14 17:54:22 +03:00
Yahnis Elsts 8d78365380
Merge pull request #493 from d79/master
Update Italian translation
2022-05-21 12:08:17 +03:00
d79 dea04443b0 Updated italian translation 2022-05-20 10:48:24 +02:00
Yahnis Elsts a68681e54b Minor: Add a TODO for the GitLab integration.
I haven't gotten around to completing it, but don't want to dismiss it either.
2022-04-15 13:24:25 +03:00
Yahnis Elsts 56c78cc6da
Merge pull request #478 from seatonjiang/master
Update Simplified Chinese (zh_CN) translations
2022-01-29 13:46:15 +02:00
Seaton Jiang 86d7d5f2bd
feat: add Simplified Chinese (zh_CN) translations 2022-01-29 12:13:39 +08:00
Yahnis Elsts db591f3277
Merge pull request #472 from wpdew/master
Add Russian and Ukrainian translations
2021-12-21 19:08:03 +02:00
Aleks Moroz bbc881e9da Added languages
Added translations into Russian and Ukrainian languages.
2021-12-20 18:03:25 +02:00
Yahnis Elsts 3a65e7ff3e Add Turkish translation. PO/MO files provided by Igor Funa. 2021-11-15 18:29:18 +02:00
Yahnis Elsts 0e869938e3 Refactoring: Extract asset detection to a method.
This applies to locally stored plugin icons and banners. The code for icons and banners was very similar, so I've turned it into a utility method to reduce code duplication.
2021-10-01 14:55:59 +03:00
Yahnis Elsts 12cff18273
Merge pull request #462 from timwiel/timwiel-pluginbanners
Use plugin banners from the local "assets" directory.
2021-09-30 19:29:10 +03:00
Tim Wiel e5453b52e4 Use plugin icons from the local "assets" directory. 2021-09-29 14:24:36 +13:00
Yahnis Elsts 8a8788d965 Use plugin icons from the local "assets" directory.
Props to @timwiel for the suggestion and the original implementation. See  #461. 

This change applies to plugins (but not themes) that are updated from a VCS hosting provider like GitHub. Previously, the plugin author would have had to use a filter to provide icons. Now they can just put them in a subdirectory named "assets" instead. Icon file names and extensions should match those described here:
https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons

Note that the update checker will use icons from the installed version, not from the VCS repository.
2021-09-27 20:25:50 +03:00
Yahnis Elsts a5dd2bb951 Make "enableReleasePackages" plural so that it's consistent with "enableReleaseAssets" 2021-09-23 18:11:12 +03:00
Yahnis Elsts 3f12a21751 Minor: Reformat some docs and fix some phrasing issues 2021-09-23 18:07:34 +03:00
Yahnis Elsts 7813fa5816
Merge pull request #460 from timwiel/timwiel-gitlabreleases
Add GitLab release support
2021-09-23 16:15:54 +03:00
Tim Wiel cea29dcaaa Fixed authentication issues for public repos and re-priortised the order of update checking from Gitlab to match the Github methodology 2021-09-23 13:48:02 +12:00
Tim Wiel 57ceef7685 Minor comment change to better reflect code functionality 2021-09-22 16:25:15 +12:00
Tim Wiel 91d089876f Ordering the priority of version checks for Gitlab and updating README.md accordingly 2021-09-22 14:41:02 +12:00
Tim Wiel e16a46fc72 Filtering out "upcoming releases" from the releases available to PUC 2021-09-22 12:53:01 +12:00
Tim Wiel 824348c036 Adding checks for the assets to ensure they are zip files which is what wordpress needs to update 2021-09-22 12:11:37 +12:00
Tim Wiel 1c63404e98 README.md update to reflect Gitlab releases functionality 2021-09-21 14:00:53 +12:00
Tim Wiel cb44a6ede1 Adding releases to GitLab API with option for release asset download from either: source OR generic package releases (see https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs/examples/release-assets-as-generic-package/) 2021-09-21 13:48:25 +12:00
Yahnis Elsts 2292442efc
Merge pull request #433 from geoffthibeau/bitbucket-default-branch-main
Adds possible default branch name 'main': Bitbucket
2021-05-19 13:51:58 +03:00
Geoff Thibeau 048b78cdd5
Adds possible default branch name 'main': Bitbucket
Adds `main` as a possible default branch name to invoke `$this->getLatestTag()` inside of `Puc_v4p11_Vcs_BitBucketApi::chooseReference()`.

Previously, only branches named `master` inherited this special behavior. With more VCS providers opting for an inclusive default branch name, this commit adds `main` as a default branch name configuration.

Related to #422.
2021-05-18 18:49:36 -05:00
Yahnis Elsts cd4df885c4
Merge pull request #432 from YahnisElsts/wp55-auto-updates
Merge a BitBucket API fix
2021-05-12 21:52:34 +03:00
Yahnis Elsts e5384a52c7 Merge branch 'master' into wp55-auto-updates 2021-05-12 21:30:14 +03:00
Yahnis Elsts 703cbd854d
Docs: Imply that the branch name is not optional
The update checker will look for a `master` branch by default, but new repositories use the name `main` instead, and it is technically possible to use any branch as the default branch. So while you don't *have to* set the branch name, it's probably a good idea to always do that.
2021-03-31 17:30:10 +03:00
Yahnis Elsts 3155f2d3f1 Change version number in file/directory names
Step 2 of version bump
2021-03-15 18:07:52 +02:00
Yahnis Elsts 06bc75f9af Change version infix from v4p10 to v4p11
Step 1 of version bump
2021-03-15 18:02:04 +02:00
Yahnis Elsts d057b36eb4
Merge pull request #419 from marcorocca/master
Fixed a call to non-existent lastRequestApiErrors property
2021-03-12 13:57:29 +02:00
Marco Rocca 8a1a779f00 Fixed wrong call to inexistent property 2021-03-12 00:10:50 +01:00
Yahnis Elsts 369c19ab1a BitBucket: Use commit hash instead of branch name when the branch is not URL-safe.
Apparently, the "/src" subsection of the BitBucket API doesn't do well with branch names that contain slashes. urlencode() doesn't help. See #409 for the initial report.
2021-01-28 19:10:17 +02:00
Yahnis Elsts 4e59df1958 Fixed a few warnings about deprecated jQuery features 2020-12-09 17:07:15 +02:00
Yahnis Elsts 4bd0a820d1 Move code that prefixes the API class with the current namespace so that getCompatibleClassVersion() gets the unprefixed name.
Alternative fix for the problem described in #396.
2020-10-14 19:13:02 +03:00
Yahnis Elsts 4778dd3eb4 Add the current namespace to metadata class names 2020-10-07 18:51:24 +03:00
Yahnis Elsts dee87bbfe6 Remove defined('__NAMESPACE__') checks since that apparently doesn't work 2020-10-06 13:01:30 +03:00
Yahnis Elsts 3c55658638 Don't change the Debug Bar panel class name if it already includes a namespace. 2020-10-05 16:51:09 +03:00
Yahnis Elsts 8125be8df7 Improve compatibility with PHP Scoper and other tools that add namespaces to third-party libraries.
See #394 for discussion.
2020-10-05 16:45:03 +03:00
Yahnis Elsts 0edd15f678 Minor: Fix incorrect version number in a doc-comment 2020-08-21 14:36:45 +03:00
Yahnis Elsts 97885642cc Merge branch 'master' into wp55-auto-updates 2020-08-21 14:33:01 +03:00
Yahnis Elsts 8c4a998c63 Hopefully fixed a fatal error related to Debug Bar
Apparently, upgrading a plugin that uses PUC 4.9 to a version that uses PUC 4.10 may trigger two fatal errors, one of which happens inside the Debug Bar extension. Cause is unclear and the errors are not reproduced, but I suspect it has to do with PUC trying to set up a Debug Bar panel after the currently active PUC version has already been replaced. This patch should fix that.
2020-08-10 22:08:34 +03:00
Yahnis Elsts 9ff0a29f38 Minor: Add .gitignore 2020-08-08 15:04:17 +03:00
Yahnis Elsts 244a3d73b0 Update translation template (POT)
No significant changes, just updated file names and line numbers.
2020-08-08 14:38:22 +03:00
Yahnis Elsts 5a98cfdae1 Change version number to 4.10 everywhere 2020-08-08 14:30:02 +03:00
Yahnis Elsts 66f5cf10c2 Change version number in directory name 2020-08-08 14:21:30 +03:00
Yahnis Elsts 08a2836c88
Merge pull request #383 from seatonjiang/master
feat: add Simplified Chinese (zh_CN) translations
2020-08-04 14:16:37 +03:00
Seaton Jiang d00fef5ca0 feat: add Simplified Chinese (zh_CN) translations 2020-08-04 08:14:31 +08:00
Yahnis Elsts 5d3e93d267 Support the auto-update feature introduced in WP 5.5
Discussed in #376
2020-08-03 19:48:01 +03:00
Yahnis Elsts 4e0d4ade46
Minor documentation edits 2020-04-13 15:29:05 +03:00
Yahnis Elsts 9835b98970
Merge pull request #361 from DavidAnderson684/patch-14
Advice on when to load the plugin updates checker
2020-04-13 15:20:00 +03:00
David Anderson 1d9e64368f
Advice on when to load the plugin updates checker
Over the past couple of years when maintaining Easy Updates Manager - https://wordpress.org/plugins/stops-core-theme-and-plugin-updates/ - we've had a lots of reports from people with third party plugins and themes whose upgrades aren't detected or performed. On investigation, this is invariably because the component loads PUC only during an `admin_*` hook, which means that those updates are effectively invisible except for a logged-in user viewing a page in the WP dashboard. So, tools like EUM, ManageWP, JetPack Manage, UpdraftCentral, WP-CLI, etc., don't see them - they're invisible.
2020-04-13 10:16:49 +00:00
Yahnis Elsts 9748abe1bd Add support for "Requires PHP" header fields.
In the update metadata the field is called "requires_php".

Closes #355
2020-04-07 16:06:24 +03:00
Yahnis Elsts ce3f43c10f Don't change "tested":"x.y" to "tested":"x.y.999" when x.y already matches the current WordPress release.
See #356
2020-04-07 15:21:40 +03:00
Yahnis Elsts 949842cee6 Minor cleanup and formatting changes 2020-03-31 17:52:07 +03:00
Yahnis Elsts 0af94b5609
Merge pull request #354 from RichardCoffee/master
Add a new factory method that allows array as parameter argument and pulls update server URI from file header
2020-03-31 16:55:26 +03:00
Richard Coffee b2ca059c05 change method name, add EXTR_SKIP to extract call 2020-03-30 15:15:35 -04:00
Richard Coffee e61f3f5cba Fix logic error 2020-03-29 15:29:23 -04:00
Richard Coffee dcc817106a add updateChecker and getServiceURI methods 2020-03-29 14:25:16 -04:00
Yahnis Elsts d4b0f965b3
Merge pull request #352 from YordanSoares/master
Updates all the Spanish locales laguage packages
2020-03-22 12:42:17 +02:00
Yordan Soares eca14fd459 Updates all the Spanish locales laguage packages
New language packages for:
1. Spanish (Argentina)
2. Spanish (Chile)
3. Spanish (Colombia)
4. Spanish (Costa Rica)
5. Spanish (Dominican Republic)
6. Spanish (Guatemala)
7. Spanish (Honduras)
8. Spanish (Mexico)
9. Spanish (Peru)
10. Spanish (Puerto Rico)
11. Spanish (Spain)
12. Spanish (Uruguay)
13. Spanish (Venezuela)
2020-03-21 15:20:24 -04:00
Yahnis Elsts 5c6c45d561 Fixed a fatal error triggered when trying to autoload some classes while inside a Phar archive 2020-02-23 12:38:27 +02:00
Yahnis Elsts e3cc1c03c9 Fixed a potential fatal error when the current PUC version is removed during an upgrade.
By default, PUC automatically checks for updates immediately after the user upgrades the plugin or theme. This can become a problem if the upgrade overwrites the PUC library with a different version. While checking for updates, PUC may attempt to autoload a class, which will trigger a fatal error if the class file was deleted during the upgrade.

Fixed by checking if the running PUC version still exists after the upgrade. If it doesn't, remove hooks and stop.
2020-02-15 15:28:12 +02:00
Yahnis Elsts 5cdadd0369 Fixed a bug where PUC might not properly whitelist the hostname used in the metadata URL if there were at least two active plugins using the same version of PUC. 2020-02-13 22:14:49 +02:00
Yahnis Elsts 28f29c940c Bump version number to 4.9 2020-02-07 13:07:19 +02:00
Yahnis Elsts 3857481c65 GitHub support: Use Basic auth instead of the access_token query parameter
See #337, #338
2020-02-04 20:29:25 +02:00
Yahnis Elsts 8e79543bf7 Minor: Add ext-json to composer.json 2020-02-04 17:43:31 +02:00
Yahnis Elsts 760225bbfe Fix fatal error "Call to a member function isMuPlugin() on null"
In certain configurations, PUC could call a method that uses the $package property before calling the parent class constructor that initialises that property. This has now been fixed by moving the parent constructor call a few lines up.

Fixes #335
2020-01-24 19:05:40 +02:00
Yahnis Elsts 8212c5235e
Add link to the metadata format reference table 2019-12-03 17:55:04 +02:00
Yahnis Elsts 7014c9d9fd Randomly offset the update check schedule within $checkPeriod
This helps spread out update requests over all hours of the day and may prevent the update server from being hit with daily traffic spikes.
See #323 for discussion.
2019-11-03 12:33:09 +02:00
Yahnis Elsts 908249c92e Minor: Remove redundant autoloading mechanism 2019-10-08 15:15:30 +03:00
Yahnis Elsts 2a7c818f18 Alternative fix to Composer autoloading issues.
It may be possible to overcome the limitations of the "files" autoloading mechanism by changing the file name in every version.
2019-10-08 15:06:40 +03:00
Yahnis Elsts 66472c5f16 Hopefully fixed a crash when loading Puc_v4_Factory with a Composer autoloader.
See #321 for details.
2019-10-08 14:45:29 +03:00
Yahnis Elsts 8ad3ff2769
Merge pull request #320 from DaveMoran/update-readme-links
Update links to readme.txt documentation
2019-10-03 12:37:04 +03:00
Dave Moran 18331fae68 Final link to readme.txt 2019-10-02 12:34:25 -04:00
Dave Moran 5ec9acf7ed Update link to proper location 2019-10-02 12:26:26 -04:00
Dave Moran 3387ed0585 Revert doctoc section 2019-10-02 12:23:28 -04:00
Dave Moran 890e581d25 Add links to new wordpress readme standards 2019-10-02 12:19:08 -04:00
Yahnis Elsts 0a0142f1ae Fixed a bug where Puc_v4_Factory was not loaded by the custom autoloader.
This could cause a fatal error in PUC 4.8 when not using the Composer autoloader.
2019-10-02 13:47:16 +03:00
Yahnis Elsts 17e1c90598 Minor: Removed another unnecessary condition 2019-10-01 14:47:45 +03:00
Yahnis Elsts a3ff7ada08 Fixed a potential bug with multiple plugins using GitHub release assets.
To allow WP to download a release asset from GitHub, the update checker needs to add an "Accept: application/octet-stream" header to the HTTP request. We use the "http_request_args" filter for that. 

Previously, we used a static variable to ensure that the filter callback is added only once. However, in PHP, static variables defined in a method are shared by all instances of the class that the method belongs to. This means that if one plugin enables release assets, adds a "http_request_args" filter, and sets ``$filterAdded` to `true`, then the next plugin that enables release assets won't add its own filter because the variable will already be `true`.

Fixed by using an instance variable (`$downloadFilterAdded`) instead of a static variable.
2019-10-01 14:35:16 +03:00
Yahnis Elsts 969f8adf21 Minor: Remove a few unneeded conditions 2019-10-01 14:25:04 +03:00
Yahnis Elsts 92f43145e7 Minor: Rephrase stuff in docs 2019-10-01 13:33:00 +03:00
Yahnis Elsts c30528c55c Minor: Fixed some spacing and style 2019-10-01 13:29:51 +03:00
Yahnis Elsts 2f81129b47
Merge pull request #319 from muensmedia/gitlab-subgroups
Allow subgroups for self hosted GitLab instances
2019-10-01 13:24:11 +03:00
Malte Müns 474a9e806b [DOCS] Improve docs how to use subgroups with self hosted GitLab
https://docs.gitlab.com/ce/user/group/subgroups/index.html
2019-09-30 11:02:43 +02:00
Malte Müns 05c76ef07d [FEATURE] Allow subgroups for self hosted GitLab instances
https://docs.gitlab.com/ce/user/group/subgroups/index.html
2019-09-30 11:02:00 +02:00
Yahnis Elsts a78cbb71d3 Bump version number to 4.8 2019-09-28 15:47:47 +03:00
Yahnis Elsts f4167ca36c Another attempt to fix the Composer autoloader 2019-09-27 17:27:54 +03:00
Yahnis Elsts bbe88a70d6 Attempt to fix errors caused by using Composer-generated autoloaders when multiple versions of the library are loaded at the same time.
See #300. Apparently, when using the `files` autoloading mechanism, Composer will only include the files for one version of the library (i.e. the first one loaded). Let's see if we can fix that by switching to a `psr-0` autoloader. This requires a bunch of changes to the standalone autoloader and the factory registration process.
2019-09-27 17:06:01 +03:00
Yahnis Elsts 0f490e940c
Merge pull request #315 from jorditarrida/master
Add Catalan (ca) and Spanish-Spain (es_ES) translations
2019-09-26 20:22:10 +03:00
Jordi Tarrida 286598b1d2 add Catalan (ca) and Spanish-Spain (es_ES) translations 2019-09-25 18:18:17 +02:00
Yahnis Elsts ee8ccd4181 Adjust the "tested" version shown in the "View details" pop-up.
PUC automatically changes "tested up to" version numbers that are in the major.minor format to major.minor.latest-patch to prevent WP from showing "this update hasn't been tested with your WP version" warnings. (This was implemented because WordPress.org does something similar.) Previously, this adjustment didn't happen when the user clicked the "view details" link in a plugin update notification, so they would still see a compatibility warning there. That has now been fixed.

Fixes #307
2019-08-19 14:09:54 +03:00
Yahnis Elsts 902e0946a0
Minor: Fixed link to metadata field definitions 2019-08-15 17:40:42 +03:00
Yahnis Elsts 6355072b9f Minor: Add a newline to the end of file because it's recommended by some code style checkers. 2019-07-15 17:58:23 +03:00
Yahnis Elsts 21fb85c931
Merge pull request #295 from GoodMorningCall/update-Japanese-POT-for-v4.7-_x
Update Japanese translation, this time with _x()
2019-07-15 17:36:51 +03:00
Yahnis Elsts 4f236b3176 Revert "Update for v4.7"
This reverts commit ab87374e8c.
2019-07-15 17:34:53 +03:00
tak b592f72fe2 Update for _x()
Update Japanese translation to support for _x().
2019-07-15 17:25:52 +09:00
Yahnis Elsts 6b4d250cbf
Merge pull request #293 from GoodMorningCall/update-Japanese-POT-for-v4.7
Update Japanese translation for v4.7
2019-07-13 12:33:52 +03:00
tak ab87374e8c Update for v4.7
Update Japanese translations to adapt to v4.7
2019-07-13 06:59:40 +09:00
Yahnis Elsts 6da68b1192 Changed version number to 4.7 2019-07-05 21:39:53 +03:00
Yahnis Elsts ce61132533 Added Slovenian translation.
Translation was provided by Igor Funa.
2019-07-02 14:25:15 +03:00
Yahnis Elsts 3f5a340ded Fully upgraded to BitBucket API 2.0.
Previously the update checker used a mix of 2.0 and 1.0. Version 1.0 was deprecated a while ago and has now stopped working for at least some users.

This should fix the errors reported in #289.
2019-06-13 16:11:05 +03:00
Yahnis Elsts 3ad92e3135 Minor: Change line endings from \r\n to \n for consistency with the rest of the project. 2019-04-18 23:11:33 +03:00
Yahnis Elsts 4643dec114 Minor: Add newlines to the end of each file.
Some code analysers require this.
2019-04-18 22:53:23 +03:00
Yahnis Elsts 5f856d8d80 Removed warning suppression from parse_url().
PUC uses parse_url() in a number of places to parse the metadata URL or repository URL. If someone provides an invalid URL then that's already a configuration error so it's not necessary to hide the warnings emitted by parse_url(). 

Also, as of PHP 5.3.3, parse_url() no longer emits warnings when it fails to parse something, so anyone using an actively supported PHP version (7.2+) wouldn't see any warnings anyway.
2019-04-18 22:30:53 +03:00
Yahnis Elsts 45374e3c02 Bump version number to 4.6 2019-04-02 20:56:11 +03:00
Yahnis Elsts 006bb9394f Probably fixed a bug where, if an older version of PUC 4.x is loaded first, the more recent version's factory (Puc_v4pN_Factory) won't be able to instantiate any classes.
This bug was caused by a combination of two facts:

1) The version that gets loaded first takes the Puc_v4_Factory alias.
2) All other versions register their class names with the existing Puc_v4_Factory, not their own factory class.

We can't really do much about the first one, but we can work around the second one by also registering each class with the version-specific factory.

See also #279
2019-03-29 19:17:36 +02:00
Yahnis Elsts 8499f5c429 GitLab: Use the protocol specified in the repository URL instead of always defaulting to HTTPS.
A user reports that some GitLab servers use plain HTTP for their APIs. See #270.
2019-03-18 14:11:42 +02:00
Yahnis Elsts 49c0fbd6b5 Minor code style adjustments. 2019-03-14 20:28:41 +02:00
Yahnis Elsts 2a51e7222b
Merge pull request #269 from DavidAnderson684/patch-13
Added missing type check
2019-03-14 20:24:06 +02:00
David Anderson d9011e1a49
Added missing type check 2019-03-14 18:21:01 +00:00
Yahnis Elsts b6e84c36ee
Merge pull request #268 from DavidAnderson684/patch-12
Ignore irrelevant updates in the upgrader_process_complete hook
2019-03-14 20:15:41 +02:00
David Anderson b26dbf8eb3
Extra check 2019-03-14 16:13:08 +00:00
David Anderson 8d3aa30f3e
Modify behaviour on upgrader_process_complete action
Won't call `maybeCheckForUpdates()` if it's not an update for this entity.
2019-03-14 16:01:09 +00:00
Yahnis Elsts 857ee82041
Merge pull request #264 from pierre-r/master
Fix wrong function name: apply_filter(s)
2019-02-27 16:00:12 +02:00
Pierre e8422cdf42 Fix wrong function name 2019-02-27 14:03:43 +01:00
Yahnis Elsts 7a3527ce55
Merge pull request #263 from Tofandel/patch-1
Add a `puc_get_vcs_service` filter
2019-02-26 12:36:10 +02:00
Adrien Foulon 02592c7fc4
Add a filter to getVcsService
The filter 'puc_get_vcs_service' will then allow user to add their self hosted gitlab or bitbucket as a recognised service
like so
add_filter('puc_get_vcs_service', function($service, $host) {
    if ($host == 'gitlab.mydomain.com') {
        return 'GitLab';
    }
    return $service;
}, 10, 2);
2019-02-25 19:03:46 +01:00
Yahnis Elsts 57a25d905a Update the docs to more clearly separate usage instructions for GitLab.com and self-hosted GitLab instances. 2019-01-04 19:13:39 +02:00
Yahnis Elsts 9d087b7d9c Add a workaround for realpath() failing to process the mu-plugins path.
Probably fixes #251
2018-12-30 13:36:24 +02:00
Yahnis Elsts d98d6bc6ca Bump version to 4.5 - step 2
Rename files and update file paths.
2018-12-30 12:38:32 +02:00
Yahnis Elsts d460807de8 Bump version to 4.5 - step #1
Renaming all of the clases and updating version numbers.
2018-12-30 12:35:16 +02:00
Yahnis Elsts e4536b4efa
Merge pull request #246 from YahnisElsts/gitlab-subgroups
Add support for Gitlab subgroups
2018-12-11 20:30:05 +02:00
Yahnis Elsts 5a6b4f9878 Merge branch 'master' into gitlab-subgroups 2018-12-11 20:14:59 +02:00
Yahnis Elsts e1570305b0
Merge pull request #245 from YahnisElsts/issue-240-patch
Fix GitLab download URLs
2018-12-11 20:09:52 +02:00
Yahnis Elsts c5036b620f Fix outdated API syntax in getRemoteFile 2018-12-09 11:02:54 +02:00
Yahnis Elsts 2dba97ecfb Don't encode slashes unnecessarily 2018-12-05 21:51:15 +02:00
Yahnis Elsts ee677e2e5b Potential fix for #240.
Props to @froger-me
2018-12-05 21:40:54 +02:00
Yahnis Elsts 871c1006c5 Added support for GitLab subgroups as described in #241
(Untested.)
2018-12-03 15:21:45 +02:00
Yahnis Elsts 14bd39a492
Merge pull request #243 from meszarosrob/master
Set $repositoryHost visibility to protected
2018-12-02 15:45:07 +02:00
Meszaros Robert 98ab02dbda
Set $repositoryHost visibility to protected 2018-11-29 17:53:27 +02:00
Yahnis Elsts ea633a91b3 Use random_bytes() when generating OAuth nonces.
mt_rand() is not cryptographically secure. This probably doesn't matter that much in most cases because it only affects BitBucket API interactions that already happen over HTTPS, but why not use a better option when it's available?

Closes #233
2018-10-23 13:23:48 +03:00
Yahnis Elsts f11ffce720 Fix the parser ignoring the last readme.txt section when it's empty. 2018-09-26 11:18:00 +03:00
Yahnis Elsts e2da891646
Merge pull request #229 from Tofandel/patch-1
Fix PHP notice "Undefined offset: 1 in readme-parser.php on line 124".
2018-09-26 11:00:31 +03:00
Adrien Foulon 89e8849957
Fix PHP notice "Undefined offset: 1 in readme-parser.php on line 124".
The for loop was iterating including the count index of the $_sections, it should be excluding
2018-09-23 16:47:42 +02:00
Yahnis Elsts c9a7d2a7da Add a note about where to post ideas on license management features 2018-08-09 15:47:20 +03:00
Yahnis Elsts 1cb79bcdce Minor: Refactor the plugin UI callback permission checks.
Let's only add our UI hooks if the user has the required permissions. This way we can avoid duplicating the permission checks in each individual callback.
2018-07-17 13:58:17 +03:00
Yahnis Elsts 4f6afa95cd Extract file parsing and lookup as a separate "Package" class. 2018-07-17 13:03:03 +03:00
Yahnis Elsts 98ac49406c Fix: Remove UI hooks when uninstalling the plugin.
It looks like I forgot to move that code when extracting the UI class.
2018-07-14 12:38:32 +03:00
Yahnis Elsts 68f4865b31 Extract plugin-specific UI as a separate class.
This includes the "View details" and "Check for updates" links that appear on the "Plugins -> Installed Plugins" page.
2018-07-14 12:15:50 +03:00
Yahnis Elsts 01863da0e8 Minor: Adjust code spacing. 2018-06-27 15:28:34 +03:00
Yahnis Elsts 4f79183092
Merge pull request #205 from dangoodman/master
Fix WordPress reporting unknown compatibility of a plugin/theme update
2018-06-27 15:11:16 +03:00
dangoodman c47c690c47 Fix code style 2018-06-27 11:24:40 +03:00
dangoodman d7dcd8851c Change fixSupportedWordpressVersion() from private to protected 2018-06-27 11:22:42 +03:00
dangoodman 05bddba61b Try to fetch an actual WP patch number 2018-06-26 13:57:44 +03:00
Yahnis Elsts e222ec10fa
Merge pull request #207 from dangoodman/pr-debugbar-typo
Fix typo in DebugBar extension availability check
2018-06-19 13:16:17 +03:00
dangoodman 15bb029ab7 Fix typo in DebugBar extension availability check 2018-06-18 21:49:05 +03:00
dangoodman 4e8f5a568e Fix WordPress reporting unknown compatibility of a plugin/theme update 2018-06-12 19:24:31 +03:00
Yahnis Elsts f26378d0c2 Minor: Added a note about using GitHub release assets 2018-05-03 17:08:22 +03:00
Yahnis Elsts a4a61b6415
Merge pull request #193 from futtta/master
Added Dutch translations.
2018-03-25 19:59:10 +03:00
futtta bf2750e548 Dutch (NL & BE, identical) translations 2018-03-25 18:33:51 +02:00
Yahnis Elsts ee8bfa1cad Minor: Emphasize the fact that the path that's passed to buildUpdateChecker must be the full path to the main plugin file (or functions.php). There have been too many issues opened lately by people who incorrectly assume that any old file path will do.
Note: Technically, for themes any file that's at the root of the theme directory will work. It doesn't have to be functions.php specifically.
2018-03-12 10:46:07 +02:00
Yahnis Elsts 889586dff7
Merge pull request #184 from Spidlace/master
Allow custom GitLab repository URLs to include a port number
2018-03-02 16:39:29 +02:00
Tony b2e15785ac minor code style issue : concatenating strings 2018-03-02 15:30:30 +01:00
Tony 3a56b83756 Add port host support for GitlabAPI 2018-03-01 13:02:22 +01:00
Yahnis Elsts 5e48f0c853 Fixed slug conflict detection.
Also fixed a related bug where calling the triggerError() method inside the update checker constructor would not trigger an error even if WP_DEBUG was enabled. The `debugMode` property didn't get initialized until the base class constructor was run. To fix that, I've added a new isDebugModeEnabled() method that performs lazy initialisation. The downside is that it duplicates one line of code from the constructor.

Closes #180
2018-02-22 18:51:25 +02:00
Yahnis Elsts b75f5555c2
Merge pull request #179 from devanonyme/master
Correction of bad mo file.
2018-02-12 19:40:52 +02:00
devanonyme 50ac73643b
Correction of bad mo file. 2018-02-12 12:21:12 -05:00
Yahnis Elsts 90a138f22d
Merge pull request #176 from devanonyme/master
Add a Canadian French translation.
2018-02-12 18:41:05 +02:00
devanonyme 9412db45ef
Add fr_CA translation files. 2018-02-12 10:48:25 -05:00
Yahnis Elsts f34eab1f5a Minor: Replace outdated class name in the readme 2018-01-18 12:15:30 +02:00
Yahnis Elsts f7f63d203d Fix PHP notice "Undefined offset: 1 in readme-parser.php on line 161".
Let's discard incorrectly formatted "upgrade notice" sections instead of triggering PHP notices.
2018-01-08 12:49:22 +02:00
Yahnis Elsts da42863436 Bump version number to 4.4. 2017-12-22 12:39:11 +02:00
Yahnis Elsts 88eee6e4a9 Add an .editorconfig
(The file was generated by exporting PhpStorm code style settings.)
2017-12-14 18:41:42 +02:00
Yahnis Elsts 60add5f915 Add support for GitHub release assets. See #93
Usage: Set up the update checker instance as usual, then call the new enableReleaseAssets() method of the GitHub API class. 

`$gitHubUpdateChecker->getVcsApi()->enableReleaseAssets();`

Notes:
- You can make PUC look for a specific asset by passing a regular expression to enableReleaseAssets(). For example, `$api->enableReleaseAssets('/custom-asset/')` will make PUC use the first asset where the file name contains the string "custom-asset".
- PUC always chooses the first matching asset.
- If the latest release has no assets or none of them match the regex, PUC will fall back to the old behaviour of using the automatically generated ZIP file.
- Private repositories only work with WP 3.7 or later. Older WordPress versions will throw an error when trying to download the update.
2017-11-27 17:32:49 +02:00
Yahnis Elsts af5207d349 Minor: Include the v4 factory. 2017-11-26 21:55:24 +02:00
Yahnis Elsts bf21da2ff2 Re-add Puc_v4_Factory for better backwards compatibility.
This way developers that used an older 4.x version shouldn't need to change their code when they update to this version.
2017-11-26 21:40:17 +02:00
Yahnis Elsts ec5ee45379 Show API errors when manually checking for updates.
Introduces a new hook: "puc_api_error". This is an action with up to 4 callback arguments:

1) $error - A WP_Error instance that provides a brief description of the error.
2) $response - The value returned by wp_remote_get(). Can be omitted if the original response is not available at this point.
3) $url - The URL that the update checker requested. Can be omitted.
4) $slug - The plugin or theme slug. Can be omitted. 


See #151
2017-11-24 17:36:15 +02:00
Yahnis Elsts 585f60d91c Add the ability to show a plugin icon on the "Dashboard -> Updates" page.
Usage: Add the following entry to your JSON file:

"icons" : {
	"1x" : "http://example.com/assets/icon-128x128.png",
	"2x" : "http://example.com/assets/icon-256x256.png",
	"svg": "http://example.com/assets/icon.svg"
} 

All of the keys are optional. They should point to different versions of the same icon:
- "1x": a 128x128 px image.
- "2x": a 256x256 px image for HiDPI screens.
- "svg": a vector version of the icon.

See WordPress.org for more information on supported icon sizes and image formats:  
https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons

Suggested in #153
2017-11-21 22:11:18 +02:00
Yahnis Elsts 150d3d8165 Rename Puc_v4_Factory to Puc_v4p3_Factory
This should fix the fatal error that happens when running PUC 4.3 together with an older 4.x release while Debug Bar is active.

See #152
2017-11-16 17:00:22 +02:00
Yahnis Elsts 22fd23a32b Fix: Remove left-over debugging code. 2017-11-03 19:20:11 +02:00
Yahnis Elsts 548b9fbec7 Minor: Fix incorrect link text in the readme 2017-11-03 13:45:11 +02:00
Yahnis Elsts 8be2d1d966 Minor: Fix another spelling error and reformat comments for consistency 2017-11-03 13:44:29 +02:00
Yahnis Elsts 1a7d95a017 Minor: Fix a spelling error in method name 2017-11-03 13:23:53 +02:00
Yahnis Elsts 92763829c6 Bump version number to 4.3 2017-11-03 13:22:55 +02:00
Yahnis Elsts 3a1f929a7f VCS integration: Support alternative readme.txt capitalisations
Apparently, some developers call the file "README.txt" instead of "readme.txt". Most version control systems are case-sensitive, so we need to known the exact capitalisation to successfully retrieve the readme from the repository. Let's search the plugin directory to find the local readme file and then use that name. 

Closes #147
2017-11-02 13:49:17 +02:00
Yahnis Elsts 9d9bab0462 Minor: Reformat and refactor addViewDetailsLink()
- WordPress escapes the site URL when building the "Visit plugin site" link, so we need to look for the escaped URL instead of the raw string.
- Using regexps is probably overkill. A simple string search will do.
- Add a default case to the switch in case a plugin returns an invalid link position.
- Move the "view_details_link_position" filter inside the foreach loop to eliminate an if().
- Move the slug check closer to the top. There's no point in running the "view_details_link" filter if the link isn't going to be shown anyway.
2017-11-02 10:13:21 +02:00
Yahnis Elsts fa412cad65
Merge pull request #146 from Mikk3lRo/always-show-details-link
Always show the "View details" link
2017-11-02 09:47:59 +02:00
Mikk3lRo eaa06eae6c My IDE still refuses to use tabs for indentation - sorry :p 2017-11-01 16:53:50 +01:00
Mikk3lRo 5703f6e338 Make "Visit Plugin Site"-link detection more robust and correct comment to reflect new default position. 2017-11-01 16:51:33 +01:00
Mikk3lRo 727b99573c Rename first -> before and last -> after and set default to before for placement of View details link. 2017-11-01 16:39:00 +01:00
Mikk3lRo 844c1fdb53 Update docblock 2017-10-31 03:07:23 +01:00
Mikk3lRo 1ebe29e1a4 Add spaces inside some paranthesis. 2017-10-31 03:04:04 +01:00
Mikk3lRo 5a4e5a44a2 Remove filter to add View Details Link. Extend / modify order of links. 2017-10-31 02:35:00 +01:00
Mikk3lRo eb12e77706 Added third argument to addViewDetailsLink. 2017-10-30 19:18:52 +01:00
Mikk3lRo 5e987d8982 Use the same method of checking for empty linkText as used in the pre-
existing addCheckForUpdatesLink
2017-10-23 23:59:09 +02:00
Mikk3lRo e5d96dbf05 Whoops, we use tabs in this one, not spaces. 2017-10-23 23:49:14 +02:00
Mikk3lRo d39c1e400c Wrong hook 2017-10-23 23:41:00 +02:00
Mikk3lRo 732179b0c0 Always show the plugin details link on the plugin list 2017-10-23 23:38:36 +02:00
Yahnis Elsts 1d3893edf9 Merge pull request #143 from Mikk3lRo/add-danish-language
Add Danish translation.
2017-10-17 19:44:46 +03:00
Mikkel-i123 1f810e1015 Add Danish translation. 2017-10-17 11:07:53 +02:00
Yahnis Elsts 21814c43a3 Merge pull request #141 from dylanmoller/master
Add Swedish translation
2017-10-17 11:48:21 +03:00
dylanmoller 6ae193fb26 added po/mo language files for Swedish translation 2017-10-16 15:23:20 +02:00
Yahnis Elsts 18818714c3 Merge pull request #140 from DavidAnderson684/patch-9
Use the wp_get_installed_translations function conditionally

This function was introduced in WP 3.7.
2017-10-13 19:09:03 +03:00
David Anderson f0a10eaca9 Use a WP 3.7+ function conditionally
`wp_get_installed_translations()` was introduced in WP 3.7. This change returns an empty result for the translations list if the function does not exist. (Encountered in the wild, fatal error).
2017-10-13 12:26:16 +00:00
Yahnis Elsts 818ceaffc0 Merge pull request #139 from Mikk3lRo/add-note-about-134
Add note about issue #134 until a better solution is found.
2017-10-11 17:47:13 +03:00
Yahnis Elsts e48d41e30d Remove PUC hooks upon uninstallation to prevent a crash
See #138 for details.
2017-10-11 17:24:23 +03:00
Mikkel-i123 500e5ebb86 Add note about issue #134 until a better solution is found. 2017-10-10 16:41:48 +02:00
Yahnis Elsts 1cc6a90acf Merge pull request #137 from aaronkirkham/master
GitLab Integration
2017-10-06 10:56:25 +03:00
aaronlad 58e28b8fd7 code style consistency changes 2017-10-05 16:52:41 +01:00
Yahnis Elsts 76c3e1cea1 Merge pull request #136 from DavidAnderson684/patch-8
Work on WP versions without wp_normalize_path()
2017-09-30 19:12:38 +03:00
David Anderson aa4272cbcc Correct typo 2017-09-30 16:08:50 +00:00
David Anderson 36eb8e3b10 Use Puc_v4_Factory::normalizePath() 2017-09-30 16:06:46 +00:00
David Anderson 972d649614 Make normalizePath public 2017-09-30 16:03:50 +00:00
aaronkirkham07@gmail.com 50b5d7170e removed getLatestCommit method
removed Factory magic to detect self-hosted gitlab instances
updated readme with gitlab instructions
2017-09-30 16:15:00 +01:00
David Anderson 2f225bdcce Code style consistency 2017-09-30 14:40:07 +00:00
aaronkirkham07@gmail.com a2ca0ba0f2 support gitlab instances installed in a subdirectory
no longer checking for 'gitlab' in the hostname
2017-09-30 15:38:16 +01:00
Yahnis Elsts 8db5115e69 Minor: Update year in license.txt 2017-09-30 12:34:06 +03:00
aaronkirkham07@gmail.com ccc07e9ce3 sprintf consistency 2017-09-30 01:55:37 +01:00
aaronkirkham07@gmail.com 4339460aed fix weird tab/spaces 2017-09-30 01:45:09 +01:00
aaronkirkham07@gmail.com cf2c07a531 support downloads from gitlab
added support for branches
implemented getLatestCommitTime method
2017-09-30 01:32:10 +01:00
aaronkirkham07@gmail.com 84f2efda8f fix spaces 2017-09-30 00:45:46 +01:00
aaronkirkham07@gmail.com 3760c5140e initial support for GitLab 2017-09-30 00:43:58 +01:00
David Anderson fbe1d818c1 Work on WP versions without wp_normalize_path()
WP < 3.9 does not have the wp_normalize_path() function available. This edit restores the ability to work on such versions.
2017-09-29 21:37:31 +00:00
Yahnis Elsts a0e272295a Merge pull request #131 from anugupta/PHP7
Fix a false-positive PHP 7 compatibility issue

Several users have reported a PHP 7 compatibility issue in ParsedownLegacy.php. This file is never used on sites running PHP 7 (it's a back-compat thing for PHP 5.2 and below), but it seems like a good idea to merge the fix anyway as it will prevent any more time being wasted on this issue.
2017-09-07 11:22:38 +03:00
Anu Gupta c7fcfb38b1 Force evaluation order for PHP 7 conpat
As per http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect

In PHP 7, indirect access to variables, properties, and methods is now evaluated strictly in left-to-right order. Code that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces
2017-09-07 00:49:29 +01:00
Yahnis Elsts 846d111947 Bump version: Step 2: Rename subdirectory 2017-07-21 14:27:31 +03:00
Yahnis Elsts f74c67145b Bump version number to 4.2 (step 1) 2017-07-21 14:16:21 +03:00
Yahnis Elsts f0cc400fbd Refactor GitHubAPI: Extract URL generation as a method.
The code that builds API URLs is probably complicated enough to warrant a separate method: it performs placeholder substitution, does authentication-related stuff (access_token), and builds the query string.
2017-07-21 12:08:37 +03:00
Yahnis Elsts f352474fd0 Minor: Simplify Utils::get()
Behaviour change: An empty path now returns the collection itself, not the default value. This doesn't really matter for the current version because it only uses constant, non-empty paths.
2017-07-20 20:23:42 +03:00
Yahnis Elsts 4fd8135f17 Minor: Explicit visibility for methods 2017-07-20 19:54:44 +03:00
Yahnis Elsts 2b96d033a5 Minor: Use strict comparisons 2017-07-20 19:52:45 +03:00
Yahnis Elsts c98ccca312 Merge pull request #117 from DavidAnderson684/patch-7
Make wp_remote_get result filterable in requestMetadata

New filter name: puc_request_metadata_http_result-$slug OR puc_request_metadata_http_result_theme-$slug
2017-07-18 11:54:22 +03:00
David Anderson 7061a5b195 Update UpdateChecker.php
Tweak filter name
2017-07-17 21:27:23 +00:00
David Anderson ef91a9409d Make wp_remote_get result filterable
I want to filter the wp_remote_get result. In my use-case, if https fails, I switch back to http (in case the user had a bad curl setup/obsolete SSL certificates) and try again.

Until now I've been patching the code, but that is, of course, silly!
2017-07-17 14:12:39 +00:00
Yahnis Elsts 8e4959a17b Merge pull request #116 from rvola/master
Updated French translation
2017-07-07 16:16:05 +03:00
Nicolas GEHIN e036e0d775 Updated language file french 2017-07-07 14:55:53 +02:00
Yahnis Elsts 2c7a113010 Merge pull request #115 from Pryx/master
Add a Czech translation
2017-07-05 18:52:17 +03:00
Vojtěch Sajdl d3aeafa06c Czech translation 2017-07-05 17:42:09 +02:00
Yahnis Elsts be797d2f7a Suppress warnings about set_time_limit being disabled.
Some hosts disable set_time_limit() and a few other functions. Calling the disabled function triggers a warning. In our case, using set_time_limit() is optional - PUC will usually work fine even if it can't increase the time limit - so lets just ignore the warning and carry on. 

Reported in #111.
2017-06-17 22:18:41 +03:00
Yahnis Elsts 8f39bceb12 Merge pull request #108 from GoodMorningCall/update-Japanese-POT-for-v4.1
Update Japanese translation for v4.1
2017-06-04 10:23:33 +03:00
tak 9555c169fa Update for v4.1
Update Japanese translations to adapt to v4.1
2017-06-04 15:30:44 +09:00
Yahnis Elsts c81fd974d1 Update POT to include _x() contexts 2017-05-20 10:59:45 +03:00
Yahnis Elsts 6f5e7a478c Merge pull request #104 from iiandrade/master
Add Portuguese Brazilian translation
2017-05-20 10:54:44 +03:00
Italo Izaac d6a34a0f36 Portuguese Brazilian translation 2017-05-19 16:02:28 -03:00
Yahnis Elsts 235a810e90 Fix an issue with Debug Bar 0.9 where the content of some PUC panels was not visible. See issue #102.
Cause: Debug Bar 0.9 now includes an admin bar menu that lists the available panels. This means that the special element that PUC uses to identify its panel titles (<span id="puc-debug-menu-link-$uid">) is no longer unique. This breaks the JS that's supposed to work around the fact that Debug Bar incorrectly assumes that every panel will have a unique PHP class name.
2017-05-16 21:16:08 +03:00
Yahnis Elsts ea2bf49144 Minor: Remove commented-out code. 2017-05-01 13:20:22 +03:00
Yahnis Elsts d4c32356fb Fix metadata documentation link 2017-04-28 18:36:43 +03:00
Yahnis Elsts 22689ce0cc Add GitHub API response to the `Vcs_Reference` instance.
This is intended for use in subclasses, e.g. to change the `downloadUrl` from `zipball_url` to an asset URL.
2017-04-12 12:13:53 +03:00
Yahnis Elsts a3f314b052 Update POT file 2017-04-07 15:58:40 +03:00
Yahnis Elsts e1395c0c22 Update readme 2017-04-07 15:45:33 +03:00
Yahnis Elsts 164aacf4c1 Bump version number to 4.1
This may look like a lot of changes, but it's essentially a simple search & replace from "v4" to "v4p1". Note that the factory class name stays the same: Puc_v4_Factory. It will only change on a major release.
2017-04-06 16:32:40 +03:00
Yahnis Elsts 28dc39ae58 Minor: Adjust code spacing 2017-04-04 20:29:03 +03:00
Yahnis Elsts b4b0f15e53 Merge pull request #91 from RichardCoffee/master
Add plugin title to admin notice
2017-04-04 20:26:10 +03:00
Laptop 3 6cabab9179 Add plugin title to admin notice 2017-04-04 01:55:45 -04:00
Yahnis Elsts f812b2d3c0 Fix a rare error caused by a bug get_theme_root()
This is workaround that addresses a potential issue with automagic plugin vs theme detection. A user reports that sometimes get_theme_root() can return an empty string when using AMP. Also, there can be multiple theme roots. 

Instead of dealing with that mess, lets simply look for a style.css file in the same directory as $absolutePath. This approach has low specificity (i.e. a plugin could have a style.css file), so it should have lower priority. I've moved it after the isPluginFile() check.

BC note: This means that when using PUC in a theme, the second argument to buildUpdateChecker() *must* be either the theme directory path, or a path to a file at the root of the theme. That is, all of these will work fine:
 /foo/wp-content/themes/my-theme
 /foo/wp-content/themes/my-theme/functions.php
 /foo/wp-content/themes/my-theme/another-php-file.php
 
 This will NOT work:
 /foo/wp-content/themes/my-theme/includes/something.php 
 
 This shouldn't be an issue for people who followed the documentation.
2017-04-03 17:56:13 +03:00
Yahnis Elsts 5c963ff869 TODO: Work around a WP bug and multiple theme directories 2017-03-30 13:52:18 +03:00
Yahnis Elsts e85abe6317 Merge pull request #89 from GoodMorningCall/add-japanese-language-file
Add Japanese translation
2017-02-26 12:59:44 +02:00
tak 72e92f0b5a Add Japanese language 2017-02-26 15:08:21 +09:00
Yahnis Elsts 749f364e4d Enable Composer autoloading.
Very bare-bones stuff, it just includes plugin-update-checker.php.
2017-02-08 16:45:19 +02:00
Yahnis Elsts b1d2b98197 Send PHP version and WP locale as query parameters.
Possible uses:
- See when it's safe to raise PHP version requirements.
- Avoid showing users updates that are incompatible with their PHP version.
- Have an LTS branch for people running old PHP versions, and deliver different update packages based on the version.
- Return updates for only those language packs that match the site locale, not all available languages.
2017-02-05 15:46:03 +02:00
Yahnis Elsts f2a2f80678 Minor: Bump version number 2017-01-31 17:42:57 +02:00
Yahnis Elsts e4854cdb38 BitBucket fix: When looking for the latest tags, sort them by commit date in descending order.
Previously, PUC didn't specify any explicit sorting criteria. I incorrectly assumed that BitBucket would return the most recent tags first. As a result, when a repository had enough tags to trigger API response pagination, PUC could miss some recent tags. Related: #48
2017-01-24 12:18:34 +02:00
Yahnis Elsts fbff383b7e Fix downloads from private GitHub repositories.
Cause: GitHub API client didn't sign download URLs (oops!). See #84
2017-01-17 09:13:17 +02:00
Yahnis Elsts f171bdf42e Merge pull request #83 from LDAV/patch-1
Add Italian translation. Props to @LDAV
2017-01-16 12:52:34 +02:00
LDAV 495c29a02d Italian language 2017-01-16 10:54:47 +01:00
LDAV a44a53da5e Italian translation 2017-01-15 12:28:16 +01:00
Yahnis Elsts 8a04b9679e Improve plugin detection. Related to #82.
Technically, it's possible to place a plugin anywhere outside the WordPress directory and then create a symlink inside /wp-content/plugins that points to the plugin directory. If the plugin developer then passes the real, symlink-resolved path to the PUC factory, PUC will assume it can't be a plugin because it's not inside the expected directory.
  
Semi-fixed by checking if the input file contains a valid plugin header. However, I would still recommend against using symlinks in this manner because it's likely to cause odd bugs elsewhere. For example, __FILE__ resolves symlinks but plugin_basename() doesn't. This means that the basename that WP sees and the basename you generate in your own code might not match.
2017-01-14 12:39:24 +02:00
Yahnis Elsts 467000eb73 Fail immediately if PUC can't tell whether it's being used in a plugin or a theme.
In theory, that should never happen, but the bug reported in #82 shows that it does.
2017-01-14 11:28:30 +02:00
Yahnis Elsts fd62858e90 Fix "Cannot declare class Puc_v4_Autoloader".
Oops, I knew I'd missed something! Well, this is that something.
2017-01-13 18:49:54 +02:00
129 changed files with 6232 additions and 3241 deletions

15
.editorconfig Normal file
View File

@ -0,0 +1,15 @@
[*]
charset=utf-8
end_of_line=lf
insert_final_newline=false
indent_style=tab
tab_width=4
[{phpunit.xml.dist,*.jhm,*.xslt,*.xul,*.rng,*.xsl,*.xsd,*.ant,*.tld,*.fxml,*.jrxml,*.xml,*.jnlp,*.wsdl}]
indent_style=space
indent_size=4
[*.svg]
indent_style=space
indent_size=4

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

40
.gitignore vendored Normal file
View File

@ -0,0 +1,40 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# The entire IDEA/PhpStorm directory
.idea/
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

View File

@ -1,45 +0,0 @@
<?php
class Puc_v4_Autoloader {
private $prefix = '';
private $rootDir = '';
private $libraryDir = '';
private $staticMap;
public function __construct() {
$this->rootDir = dirname(__FILE__) . '/';
$nameParts = explode('_', __CLASS__, 3);
$this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
$this->libraryDir = realpath($this->rootDir . '../..') . '/';
$this->staticMap = array(
'PucReadmeParser' => 'vendor/readme-parser.php',
'Parsedown' => 'vendor/ParsedownLegacy.php',
);
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
$this->staticMap['Parsedown'] = 'vendor/Parsedown.php';
}
spl_autoload_register(array($this, 'autoload'));
}
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;
}
}
}
}

View File

@ -1,117 +0,0 @@
<?php
if ( !class_exists('Puc_v4_DebugBar_Extension', false) ):
class Puc_v4_DebugBar_Extension {
/** @var Puc_v4_UpdateChecker */
protected $updateChecker;
protected $panelClass = 'Puc_v4_DebugBar_Panel';
public function __construct($updateChecker, $panelClass = null) {
$this->updateChecker = $updateChecker;
if ( isset($panelClass) ) {
$this->panelClass = $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'));
}
/**
* Register the PUC Debug Bar panel.
*
* @param array $panels
* @return array
*/
public function addDebugBarPanel($panels) {
if ( $this->updateChecker->userCanInstallUpdates() ) {
$panels[] = new $this->panelClass($this->updateChecker);
}
return $panels;
}
/**
* Enqueue our Debug Bar scripts and styles.
*/
public function enqueuePanelDependencies() {
wp_enqueue_style(
'puc-debug-bar-style-v4',
$this->getLibraryUrl("/css/puc-debug-bar.css"),
array('debug-bar'),
'20161217'
);
wp_enqueue_script(
'puc-debug-bar-js-v4',
$this->getLibraryUrl("/js/debug-bar.js"),
array('jquery'),
'20161219'
);
}
/**
* Run an update check and output the result. Useful for making sure that
* the update checking process works as expected.
*/
public function ajaxCheckNow() {
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
return;
}
$this->preAjaxReqest();
$update = $this->updateChecker->checkForUpdates();
if ( $update !== null ) {
echo "An update is available:";
echo '<pre>', htmlentities(print_r($update, true)), '</pre>';
} else {
echo 'No updates found.';
}
exit;
}
/**
* Check access permissions and enable error display (for debugging).
*/
protected function preAjaxReqest() {
if ( !$this->updateChecker->userCanInstallUpdates() ) {
die('Access denied');
}
check_ajax_referer('puc-ajax');
error_reporting(E_ALL);
@ini_set('display_errors','On');
}
/**
* @param string $filePath
* @return string
*/
private function getLibraryUrl($filePath) {
$absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/'));
//Where is the library located inside the WordPress directory structure?
$absolutePath = wp_normalize_path($absolutePath);
$pluginDir = wp_normalize_path(WP_PLUGIN_DIR);
$muPluginDir = wp_normalize_path(WPMU_PLUGIN_DIR);
$themeDir = wp_normalize_path(get_theme_root());
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
//It's part of a plugin.
return plugins_url(basename($absolutePath), $absolutePath);
} else if ( strpos($absolutePath, $themeDir) === 0 ) {
//It's part of a theme.
$relativePath = substr($absolutePath, strlen($themeDir) + 1);
$template = substr($relativePath, 0, strpos($relativePath, '/'));
$baseUrl = get_theme_root_uri($template);
if ( !empty($baseUrl) && $relativePath ) {
return $baseUrl . '/' . $relativePath;
}
}
return '';
}
}
endif;

View File

@ -1,33 +0,0 @@
<?php
if ( !class_exists('Puc_v4_DebugBar_PluginExtension', false) ):
class Puc_v4_DebugBar_PluginExtension extends Puc_v4_DebugBar_Extension {
/** @var Puc_v4_Plugin_UpdateChecker */
protected $updateChecker;
public function __construct($updateChecker) {
parent::__construct($updateChecker, 'Puc_v4_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->preAjaxReqest();
$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_v4_DebugBar_PluginPanel', false) ):
class Puc_v4_DebugBar_PluginPanel extends Puc_v4_DebugBar_Panel {
/**
* @var Puc_v4_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_v4_DebugBar_ThemePanel', false) ):
class Puc_v4_DebugBar_ThemePanel extends Puc_v4_DebugBar_Panel {
/**
* @var Puc_v4_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;

View File

@ -1,232 +0,0 @@
<?php
if ( !class_exists('Puc_v4_Factory', false) ):
/**
* A factory that builds update checker instances.
*
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
* and 4.1), this factory will always use the latest available minor version. Register class
* versions by calling {@link PucFactory::addVersion()}.
*
* 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_v4_Factory {
protected static $classVersions = array();
protected static $sorted = false;
protected static $myMajorVersion = '';
protected static $latestCompatibleVersion = '';
/**
* Create a new instance of the update checker.
*
* 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_v4_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 $muPluginFile The plugin filename relative to the mu-plugins directory.
* @return Puc_v4_Plugin_UpdateChecker|Puc_v4_Theme_UpdateChecker|Puc_v4_Vcs_BaseChecker
*/
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$fullPath = wp_normalize_path($fullPath);
$id = null;
//Plugin or theme?
if ( self::isPluginFile($fullPath) ) {
$type = 'Plugin';
$id = $fullPath;
} else {
$type = 'Theme';
//Get the name of the theme's directory. E.g. "wp-content/themes/foo/whatever.php" => "foo".
$themeRoot = wp_normalize_path(get_theme_root());
$pathComponents = explode('/', substr($fullPath, strlen($themeRoot) + 1));
$id = $pathComponents[0];
}
//Which hosting service does the URL point to?
$service = self::getVcsService($metadataUrl);
$apiClass = null;
if ( empty($service) ) {
//The default is to get update information from a remote JSON file.
$checkerClass = $type . '_UpdateChecker';
} else {
//You can also use a VCS repository like GitHub.
$checkerClass = 'Vcs_' . $type . 'UpdateChecker';
$apiClass = $service . 'Api';
}
$checkerClass = self::getCompatibleClassVersion($checkerClass);
if ( $checkerClass === null ) {
trigger_error(
sprintf(
'PUC %s does not support updates for %ss %s',
htmlentities(self::$latestCompatibleVersion),
strtolower($type),
$service ? ('hosted on ' . htmlentities($service)) : 'using JSON metadata'
),
E_USER_ERROR
);
return null;
}
if ( !isset($apiClass) ) {
//Plain old update checker.
return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
} else {
//VCS checker + an API client.
$apiClass = self::getCompatibleClassVersion($apiClass);
if ( $apiClass === null ) {
trigger_error(sprintf(
'PUC %s does not support %s',
htmlentities(self::$latestCompatibleVersion),
htmlentities($service)
), E_USER_ERROR);
return null;
}
return new $checkerClass(
new $apiClass($metadataUrl),
$id,
$slug,
$checkPeriod,
$optionName,
$muPluginFile
);
}
}
/**
* Check if the path points to something inside the "plugins" or "mu-plugins" directories.
*
* @param string $absolutePath
* @return bool
*/
protected static function isPluginFile($absolutePath) {
$pluginDir = wp_normalize_path(WP_PLUGIN_DIR);
$muPluginDir = wp_normalize_path(WPMU_PLUGIN_DIR);
$absolutePath = wp_normalize_path($absolutePath);
return (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0);
}
/**
* Get the name of the hosting service that the URL points to.
*
* @param string $metadataUrl
* @return string|null
*/
private static function getVcsService($metadataUrl) {
$service = null;
//Which hosting service does the URL point to?
$host = @parse_url($metadataUrl, PHP_URL_HOST);
$path = @parse_url($metadataUrl, PHP_URL_PATH);
//Check if the path looks like "/user-name/repository".
$usernameRepoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
if ( preg_match($usernameRepoRegex, $path) ) {
$knownServices = array(
'github.com' => 'GitHub',
'bitbucket.org' => 'BitBucket',
'gitlab.com' => 'GitLab',
);
if ( isset($knownServices[$host]) ) {
$service = $knownServices[$host];
}
}
return $service;
}
/**
* Get the latest version of the specified class that has the same major version number
* as this factory class.
*
* @param string $class Partial class name.
* @return string|null Full class name.
*/
protected static function getCompatibleClassVersion($class) {
if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
return self::$classVersions[$class][self::$latestCompatibleVersion];
}
return null;
}
/**
* Get the specific class name for the latest available version of a class.
*
* @param string $class
* @return null|string
*/
public static function getLatestClassVersion($class) {
if ( !self::$sorted ) {
self::sortVersions();
}
if ( isset(self::$classVersions[$class]) ) {
return reset(self::$classVersions[$class]);
} else {
return null;
}
}
/**
* Sort available class versions in descending order (i.e. newest first).
*/
protected static function sortVersions() {
foreach ( self::$classVersions as $class => $versions ) {
uksort($versions, array(__CLASS__, 'compareVersions'));
self::$classVersions[$class] = $versions;
}
self::$sorted = true;
}
protected static function compareVersions($a, $b) {
return -version_compare($a, $b);
}
/**
* Register a version of a class.
*
* @access private This method is only for internal use by the library.
*
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
* @param string $version Version number, e.g. '1.2'.
*/
public static function addVersion($generalClass, $versionedClass, $version) {
if ( empty(self::$myMajorVersion) ) {
$nameParts = explode('_', __CLASS__, 3);
self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1);
}
//Store the greatest version number that matches our major version.
$components = explode('.', $version);
if ( $components[0] === self::$myMajorVersion ) {
if (
empty(self::$latestCompatibleVersion)
|| version_compare($version, self::$latestCompatibleVersion, '>')
) {
self::$latestCompatibleVersion = $version;
}
}
if ( !isset(self::$classVersions[$generalClass]) ) {
self::$classVersions[$generalClass] = array();
}
self::$classVersions[$generalClass][$version] = $versionedClass;
self::$sorted = false;
}
}
endif;

View File

@ -1,274 +0,0 @@
<?php
if ( !class_exists('Puc_v4_Vcs_GitHubApi', false) ):
class Puc_v4_Vcs_GitHubApi extends Puc_v4_Vcs_Api {
/**
* @var string GitHub username.
*/
protected $userName;
/**
* @var string GitHub repository name.
*/
protected $repositoryName;
/**
* @var string Either a fully qualified repository URL, or just "user/repo-name".
*/
protected $repositoryUrl;
/**
* @var string GitHub authentication token. Optional.
*/
protected $accessToken;
public function __construct($repositoryUrl, $accessToken = null) {
$path = @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 . '"');
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitHub.
*
* @return Puc_v4_Vcs_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_v4_Vcs_Reference(array(
'name' => $release->tag_name,
'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
'downloadUrl' => $this->signDownloadUrl($release->zipball_url),
'updated' => $release->created_at,
));
if ( !empty($release->body) ) {
/** @noinspection PhpUndefinedClassInspection */
$reference->changelog = Parsedown::instance()->text($release->body);
}
if ( isset($release->assets[0]) ) {
$reference->downloadCount = $release->assets[0]->download_count;
}
return $reference;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4_Vcs_Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Puc_v4_Vcs_Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->signDownloadUrl($tag->zipball_url),
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Puc_v4_Vcs_Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Puc_v4_Vcs_Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
));
if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
$reference->updated = $branch->commit->commit->author->date;
}
return $reference;
}
/**
* Get the latest commit that changed the specified file.
*
* @param string $filename
* @param string $ref Reference name (e.g. branch or tag).
* @return StdClass|null
*/
public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api(
'/repos/:user/:repo/commits',
array(
'path' => $filename,
'sha' => $ref,
)
);
if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
return $commits[0];
}
return null;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
return $commits[0]->commit->author->date;
}
return null;
}
/**
* Perform a GitHub API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|WP_Error
*/
protected function api($url, $queryParams = array()) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace('/:' . $name, '/' . urlencode($value), $url);
}
$url = 'https://api.github.com' . $url;
if ( !empty($this->accessToken) ) {
$queryParams['access_token'] = $this->accessToken;
}
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
$options = array('timeout' => 10);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
return $document;
}
return new WP_Error(
'puc-github-http-error',
'GitHub API error. HTTP status: ' . $code
);
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$apiUrl = '/repos/:user/:repo/contents/' . $path;
$response = $this->api($apiUrl, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
urlencode($this->userName),
urlencode($this->repositoryName),
urlencode($ref)
);
if ( !empty($this->accessToken) ) {
$url = $this->signDownloadUrl($url);
}
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4_Vcs_Reference|null
*/
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.');
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
}
/**
* Figure out which reference (i.e tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
if ( $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);
}
return $updateSource;
}
}
endif;

View File

@ -1,101 +0,0 @@
<?php
if ( !class_exists('Puc_v4_Vcs_ThemeUpdateChecker', false) ):
class Puc_v4_Vcs_ThemeUpdateChecker extends Puc_v4_Theme_UpdateChecker implements Puc_v4_Vcs_BaseChecker {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
/**
* @var Puc_v4_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4_Vcs_ThemeUpdateChecker constructor.
*
* @param Puc_v4_Vcs_Api $api
* @param null $stylesheet
* @param null $customSlug
* @param int $checkPeriod
* @param string $optionName
*/
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);
}
public function requestUpdate() {
$api = $this->api;
$update = new Puc_v4_Theme_Update();
$update->slug = $this->slug;
//Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$update->download_url = $updateSource->downloadUrl;
} else {
$ref = $this->branch;
}
//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->getFileHeader($api->getRemoteFile('style.css', $ref));
$update->version = Puc_v4_Utils::findNotEmpty(array(
$remoteHeader['Version'],
Puc_v4_Utils::get($updateSource, 'version'),
));
//The details URL defaults to the Theme URI header or the repository URL.
$update->details_url = Puc_v4_Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'],
$this->theme->get('ThemeURI'),
$this->metadataUrl,
));
if ( empty($update->version) ) {
//It looks like we didn't find a valid update after all.
$update = null;
}
$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 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;

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

@ -0,0 +1,199 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
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 UpdateChecker */
protected $updateChecker;
protected $panelClass = Panel::class;
public function __construct($updateChecker, $panelClass = null) {
$this->updateChecker = $updateChecker;
if ( isset($panelClass) ) {
$this->panelClass = $panelClass;
}
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_v5_debug_check_now', array($this, 'ajaxCheckNow'));
}
/**
* Register the PUC Debug Bar panel.
*
* @param array $panels
* @return array
*/
public function addDebugBarPanel($panels) {
if ( $this->updateChecker->userCanInstallUpdates() ) {
$panels[] = new $this->panelClass($this->updateChecker);
}
return $panels;
}
/**
* Enqueue our Debug Bar scripts and styles.
*/
public function enqueuePanelDependencies() {
wp_enqueue_style(
'puc-debug-bar-style-v5',
$this->getLibraryUrl("/css/puc-debug-bar.css"),
array('debug-bar'),
'20221008'
);
wp_enqueue_script(
'puc-debug-bar-js-v5',
$this->getLibraryUrl("/js/debug-bar.js"),
array('jquery'),
'20221008'
);
}
/**
* Run an update check and output the result. Useful for making sure that
* the update checking process works as expected.
*/
public function ajaxCheckNow() {
//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:";
//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.';
}
$errors = $this->updateChecker->getLastRequestApiErrors();
if ( !empty($errors) ) {
printf('<p>The update checker encountered %d API error%s.</p>', count($errors), (count($errors) > 1) ? 's' : '');
foreach (array_values($errors) as $num => $item) {
$wpError = $item['error'];
/** @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()));
if ( isset($item['url']) ) {
printf('<dt>Requested URL:</dt><dd><code>%s</code></dd>', esc_html($item['url']));
}
if ( isset($item['httpResponse']) ) {
if ( is_wp_error($item['httpResponse']) ) {
$httpError = $item['httpResponse'];
/** @var \WP_Error $httpError */
printf(
'<dt>WordPress HTTP API error:</dt><dd>%s (<code>%s</code>)</dd>',
esc_html($httpError->get_error_message()),
esc_html($httpError->get_error_code())
);
} else {
//Status code.
printf(
'<dt>HTTP status:</dt><dd><code>%d %s</code></dd>',
esc_html(wp_remote_retrieve_response_code($item['httpResponse'])),
esc_html(wp_remote_retrieve_response_message($item['httpResponse']))
);
//Headers.
echo '<dt>Response headers:</dt><dd><pre>';
foreach (wp_remote_retrieve_headers($item['httpResponse']) as $name => $value) {
printf("%s: %s\n", esc_html($name), esc_html($value));
}
echo '</pre></dd>';
//Body.
$body = wp_remote_retrieve_body($item['httpResponse']);
if ( $body === '' ) {
$body = '(Empty response.)';
} else if ( strlen($body) > self::RESPONSE_BODY_LENGTH_LIMIT ) {
$length = strlen($body);
$body = substr($body, 0, self::RESPONSE_BODY_LENGTH_LIMIT)
. sprintf("\n(Long string truncated. Total length: %d bytes.)", $length);
}
printf('<dt>Response body:</dt><dd><pre>%s</pre></dd>', esc_html($body));
}
}
echo '<dl>';
}
}
exit;
}
/**
* Check access permissions and enable error display (for debugging).
*/
protected function preAjaxRequest() {
if ( !$this->updateChecker->userCanInstallUpdates() ) {
die('Access denied');
}
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');
}
/**
* Remove hooks that were added by this extension.
*/
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_v5_debug_check_now', array($this, 'ajaxCheckNow'));
}
/**
* @param string $filePath
* @return string
*/
private function getLibraryUrl($filePath) {
$absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/'));
//Where is the library located inside the WordPress directory structure?
$absolutePath = PucFactory::normalizePath($absolutePath);
$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.
return plugins_url(basename($absolutePath), $absolutePath);
} else if ( strpos($absolutePath, $themeDir) === 0 ) {
//It's part of a theme.
$relativePath = substr($absolutePath, strlen($themeDir) + 1);
$template = substr($relativePath, 0, strpos($relativePath, '/'));
$baseUrl = get_theme_root_uri($template);
if ( !empty($baseUrl) && $relativePath ) {
return $baseUrl . '/' . $relativePath;
}
}
return '';
}
}
endif;

View File

@ -1,9 +1,12 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists('Puc_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Panel', false) ):
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker;
class Puc_v4_DebugBar_Panel extends Debug_Bar_Panel {
/** @var Puc_v4_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>';
@ -11,7 +14,7 @@ if ( !class_exists('Puc_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
$title = sprintf(
'<span id="puc-debug-menu-link-%s">PUC (%s)</span>',
'<span class="puc-debug-menu-link-%s">PUC (%s)</span>',
esc_attr($this->updateChecker->getUniqueName('uid')),
$this->updateChecker->slug
);
@ -20,7 +23,7 @@ if ( !class_exists('Puc_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
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_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
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_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
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_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
$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_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
$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,12 +168,19 @@ if ( !class_exists('Puc_v4_DebugBar_Panel', false) && class_exists('Debug_Bar_Pa
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
);
}
}
endif;
endif;

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

@ -0,0 +1,105 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(InstalledPackage::class, false) ):
/**
* This class represents a currently installed plugin or theme.
*
* 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 InstalledPackage {
/**
* @var UpdateChecker
*/
protected $updateChecker;
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string|null Version number.
*/
abstract public function getInstalledVersion();
/**
* Get the full path of the plugin or theme directory (without a trailing slash).
*
* @return string
*/
abstract public function getAbsoluteDirectoryPath();
/**
* Check whether a regular file exists in the package's directory.
*
* @param string $relativeFileName File name relative to the package directory.
* @return bool
*/
public function fileExists($relativeFileName) {
return is_file(
$this->getAbsoluteDirectoryPath()
. DIRECTORY_SEPARATOR
. ltrim($relativeFileName, '/\\')
);
}
/* -------------------------------------------------------------------
* File header parsing
* -------------------------------------------------------------------
*/
/**
* Parse plugin or theme metadata from the header comment.
*
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
*
* @param string|null $content File contents.
* @return string[]
*/
public function getFileHeader($content) {
$content = (string)$content;
//WordPress only looks at the first 8 KiB of the file, so we do the same.
$content = substr($content, 0, 8192);
//Normalize line endings.
$content = str_replace("\r", "\n", $content);
$headers = $this->getHeaderNames();
$results = array();
foreach ($headers as $field => $name) {
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
if ( ($success === 1) && $matches[1] ) {
$value = $matches[1];
if ( function_exists('_cleanup_header_comment') ) {
$value = _cleanup_header_comment($value);
}
$results[$field] = $value;
} else {
$results[$field] = '';
}
}
return $results;
}
/**
* @return array Format: ['HeaderKey' => 'Header Name']
*/
abstract protected function getHeaderNames();
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @return string Either the value of the header, or an empty string if the header doesn't exist.
*/
abstract public function getHeaderValue($headerName);
}
endif;

View File

@ -1,5 +1,11 @@
<?php
if ( !class_exists('Puc_v4_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_v4_Metadata', false) ):
* @copyright 2016
* @access public
*/
abstract class Puc_v4_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_v4_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_v4_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) ){
trigger_error(
"Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/",
E_USER_NOTICE
);
$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));
//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) ){
trigger_error($valid->get_error_message(), E_USER_NOTICE);
do_action('puc_api_error', $valid);
//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_v4_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_v4_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_v4_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_v4_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_v4_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;
endif;

View File

@ -1,11 +1,12 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4_OAuthSignature', false) ):
if ( !class_exists(OAuthSignature::class, false) ):
/**
* A basic signature generator for zero-legged OAuth 1.0.
*/
class Puc_v4_OAuthSignature {
class OAuthSignature {
private $consumerKey = '';
private $consumerSecret = '';
@ -25,10 +26,10 @@ if ( !class_exists('Puc_v4_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.
@ -80,9 +81,22 @@ if ( !class_exists('Puc_v4_OAuthSignature', false) ):
*/
private function nonce() {
$mt = microtime();
$rand = mt_rand();
$rand = null;
if ( is_callable('random_bytes') ) {
try {
$rand = random_bytes(16);
} catch (\Exception $ex) {
//Fall back to mt_rand (below).
}
}
if ( $rand === null ) {
//phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand
$rand = function_exists('wp_rand') ? wp_rand() : mt_rand();
}
return md5($mt . '_' . $rand);
}
}
endif;
endif;

188
Puc/v5p6/Plugin/Package.php Normal file
View File

@ -0,0 +1,188 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\PucFactory;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/**
* @var UpdateChecker
*/
protected $updateChecker;
/**
* @var string Full path of the main plugin file.
*/
protected $pluginAbsolutePath = '';
/**
* @var string Plugin basename.
*/
private $pluginFile;
/**
* @var string|null
*/
private $cachedInstalledVersion = null;
public function __construct($pluginAbsolutePath, $updateChecker) {
$this->pluginAbsolutePath = $pluginAbsolutePath;
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
parent::__construct($updateChecker);
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
}
public function getInstalledVersion() {
if ( isset($this->cachedInstalledVersion) ) {
return $this->cachedInstalledVersion;
}
$pluginHeader = $this->getPluginHeader();
if ( isset($pluginHeader['Version']) ) {
$this->cachedInstalledVersion = $pluginHeader['Version'];
return $pluginHeader['Version'];
} else {
//This can happen if the filename points to something that is not a plugin.
$this->updateChecker->triggerError(
sprintf(
"Cannot read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->updateChecker->pluginFile
),
E_USER_WARNING
);
return null;
}
}
/**
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
* return the filter argument unmodified.
*
* @param mixed $filterArgument
* @return mixed
*/
public function clearCachedVersion($filterArgument = null) {
$this->cachedInstalledVersion = null;
return $filterArgument;
}
public function getAbsoluteDirectoryPath() {
return dirname($this->pluginAbsolutePath);
}
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @param string $defaultValue
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
*/
public function getHeaderValue($headerName, $defaultValue = '') {
$headers = $this->getPluginHeader();
if ( isset($headers[$headerName]) && ($headers[$headerName] !== '') ) {
return $headers[$headerName];
}
return $defaultValue;
}
protected function getHeaderNames() {
return array(
'Name' => 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
//The newest WordPress version that this plugin requires or has been tested with.
//We support several different formats for compatibility with other libraries.
'Tested WP' => 'Tested WP',
'Requires WP' => 'Requires WP',
'Tested up to' => 'Tested up to',
'Requires at least' => 'Requires at least',
);
}
/**
* Get the translated plugin title.
*
* @return string
*/
public function getPluginTitle() {
$title = '';
$header = $this->getPluginHeader();
if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) {
$title = translate($header['Name'], $header['TextDomain']);
}
return $title;
}
/**
* Get plugin's metadata from its file header.
*
* @return array
*/
public function getPluginHeader() {
if ( !is_file($this->pluginAbsolutePath) ) {
//This can happen if the plugin filename is wrong.
$this->updateChecker->triggerError(
sprintf(
"Can't to read the plugin header for '%s'. The file does not exist.",
$this->updateChecker->pluginFile
),
E_USER_WARNING
);
return array();
}
if ( !function_exists('get_plugin_data') ) {
require_once(ABSPATH . '/wp-admin/includes/plugin.php');
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
}
public function removeHooks() {
remove_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
remove_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
}
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @return bool
*/
public function isMuPlugin() {
static $cachedResult = null;
if ( $cachedResult === null ) {
if ( !defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR) ) {
$cachedResult = false;
return $cachedResult;
}
//Convert both paths to the canonical form before comparison.
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
$pluginPath = realpath($this->pluginAbsolutePath);
//If realpath() fails, just normalize the syntax instead.
if (($muPluginDir === false) || ($pluginPath === false)) {
$muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
$pluginPath = PucFactory::normalizePath($this->pluginAbsolutePath);
}
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
}
return $cachedResult;
}
}
endif;

View File

@ -1,5 +1,9 @@
<?php
if ( !class_exists('Puc_v4_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_v4_Plugin_Info', false) ):
* @copyright 2016
* @access public
*/
class Puc_v4_Plugin_Info extends Puc_v4_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;
@ -16,15 +20,18 @@ if ( !class_exists('Puc_v4_Plugin_Info', false) ):
public $version;
public $homepage;
public $sections = array();
public $banners;
public $translations = array();
public $download_url;
public $banners;
public $icons = array();
public $translations = array();
public $author;
public $author_homepage;
public $requires;
public $tested;
public $requires_php;
public $upgrade_notice;
public $rating;
@ -32,6 +39,7 @@ if ( !class_exists('Puc_v4_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.
@ -51,8 +59,9 @@ if ( !class_exists('Puc_v4_Plugin_Info', false) ):
return null;
}
//json_decode decodes assoc. arrays as objects. We want it as an array.
//json_decode decodes assoc. arrays as objects. We want them as arrays.
$instance->sections = (array)$instance->sections;
$instance->icons = (array)$instance->icons;
return $instance;
}
@ -60,8 +69,8 @@ if ( !class_exists('Puc_v4_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 (
@ -69,7 +78,7 @@ if ( !class_exists('Puc_v4_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."
);
@ -84,13 +93,14 @@ if ( !class_exists('Puc_v4_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.
$sameFormat = array(
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
'requires_php',
);
foreach($sameFormat as $field){
if ( isset($this->$field) ) {
@ -124,4 +134,4 @@ if ( !class_exists('Puc_v4_Plugin_Info', false) ):
}
}
endif;
endif;

294
Puc/v5p6/Plugin/Ui.php Normal file
View File

@ -0,0 +1,294 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
if ( !class_exists(Ui::class, false) ):
/**
* Additional UI elements for plugins.
*/
class Ui {
private $updateChecker;
private $manualCheckErrorTransient = '';
/**
* @param UpdateChecker $updateChecker
*/
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
$this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors');
add_action('admin_init', array($this, 'onAdminInit'));
}
public function onAdminInit() {
if ( $this->updateChecker->userCanInstallUpdates() ) {
$this->handleManualCheck();
add_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10, 3);
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
}
}
/**
* Add a "View Details" link to the plugin row in the "Plugins" page. By default,
* the new link will appear before the "Visit plugin site" link (if present).
*
* You can change the link text by using the "puc_view_details_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* You can change the position of the link using the
* "puc_view_details_link_position-$slug" filter.
* Returning 'before' or 'after' will place the link immediately before/after
* the "Visit plugin site" link.
* Returning 'append' places the link after any existing links at the time of the hook.
* Returning 'replace' replaces the "Visit plugin site" link.
* Returning anything else disables the link when there is a "Visit plugin site" link.
*
* If there is no "Visit plugin site" link 'append' is always used!
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @param array $pluginData Array of plugin header data.
* @return array
*/
public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = array()) {
if ( $this->isMyPluginFile($pluginFile) && !isset($pluginData['slug']) ) {
$linkText = apply_filters($this->updateChecker->getUniqueName('view_details_link'), __('View details'));
if ( !empty($linkText) ) {
$viewDetailsLinkPosition = 'append';
//Find the "Visit plugin site" link (if present).
$visitPluginSiteLinkIndex = count($pluginMeta) - 1;
if ( $pluginData['PluginURI'] ) {
$escapedPluginUri = esc_url($pluginData['PluginURI']);
foreach ($pluginMeta as $linkIndex => $existingLink) {
if ( strpos($existingLink, $escapedPluginUri) !== false ) {
$visitPluginSiteLinkIndex = $linkIndex;
$viewDetailsLinkPosition = apply_filters(
$this->updateChecker->getUniqueName('view_details_link_position'),
'before'
);
break;
}
}
}
$viewDetailsLink = sprintf('<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->slug) .
'&TB_iframe=true&width=600&height=550')),
esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])),
esc_attr($pluginData['Name']),
$linkText
);
switch ($viewDetailsLinkPosition) {
case 'before':
array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink);
break;
case 'after':
array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink);
break;
case 'replace':
$pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink;
break;
case 'append':
default:
$pluginMeta[] = $viewDetailsLink;
break;
}
}
}
return $pluginMeta;
}
/**
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
* the new link will appear after the "Visit plugin site" link if present, otherwise
* after the "View plugin details" link.
*
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @return array
*/
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
if ( $this->isMyPluginFile($pluginFile) ) {
$linkUrl = wp_nonce_url(
add_query_arg(
array(
'puc_check_for_updates' => 1,
'puc_slug' => $this->updateChecker->slug,
),
self_admin_url('plugins.php')
),
'puc_check_for_updates'
);
$linkText = apply_filters(
$this->updateChecker->getUniqueName('manual_check_link'),
__('Check for updates', 'plugin-update-checker')
);
if ( !empty($linkText) ) {
/** @noinspection HtmlUnknownTarget */
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
}
}
return $pluginMeta;
}
protected function isMyPluginFile($pluginFile) {
return ($pluginFile == $this->updateChecker->pluginFile)
|| (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile));
}
/**
* Check for updates when the user clicks the "Check for updates" link.
*
* @see self::addCheckForUpdatesLink()
*
* @return void
*/
public function handleManualCheck() {
$shouldCheck =
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
&& $_GET['puc_slug'] == $this->updateChecker->slug
&& check_admin_referer('puc_check_for_updates');
if ( $shouldCheck ) {
$update = $this->updateChecker->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available';
$lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors();
if ( ($update === null) && !empty($lastRequestApiErrors) ) {
//Some errors are not critical. For example, if PUC tries to retrieve the readme.txt
//file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates
//from working. Maybe the plugin simply doesn't have a readme.
//Let's only show important errors.
$foundCriticalErrors = false;
$questionableErrorCodes = array(
'puc-github-http-error',
'puc-gitlab-http-error',
'puc-bitbucket-http-error',
);
foreach ($lastRequestApiErrors as $item) {
$wpError = $item['error'];
/** @var \WP_Error $wpError */
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
$foundCriticalErrors = true;
break;
}
}
if ( $foundCriticalErrors ) {
$status = 'error';
set_site_transient($this->manualCheckErrorTransient, $lastRequestApiErrors, 60);
}
}
wp_safe_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->updateChecker->slug,
),
self_admin_url('plugins.php')
));
exit;
}
}
/**
* Display the results of a manual update check.
*
* @see self::handleManualCheck()
*
* 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 = sanitize_key($_GET['puc_update_check_result']);
$title = $this->updateChecker->getInstalledPackage()->getPluginTitle();
$noticeClass = 'updated notice-success';
$details = '';
if ( $status == 'no_update' ) {
$message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status == 'update_available' ) {
$message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status === 'error' ) {
$message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title);
$noticeClass = 'error notice-error';
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
delete_site_transient($this->manualCheckErrorTransient);
} else {
$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>',
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
}
/**
* Format the list of errors that were thrown during an update check.
*
* @param array $errors
* @return string
*/
protected function formatManualCheckErrors($errors) {
if ( empty($errors) ) {
return '';
}
$output = '';
$showAsList = count($errors) > 1;
if ( $showAsList ) {
$output .= '<ol>';
$formatString = '<li>%1$s <code>%2$s</code></li>';
} else {
$formatString = '<p>%1$s <code>%2$s</code></p>';
}
foreach ($errors as $item) {
$wpError = $item['error'];
/** @var \WP_Error $wpError */
$output .= sprintf(
$formatString,
esc_html($wpError->get_error_message()),
esc_html($wpError->get_error_code())
);
}
if ( $showAsList ) {
$output .= '</ol>';
}
return $output;
}
public function removeHooks() {
remove_action('admin_init', array($this, 'onAdminInit'));
remove_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10);
remove_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10);
remove_action('all_admin_notices', array($this, 'displayManualCheckResult'));
}
}
endif;

View File

@ -1,37 +1,43 @@
<?php
if ( !class_exists('Puc_v4_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.
*
* @author Janis Elsts
* @copyright 2016
* @version 3.2
* @access public
*/
class Puc_v4_Plugin_Update extends Puc_v4_Update {
class Update extends BaseUpdate {
public $id = 0;
public $homepage;
public $upgrade_notice;
public $tested;
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', 'upgrade_notice', '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_v4_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_v4_Plugin_Info::fromJson($json);
if ( $pluginInfo != null ) {
$pluginInfo = PluginInfo::fromJson($json);
if ( $pluginInfo !== null ) {
return self::fromPluginInfo($pluginInfo);
} else {
return null;
@ -42,18 +48,18 @@ if ( !class_exists('Puc_v4_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_v4_Plugin_Info $info
* @return Puc_v4_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_v4_Plugin_Info|Puc_v4_Plugin_Update $object The source object.
* @return Puc_v4_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();
@ -73,20 +79,40 @@ if ( !class_exists('Puc_v4_Plugin_Update', false) ):
*
* @return object
*/
public function toWpFormat(){
public function toWpFormat() {
$update = parent::toWpFormat();
$update->id = $this->id;
$update->url = $this->homepage;
$update->tested = $this->tested;
$update->requires_php = $this->requires_php;
$update->plugin = $this->filename;
$update->autoupdate = $this->autoupdate;
if ( !empty($this->upgrade_notice) ){
if ( !empty($this->upgrade_notice) ) {
$update->upgrade_notice = $this->upgrade_notice;
}
if ( !empty($this->icons) && is_array($this->icons) ) {
//This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'.
//Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
$icons = array_intersect_key(
$this->icons,
array('svg' => true, '1x' => true, '2x' => true, 'default' => true)
);
if ( !empty($icons) ) {
$update->icons = $icons;
//It appears that the 'default' icon isn't used anywhere in WordPress 4.9,
//but lets set it just in case a future release needs it.
if ( !isset($update->icons['default']) ) {
$update->icons['default'] = current($update->icons);
}
}
}
return $update;
}
}
endif;
endif;

View File

@ -1,22 +1,34 @@
<?php
if ( !class_exists('Puc_v4_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.
*
* @author Janis Elsts
* @copyright 2016
* @copyright 2018
* @access public
*/
class Puc_v4_Plugin_UpdateChecker extends Puc_v4_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.
private $cachedInstalledVersion = null;
/**
* @var Package
*/
protected $package;
private $extraUi = null;
/**
* Class constructor.
@ -40,34 +52,40 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
}
//Plugin slugs must be unique.
$slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug;
$slugCheckFilter = 'puc_is_slug_in_use-' . $slug;
$slugUsedBy = apply_filters($slugCheckFilter, false);
if ( $slugUsedBy ) {
$this->triggerError(sprintf(
'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
htmlentities($this->slug),
htmlentities($slugUsedBy)
$slug,
$slugUsedBy
), E_USER_ERROR);
}
add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
$this->muPluginFile = $this->pluginFile;
}
parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
//To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin.
//Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964
add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks'));
$this->extraUi = new Ui($this);
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4_Scheduler
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
$scheduler = new Puc_v4_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;
}
@ -82,30 +100,48 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
//Override requests for plugin information
add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
add_action('admin_init', array($this, 'handleManualCheck'));
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
parent::installHooks();
}
/**
* Remove update checker hooks.
*
* The intent is to prevent a fatal error that can happen if the plugin has an uninstall
* hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance),
* the uninstall hook runs, WP deletes the plugin files and then updates some transients.
* If PUC hooks are still around at this time, they could throw an error while trying to
* autoload classes from files that no longer exist.
*
* The "site_transient_{$transient}" filter is the main problem here, but let's also remove
* most other PUC hooks to be safe.
*
* @internal
*/
public function removeHooks() {
parent::removeHooks();
$this->extraUi->removeHooks();
$this->package->removeHooks();
remove_filter('plugins_api', array($this, 'injectInfo'), 20);
}
/**
* Retrieve plugin info from the configured API endpoint.
*
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return Puc_v4_Plugin_Info
* @return PluginInfo
*/
public function requestInfo($queryArgs = array()) {
list($pluginInfo, $result) = $this->requestMetadata('Puc_v4_Plugin_Info', 'request_info', $queryArgs);
list($pluginInfo, $result) = $this->requestMetadata(
PluginInfo::class,
'request_info',
$queryArgs
);
if ( $pluginInfo !== null ) {
/** @var Puc_v4_Plugin_Info $pluginInfo */
/** @var PluginInfo $pluginInfo */
$pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug;
}
@ -117,101 +153,24 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses PluginUpdateChecker::requestInfo()
* @uses UpdateChecker::requestInfo()
*
* @return Puc_v4_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()
//and transforms the result accordingly.
$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
if ( $pluginInfo == null ){
if ( $pluginInfo === null ){
return null;
}
$update = Puc_v4_Plugin_Update::fromPluginInfo($pluginInfo);
$update = Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update);
return $update;
}
/**
* Get the currently installed version of the plugin.
*
* @return string Version number.
*/
public function getInstalledVersion(){
if ( isset($this->cachedInstalledVersion) ) {
return $this->cachedInstalledVersion;
}
$pluginHeader = $this->getPluginHeader();
if ( isset($pluginHeader['Version']) ) {
$this->cachedInstalledVersion = $pluginHeader['Version'];
return $pluginHeader['Version'];
} else {
//This can happen if the filename points to something that is not a plugin.
$this->triggerError(
sprintf(
"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->pluginFile
),
E_USER_WARNING
);
return null;
}
}
/**
* Get plugin's metadata from its file header.
*
* @return array
*/
protected function getPluginHeader() {
if ( !is_file($this->pluginAbsolutePath) ) {
//This can happen if the plugin filename is wrong.
$this->triggerError(
sprintf(
"Can't to read the plugin header for '%s'. The file does not exist.",
$this->pluginFile
),
E_USER_WARNING
);
return array();
}
if ( !function_exists('get_plugin_data') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
}
/**
* @return array
*/
protected function getHeaderNames() {
return array(
'Name' => 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
//The newest WordPress version that this plugin requires or has been tested with.
//We support several different formats for compatibility with other libraries.
'Tested WP' => 'Tested WP',
'Requires WP' => 'Requires WP',
'Tested up to' => 'Tested up to',
'Requires at least' => 'Requires at least',
);
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
@ -232,6 +191,8 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
}
$pluginInfo = $this->requestInfo();
$this->fixSupportedWordpressVersion($pluginInfo);
$pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo);
if ( $pluginInfo ) {
return $pluginInfo->toWpFormat();
@ -247,12 +208,12 @@ if ( !class_exists('Puc_v4_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->isMuPlugin() ) {
if ( $this->package->isMuPlugin() ) {
//WP does not support automatic update installation for mu-plugins, but we can
//still display a notice.
$updateToAdd->package = null;
@ -261,8 +222,8 @@ if ( !class_exists('Puc_v4_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);
@ -279,17 +240,33 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
* @return string
*/
protected function getUpdateListKey() {
if ( $this->isMuPlugin() ) {
if ( $this->package->isMuPlugin() ) {
return $this->muPluginFile;
}
return $this->pluginFile;
}
protected function getNoUpdateItemFields() {
return array_merge(
parent::getNoUpdateItemFields(),
array(
'id' => $this->pluginFile,
'slug' => $this->slug,
'plugin' => $this->pluginFile,
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'compatibility' => new \stdClass(),
)
);
}
/**
* 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) {
@ -299,7 +276,7 @@ if ( !class_exists('Puc_v4_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) {
@ -315,103 +292,25 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4_Plugin_Update|null
* @return Update|null
*/
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) ) {
/** @var Puc_v4_Plugin_Update $update */
/** @var Update $update */
$update->filename = $this->pluginFile;
}
return $update;
}
/**
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
* the new link will appear after the "Visit plugin site" link.
* Get the translated plugin title.
*
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @return array
* @deprecated
* @return string
*/
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
$isRelevant = ($pluginFile == $this->pluginFile)
|| (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
if ( $isRelevant && $this->userCanInstallUpdates() ) {
$linkUrl = wp_nonce_url(
add_query_arg(
array(
'puc_check_for_updates' => 1,
'puc_slug' => $this->slug,
),
self_admin_url('plugins.php')
),
'puc_check_for_updates'
);
$linkText = apply_filters(
$this->getUniqueName('manual_check_link'),
__('Check for updates', 'plugin-update-checker')
);
if ( !empty($linkText) ) {
/** @noinspection HtmlUnknownTarget */
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
}
}
return $pluginMeta;
}
/**
* Check for updates when the user clicks the "Check for updates" link.
* @see self::addCheckForUpdatesLink()
*
* @return void
*/
public function handleManualCheck() {
$shouldCheck =
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
&& $_GET['puc_slug'] == $this->slug
&& $this->userCanInstallUpdates()
&& check_admin_referer('puc_check_for_updates');
if ( $shouldCheck ) {
$update = $this->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available';
wp_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->slug,
),
self_admin_url('plugins.php')
));
}
}
/**
* Display the results of a manual update check.
* @see self::handleManualCheck()
*
* You can change the result message by using the "puc_manual_check_message-$slug" filter.
*/
public function displayManualCheckResult() {
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
$status = strval($_GET['puc_update_check_result']);
if ( $status == 'no_update' ) {
$message = __('This plugin is up to date.', 'plugin-update-checker');
} else if ( $status == 'update_available' ) {
$message = __('A new version of this plugin is available.', 'plugin-update-checker');
} else {
$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
}
printf(
'<div class="updated notice is-dismissible"><p>%s</p></div>',
apply_filters($this->getUniqueName('manual_check_message'), $message, $status)
);
}
public function getPluginTitle() {
return $this->package->getPluginTitle();
}
/**
@ -426,20 +325,11 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @deprecated
* @return bool
*/
protected function isMuPlugin() {
static $cachedResult = null;
if ( $cachedResult === null ) {
//Convert both paths to the canonical form before comparison.
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
$pluginPath = realpath($this->pluginAbsolutePath);
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
}
return $cachedResult;
return $this->package->isMuPlugin();
}
/**
@ -449,19 +339,7 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
* @return bool
*/
protected function isUnknownMuPlugin() {
return empty($this->muPluginFile) && $this->isMuPlugin();
}
/**
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
* return the filter argument unmodified.
*
* @param mixed $filterArgument
* @return mixed
*/
public function clearCachedVersion($filterArgument = null) {
$this->cachedInstalledVersion = null;
return $filterArgument;
return empty($this->muPluginFile) && $this->package->isMuPlugin();
}
/**
@ -524,8 +402,24 @@ if ( !class_exists('Puc_v4_Plugin_UpdateChecker', false) ):
}
protected function createDebugBarExtension() {
return new Puc_v4_DebugBar_PluginExtension($this);
return new DebugBar\PluginExtension($this);
}
/**
* Create a package instance that represents this plugin or theme.
*
* @return InstalledPackage
*/
protected function createInstalledPackage() {
return new Package($this->pluginAbsolutePath, $this);
}
/**
* @return Package
*/
public function getInstalledPackage() {
return $this->package;
}
}
endif;
endif;

362
Puc/v5p6/PucFactory.php Normal file
View File

@ -0,0 +1,362 @@
<?php
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.
*
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
* and 4.1), this factory will always use the latest available minor version. Register class
* versions by calling {@link PucFactory::addVersion()}.
*
* 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 PucFactory {
protected static $classVersions = array();
protected static $sorted = false;
protected static $myMajorVersion = '';
protected static $latestCompatibleVersion = '';
/**
* A wrapper method for buildUpdateChecker() that reads the metadata URL from the plugin or theme header.
*
* @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 Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/
public static function buildFromHeader($fullPath, $args = array()) {
$fullPath = self::normalizePath($fullPath);
//Set up defaults.
$defaults = array(
'metadataUrl' => '',
'slug' => '',
'checkPeriod' => 12,
'optionName' => '',
'muPluginFile' => '',
);
$args = array_merge($defaults, array_intersect_key($args, $defaults));
extract($args, EXTR_SKIP);
//Check for the service URI
if ( empty($metadataUrl) ) {
$metadataUrl = self::getServiceURI($fullPath);
}
return self::buildUpdateChecker($metadataUrl, $fullPath, $slug, $checkPeriod, $optionName, $muPluginFile);
}
/**
* Create a new instance of the update checker.
*
* 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 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 bookkeeping info about update checks.
* @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
* @return Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$fullPath = self::normalizePath($fullPath);
$id = null;
//Plugin or theme?
$themeDirectory = self::getThemeDirectoryName($fullPath);
if ( self::isPluginFile($fullPath) ) {
$type = 'Plugin';
$id = $fullPath;
} else if ( $themeDirectory !== null ) {
$type = 'Theme';
$id = $themeDirectory;
} else {
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.',
esc_html($fullPath)
));
}
//Which hosting service does the URL point to?
$service = self::getVcsService($metadataUrl);
$apiClass = null;
if ( empty($service) ) {
//The default is to get update information from a remote JSON file.
$checkerClass = $type . '\\UpdateChecker';
} else {
//You can also use a VCS repository like GitHub.
$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(
esc_html(sprintf(
'PUC %s does not support updates for %ss %s',
self::$latestCompatibleVersion,
strtolower($type),
$service ? ('hosted on ' . $service) : 'using JSON metadata'
)),
E_USER_ERROR
);
}
if ( !isset($apiClass) ) {
//Plain old update checker.
return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
} else {
//VCS checker + an API client.
$apiClass = self::getCompatibleClassVersion($apiClass);
if ( $apiClass === null ) {
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(esc_html(sprintf(
'PUC %s does not support %s',
self::$latestCompatibleVersion,
$service
)), E_USER_ERROR);
}
return new $checkerClass(
new $apiClass($metadataUrl),
$id,
$slug,
$checkPeriod,
$optionName,
$muPluginFile
);
}
}
/**
*
* 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.6)
*
* @param string $path Path to normalize.
* @return string Normalized path.
*/
public static function normalizePath($path) {
if ( function_exists('wp_normalize_path') ) {
return wp_normalize_path($path);
}
$path = str_replace('\\', '/', $path);
$path = preg_replace('|(?<=.)/+|', '/', $path);
if ( substr($path, 1, 1) === ':' ) {
$path = ucfirst($path);
}
return $path;
}
/**
* Check if the path points to a plugin file.
*
* @param string $absolutePath Normalized path.
* @return bool
*/
protected static function isPluginFile($absolutePath) {
//Is the file inside the "plugins" or "mu-plugins" directory?
$pluginDir = self::normalizePath(WP_PLUGIN_DIR);
$muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR);
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
return true;
}
//Is it a file at all? Caution: is_file() can fail if the parent dir. doesn't have the +x permission set.
if ( !is_file($absolutePath) ) {
return false;
}
//Does it have a valid plugin header?
//This is a last-ditch check for plugins symlinked from outside the WP root.
if ( function_exists('get_file_data') ) {
$headers = get_file_data($absolutePath, array('Name' => 'Plugin Name'), 'plugin');
return !empty($headers['Name']);
}
return false;
}
/**
* Get the name of the theme's directory from a full path to a file inside that directory.
* E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo".
*
* Note that subdirectories are currently not supported. For example,
* "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL.
*
* @param string $absolutePath Normalized path.
* @return string|null Directory name, or NULL if the path doesn't point to a theme.
*/
protected static function getThemeDirectoryName($absolutePath) {
if ( is_file($absolutePath) ) {
$absolutePath = dirname($absolutePath);
}
if ( file_exists($absolutePath . '/style.css') ) {
return basename($absolutePath);
}
return null;
}
/**
* Get the service URI from the file header.
*
* @param string $fullPath
* @return string
*/
private static function getServiceURI($fullPath) {
//Look for the URI
if ( is_readable($fullPath) ) {
$seek = array(
'github' => 'GitHub URI',
'gitlab' => 'GitLab URI',
'bucket' => 'BitBucket URI',
);
$seek = apply_filters('puc_get_source_uri', $seek);
$data = get_file_data($fullPath, $seek);
foreach ($data as $key => $uri) {
if ( $uri ) {
return $uri;
}
}
}
//URI was not found so throw an error.
throw new \RuntimeException(
sprintf('Unable to locate URI in header of "%s"', esc_html($fullPath))
);
}
/**
* Get the name of the hosting service that the URL points to.
*
* @param string $metadataUrl
* @return string|null
*/
private static function getVcsService($metadataUrl) {
$service = null;
//Which hosting service does the URL point to?
$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".
$repoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
if ( $host === 'gitlab.com' ) {
$repoRegex = '@^/?(?:[^/#?&]++/){1,20}(?:[^/#?&]++)/?$@';
}
if ( preg_match($repoRegex, $path) ) {
$knownServices = array(
'github.com' => 'GitHub',
'bitbucket.org' => 'BitBucket',
'gitlab.com' => 'GitLab',
);
if ( isset($knownServices[$host]) ) {
$service = $knownServices[$host];
}
}
return apply_filters('puc_get_vcs_service', $service, $host, $path, $metadataUrl);
}
/**
* Get the latest version of the specified class that has the same major version number
* as this factory class.
*
* @param string $class Partial class name.
* @return string|null Full class name.
*/
protected static function getCompatibleClassVersion($class) {
if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
return self::$classVersions[$class][self::$latestCompatibleVersion];
}
return null;
}
/**
* Get the specific class name for the latest available version of a class.
*
* @param string $class
* @return null|string
*/
public static function getLatestClassVersion($class) {
if ( !self::$sorted ) {
self::sortVersions();
}
if ( isset(self::$classVersions[$class]) ) {
return reset(self::$classVersions[$class]);
} else {
return null;
}
}
/**
* Sort available class versions in descending order (i.e. newest first).
*/
protected static function sortVersions() {
foreach ( self::$classVersions as $class => $versions ) {
uksort($versions, array(__CLASS__, 'compareVersions'));
self::$classVersions[$class] = $versions;
}
self::$sorted = true;
}
protected static function compareVersions($a, $b) {
return -version_compare($a, $b);
}
/**
* Register a version of a class.
*
* @access private This method is only for internal use by the library.
*
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
* @param string $version Version number, e.g. '1.2'.
*/
public static function addVersion($generalClass, $versionedClass, $version) {
if ( empty(self::$myMajorVersion) ) {
$lastNamespaceSegment = substr(__NAMESPACE__, strrpos(__NAMESPACE__, '\\') + 1);
self::$myMajorVersion = substr(ltrim($lastNamespaceSegment, 'v'), 0, 1);
}
//Store the greatest version number that matches our major version.
$components = explode('.', $version);
if ( $components[0] === self::$myMajorVersion ) {
if (
empty(self::$latestCompatibleVersion)
|| version_compare($version, self::$latestCompatibleVersion, '>')
) {
self::$latestCompatibleVersion = $version;
}
}
if ( !isset(self::$classVersions[$generalClass]) ) {
self::$classVersions[$generalClass] = array();
}
self::$classVersions[$generalClass][$version] = $versionedClass;
self::$sorted = false;
}
}
endif;

View File

@ -1,11 +1,13 @@
<?php
if ( !class_exists('Puc_v4_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_v4_UpdateChecker::checkForUpdates() to perform the actual checks.
* It calls @see UpdateChecker::checkForUpdates() to perform the actual checks.
*/
class Puc_v4_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_v4_Scheduler', false) ):
protected $hourlyCheckHooks = array('load-update.php');
/**
* @var Puc_v4_UpdateChecker
* @var UpdateChecker
*/
protected $updateChecker;
@ -22,7 +24,7 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
/**
* Scheduler constructor.
*
* @param Puc_v4_UpdateChecker $updateChecker
* @param UpdateChecker $updateChecker
* @param int $checkPeriod How often to check for updates (in hours).
* @param array $hourlyHooks
*/
@ -47,11 +49,27 @@ if ( !class_exists('Puc_v4_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') ) {
wp_schedule_event(time(), $scheduleName, $this->cronHook);
//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.
$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
);
wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook);
}
add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
@ -62,13 +80,15 @@ if ( !class_exists('Puc_v4_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, 'maybeCheckForUpdates'), 11, 0);
add_action('upgrader_process_complete', array($this, 'removeHooksIfLibraryGone'), 1, 0);
add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2);
} else {
//Periodic checks are disabled.
@ -76,6 +96,76 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
}
}
/**
* Remove all hooks if this version of PUC has been deleted or overwritten.
*
* Callback for the "upgrader_process_complete" action.
*/
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.
clearstatcache();
if ( !file_exists(__FILE__) ) {
$this->removeHooks();
$this->updateChecker->removeHooks();
}
}
/**
* 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'])
|| 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme'))
) {
return;
}
//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, Theme\UpdateChecker::class) ) {
if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
return;
}
//Letting too many things going through for checks is not a real problem, so we compare widely.
if ( !in_array(
strtolower($this->updateChecker->directoryName),
array_map('strtolower', $upgradeInfo['themes'])
) ) {
return;
}
}
if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
return;
}
//Themes pass in directory names in the information array, but plugins use the relative plugin path.
if ( !in_array(
strtolower($this->updateChecker->directoryName),
array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
) ) {
return;
}
}
$this->maybeCheckForUpdates();
}
/**
* Check for updates if the configured check interval has already elapsed.
* Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
@ -89,7 +179,7 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
*
* This method is declared public because it's a hook callback. Calling it directly is not recommended.
*/
public function maybeCheckForUpdates(){
public function maybeCheckForUpdates() {
if ( empty($this->checkPeriod) ){
return;
}
@ -97,6 +187,21 @@ if ( !class_exists('Puc_v4_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'),
@ -127,7 +232,7 @@ if ( !class_exists('Puc_v4_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;
@ -144,7 +249,7 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
* @param array $schedules
* @return array
*/
public function _addCustomSchedule($schedules){
public function _addCustomSchedule($schedules) {
if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
$scheduleName = 'every' . $this->checkPeriod . 'hours';
$schedules[$scheduleName] = array(
@ -160,7 +265,7 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
*
* @return void
*/
public function removeUpdaterCron(){
public function removeUpdaterCron() {
wp_clear_scheduled_hook($this->cronHook);
}
@ -172,6 +277,24 @@ if ( !class_exists('Puc_v4_Scheduler', false) ):
public function getCronHookName() {
return $this->cronHook;
}
/**
* Remove most hooks added by the scheduler.
*/
public function removeHooks() {
remove_filter('cron_schedules', array($this, '_addCustomSchedule'));
remove_action('admin_init', array($this, 'maybeCheckForUpdates'));
remove_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
if ( $this->cronHook !== null ) {
remove_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
}
if ( !empty($this->hourlyCheckHooks) ) {
foreach ($this->hourlyCheckHooks as $hook) {
remove_action($hook, array($this, 'maybeCheckForUpdates'));
}
}
}
}
endif;

View File

@ -1,8 +1,9 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4_StateStore', false) ):
if ( !class_exists(StateStore::class, false) ):
class Puc_v4_StateStore {
class StateStore {
/**
* @var int Last update check timestamp.
*/
@ -14,7 +15,7 @@ if ( !class_exists('Puc_v4_StateStore', false) ):
protected $checkedVersion = '';
/**
* @var Puc_v4_Update|null Cached update.
* @var Update|null Cached update.
*/
protected $update = null;
@ -65,7 +66,7 @@ if ( !class_exists('Puc_v4_StateStore', false) ):
}
/**
* @return null|Puc_v4_Update
* @return null|Update
*/
public function getUpdate() {
$this->lazyLoad();
@ -73,10 +74,10 @@ if ( !class_exists('Puc_v4_StateStore', false) ):
}
/**
* @param Puc_v4_Update|null $update
* @param Update|null $update
* @return $this
*/
public function setUpdate(Puc_v4_Update $update = null) {
public function setUpdate($update = null) {
$this->lazyLoad();
$this->update = $update;
return $this;
@ -127,7 +128,7 @@ if ( !class_exists('Puc_v4_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_v4_StateStore', false) ):
$updateClass = get_class($this->update);
$state->updateClass = $updateClass;
$prefix = $this->getLibPrefix();
if ( Puc_v4_Utils::startsWith($updateClass, $prefix) ) {
if ( Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix));
}
}
@ -162,15 +163,20 @@ if ( !class_exists('Puc_v4_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_v4_Utils::get($state, 'lastCheck', 0));
$this->checkedVersion = Puc_v4_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_v4_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_v4_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

@ -0,0 +1,69 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
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.
*/
protected $theme;
public function __construct($stylesheet, $updateChecker) {
$this->stylesheet = $stylesheet;
$this->theme = wp_get_theme($this->stylesheet);
parent::__construct($updateChecker);
}
public function getInstalledVersion() {
return $this->theme->get('Version');
}
public function getAbsoluteDirectoryPath() {
if ( method_exists($this->theme, 'get_stylesheet_directory') ) {
return $this->theme->get_stylesheet_directory(); //Available since WP 3.4.
}
return get_theme_root($this->stylesheet) . '/' . $this->stylesheet;
}
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @param string $defaultValue
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
*/
public function getHeaderValue($headerName, $defaultValue = '') {
$value = $this->theme->get($headerName);
if ( ($headerName === false) || ($headerName === '') ) {
return $defaultValue;
}
return $value;
}
protected function getHeaderNames() {
return array(
'Name' => 'Theme Name',
'ThemeURI' => 'Theme URI',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'Version' => 'Version',
'Template' => 'Template',
'Status' => 'Status',
'Tags' => 'Tags',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
);
}
}
endif;

View File

@ -1,8 +1,12 @@
<?php
if ( !class_exists('Puc_v4_Theme_Update', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
class Puc_v4_Theme_Update extends Puc_v4_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_v4_Theme_Update', false) ):
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param StdClass|Puc_v4_Theme_Update $object The source object.
* @return Puc_v4_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_v4_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)
);
@ -81,4 +85,4 @@ if ( !class_exists('Puc_v4_Theme_Update', false) ):
}
}
endif;
endif;

View File

@ -1,28 +1,29 @@
<?php
if ( !class_exists('Puc_v4_Theme_UpdateChecker', false) ):
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
class Puc_v4_Theme_UpdateChecker extends Puc_v4_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.
*/
protected $stylesheet;
/**
* @var WP_Theme Theme object.
*/
protected $theme;
public function __construct($metadataUrl, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
if ( $stylesheet === null ) {
$stylesheet = get_stylesheet();
}
$this->stylesheet = $stylesheet;
$this->theme = wp_get_theme($this->stylesheet);
parent::__construct(
$metadataUrl,
@ -45,13 +46,13 @@ if ( !class_exists('Puc_v4_Theme_UpdateChecker', false) ):
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @return Puc_v4_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_v4_Theme_Update', 'request_update');
list($themeUpdate, $result) = $this->requestMetadata(Update::class, 'request_update');
if ( $themeUpdate !== null ) {
/** @var Puc_v4_Theme_Update $themeUpdate */
/** @var Update $themeUpdate */
$themeUpdate->slug = $this->slug;
}
@ -59,33 +60,34 @@ if ( !class_exists('Puc_v4_Theme_UpdateChecker', false) ):
return $themeUpdate;
}
public function userCanInstallUpdates() {
return current_user_can('update_themes');
protected function getNoUpdateItemFields() {
return array_merge(
parent::getNoUpdateItemFields(),
array(
'theme' => $this->directoryName,
'requires' => '',
)
);
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string Version number.
*/
public function getInstalledVersion() {
return $this->theme->get('Version');
public function userCanInstallUpdates() {
return current_user_can('update_themes');
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4_Scheduler
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
return new Puc_v4_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) {
@ -93,7 +95,7 @@ if ( !class_exists('Puc_v4_Theme_UpdateChecker', false) ):
}
protected function createDebugBarExtension() {
return new Puc_v4_DebugBar_Extension($this, 'Puc_v4_DebugBar_ThemePanel');
return new DebugBar\Extension($this, DebugBar\ThemePanel::class);
}
/**
@ -145,23 +147,13 @@ if ( !class_exists('Puc_v4_Theme_UpdateChecker', false) ):
}
/**
* @return array
* Create a package instance that represents this plugin or theme.
*
* @return InstalledPackage
*/
protected function getHeaderNames() {
return array(
'Name' => 'Theme Name',
'ThemeURI' => 'Theme URI',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'Version' => 'Version',
'Template' => 'Template',
'Status' => 'Status',
'Tags' => 'Tags',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
);
protected function createInstalledPackage() {
return new Package($this->stylesheet, $this);
}
}
endif;
endif;

View File

@ -1,5 +1,9 @@
<?php
if ( !class_exists('Puc_v4_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_v4_Update', false) ):
* @author Janis Elsts
* @access public
*/
abstract class Puc_v4_Update extends Puc_v4_Metadata {
abstract class Update extends Metadata {
public $slug;
public $version;
public $download_url;
@ -31,4 +35,4 @@ if ( !class_exists('Puc_v4_Update', false) ):
}
}
endif;
endif;

View File

@ -1,18 +1,31 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4_UpdateChecker', false) ):
use stdClass;
use WP_Error;
abstract class Puc_v4_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()
* and should be logged to the standard PHP error log.
* @var bool
*/
public $debugMode = false;
public $debugMode = null;
/**
* @var string Where to store the update info.
@ -36,20 +49,45 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
public $slug = '';
/**
* @var Puc_v4_Scheduler
* @var InstalledPackage
*/
protected $package;
/**
* @var Scheduler
*/
public $scheduler;
/**
* @var Puc_v4_UpgraderStatus
* @var UpgraderStatus
*/
protected $upgraderStatus;
/**
* @var Puc_v4_StateStore
* @var StateStore
*/
protected $updateState;
/**
* @var array List of API errors triggered during the last checkForUpdates() call.
*/
protected $lastRequestApiErrors = array();
/**
* @var string|mixed The default is 0 because parse_url() can return NULL or FALSE.
*/
protected $cachedMetadataHost = 0;
/**
* @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;
@ -67,9 +105,14 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
}
}
if ( empty($this->translationType) ) {
$this->translationType = $this->componentType;
}
$this->package = $this->createInstalledPackage();
$this->scheduler = $this->createScheduler($checkPeriod);
$this->upgraderStatus = new Puc_v4_UpgraderStatus();
$this->updateState = new Puc_v4_StateStore($this->optionName);
$this->upgraderStatus = new UpgraderStatus();
$this->updateState = new StateStore($this->optionName);
if ( did_action('init') ) {
$this->loadTextDomain();
@ -78,6 +121,10 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
}
$this->installHooks();
if ( ($this->wpCliCheckTrigger === null) && defined('WP_CLI') ) {
$this->wpCliCheckTrigger = new WpCliCheckTrigger($this->componentType, $this->scheduler);
}
}
/**
@ -124,6 +171,10 @@ if ( !class_exists('Puc_v4_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();
@ -132,6 +183,33 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
}
}
/**
* Remove hooks that were added by this update checker instance.
*/
public function removeHooks() {
remove_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
remove_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
remove_action(
'delete_site_transient_' . $this->updateTransient,
array($this, 'clearCachedTranslationUpdates')
);
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'));
if ( $this->scheduler ) {
$this->scheduler->removeHooks();
}
if ( $this->debugBarExtension ) {
$this->debugBarExtension->removeHooks();
}
}
/**
* Check if the current user has the required permissions to install updates.
*
@ -158,17 +236,30 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
* @return bool
*/
public function allowMetadataHost($allow, $host) {
static $metadataHost = 0; //Using 0 instead of NULL because parse_url can return NULL.
if ( $metadataHost === 0 ) {
$metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
if ( $this->cachedMetadataHost === 0 ) {
$this->cachedMetadataHost = wp_parse_url($this->metadataUrl, PHP_URL_HOST);
}
if ( is_string($metadataHost) && (strtolower($host) === strtolower($metadataHost)) ) {
if ( is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost)) ) {
return true;
}
return $allow;
}
/**
* Create a package instance that represents this plugin or theme.
*
* @return InstalledPackage
*/
abstract protected function createInstalledPackage();
/**
* @return InstalledPackage
*/
public function getInstalledPackage() {
return $this->package;
}
/**
* Create an instance of the scheduler.
*
@ -176,14 +267,84 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
* and substitute their own scheduler.
*
* @param int $checkPeriod
* @return Puc_v4_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_v4_Update|null
* @return Update|null
*/
public function checkForUpdates() {
$installedVersion = $this->getInstalledVersion();
@ -196,6 +357,10 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
return null;
}
//Start collecting API errors.
$this->lastRequestApiErrors = array();
add_action('puc_api_error', array($this, 'collectApiErrors'), 10, 4);
$state = $this->updateState;
$state->setLastCheckToNow()
->setCheckedVersion($installedVersion)
@ -204,13 +369,16 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
$state->setUpdate($this->requestUpdate());
$state->save();
//Stop collecting API errors.
remove_action('puc_api_error', array($this, 'collectApiErrors'), 10);
return $this->getUpdate();
}
/**
* Load the update checker state from the DB.
*
* @return Puc_v4_StateStore
* @return StateStore
*/
public function getUpdateState() {
return $this->updateState->lazyLoad();
@ -235,7 +403,7 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4_Update|null
* @return Update|null
*/
public function getUpdate() {
$update = $this->updateState->getUpdate();
@ -256,21 +424,24 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
*
* Subclasses should run the update through filterUpdateResult before returning it.
*
* @return Puc_v4_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_v4_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_v4_Update
* @return T
*/
protected function filterUpdateResult($update, $httpResult = null) {
//Let plugins/themes modify the update.
$update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult);
$this->fixSupportedWordpressVersion($update);
if ( isset($update, $update->translations) ) {
//Keep only those translation updates that apply to this site.
$update->translations = $this->filterApplicableTranslations($update->translations);
@ -279,12 +450,76 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
return $update;
}
/**
* The "Tested up to" field in the plugin metadata is supposed to be in the form of "major.minor",
* while WordPress core's list_plugin_updates() expects the $update->tested field to be an exact
* version, e.g. "major.minor.patch", to say it's compatible. In other case it shows
* "Compatibility: Unknown".
* The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to".
*
* @param Metadata|null $update
*/
protected function fixSupportedWordpressVersion($update = null) {
if ( !isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested) ) {
return;
}
$actualWpVersions = array();
$wpVersion = $GLOBALS['wp_version'];
if ( function_exists('get_core_updates') ) {
$coreUpdates = get_core_updates();
if ( is_array($coreUpdates) ) {
foreach ($coreUpdates as $coreUpdate) {
if ( isset($coreUpdate->current) ) {
$actualWpVersions[] = $coreUpdate->current;
}
}
}
}
$actualWpVersions[] = $wpVersion;
$actualWpPatchNumber = null;
foreach ($actualWpVersions as $version) {
if ( preg_match('/^(?P<majorMinor>\d++\.\d++)(?:\.(?P<patch>\d++))?/', $version, $versionParts) ) {
if ( $versionParts['majorMinor'] === $update->tested ) {
$patch = isset($versionParts['patch']) ? intval($versionParts['patch']) : 0;
if ( $actualWpPatchNumber === null ) {
$actualWpPatchNumber = $patch;
} else {
$actualWpPatchNumber = max($actualWpPatchNumber, $patch);
}
}
}
}
if ( $actualWpPatchNumber === null ) {
$actualWpPatchNumber = 999;
}
if ( $actualWpPatchNumber > 0 ) {
$update->tested .= '.' . $actualWpPatchNumber;
}
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string Version number.
* @return string|null Version number.
*/
abstract public function getInstalledVersion();
public function getInstalledVersion() {
return $this->package->getInstalledVersion();
}
/**
* Get the full path of the plugin or theme directory.
*
* @return string
*/
public function getAbsoluteDirectoryPath() {
return $this->package->getAbsoluteDirectoryPath();
}
/**
* Trigger a PHP error, but only when $debugMode is enabled.
@ -292,12 +527,23 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
* @param string $message
* @param int $errorType
*/
protected function triggerError($message, $errorType) {
if ($this->debugMode) {
trigger_error($message, $errorType);
public function triggerError($message, $errorType) {
if ( $this->isDebugModeEnabled() ) {
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- Only happens in debug mode.
trigger_error(esc_html($message), $errorType);
}
}
/**
* @return bool
*/
protected function isDebugModeEnabled() {
if ( $this->debugMode === null ) {
$this->debugMode = (bool)(constant('WP_DEBUG'));
}
return $this->debugMode;
}
/**
* Get the full name of an update checker filter, action or DB entry.
*
@ -309,12 +555,40 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
*/
public function getUniqueName($baseTag) {
$name = 'puc_' . $baseTag;
if ($this->filterSuffix !== '') {
if ( $this->filterSuffix !== '' ) {
$name .= '_' . $this->filterSuffix;
}
return $name . '-' . $this->slug;
}
/**
* Store API errors that are generated when checking for updates.
*
* @internal
* @param \WP_Error $error
* @param array|null $httpResponse
* @param string|null $url
* @param string|null $slug
*/
public function collectApiErrors($error, $httpResponse = null, $url = null, $slug = null) {
if ( isset($slug) && ($slug !== $this->slug) ) {
return;
}
$this->lastRequestApiErrors[] = array(
'error' => $error,
'httpResponse' => $httpResponse,
'url' => $url,
);
}
/**
* @return array
*/
public function getLastRequestApiErrors() {
return $this->lastRequestApiErrors;
}
/* -------------------------------------------------------------------
* PUC filters and filter utilities
* -------------------------------------------------------------------
@ -344,8 +618,8 @@ if ( !class_exists('Puc_v4_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?
@ -362,15 +636,19 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
} else {
//Clean up any stale update info.
$updates = $this->removeUpdateFromList($updates);
//Add a placeholder item to the "no_update" list to enable auto-update support.
//If we don't do this, the option to enable automatic updates will only show up
//when an update is available.
$updates = $this->addNoUpdateItem($updates);
}
return $updates;
}
/**
* @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) ) {
@ -383,8 +661,8 @@ if ( !class_exists('Puc_v4_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) ) {
@ -393,6 +671,40 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
return $updates;
}
/**
* 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
*/
protected function addNoUpdateItem($updates) {
if ( !is_object($updates) ) {
$updates = new stdClass();
$updates->response = array();
$updates->no_update = array();
} else if ( !isset($updates->no_update) ) {
$updates->no_update = array();
}
$updates->no_update[$this->getUpdateListKey()] = (object) $this->getNoUpdateItemFields();
return $updates;
}
/**
* Subclasses should override this method to add fields that are specific to plugins or themes.
* @return array
*/
protected function getNoUpdateItemFields() {
return array(
'new_version' => $this->getInstalledVersion(),
'url' => '',
'package' => '',
'requires_php' => '',
);
}
/**
* Get the key that will be used when adding updates to the update list that's maintained
* by the WordPress core. The list is always an associative array, but the key is different
@ -426,20 +738,26 @@ if ( !class_exists('Puc_v4_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_v4_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()).
$installedVersion = $this->getInstalledVersion();
$queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
$queryArgs = array_merge(
array(
'installed_version' => strval($this->getInstalledVersion()),
'php' => phpversion(),
'locale' => get_locale(),
),
$queryArgs
);
$queryArgs = apply_filters($this->getUniqueName($filterRoot . '_query_args'), $queryArgs);
//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',
),
@ -454,12 +772,18 @@ if ( !class_exists('Puc_v4_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 ( (strpos($metaClass, '\\') === false) ) {
$metaClass = __NAMESPACE__ . '\\' . $metaClass;
}
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
} else {
do_action('puc_api_error', $status, $result, $url, $this->slug);
$this->triggerError(
sprintf('The URL %s does not point to a valid metadata file. ', $url)
. $status->get_error_message(),
@ -519,7 +843,7 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
$installedTranslations = $this->getInstalledTranslations();
$applicableTranslations = array();
foreach($translations as $translation) {
foreach ($translations as $translation) {
//Does it match one of the available core languages?
$isApplicable = array_key_exists($translation->language, $languages);
//Is it more recent than an already-installed translation?
@ -543,6 +867,9 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
* @return array
*/
protected function getInstalledTranslations() {
if ( !function_exists('wp_get_installed_translations') ) {
return array();
}
$installedTranslations = wp_get_installed_translations($this->translationType . 's');
if ( isset($installedTranslations[$this->directoryName]) ) {
$installedTranslations = $installedTranslations[$this->directoryName];
@ -655,12 +982,12 @@ if ( !class_exists('Puc_v4_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) ) {
@ -672,25 +999,62 @@ if ( !class_exists('Puc_v4_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>',
@ -714,7 +1078,7 @@ if ( !class_exists('Puc_v4_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);
@ -728,7 +1092,7 @@ if ( !class_exists('Puc_v4_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) ) {
@ -741,52 +1105,6 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
return false;
}
/* -------------------------------------------------------------------
* File header parsing
* -------------------------------------------------------------------
*/
/**
* Parse plugin or theme metadata from the header comment.
*
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
*
* @param string|null $content File contents.
* @return string[]
*/
public function getFileHeader($content) {
$content = (string) $content;
//WordPress only looks at the first 8 KiB of the file, so we do the same.
$content = substr($content, 0, 8192);
//Normalize line endings.
$content = str_replace("\r", "\n", $content);
$headers = $this->getHeaderNames();
$results = array();
foreach ($headers as $field => $name) {
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
if ( ($success === 1) && $matches[1] ) {
$value = $matches[1];
if ( function_exists('_cleanup_header_comment') ) {
$value = _cleanup_header_comment($value);
}
$results[$field] = $value;
} else {
$results[$field] = '';
}
}
return $results;
}
/**
* @return array Format: ['HeaderKey' => 'Header Name']
*/
abstract protected function getHeaderNames();
/* -------------------------------------------------------------------
* DebugBar integration
* -------------------------------------------------------------------
@ -796,19 +1114,23 @@ if ( !class_exists('Puc_v4_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')) ) {
$this->createDebugBarExtension();
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_v4_DebugBar_Extension($this);
return new DebugBar\Extension($this);
}
/**
* Display additional configuration details in the Debug Bar panel.
*
* @param Puc_v4_DebugBar_Panel $panel
* @param DebugBar\Panel $panel
*/
public function onDisplayConfiguration($panel) {
//Do nothing. Subclasses can use this to add additional info to the panel.
@ -816,4 +1138,4 @@ if ( !class_exists('Puc_v4_UpdateChecker', false) ):
}
endif;
endif;

View File

@ -1,5 +1,7 @@
<?php
if ( !class_exists('Puc_v4_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_v4_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_v4_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_v4_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_v4_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_v4_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_v4_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_v4_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_v4_UpgraderStatus', false) ):
*/
private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
@ -196,4 +197,4 @@ if ( !class_exists('Puc_v4_UpgraderStatus', false) ):
}
}
endif;
endif;

View File

@ -1,8 +1,9 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists('Puc_v4_Utils', false) ):
if ( !class_exists(Utils::class, false) ):
class Puc_v4_Utils {
class Utils {
/**
* Get a value from a nested array or object based on a path.
*
@ -16,28 +17,20 @@ if ( !class_exists('Puc_v4_Utils', false) ):
if ( is_string($path) ) {
$path = explode($separator, $path);
}
if ( empty($path) ) {
return $default;
}
//Follow the $path into $input as far as possible.
$currentValue = $collection;
$pathExists = true;
foreach ($path as $node) {
if ( is_array($currentValue) && isset($currentValue[$node]) ) {
$currentValue = $currentValue[$node];
} else if ( is_object($currentValue) && isset($currentValue->$node) ) {
$currentValue = $currentValue->$node;
} else {
$pathExists = false;
break;
return $default;
}
}
if ( $pathExists ) {
return $currentValue;
}
return $default;
return $currentValue;
}
/**
@ -74,4 +67,4 @@ if ( !class_exists('Puc_v4_Utils', false) ):
}
}
endif;
endif;

View File

@ -1,8 +1,45 @@
<?php
if ( !class_exists('Puc_v4_Vcs_Api') ):
abstract class Puc_v4_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 = '';
/**
* @var string
@ -21,7 +58,18 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
protected $httpFilterName = '';
/**
* Puc_v4_Vcs_Api constructor.
* @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;
/**
* Api constructor.
*
* @param string $repositoryUrl
* @param array|string|null $credentials
@ -39,12 +87,41 @@ if ( !class_exists('Puc_v4_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_v4_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
@ -54,7 +131,7 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
* @return array Parsed readme.
*/
public function getRemoteReadme($ref = 'master') {
$fileContents = $this->getRemoteFile('readme.txt', $ref);
$fileContents = $this->getRemoteFile($this->getLocalReadmeName(), $ref);
if ( empty($fileContents) ) {
return array();
}
@ -63,11 +140,43 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
return $parser->parse_readme_contents($fileContents);
}
/**
* Get the case-sensitive name of the local readme.txt file.
*
* In most cases it should just be called "readme.txt", but some plugins call it "README.txt",
* "README.TXT", or even "Readme.txt". Most VCS are case-sensitive so we need to know the correct
* capitalization.
*
* Defaults to "readme.txt" (all lowercase).
*
* @return string
*/
public function getLocalReadmeName() {
static $fileName = null;
if ( $fileName !== null ) {
return $fileName;
}
$fileName = 'readme.txt';
if ( isset($this->localDirectory) ) {
$files = scandir($this->localDirectory);
if ( !empty($files) ) {
foreach ($files as $possibleFileName) {
if ( strcasecmp($possibleFileName, 'readme.txt') === 0 ) {
$fileName = $possibleFileName;
break;
}
}
}
}
return $fileName;
}
/**
* Get a branch.
*
* @param string $branchName
* @return Puc_v4_Vcs_Reference|null
* @return Reference|null
*/
abstract public function getBranch($branchName);
@ -75,7 +184,7 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4_Vcs_Reference|null
* @return Reference|null
*/
abstract public function getTag($tagName);
@ -83,7 +192,7 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
* Get the tag that looks like the highest version number.
* (Implementations should skip pre-release versions if possible.)
*
* @return Puc_v4_Vcs_Reference|null
* @return Reference|null
*/
abstract public function getLatestTag();
@ -109,7 +218,7 @@ if ( !class_exists('Puc_v4_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) {
@ -121,8 +230,8 @@ if ( !class_exists('Puc_v4_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.
@ -136,8 +245,8 @@ if ( !class_exists('Puc_v4_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) {
@ -186,7 +295,6 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
return null;
}
/** @noinspection PhpUndefinedClassInspection */
return Parsedown::instance()->text($changelog);
}
@ -196,7 +304,10 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
* @param string $directory
* @return string|null
*/
protected function findChangelogName($directory) {
protected function findChangelogName($directory = null) {
if ( !isset($directory) ) {
$directory = $this->localDirectory;
}
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
return null;
}
@ -238,6 +349,31 @@ if ( !class_exists('Puc_v4_Vcs_Api') ):
public function setHttpFilterName($filterName) {
$this->httpFilterName = $filterName;
}
/**
* @param string $filterName
*/
public function setStrategyFilterName($filterName) {
$this->strategyFilterName = $filterName;
}
/**
* @param string $directory
*/
public function setLocalDirectory($directory) {
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
$this->localDirectory = null;
} else {
$this->localDirectory = $directory;
}
}
/**
* @param string $slug
*/
public function setSlug($slug) {
$this->slug = $slug;
}
}
endif;

View File

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

View File

@ -1,9 +1,15 @@
<?php
if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
class Puc_v4_Vcs_BitBucketApi extends Puc_v4_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_v4_OAuthSignature
* @var OAuthSignature
*/
private $oauth = null;
@ -18,39 +24,32 @@ if ( !class_exists('Puc_v4_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_v4_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array(
self::STRATEGY_STABLE_TAG => function () use ($configBranch) {
return $this->getStableTag($configBranch);
},
);
//Check if there's a "Stable tag: 1.2.3" header that points to a valid tag.
$updateSource = $this->getStableTag($configBranch);
//Look for version-like tags.
if ( !$updateSource && ($configBranch === 'master') ) {
$updateSource = $this->getLatestTag();
}
//If all else fails, use the specified branch itself.
if ( !$updateSource ) {
$updateSource = $this->getBranch($configBranch);
if ( ($configBranch === 'master' || $configBranch === 'main') ) {
$strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
return $updateSource;
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
public function getBranch($branchName) {
@ -59,8 +58,16 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
return null;
}
return new Puc_v4_Vcs_Reference(array(
'name' => $branch->name,
//The "/src/{stuff}/{path}" endpoint doesn't seem to handle branch names that contain slashes.
//If we don't encode the slash, we get a 404. If we encode it as "%2F", we get a 401.
//To avoid issues, if the branch name is not URL-safe, let's use the commit hash instead.
$ref = $branch->name;
if ((urlencode($ref) !== $ref) && isset($branch->target->hash)) {
$ref = $branch->target->hash;
}
return new Reference(array(
'name' => $ref,
'updated' => $branch->target->date,
'downloadUrl' => $this->getDownloadUrl($branch->name),
));
@ -70,7 +77,7 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4_Vcs_Reference|null
* @return Reference|null
*/
public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName);
@ -78,7 +85,7 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
return null;
}
return new Puc_v4_Vcs_Reference(array(
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
@ -89,10 +96,10 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4_Vcs_Reference|null
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/refs/tags');
$tags = $this->api('/refs/tags?sort=-target.date');
if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
return null;
}
@ -103,7 +110,7 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
//Return the first result.
if ( !empty($versionTags) ) {
$tag = $versionTags[0];
return new Puc_v4_Vcs_Reference(array(
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
@ -117,7 +124,7 @@ if ( !class_exists('Puc_v4_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_v4_Vcs_Reference
* @return null|Reference
*/
protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch);
@ -157,11 +164,11 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('src/' . $ref . '/' . ltrim($path), '1.0');
if ( is_wp_error($response) || !isset($response, $response->data) ) {
$response = $this->api('src/' . $ref . '/' . ltrim($path));
if ( is_wp_error($response) || !is_string($response) ) {
return null;
}
return $response->data;
return $response;
}
/**
@ -183,10 +190,11 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
*
* @param string $url
* @param string $version
* @return mixed|WP_Error
* @return mixed|\WP_Error
*/
public function api($url, $version = '2.0') {
//printf('Requesting %s<br>' . "\n", $url);
$url = ltrim($url, '/');
$isSrcResource = Utils::startsWith($url, 'src/');
$url = implode('/', array(
'https://api.bitbucket.org',
@ -194,33 +202,44 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
'repositories',
$this->username,
$this->repository,
ltrim($url, '/')
$url
));
$baseUrl = $url;
if ( $this->oauth ) {
$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);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
if ( $isSrcResource ) {
//Most responses are JSON-encoded, but src resources just
//return raw file contents.
$document = $body;
} else {
$document = json_decode($body);
}
return $document;
}
return new WP_Error(
$error = new \WP_Error(
'puc-bitbucket-http-error',
'BitBucket API error. HTTP status: ' . $code
sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
@ -230,7 +249,7 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
parent::setAuthentication($credentials);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
$this->oauth = new Puc_v4_OAuthSignature(
$this->oauth = new OAuthSignature(
$credentials['consumer_key'],
$credentials['consumer_secret']
);
@ -241,7 +260,7 @@ if ( !class_exists('Puc_v4_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);
@ -250,4 +269,4 @@ if ( !class_exists('Puc_v4_Vcs_BitBucketApi', false) ):
}
}
endif;
endif;

467
Puc/v5p6/Vcs/GitHubApi.php Normal file
View File

@ -0,0 +1,467 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use Parsedown;
if ( !class_exists(GitHubApi::class, false) ):
class GitHubApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
/**
* @var string GitHub username.
*/
protected $userName;
/**
* @var string GitHub repository name.
*/
protected $repositoryName;
/**
* @var string Either a fully qualified repository URL, or just "user/repo-name".
*/
protected $repositoryUrl;
/**
* @var string GitHub authentication token. Optional.
*/
protected $accessToken;
/**
* @var bool
*/
private $downloadFilterAdded = false;
public function __construct($repositoryUrl, $accessToken = null) {
$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 . '"');
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitHub.
*
* @return Reference|null
*/
public function getLatestRelease() {
//The "latest release" endpoint returns one release and always skips pre-releases,
//so we can only use it if that's compatible with the current filter settings.
if (
$this->shouldSkipPreReleases()
&& (
($this->releaseFilterMaxReleases === 1) || !$this->hasCustomReleaseFilter()
)
) {
//Just get the latest release.
$release = $this->api('/repos/:user/:repo/releases/latest');
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;
}
}
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 null;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
if ( is_wp_error($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $tag->zipball_url,
'apiResponse' => $tag,
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
$reference->updated = $branch->commit->commit->author->date;
}
return $reference;
}
/**
* Get the latest commit that changed the specified file.
*
* @param string $filename
* @param string $ref Reference name (e.g. branch or tag).
* @return \StdClass|null
*/
public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api(
'/repos/:user/:repo/commits',
array(
'path' => $filename,
'sha' => $ref,
)
);
if ( !is_wp_error($commits) && isset($commits[0]) ) {
return $commits[0];
}
return null;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
if ( !is_wp_error($commits) && isset($commits[0]) ) {
return $commits[0]->commit->author->date;
}
return null;
}
/**
* Perform a GitHub API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( $this->isAuthenticationEnabled() ) {
$options['headers'] = array('Authorization' => $this->getAuthorizationHeader());
}
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
return $document;
}
$error = new \WP_Error(
'puc-github-http-error',
sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace('/:' . $name, '/' . urlencode($value), $url);
}
$url = 'https://api.github.com' . $url;
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$apiUrl = '/repos/:user/:repo/contents/' . $path;
$response = $this->api($apiUrl, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
urlencode($this->userName),
urlencode($this->repositoryName),
urlencode($ref)
);
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return void
*/
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.');
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
//Optimization: Instead of filtering all HTTP requests, let's do it only when
//WordPress is about to download an update.
add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+
}
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array();
if ( $configBranch === 'master' || $configBranch === 'main') {
//Use the latest release.
$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');
}
//Alternatively, just use the branch itself.
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
/**
* Get the unchanging part of a release asset URL. Used to identify download attempts.
*
* @return string
*/
protected function getAssetApiBaseUrl() {
return sprintf(
'//api.github.com/repos/%1$s/%2$s/releases/assets/',
$this->userName,
$this->repositoryName
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->name) ) {
return $releaseAsset->name;
}
return null;
}
/**
* @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;
}
return $result;
}
/**
* 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
*
* @internal
* @param array $requestArgs
* @param string $url
* @return array
*/
public function setUpdateDownloadHeaders($requestArgs, $url = '') {
//Is WordPress trying to download one of our release assets?
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.
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
if ( $this->isAuthenticationEnabled() && (strpos($url, $repoApiBaseUrl)) === 0 ) {
$requestArgs['headers']['Authorization'] = $this->getAuthorizationHeader();
}
return $requestArgs;
}
/**
* When following a redirect, the Requests library will automatically forward
* the authorization header to other hosts. We don't want that because it breaks
* AWS downloads and can leak authorization information.
*
* @param string $location
* @param array $headers
* @internal
*/
public function removeAuthHeaderFromRedirects(&$location, &$headers) {
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
if ( strpos($location, $repoApiBaseUrl) === 0 ) {
return; //This request is going to GitHub, so it's fine.
}
//Remove the header.
if ( isset($headers['Authorization']) ) {
unset($headers['Authorization']);
}
}
/**
* Generate the value of the "Authorization" header.
*
* @return string
*/
protected function getAuthorizationHeader() {
return 'Basic ' . base64_encode($this->userName . ':' . $this->accessToken);
}
}
endif;

414
Puc/v5p6/Vcs/GitLabApi.php Normal file
View File

@ -0,0 +1,414 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !class_exists(GitLabApi::class, false) ):
class GitLabApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
/**
* @var string GitLab username.
*/
protected $userName;
/**
* @var string GitLab server host.
*/
protected $repositoryHost;
/**
* @var string Protocol used by this GitLab server: "http" or "https".
*/
protected $repositoryProtocol = 'https';
/**
* @var string GitLab repository name.
*/
protected $repositoryName;
/**
* @var string GitLab authentication token. Optional.
*/
protected $accessToken;
/**
* @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 = wp_parse_url($repositoryUrl, PHP_URL_PORT);
if ( !empty($port) ) {
$port = ':' . $port;
}
$this->repositoryHost = wp_parse_url($repositoryUrl, PHP_URL_HOST) . $port;
if ( $this->repositoryHost !== 'gitlab.com' ) {
$this->repositoryProtocol = wp_parse_url($repositoryUrl, PHP_URL_SCHEME);
}
//Find the repository information
$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'];
} elseif ( ($this->repositoryHost === 'gitlab.com') ) {
//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 . '"');
}
$lastPart = array_pop($parts);
$this->userName = implode('/', $parts);
$this->repositoryName = $lastPart;
} else {
//There could be subgroups in the URL: gitlab.domain.com/group/subgroup/subgroup2/repository
if ( $subgroup !== null ) {
$path = str_replace(trailingslashit($subgroup), '', $path);
}
//This is not a traditional url, it could be gitlab is in a deeper subdirectory.
//Get the path segments.
$segments = explode('/', untrailingslashit(ltrim($path, '/')));
//We need at least /user-name/repository-name/
if ( count($segments) < 2 ) {
throw new \InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
}
//Get the username and repository name.
$usernameRepo = array_splice($segments, -2, 2);
$this->userName = $usernameRepo[0];
$this->repositoryName = $usernameRepo[1];
//Append the remaining segments to the host if there are segments left.
if ( count($segments) > 0 ) {
$this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments);
}
//Add subgroups to username.
if ( $subgroup !== null ) {
$this->userName = $usernameRepo[0] . '/' . untrailingslashit($subgroup);
}
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitLab.
*
* @return Reference|null
*/
public function getLatestRelease() {
$releases = $this->api('/:id/releases', array('per_page' => $this->releaseFilterMaxReleases));
if ( is_wp_error($releases) || empty($releases) || !is_array($releases) ) {
return null;
}
foreach ($releases as $release) {
if (
//Skip invalid/unsupported releases.
!is_object($release)
|| !isset($release->tag_name)
//Skip upcoming releases.
|| (
!empty($release->upcoming_release)
&& $this->shouldSkipPreReleases()
)
) {
continue;
}
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
//Apply custom filters.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
$downloadUrl = $this->findReleaseDownloadUrl($release);
if ( empty($downloadUrl) ) {
//The latest release doesn't have valid download URL.
return null;
}
if ( !empty($this->accessToken) ) {
$downloadUrl = add_query_arg('private_token', $this->accessToken, $downloadUrl);
}
return new Reference(array(
'name' => $release->tag_name,
'version' => $versionNumber,
'downloadUrl' => $downloadUrl,
'updated' => $release->released_at,
'apiResponse' => $release,
));
}
return null;
}
/**
* @param object $release
* @return string|null
*/
protected function findReleaseDownloadUrl($release) {
if ( $this->releaseAssetsEnabled ) {
if ( isset($release->assets, $release->assets->links) ) {
//Use the first asset link where the URL matches the filter.
foreach ($release->assets->links as $link) {
if ( $this->matchesAssetFilter($link) ) {
return $link->url;
}
}
}
if ( $this->releaseAssetPreference === Api::REQUIRE_RELEASE_ASSETS ) {
//Falling back to source archives is not allowed, so give up.
return null;
}
}
//Use the first source code archive that's in ZIP format.
foreach ($release->assets->sources as $source) {
if ( isset($source->format) && ($source->format === 'zip') ) {
return $source->url;
}
}
return null;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/:id/repository/tags');
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
'apiResponse' => $tag,
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->committed_date) ) {
$reference->updated = $branch->commit->committed_date;
}
return $reference;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref));
if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) {
return null;
}
return $commits[0]->committed_date;
}
/**
* Perform a GitLab API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
return json_decode($body);
}
$error = new \WP_Error(
'puc-gitlab-http-error',
sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
'id' => $this->userName . '/' . $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace("/:{$name}", '/' . urlencode($value), $url);
}
$url = substr($url, 1);
$url = sprintf('%1$s://%2$s/api/v4/projects/%3$s', $this->repositoryProtocol, $this->repositoryHost, $url);
if ( !empty($this->accessToken) ) {
$queryParams['private_token'] = $this->accessToken;
}
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'%1$s://%2$s/api/v4/projects/%3$s/repository/archive.zip',
$this->repositoryProtocol,
$this->repositoryHost,
urlencode($this->userName . '/' . $this->repositoryName)
);
$url = add_query_arg('sha', urlencode($ref), $url);
if ( !empty($this->accessToken) ) {
$url = add_query_arg('private_token', $this->accessToken, $url);
}
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return void
*/
public function getTag($tagName) {
throw new \LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
}
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array();
if ( ($configBranch === 'main') || ($configBranch === 'master') ) {
$strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
$strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
}
/**
* Use release assets that link to GitLab generic packages (e.g. .zip files)
* instead of automatically generated source archives.
*
* This is included for backwards compatibility with older versions of PUC.
*
* @return void
* @deprecated Use enableReleaseAssets() instead.
* @noinspection PhpUnused -- Public API
*/
public function enableReleasePackages() {
$this->enableReleaseAssets(
/** @lang RegExp */ '/\.zip($|[?&#])/i',
Api::REQUIRE_RELEASE_ASSETS
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->url) ) {
return $releaseAsset->url;
}
return null;
}
}
endif;

View File

@ -1,21 +1,18 @@
<?php
if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
class Puc_v4_Vcs_PluginUpdateChecker extends Puc_v4_Plugin_UpdateChecker implements Puc_v4_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_v4_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4_Vcs_PluginUpdateChecker constructor.
* PluginUpdateChecker constructor.
*
* @param Puc_v4_Vcs_Api $api
* @param Api $api
* @param string $pluginFile
* @param string $slug
* @param int $checkPeriod
@ -24,23 +21,31 @@ if ( !class_exists('Puc_v4_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);
}
public function requestInfo($unusedParameter = null) {
//We have to make several remote API requests to gather all the necessary info
//which can take a while on slow networks.
set_time_limit(60);
if ( function_exists('set_time_limit') ) {
@set_time_limit(60);
}
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$info = new Puc_v4_Plugin_Info();
$info = new Plugin\PluginInfo();
$info->filename = $this->pluginFile;
$info->slug = $this->slug;
$this->setInfoFromHeader($this->getPluginHeader(), $info);
$this->setInfoFromHeader($this->package->getPluginHeader(), $info);
$this->setIconsFromLocalAssets($info);
$this->setBannersFromLocalAssets($info);
//Pick a branch or tag.
$updateSource = $api->chooseReference($this->branch);
@ -58,6 +63,16 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
}
} else {
//There's probably a network problem or an authentication error.
do_action(
'puc_api_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 '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
return null;
}
@ -66,10 +81,25 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
$mainPluginFile = basename($this->pluginFile);
$remotePlugin = $api->getRemoteFile($mainPluginFile, $ref);
if ( !empty($remotePlugin) ) {
$remoteHeader = $this->getFileHeader($remotePlugin);
$remoteHeader = $this->package->getFileHeader($remotePlugin);
$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() ) {
@ -78,7 +108,7 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
//The changelog might be in a separate file.
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = $api->getRemoteChangelog($ref, dirname($this->getAbsolutePath()));
$info->sections['changelog'] = $api->getRemoteChangelog($ref, $this->package->getAbsoluteDirectoryPath());
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
}
@ -102,18 +132,14 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
* @return bool
*/
protected function readmeTxtExistsLocally() {
$pluginDirectory = dirname($this->pluginAbsolutePath);
if ( empty($this->pluginAbsolutePath) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
return false;
}
return is_file($pluginDirectory . '/readme.txt');
return $this->package->fileExists($this->api->getLocalReadmeName());
}
/**
* Copy plugin metadata from a file header to a Plugin Info object.
*
* @param array $fileHeader
* @param Puc_v4_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array(
@ -128,6 +154,8 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
'Tested WP' => 'tested',
'Requires at least' => 'requires',
'Tested up to' => 'tested',
'Requires PHP' => 'requires_php',
);
foreach ($headerToPropertyMap as $headerName => $property) {
if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
@ -144,7 +172,7 @@ if ( !class_exists('Puc_v4_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_v4_Plugin_Info $pluginInfo
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
$readme = $this->api->getRemoteReadme($ref);
@ -161,38 +189,87 @@ if ( !class_exists('Puc_v4_Vcs_PluginUpdateChecker') ):
if ( !empty($readme['requires_at_least']) ) {
$pluginInfo->requires = $readme['requires_at_least'];
}
if ( !empty($readme['requires_php']) ) {
$pluginInfo->requires_php = $readme['requires_php'];
}
if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
$pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
}
}
public function setBranch($branch) {
$this->branch = $branch;
return $this;
/**
* Add icons from the currently installed version to a Plugin Info object.
*
* The icons should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setIconsFromLocalAssets($pluginInfo) {
$icons = $this->getLocalAssetUrls(array(
'icon.svg' => 'svg',
'icon-256x256.png' => '2x',
'icon-256x256.jpg' => '2x',
'icon-128x128.png' => '1x',
'icon-128x128.jpg' => '1x',
));
if ( !empty($icons) ) {
//The "default" key seems to be used only as last-resort fallback in WP core (5.8/5.9),
//but we'll set it anyway in case some code somewhere needs it.
reset($icons);
$firstKey = key($icons);
$icons['default'] = $icons[$firstKey];
$pluginInfo->icons = $icons;
}
}
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
/**
* Add banners from the currently installed version to a Plugin Info object.
*
* The banners should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-headers
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setBannersFromLocalAssets($pluginInfo) {
$banners = $this->getLocalAssetUrls(array(
'banner-772x250.png' => 'high',
'banner-772x250.jpg' => 'high',
'banner-1544x500.png' => 'low',
'banner-1544x500.jpg' => 'low',
));
if ( !empty($banners) ) {
$pluginInfo->banners = $banners;
}
}
public function getUpdate() {
$update = parent::getUpdate();
/**
* @param array<string, string> $filesToKeys
* @return array<string, string>
*/
protected function getLocalAssetUrls($filesToKeys) {
$assetDirectory = $this->package->getAbsoluteDirectoryPath() . DIRECTORY_SEPARATOR . 'assets';
if ( !is_dir($assetDirectory) ) {
return array();
}
$assetBaseUrl = trailingslashit(plugins_url('', $assetDirectory . '/imaginary.file'));
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
$foundAssets = array();
foreach ($filesToKeys as $fileName => $key) {
$fullBannerPath = $assetDirectory . DIRECTORY_SEPARATOR . $fileName;
if ( !isset($icons[$key]) && is_file($fullBannerPath) ) {
$foundAssets[$key] = $assetBaseUrl . $fileName;
}
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
return $foundAssets;
}
}
endif;
endif;

View File

@ -1,5 +1,7 @@
<?php
if ( !class_exists('Puc_v4_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_v4_Vcs_Reference', false) ):
* @property string|null $changelog
* @property int|null $downloadCount
*/
class Puc_v4_Vcs_Reference {
class Reference {
private $properties = array();
public function __construct($properties = array()) {
@ -24,7 +26,7 @@ if ( !class_exists('Puc_v4_Vcs_Reference', false) ):
* @param string $name
* @return mixed|null
*/
function __get($name) {
public function __get($name) {
return array_key_exists($name, $this->properties) ? $this->properties[$name] : null;
}
@ -32,7 +34,7 @@ if ( !class_exists('Puc_v4_Vcs_Reference', false) ):
* @param string $name
* @param mixed $value
*/
function __set($name, $value) {
public function __set($name, $value) {
$this->properties[$name] = $value;
}
@ -40,10 +42,10 @@ if ( !class_exists('Puc_v4_Vcs_Reference', false) ):
* @param string $name
* @return bool
*/
function __isset($name) {
public function __isset($name) {
return isset($this->properties[$name]);
}
}
endif;
endif;

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

@ -0,0 +1,83 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
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;
/**
* ThemeUpdateChecker constructor.
*
* @param Api $api
* @param null $stylesheet
* @param null $customSlug
* @param int $checkPeriod
* @param string $optionName
*/
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
$this->api = $api;
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);
}
public function requestUpdate() {
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$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.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$update->download_url = $updateSource->downloadUrl;
} else {
do_action(
'puc_api_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 '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
$ref = $this->branch;
}
//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 = Utils::findNotEmpty(array(
$remoteHeader['Version'],
Utils::get($updateSource, 'version'),
));
//The details URL defaults to the Theme URI header or the repository URL.
$update->details_url = Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'],
$this->package->getHeaderValue('ThemeURI'),
$this->metadataUrl,
));
if ( empty($update->version) ) {
//It looks like we didn't find a valid update after all.
$update = null;
}
$update = $this->filterUpdateResult($update);
return $update;
}
}
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;
}
}

198
README.md
View File

@ -18,6 +18,10 @@ From the users' perspective, it works just like with plugins and themes hosted o
- [Notes](#notes-1)
- [BitBucket Integration](#bitbucket-integration)
- [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)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
@ -25,6 +29,8 @@ 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 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
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
@ -35,21 +41,21 @@ 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."
}
}
```
This is a minimal example that leaves out optional fields. See [this table](https://spreadsheets.google.com/pub?key=0AqP80E74YcUWdEdETXZLcXhjd2w0cHMwX2U1eDlWTHc&authkey=CK7h9toK&hl=en&single=true&gid=0&output=html) for a full list of supported fields and their descriptions.
This is a minimal example that leaves out optional fields. See [this table](https://docs.google.com/spreadsheets/d/1eOBbW7Go2qEQXReOOCdidMTf_tDYRq4JfegcO1CBPIs/edit?usp=sharing) for a full list of supported fields and their descriptions.
- Theme example:
```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"
}
```
@ -59,18 +65,21 @@ 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',
__FILE__,
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'
);
```
Note: If you're using the Composer autoloader, you don't need to explicitly `require` the library.
#### How to Release an Update
Change the `version` number in the JSON file and make sure that `download_url` points to the latest version. Update the other fields if necessary. Tip: You can use [wp-update-server](https://github.com/YahnisElsts/wp-update-server) to automate this process.
By default, the library will check the specified URL for changes every 12 hours. You can force it to check immediately by clicking the "Check Now" link on the "Plugins" page (it's next to the "Visit plugin site" link). Themes don't get a "check now" link, but you can also trigger an update check like this:
By default, the library will check the specified URL for changes every 12 hours. You can force it to check immediately by clicking the "Check for updates" link on the "Plugins" page (it's next to the "Visit plugin site" link). Themes don't have that link, but you can also trigger an update check like this:
1. Install [Debug Bar](https://srd.wordpress.org/plugins/debug-bar/).
2. Click the "Debug" menu in the Admin Bar (a.k.a Toolbar).
@ -79,7 +88,7 @@ By default, the library will check the specified URL for changes every 12 hours.
#### Notes
- The second argument passed to `buildUpdateChecker` must be the absolute path to the main plugin file or any file in the theme directory. If you followed the "getting started" instructions, you can just use the `__FILE__` constant.
- The third argument - i.e. the slug - is optional but recommended. If it's omitted, the update checker will use the name of the main plugin file as the slug (e.g. `my-cool-plugin.php` &rarr; `my-cool-plugin`). This can lead to conflicts if your plugin has a generic file name like `plugin.php`.
- The third argument - i.e. the slug - is optional but recommended. In most cases, the slug should be the same as the name of your plugin directory. For example, if your plugin lives in `/wp-content/plugins/my-plugin`, set the slug to `my-plugin`. If the slug is omitted, the update checker will use the name of the main plugin file as the slug (e.g. `my-cool-plugin.php` &rarr; `my-cool-plugin`). This can lead to conflicts if your plugin has a generic file name like `plugin.php`.
This doesn't affect themes because PUC uses the theme directory name as the default slug. Still, if you're planning to use the slug in your own code - e.g. to filter updates or override update checker behaviour - it can be a good idea to set it explicitly.
@ -90,19 +99,21 @@ 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'
);
//Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
//Optional: If you're using a private repository, specify the access token like this:
$myUpdateChecker->setAuthentication('your-token-here');
//Optional: Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
```
3. Plugins only: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/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.
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 an Update
@ -112,11 +123,16 @@ This library supports a couple of different ways to release updates on GitHub. P
Create a new release using the "Releases" feature on GitHub. The tag name and release title don't matter. The description is optional, but if you do provide one, it will be displayed when the user clicks the "View version x.y.z details" link on the "Plugins" page. Note that PUC ignores releases marked as "This is a pre-release".
If you want to use release assets, call the `enableReleaseAssets()` method after creating the update checker instance:
```php
$myUpdateChecker->getVcsApi()->enableReleaseAssets();
```
- **Tags**
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**
@ -164,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'
@ -172,6 +190,9 @@ The library will pull update details from the following parts of a release/tag/b
//Optional: If you're using a private repository, create an OAuth consumer
//and set the authentication credentials like this:
//Note: For now you need to check "This is a private consumer" when
//creating the consumer to work around #134:
// https://github.com/YahnisElsts/plugin-update-checker/issues/134
$myUpdateChecker->setAuthentication(array(
'consumer_key' => '...',
'consumer_secret' => '...',
@ -180,7 +201,7 @@ The library will pull update details from the following parts of a release/tag/b
//Optional: Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
```
3. Optional: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. For plugins, the contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
3. Optional: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/readme.txt) to your repository. For plugins, the contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
#### How to Release an Update
@ -188,7 +209,7 @@ BitBucket doesn't have an equivalent to GitHub's releases, so the process is sli
- **`Stable tag` header**
This is the recommended approach if you're using tags to mark each version. Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. Set the "stable tag" header to the tag that represents the latest release. Example:
This is the recommended approach if you're using tags to mark each version. Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/readme.txt) to your repository. Set the "stable tag" header to the tag that represents the latest release. Example:
```text
Stable tag: v1.2.3
```
@ -200,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**
@ -210,11 +231,142 @@ BitBucket doesn't have an equivalent to GitHub's releases, so the process is sli
```
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: If you set the branch to `master`, the update checker will still look for tags first.
### GitLab Integration
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
2. Add the following code to the main plugin file or `functions.php` and define how you want to check for updates from Gitlab (refer to: [Gitlab: How to Release an Update](#how-to-release-a-gitlab-update)):
```php
require 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://gitlab.com/user-name/repo-name/',
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: If you're using a private repository, specify the access token like this:
$myUpdateChecker->setAuthentication('your-token-here');
```
Alternatively, if you're using a self-hosted GitLab instance, initialize the update checker like this:
```php
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 3 different ways.
- **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**
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**
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
------------------
Currently, the update checker doesn't have any built-in license management features. It only provides some hooks that you can use to, for example, append license keys to update requests (`$updateChecker->addQueryArgFilter()`). If you're looking for ways to manage and verify licenses, please post your feedback in [this issue](https://github.com/YahnisElsts/plugin-update-checker/issues/222).
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.
- [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.
- [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](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

@ -1,19 +1,23 @@
{
"name": "yahnis-elsts/plugin-update-checker",
"type": "library",
"description": "A custom update checker for WordPress plugins and themes. Useful if you can't host your plugin in the official WP repository but still want it to support automatic updates.",
"keywords": ["wordpress", "plugin updates", "automatic updates", "theme updates"],
"homepage": "https://github.com/YahnisElsts/plugin-update-checker/",
"license": "MIT",
"authors": [
{
"name": "Yahnis Elsts",
"email": "whiteshadow@w-shadow.com",
"homepage": "http://w-shadow.com/",
"role": "Developer"
}
],
"require": {
"php": ">=5.2.0"
}
}
{
"name": "yahnis-elsts/plugin-update-checker",
"type": "library",
"description": "A custom update checker for WordPress plugins and themes. Useful if you can't host your plugin in the official WP repository but still want it to support automatic updates.",
"keywords": ["wordpress", "plugin updates", "automatic updates", "theme updates"],
"homepage": "https://github.com/YahnisElsts/plugin-update-checker/",
"license": "MIT",
"authors": [
{
"name": "Yahnis Elsts",
"email": "whiteshadow@w-shadow.com",
"homepage": "https://w-shadow.com/",
"role": "Developer"
}
],
"require": {
"php": ">=5.6.20",
"ext-json": "*"
},
"autoload": {
"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;
}
@ -59,4 +59,12 @@ table.puc-debug-data td {
.puc-ajax-nonce {
display: none;
}
}
.puc-ajax-response dt {
margin: 0;
}
.puc-ajax-response dd {
margin: 0 0 1em;
}

View File

@ -1,47 +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'."
},
"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"]').click(function() {
runAjaxAction(this, 'puc_v4_debug_check_now');
$('.puc-debug-bar-panel-v5 input[name="puc-check-now-button"]').on('click', function() {
runAjaxAction(this, 'puc_v5_debug_check_now');
return false;
});
$('.puc-debug-bar-panel-v4 input[name="puc-request-info-button"]').click(function() {
runAjaxAction(this, 'puc_v4_debug_request_info');
$('.puc-debug-bar-panel-v5 input[name="puc-request-info-button"]').on('click', function() {
runAjaxAction(this, 'puc_v5_debug_request_info');
return false;
});
@ -34,7 +36,7 @@ jQuery(function($) {
// Debug Bar uses the panel class name as part of its link and container IDs. This means we can
// end up with multiple identical IDs if more than one plugin uses the update checker library.
// Fix it by replacing the class name with the plugin slug.
var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v4');
var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v5');
panels.each(function() {
var panel = $(this);
var uid = panel.data('uid');
@ -44,7 +46,7 @@ jQuery(function($) {
target.attr('id', 'debug-menu-target-puc-' + uid);
//Change the menu link ID as well and point it at the new target ID.
$('#puc-debug-menu-link-' + uid)
$('#debug-bar-menu').find('.puc-debug-menu-link-' + uid)
.closest('.debug-menu-link')
.attr('id', 'debug-menu-link-puc-' + uid)
.attr('href', '#' + target.attr('id'));

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2019-09-25 18:15+0200\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: ca\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprova si hi ha actualitzacions"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Lextensió %s està actualitzada."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nova versió de lextensió %s està disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No sha pogut determinar si hi ha actualitzacions per a %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estat del comprovador dactualitzacions desconegut \"%s\""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hi ha cap registre de canvis disponible."

Binary file not shown.

View File

@ -0,0 +1,45 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-05-20 10:53+0300\n"
"PO-Revision-Date: 2017-07-05 15:39+0000\n"
"Last-Translator: Vojtěch Sajdl <vojtech@sajdl.com>\n"
"Language-Team: Czech (Czech Republic)\n"
"Language: cs-CZ\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Loco-Source-Locale: cs_CZ\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"
"X-Loco-Parser: loco_parse_po"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Zkontrolovat aktualizace"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Plugin %s je aktuální."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Nová verze pluginu %s je dostupná."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Neznámý status kontroly aktualizací \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Changelog není dostupný."

Binary file not shown.

View File

@ -0,0 +1,42 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-05-20 10:53+0300\n"
"PO-Revision-Date: 2017-10-17 11:07+0200\n"
"Last-Translator: Mikk3lRo\n"
"Language-Team: Mikk3lRo\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Language: da_DK\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Undersøg for opdateringer"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Plugin'et %s er allerede opdateret."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "En ny version af plugin'et %s er tilgængelig."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Ukendt opdateringsstatus: \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Der er ingen ændringslog tilgængelig."

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 "Δεν υπάρχει διαθέσιμο αρχείο αλλαγών."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:13-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 14:56-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:14-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 14:57-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:15-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:15-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 15:15-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2020-03-21 14:57-0400\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.3\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: es_ES\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Comprobar si hay actualizaciones"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "El plugin %s está actualizado."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nueva versión del %s plugin está disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "No se pudo determinar si hay actualizaciones disponibles para %s."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Estado del comprobador de actualización desconocido «%s»"
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "No hay un registro de cambios disponible."

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,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2018-02-12 10:32-0500\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Eric Gagnon <eric.gagnon@banq.qc.ca>\n"
"Language: fr_CA\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Vérifier les mises à jour"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Lextension %s est à jour."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Une nouvelle version de lextension %s est disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Impossible de déterminer si une mise à jour est disponible pour \"%s\""
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Un problème inconnu est survenu \"%s\""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "Il ny a aucun journal de mise à jour disponible."

View File

@ -1,38 +1,42 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-02-17 14:21+0100\n"
"PO-Revision-Date: 2016-08-04 21:08+0200\n"
"Last-Translator: studio RVOLA <hello@rvola.com>\n"
"POT-Creation-Date: 2017-07-07 14:53+0200\n"
"PO-Revision-Date: 2017-07-07 14:54+0200\n"
"Language-Team: studio RVOLA <http://www.rvola.com>\n"
"Language: fr_FR\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-Generator: Poedit 2.0.2\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Nicolas GEHIN\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:120
msgid "There is no changelog available."
msgstr "Il ny a aucun journal de mise à jour disponible."
#: plugin-update-checker.php:637
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Vérifier les mises à jour"
#: plugin-update-checker.php:681
msgid "This plugin is up to date."
msgstr "Cette extension est à jour."
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Lextension %s est à jour."
#: plugin-update-checker.php:683
msgid "A new version of this plugin is available."
msgstr "Une nouvelle version de cette extension est disponible."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Une nouvelle version de lextension %s est disponible."
#: plugin-update-checker.php:685
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Un problème inconnu est survenu \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:85
msgid "There is no changelog available."
msgstr "Il ny a aucun journal de mise à jour disponible."

Binary file not shown.

View File

@ -0,0 +1,48 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2020-08-08 14:36+0300\n"
"PO-Revision-Date: 2022-05-20 00:17+0200\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.0\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: d79\n"
"Language: it_IT\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p11/Plugin/Ui.php:128
msgid "Check for updates"
msgstr "Verifica aggiornamenti"
#: Puc/v4p11/Plugin/Ui.php:213
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Il plugin %s è aggiornato."
#: Puc/v4p11/Plugin/Ui.php:215
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Una nuova versione del plugin %s è disponibile."
#: Puc/v4p11/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Non è possibile verificare se c'è un aggiornamento disponibile per %s."
#: Puc/v4p11/Plugin/Ui.php:223
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Stato di controllo aggiornamenti sconosciuto \"%s\""
#: Puc/v4p11/Vcs/PluginUpdateChecker.php:98
msgid "There is no changelog available."
msgstr "Non c'è alcun registro delle modifiche disponibile."

Binary file not shown.

View File

@ -0,0 +1,57 @@
msgid ""
msgstr ""
"Project-Id-Version: \n"
"POT-Creation-Date: 2019-07-15 17:07+0900\n"
"PO-Revision-Date: 2019-07-15 17:12+0900\n"
"Last-Translator: tak <tak7725@gmail.com>\n"
"Language-Team: \n"
"Language: ja_JP\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.2.3\n"
"X-Poedit-Basepath: ../../../../../../Applications/XAMPP/xamppfiles/htdocs/"
"kisagai/wordpress/wp-content/plugins/simple-stripe-gateway/Puc\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-KeywordsList: __;_x:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
#: v4p7/Plugin/Ui.php:54
msgid "View details"
msgstr "詳細を表示"
#: v4p7/Plugin/Ui.php:77
#, php-format
msgid "More information about %s"
msgstr "%sについての詳細"
#: v4p7/Plugin/Ui.php:128
msgid "Check for updates"
msgstr "アップデートを確認"
#: v4p7/Plugin/Ui.php:213
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "%s プラグインは、最新バージョンです。"
#: v4p7/Plugin/Ui.php:215
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "%s プラグインの最新バージョンがあります。"
#: v4p7/Plugin/Ui.php:217
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "%s のアップデートがあるかどうかを判断できませんでした。"
#: v4p7/Plugin/Ui.php:223
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "バージョンアップの確認で想定外の状態になりました。ステータス:”%s”"
#: v4p7/Vcs/PluginUpdateChecker.php:98
msgid "There is no changelog available."
msgstr "更新履歴はありません。"

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More