UpdateChecker.php 35 KB

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