UpdateChecker.php 31 KB

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