-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
UpdateChecker.php
1007 lines (874 loc) · 30.8 KB
/
UpdateChecker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p3;
use stdClass;
use WP_Error;
if ( !class_exists(UpdateChecker::class, false) ):
abstract class UpdateChecker {
protected $filterSuffix = '';
protected $updateTransient = '';
protected $translationType = ''; //This can be "plugin" or "theme".
/**
* 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 = null;
/**
* @var string Where to store the update info.
*/
public $optionName = '';
/**
* @var string The URL of the metadata file.
*/
public $metadataUrl = '';
/**
* @var string Plugin or theme directory name.
*/
public $directoryName = '';
/**
* @var string The slug that will be used in update checker hooks and remote API requests.
* Usually matches the directory name unless the plugin/theme directory has been renamed.
*/
public $slug = '';
/**
* @var InstalledPackage
*/
protected $package;
/**
* @var Scheduler
*/
public $scheduler;
/**
* @var UpgraderStatus
*/
protected $upgraderStatus;
/**
* @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;
public function __construct($metadataUrl, $directoryName, $slug = null, $checkPeriod = 12, $optionName = '') {
$this->debugMode = (bool)(constant('WP_DEBUG'));
$this->metadataUrl = $metadataUrl;
$this->directoryName = $directoryName;
$this->slug = !empty($slug) ? $slug : $this->directoryName;
$this->optionName = $optionName;
if ( empty($this->optionName) ) {
//BC: Initially the library only supported plugin updates and didn't use type prefixes
//in the option name. Lets use the same prefix-less name when possible.
if ( $this->filterSuffix === '' ) {
$this->optionName = 'external_updates-' . $this->slug;
} else {
$this->optionName = $this->getUniqueName('external_updates');
}
}
$this->package = $this->createInstalledPackage();
$this->scheduler = $this->createScheduler($checkPeriod);
$this->upgraderStatus = new UpgraderStatus();
$this->updateState = new StateStore($this->optionName);
if ( did_action('init') ) {
$this->loadTextDomain();
} else {
add_action('init', array($this, 'loadTextDomain'));
}
$this->installHooks();
}
/**
* @internal
*/
public function loadTextDomain() {
//We're not using load_plugin_textdomain() or its siblings because figuring out where
//the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy.
$domain = 'plugin-update-checker';
$locale = apply_filters(
'plugin_locale',
(is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(),
$domain
);
$moFile = $domain . '-' . $locale . '.mo';
$path = realpath(dirname(__FILE__) . '/../../languages');
if ($path && file_exists($path)) {
load_textdomain($domain, $path . '/' . $moFile);
}
}
protected function installHooks() {
//Insert our update info into the update array maintained by WP.
add_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
//Insert translation updates into the update list.
add_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
//Clear translation updates when WP clears the update cache.
//This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
//it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
add_action(
'delete_site_transient_' . $this->updateTransient,
array($this, 'clearCachedTranslationUpdates')
);
//Rename the update directory to be the same as the existing directory.
if ( $this->directoryName !== '.' ) {
add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
}
//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);
//DebugBar integration.
if ( did_action('plugins_loaded') ) {
$this->maybeInitDebugBar();
} else {
add_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
}
}
/**
* 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_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.
*
* @return bool
*/
abstract public function userCanInstallUpdates();
/**
* Explicitly allow HTTP requests to the metadata URL.
*
* WordPress has a security feature where the HTTP API will reject all requests that are sent to
* another site hosted on the same server as the current site (IP match), a local host, or a local
* IP, unless the host exactly matches the current site.
*
* This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
*
* That can be a problem when you're developing your plugin and you decide to host the update information
* on the same server as your test site. Update requests will mysteriously fail.
*
* We fix that by adding an exception for the metadata host.
*
* @param bool $allow
* @param string $host
* @return bool
*/
public function allowMetadataHost($allow, $host) {
if ( $this->cachedMetadataHost === 0 ) {
$this->cachedMetadataHost = wp_parse_url($this->metadataUrl, PHP_URL_HOST);
}
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.
*
* This is implemented as a method to make it possible for plugins to subclass the update checker
* and substitute their own scheduler.
*
* @param int $checkPeriod
* @return Scheduler
*/
abstract protected function createScheduler($checkPeriod);
/**
* Check for updates. The results are stored in the DB option specified in $optionName.
*
* @return Update|null
*/
public function checkForUpdates() {
$installedVersion = $this->getInstalledVersion();
//Fail silently if we can't find the plugin/theme or read its header.
if ( $installedVersion === null ) {
$this->triggerError(
sprintf('Skipping update check for %s - installed version unknown.', $this->slug),
E_USER_WARNING
);
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)
->save(); //Save before checking in case something goes wrong
$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 StateStore
*/
public function getUpdateState() {
return $this->updateState->lazyLoad();
}
/**
* Reset update checker state - i.e. last check time, cached update data and so on.
*
* Call this when your plugin is being uninstalled, or if you want to
* clear the update cache.
*/
public function resetUpdateState() {
$this->updateState->delete();
}
/**
* Get the details of the currently available update, if any.
*
* If no updates are available, or if the last known update version is below or equal
* to the currently installed version, this method will return NULL.
*
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Update|null
*/
public function getUpdate() {
$update = $this->updateState->getUpdate();
//Is there an update available?
if ( isset($update) ) {
//Check if the update is actually newer than the currently installed version.
$installedVersion = $this->getInstalledVersion();
if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
return $update;
}
}
return null;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* Subclasses should run the update through filterUpdateResult before returning it.
*
* @return Update An instance of Update, or NULL when no updates are available.
*/
abstract public function requestUpdate();
/**
* Filter the result of a requestUpdate() call.
*
* @template T of Update
* @param T|null $update
* @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
* @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);
}
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(Metadata $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|null Version number.
*/
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.
*
* @param string $message
* @param int $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.
*
* This method adds the "puc_" prefix and the "-$slug" suffix to the filter name.
* For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug".
*
* @param string $baseTag
* @return string
*/
public function getUniqueName($baseTag) {
$name = 'puc_' . $baseTag;
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
* -------------------------------------------------------------------
*/
/**
* Register a callback for one of the update checker filters.
*
* Identical to add_filter(), except it automatically adds the "puc_" prefix
* and the "-$slug" suffix to the filter name. For example, "request_info_result"
* becomes "puc_request_info_result-your_plugin_slug".
*
* @param string $tag
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
*/
public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs);
}
/* -------------------------------------------------------------------
* Inject updates
* -------------------------------------------------------------------
*/
/**
* Insert the latest update (if any) into the update list maintained by WP.
*
* @param \stdClass $updates Update list.
* @return \stdClass Modified update list.
*/
public function injectUpdate($updates) {
//Is there an update to insert?
$update = $this->getUpdate();
if ( !$this->shouldShowUpdates() ) {
$update = null;
}
if ( !empty($update) ) {
//Let plugins filter the update info before it's passed on to WordPress.
$update = apply_filters($this->getUniqueName('pre_inject_update'), $update);
$updates = $this->addUpdateToList($updates, $update->toWpFormat());
} 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
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( !is_object($updates) ) {
$updates = new stdClass();
$updates->response = array();
}
$updates->response[$this->getUpdateListKey()] = $updateToAdd;
return $updates;
}
/**
* @param \stdClass|null $updates
* @return \stdClass|null
*/
protected function removeUpdateFromList($updates) {
if ( isset($updates, $updates->response) ) {
unset($updates->response[$this->getUpdateListKey()]);
}
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
* for plugins and themes.
*
* @return string
*/
abstract protected function getUpdateListKey();
/**
* Should we show available updates?
*
* Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't
* support automatic updates installation for mu-plugins, so PUC usually won't show update
* notifications in that case. See the plugin-specific subclass for details.
*
* Note: This method only applies to updates that are displayed (or not) in the WordPress
* admin. It doesn't affect APIs like requestUpdate and getUpdate.
*
* @return bool
*/
protected function shouldShowUpdates() {
return true;
}
/* -------------------------------------------------------------------
* JSON-based update API
* -------------------------------------------------------------------
*/
/**
* Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl.
*
* @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<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()).
$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' => wp_doing_cron() ? 10 : 3,
'headers' => array(
'Accept' => 'application/json',
),
);
$options = apply_filters($this->getUniqueName($filterRoot . '_options'), $options);
//The metadata file should be at 'http://your-api.com/url/here/$slug/info.json'
$url = $this->metadataUrl;
if ( !empty($queryArgs) ){
$url = add_query_arg($queryArgs, $url);
}
$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(),
E_USER_WARNING
);
}
return array($metadata, $result);
}
/**
* Check if $result is a successful update API response.
*
* @param array|WP_Error $result
* @return true|WP_Error
*/
protected function validateApiResponse($result) {
if ( is_wp_error($result) ) { /** @var WP_Error $result */
return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
}
if ( !isset($result['response']['code']) ) {
return new WP_Error(
'puc_no_response_code',
'wp_remote_get() returned an unexpected result.'
);
}
if ( $result['response']['code'] !== 200 ) {
return new WP_Error(
'puc_unexpected_response_code',
'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
);
}
if ( empty($result['body']) ) {
return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
}
return true;
}
/* -------------------------------------------------------------------
* Language packs / Translation updates
* -------------------------------------------------------------------
*/
/**
* Filter a list of translation updates and return a new list that contains only updates
* that apply to the current site.
*
* @param array $translations
* @return array
*/
protected function filterApplicableTranslations($translations) {
$languages = array_flip(array_values(get_available_languages()));
$installedTranslations = $this->getInstalledTranslations();
$applicableTranslations = array();
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?
if ( isset($installedTranslations[$translation->language]) ) {
$updateTimestamp = strtotime($translation->updated);
$installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
$isApplicable = $updateTimestamp > $installedTimestamp;
}
if ( $isApplicable ) {
$applicableTranslations[] = $translation;
}
}
return $applicableTranslations;
}
/**
* Get a list of installed translations for this plugin or theme.
*
* @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];
} else {
$installedTranslations = array();
}
return $installedTranslations;
}
/**
* Insert translation updates into the list maintained by WordPress.
*
* @param stdClass $updates
* @return stdClass
*/
public function injectTranslationUpdates($updates) {
$translationUpdates = $this->getTranslationUpdates();
if ( empty($translationUpdates) ) {
return $updates;
}
//Being defensive.
if ( !is_object($updates) ) {
$updates = new stdClass();
}
if ( !isset($updates->translations) ) {
$updates->translations = array();
}
//In case there's a name collision with a plugin or theme hosted on wordpress.org,
//remove any preexisting updates that match our thing.
$updates->translations = array_values(array_filter(
$updates->translations,
array($this, 'isNotMyTranslation')
));
//Add our updates to the list.
foreach($translationUpdates as $update) {
$convertedUpdate = array_merge(
array(
'type' => $this->translationType,
'slug' => $this->directoryName,
'autoupdate' => 0,
//AFAICT, WordPress doesn't actually use the "version" field for anything.
//But lets make sure it's there, just in case.
'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
),
(array)$update
);
$updates->translations[] = $convertedUpdate;
}
return $updates;
}
/**
* Get a list of available translation updates.
*
* This method will return an empty array if there are no updates.
* Uses cached update data.
*
* @return array
*/
public function getTranslationUpdates() {
return $this->updateState->getTranslations();
}
/**
* Remove all cached translation updates.
*
* @see wp_clean_update_cache
*/
public function clearCachedTranslationUpdates() {
$this->updateState->setTranslations(array());
}
/**
* Filter callback. Keeps only translations that *don't* match this plugin or theme.
*
* @param array $translation
* @return bool
*/
protected function isNotMyTranslation($translation) {
$isMatch = isset($translation['type'], $translation['slug'])
&& ($translation['type'] === $this->translationType)
&& ($translation['slug'] === $this->directoryName);
return !$isMatch;
}
/* -------------------------------------------------------------------
* Fix directory name when installing updates
* -------------------------------------------------------------------
*/
/**
* Rename the update directory to match the existing plugin/theme directory.
*
* When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
* exactly one directory, and that the directory name will be the same as the directory where
* the plugin or theme is currently installed.
*
* GitHub and other repositories provide ZIP downloads, but they often use directory names like
* "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
*
* This is a hook callback. Don't call it from a plugin.
*
* @access protected
*
* @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
* @return string|WP_Error
*/
public function fixDirectoryName($source, $remoteSource, $upgrader) {
global $wp_filesystem;
/** @var \WP_Filesystem_Base $wp_filesystem */
//Basic sanity checks.
if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
return $source;
}
//If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged.
if ( !$this->isBeingUpgraded($upgrader) ) {
return $source;
}
//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…',
'<span class="code">' . basename($source) . '</span>',
'<span class="code">' . $this->directoryName . '</span>'
));
if ( $wp_filesystem->move($source, $correctedSource, true) ) {
$upgrader->skin->feedback('Directory successfully renamed.');
return $correctedSource;
} else {
return new WP_Error(
'puc-rename-failed',
'Unable to rename the update to match the existing directory.'
);
}
}
return $source;
}
/**
* 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.
* @return bool
*/
abstract public function isBeingUpgraded($upgrader = null);
/**
* Check for incorrect update directory structure. An update must contain a single directory,
* all other files should be inside that directory.
*
* @param string $remoteSource Directory path.
* @return bool
*/
protected function isBadDirectoryStructure($remoteSource) {
global $wp_filesystem;
/** @var \WP_Filesystem_Base $wp_filesystem */
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) {
$sourceFiles = array_keys($sourceFiles);
$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
}
//Assume it's fine.
return false;
}
/* -------------------------------------------------------------------
* DebugBar integration
* -------------------------------------------------------------------
*/
/**
* Initialize the update checker Debug Bar plugin/add-on thingy.
*/
public function maybeInitDebugBar() {
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 DebugBar\Extension($this);
}
/**
* Display additional configuration details in the Debug Bar panel.
*
* @param DebugBar\Panel $panel
*/