An updated theme (based on Atticus Finch) for ClassicPress
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

824 lines
26 KiB

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