Passed
Push — main ( 44ea53...137754 )
by TARIQ
15:15 queued 02:39
created

UpdateChecker::resetUpdateState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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