PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/includes/theme.php

http://github.com/markjaquith/WordPress
PHP | 937 lines | 538 code | 99 blank | 300 comment | 76 complexity | 0ac7f1509ae638930015547fafa57146 MD5 | raw file
Possible License(s): 0BSD
  1. <?php
  2. /**
  3. * WordPress Theme Administration API
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. */
  8. /**
  9. * Remove a theme
  10. *
  11. * @since 2.8.0
  12. *
  13. * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
  14. *
  15. * @param string $stylesheet Stylesheet of the theme to delete.
  16. * @param string $redirect Redirect to page when complete.
  17. * @return bool|null|WP_Error True on success, false if `$stylesheet` is empty, WP_Error on failure.
  18. * Null if filesystem credentials are required to proceed.
  19. */
  20. function delete_theme( $stylesheet, $redirect = '' ) {
  21. global $wp_filesystem;
  22. if ( empty( $stylesheet ) ) {
  23. return false;
  24. }
  25. if ( empty( $redirect ) ) {
  26. $redirect = wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet );
  27. }
  28. ob_start();
  29. $credentials = request_filesystem_credentials( $redirect );
  30. $data = ob_get_clean();
  31. if ( false === $credentials ) {
  32. if ( ! empty( $data ) ) {
  33. require_once ABSPATH . 'wp-admin/admin-header.php';
  34. echo $data;
  35. require_once ABSPATH . 'wp-admin/admin-footer.php';
  36. exit;
  37. }
  38. return;
  39. }
  40. if ( ! WP_Filesystem( $credentials ) ) {
  41. ob_start();
  42. // Failed to connect. Error and request again.
  43. request_filesystem_credentials( $redirect, '', true );
  44. $data = ob_get_clean();
  45. if ( ! empty( $data ) ) {
  46. require_once ABSPATH . 'wp-admin/admin-header.php';
  47. echo $data;
  48. require_once ABSPATH . 'wp-admin/admin-footer.php';
  49. exit;
  50. }
  51. return;
  52. }
  53. if ( ! is_object( $wp_filesystem ) ) {
  54. return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
  55. }
  56. if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
  57. return new WP_Error( 'fs_error', __( 'Filesystem error.' ), $wp_filesystem->errors );
  58. }
  59. // Get the base plugin folder.
  60. $themes_dir = $wp_filesystem->wp_themes_dir();
  61. if ( empty( $themes_dir ) ) {
  62. return new WP_Error( 'fs_no_themes_dir', __( 'Unable to locate WordPress theme directory.' ) );
  63. }
  64. $themes_dir = trailingslashit( $themes_dir );
  65. $theme_dir = trailingslashit( $themes_dir . $stylesheet );
  66. $deleted = $wp_filesystem->delete( $theme_dir, true );
  67. if ( ! $deleted ) {
  68. return new WP_Error(
  69. 'could_not_remove_theme',
  70. /* translators: %s: Theme name. */
  71. sprintf( __( 'Could not fully remove the theme %s.' ), $stylesheet )
  72. );
  73. }
  74. $theme_translations = wp_get_installed_translations( 'themes' );
  75. // Remove language files, silently.
  76. if ( ! empty( $theme_translations[ $stylesheet ] ) ) {
  77. $translations = $theme_translations[ $stylesheet ];
  78. foreach ( $translations as $translation => $data ) {
  79. $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.po' );
  80. $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.mo' );
  81. $json_translation_files = glob( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '-*.json' );
  82. if ( $json_translation_files ) {
  83. array_map( array( $wp_filesystem, 'delete' ), $json_translation_files );
  84. }
  85. }
  86. }
  87. // Remove the theme from allowed themes on the network.
  88. if ( is_multisite() ) {
  89. WP_Theme::network_disable_theme( $stylesheet );
  90. }
  91. // Force refresh of theme update information.
  92. delete_site_transient( 'update_themes' );
  93. return true;
  94. }
  95. /**
  96. * Gets the page templates available in this theme.
  97. *
  98. * @since 1.5.0
  99. * @since 4.7.0 Added the `$post_type` parameter.
  100. *
  101. * @param WP_Post|null $post Optional. The post being edited, provided for context.
  102. * @param string $post_type Optional. Post type to get the templates for. Default 'page'.
  103. * @return string[] Array of template file names keyed by the template header name.
  104. */
  105. function get_page_templates( $post = null, $post_type = 'page' ) {
  106. return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) );
  107. }
  108. /**
  109. * Tidies a filename for url display by the theme editor.
  110. *
  111. * @since 2.9.0
  112. * @access private
  113. *
  114. * @param string $fullpath Full path to the theme file
  115. * @param string $containingfolder Path of the theme parent folder
  116. * @return string
  117. */
  118. function _get_template_edit_filename( $fullpath, $containingfolder ) {
  119. return str_replace( dirname( dirname( $containingfolder ) ), '', $fullpath );
  120. }
  121. /**
  122. * Check if there is an update for a theme available.
  123. *
  124. * Will display link, if there is an update available.
  125. *
  126. * @since 2.7.0
  127. * @see get_theme_update_available()
  128. *
  129. * @param WP_Theme $theme Theme data object.
  130. */
  131. function theme_update_available( $theme ) {
  132. echo get_theme_update_available( $theme );
  133. }
  134. /**
  135. * Retrieve the update link if there is a theme update available.
  136. *
  137. * Will return a link if there is an update available.
  138. *
  139. * @since 3.8.0
  140. *
  141. * @staticvar object $themes_update
  142. *
  143. * @param WP_Theme $theme WP_Theme object.
  144. * @return string|false HTML for the update link, or false if invalid info was passed.
  145. */
  146. function get_theme_update_available( $theme ) {
  147. static $themes_update = null;
  148. if ( ! current_user_can( 'update_themes' ) ) {
  149. return false;
  150. }
  151. if ( ! isset( $themes_update ) ) {
  152. $themes_update = get_site_transient( 'update_themes' );
  153. }
  154. if ( ! ( $theme instanceof WP_Theme ) ) {
  155. return false;
  156. }
  157. $stylesheet = $theme->get_stylesheet();
  158. $html = '';
  159. if ( isset( $themes_update->response[ $stylesheet ] ) ) {
  160. $update = $themes_update->response[ $stylesheet ];
  161. $theme_name = $theme->display( 'Name' );
  162. $details_url = add_query_arg(
  163. array(
  164. 'TB_iframe' => 'true',
  165. 'width' => 1024,
  166. 'height' => 800,
  167. ),
  168. $update['url']
  169. ); // Theme browser inside WP? Replace this. Also, theme preview JS will override this on the available list.
  170. $update_url = wp_nonce_url( admin_url( 'update.php?action=upgrade-theme&amp;theme=' . urlencode( $stylesheet ) ), 'upgrade-theme_' . $stylesheet );
  171. if ( ! is_multisite() ) {
  172. if ( ! current_user_can( 'update_themes' ) ) {
  173. $html = sprintf(
  174. /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */
  175. '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.' ) . '</strong></p>',
  176. $theme_name,
  177. esc_url( $details_url ),
  178. sprintf(
  179. 'class="thickbox open-plugin-details-modal" aria-label="%s"',
  180. /* translators: 1: Theme name, 2: Version number. */
  181. esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
  182. ),
  183. $update['new_version']
  184. );
  185. } elseif ( empty( $update['package'] ) ) {
  186. $html = sprintf(
  187. /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */
  188. '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' ) . '</strong></p>',
  189. $theme_name,
  190. esc_url( $details_url ),
  191. sprintf(
  192. 'class="thickbox open-plugin-details-modal" aria-label="%s"',
  193. /* translators: 1: Theme name, 2: Version number. */
  194. esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
  195. ),
  196. $update['new_version']
  197. );
  198. } else {
  199. $html = sprintf(
  200. /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number, 5: Update URL, 6: Additional link attributes. */
  201. '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.' ) . '</strong></p>',
  202. $theme_name,
  203. esc_url( $details_url ),
  204. sprintf(
  205. 'class="thickbox open-plugin-details-modal" aria-label="%s"',
  206. /* translators: 1: Theme name, 2: Version number. */
  207. esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
  208. ),
  209. $update['new_version'],
  210. $update_url,
  211. sprintf(
  212. 'aria-label="%s" id="update-theme" data-slug="%s"',
  213. /* translators: %s: Theme name. */
  214. esc_attr( sprintf( __( 'Update %s now' ), $theme_name ) ),
  215. $stylesheet
  216. )
  217. );
  218. }
  219. }
  220. }
  221. return $html;
  222. }
  223. /**
  224. * Retrieve list of WordPress theme features (aka theme tags).
  225. *
  226. * @since 3.1.0
  227. *
  228. * @param bool $api Optional. Whether try to fetch tags from the WordPress.org API. Defaults to true.
  229. * @return array Array of features keyed by category with translations keyed by slug.
  230. */
  231. function get_theme_feature_list( $api = true ) {
  232. // Hard-coded list is used if API is not accessible.
  233. $features = array(
  234. __( 'Subject' ) => array(
  235. 'blog' => __( 'Blog' ),
  236. 'e-commerce' => __( 'E-Commerce' ),
  237. 'education' => __( 'Education' ),
  238. 'entertainment' => __( 'Entertainment' ),
  239. 'food-and-drink' => __( 'Food & Drink' ),
  240. 'holiday' => __( 'Holiday' ),
  241. 'news' => __( 'News' ),
  242. 'photography' => __( 'Photography' ),
  243. 'portfolio' => __( 'Portfolio' ),
  244. ),
  245. __( 'Features' ) => array(
  246. 'accessibility-ready' => __( 'Accessibility Ready' ),
  247. 'custom-background' => __( 'Custom Background' ),
  248. 'custom-colors' => __( 'Custom Colors' ),
  249. 'custom-header' => __( 'Custom Header' ),
  250. 'custom-logo' => __( 'Custom Logo' ),
  251. 'editor-style' => __( 'Editor Style' ),
  252. 'featured-image-header' => __( 'Featured Image Header' ),
  253. 'featured-images' => __( 'Featured Images' ),
  254. 'footer-widgets' => __( 'Footer Widgets' ),
  255. 'full-width-template' => __( 'Full Width Template' ),
  256. 'post-formats' => __( 'Post Formats' ),
  257. 'sticky-post' => __( 'Sticky Post' ),
  258. 'theme-options' => __( 'Theme Options' ),
  259. ),
  260. __( 'Layout' ) => array(
  261. 'grid-layout' => __( 'Grid Layout' ),
  262. 'one-column' => __( 'One Column' ),
  263. 'two-columns' => __( 'Two Columns' ),
  264. 'three-columns' => __( 'Three Columns' ),
  265. 'four-columns' => __( 'Four Columns' ),
  266. 'left-sidebar' => __( 'Left Sidebar' ),
  267. 'right-sidebar' => __( 'Right Sidebar' ),
  268. ),
  269. );
  270. if ( ! $api || ! current_user_can( 'install_themes' ) ) {
  271. return $features;
  272. }
  273. $feature_list = get_site_transient( 'wporg_theme_feature_list' );
  274. if ( ! $feature_list ) {
  275. set_site_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS );
  276. }
  277. if ( ! $feature_list ) {
  278. $feature_list = themes_api( 'feature_list', array() );
  279. if ( is_wp_error( $feature_list ) ) {
  280. return $features;
  281. }
  282. }
  283. if ( ! $feature_list ) {
  284. return $features;
  285. }
  286. set_site_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS );
  287. $category_translations = array(
  288. 'Layout' => __( 'Layout' ),
  289. 'Features' => __( 'Features' ),
  290. 'Subject' => __( 'Subject' ),
  291. );
  292. // Loop over the wp.org canonical list and apply translations.
  293. $wporg_features = array();
  294. foreach ( (array) $feature_list as $feature_category => $feature_items ) {
  295. if ( isset( $category_translations[ $feature_category ] ) ) {
  296. $feature_category = $category_translations[ $feature_category ];
  297. }
  298. $wporg_features[ $feature_category ] = array();
  299. foreach ( $feature_items as $feature ) {
  300. if ( isset( $features[ $feature_category ][ $feature ] ) ) {
  301. $wporg_features[ $feature_category ][ $feature ] = $features[ $feature_category ][ $feature ];
  302. } else {
  303. $wporg_features[ $feature_category ][ $feature ] = $feature;
  304. }
  305. }
  306. }
  307. return $wporg_features;
  308. }
  309. /**
  310. * Retrieves theme installer pages from the WordPress.org Themes API.
  311. *
  312. * It is possible for a theme to override the Themes API result with three
  313. * filters. Assume this is for themes, which can extend on the Theme Info to
  314. * offer more choices. This is very powerful and must be used with care, when
  315. * overriding the filters.
  316. *
  317. * The first filter, {@see 'themes_api_args'}, is for the args and gives the action
  318. * as the second parameter. The hook for {@see 'themes_api_args'} must ensure that
  319. * an object is returned.
  320. *
  321. * The second filter, {@see 'themes_api'}, allows a plugin to override the WordPress.org
  322. * Theme API entirely. If `$action` is 'query_themes', 'theme_information', or 'feature_list',
  323. * an object MUST be passed. If `$action` is 'hot_tags', an array should be passed.
  324. *
  325. * Finally, the third filter, {@see 'themes_api_result'}, makes it possible to filter the
  326. * response object or array, depending on the `$action` type.
  327. *
  328. * Supported arguments per action:
  329. *
  330. * | Argument Name | 'query_themes' | 'theme_information' | 'hot_tags' | 'feature_list' |
  331. * | -------------------| :------------: | :-----------------: | :--------: | :--------------: |
  332. * | `$slug` | No | Yes | No | No |
  333. * | `$per_page` | Yes | No | No | No |
  334. * | `$page` | Yes | No | No | No |
  335. * | `$number` | No | No | Yes | No |
  336. * | `$search` | Yes | No | No | No |
  337. * | `$tag` | Yes | No | No | No |
  338. * | `$author` | Yes | No | No | No |
  339. * | `$user` | Yes | No | No | No |
  340. * | `$browse` | Yes | No | No | No |
  341. * | `$locale` | Yes | Yes | No | No |
  342. * | `$fields` | Yes | Yes | No | No |
  343. *
  344. * @since 2.8.0
  345. *
  346. * @param string $action API action to perform: 'query_themes', 'theme_information',
  347. * 'hot_tags' or 'feature_list'.
  348. * @param array|object $args {
  349. * Optional. Array or object of arguments to serialize for the Themes API.
  350. *
  351. * @type string $slug The theme slug. Default empty.
  352. * @type int $per_page Number of themes per page. Default 24.
  353. * @type int $page Number of current page. Default 1.
  354. * @type int $number Number of tags to be queried.
  355. * @type string $search A search term. Default empty.
  356. * @type string $tag Tag to filter themes. Default empty.
  357. * @type string $author Username of an author to filter themes. Default empty.
  358. * @type string $user Username to query for their favorites. Default empty.
  359. * @type string $browse Browse view: 'featured', 'popular', 'updated', 'favorites'.
  360. * @type string $locale Locale to provide context-sensitive results. Default is the value of get_locale().
  361. * @type array $fields {
  362. * Array of fields which should or should not be returned.
  363. *
  364. * @type bool $description Whether to return the theme full description. Default false.
  365. * @type bool $sections Whether to return the theme readme sections: description, installation,
  366. * FAQ, screenshots, other notes, and changelog. Default false.
  367. * @type bool $rating Whether to return the rating in percent and total number of ratings.
  368. * Default false.
  369. * @type bool $ratings Whether to return the number of rating for each star (1-5). Default false.
  370. * @type bool $downloaded Whether to return the download count. Default false.
  371. * @type bool $downloadlink Whether to return the download link for the package. Default false.
  372. * @type bool $last_updated Whether to return the date of the last update. Default false.
  373. * @type bool $tags Whether to return the assigned tags. Default false.
  374. * @type bool $homepage Whether to return the theme homepage link. Default false.
  375. * @type bool $screenshots Whether to return the screenshots. Default false.
  376. * @type int $screenshot_count Number of screenshots to return. Default 1.
  377. * @type bool $screenshot_url Whether to return the URL of the first screenshot. Default false.
  378. * @type bool $photon_screenshots Whether to return the screenshots via Photon. Default false.
  379. * @type bool $template Whether to return the slug of the parent theme. Default false.
  380. * @type bool $parent Whether to return the slug, name and homepage of the parent theme. Default false.
  381. * @type bool $versions Whether to return the list of all available versions. Default false.
  382. * @type bool $theme_url Whether to return theme's URL. Default false.
  383. * @type bool $extended_author Whether to return nicename or nicename and display name. Default false.
  384. * }
  385. * }
  386. * @return object|array|WP_Error Response object or array on success, WP_Error on failure. See the
  387. * {@link https://developer.wordpress.org/reference/functions/themes_api/ function reference article}
  388. * for more information on the make-up of possible return objects depending on the value of `$action`.
  389. */
  390. function themes_api( $action, $args = array() ) {
  391. // Include an unmodified $wp_version.
  392. require ABSPATH . WPINC . '/version.php';
  393. if ( is_array( $args ) ) {
  394. $args = (object) $args;
  395. }
  396. if ( 'query_themes' == $action ) {
  397. if ( ! isset( $args->per_page ) ) {
  398. $args->per_page = 24;
  399. }
  400. }
  401. if ( ! isset( $args->locale ) ) {
  402. $args->locale = get_user_locale();
  403. }
  404. if ( ! isset( $args->wp_version ) ) {
  405. $args->wp_version = substr( $wp_version, 0, 3 ); // x.y
  406. }
  407. /**
  408. * Filters arguments used to query for installer pages from the WordPress.org Themes API.
  409. *
  410. * Important: An object MUST be returned to this filter.
  411. *
  412. * @since 2.8.0
  413. *
  414. * @param object $args Arguments used to query for installer pages from the WordPress.org Themes API.
  415. * @param string $action Requested action. Likely values are 'theme_information',
  416. * 'feature_list', or 'query_themes'.
  417. */
  418. $args = apply_filters( 'themes_api_args', $args, $action );
  419. /**
  420. * Filters whether to override the WordPress.org Themes API.
  421. *
  422. * Passing a non-false value will effectively short-circuit the WordPress.org API request.
  423. *
  424. * If `$action` is 'query_themes', 'theme_information', or 'feature_list', an object MUST
  425. * be passed. If `$action` is 'hot_tags', an array should be passed.
  426. *
  427. * @since 2.8.0
  428. *
  429. * @param false|object|array $override Whether to override the WordPress.org Themes API. Default false.
  430. * @param string $action Requested action. Likely values are 'theme_information',
  431. * 'feature_list', or 'query_themes'.
  432. * @param object $args Arguments used to query for installer pages from the Themes API.
  433. */
  434. $res = apply_filters( 'themes_api', false, $action, $args );
  435. if ( ! $res ) {
  436. $url = 'http://api.wordpress.org/themes/info/1.2/';
  437. $url = add_query_arg(
  438. array(
  439. 'action' => $action,
  440. 'request' => $args,
  441. ),
  442. $url
  443. );
  444. $http_url = $url;
  445. $ssl = wp_http_supports( array( 'ssl' ) );
  446. if ( $ssl ) {
  447. $url = set_url_scheme( $url, 'https' );
  448. }
  449. $http_args = array(
  450. 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ),
  451. );
  452. $request = wp_remote_get( $url, $http_args );
  453. if ( $ssl && is_wp_error( $request ) ) {
  454. if ( ! wp_doing_ajax() ) {
  455. trigger_error(
  456. sprintf(
  457. /* translators: %s: Support forums URL. */
  458. __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
  459. __( 'https://wordpress.org/support/forums/' )
  460. ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ),
  461. headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE
  462. );
  463. }
  464. $request = wp_remote_get( $http_url, $http_args );
  465. }
  466. if ( is_wp_error( $request ) ) {
  467. $res = new WP_Error(
  468. 'themes_api_failed',
  469. sprintf(
  470. /* translators: %s: Support forums URL. */
  471. __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
  472. __( 'https://wordpress.org/support/forums/' )
  473. ),
  474. $request->get_error_message()
  475. );
  476. } else {
  477. $res = json_decode( wp_remote_retrieve_body( $request ), true );
  478. if ( is_array( $res ) ) {
  479. // Object casting is required in order to match the info/1.0 format.
  480. $res = (object) $res;
  481. } elseif ( null === $res ) {
  482. $res = new WP_Error(
  483. 'themes_api_failed',
  484. sprintf(
  485. /* translators: %s: Support forums URL. */
  486. __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
  487. __( 'https://wordpress.org/support/forums/' )
  488. ),
  489. wp_remote_retrieve_body( $request )
  490. );
  491. }
  492. if ( isset( $res->error ) ) {
  493. $res = new WP_Error( 'themes_api_failed', $res->error );
  494. }
  495. }
  496. // Back-compat for info/1.2 API, upgrade the theme objects in query_themes to objects.
  497. if ( 'query_themes' == $action ) {
  498. foreach ( $res->themes as $i => $theme ) {
  499. $res->themes[ $i ] = (object) $theme;
  500. }
  501. }
  502. // Back-compat for info/1.2 API, downgrade the feature_list result back to an array.
  503. if ( 'feature_list' == $action ) {
  504. $res = (array) $res;
  505. }
  506. }
  507. /**
  508. * Filters the returned WordPress.org Themes API response.
  509. *
  510. * @since 2.8.0
  511. *
  512. * @param array|object|WP_Error $res WordPress.org Themes API response.
  513. * @param string $action Requested action. Likely values are 'theme_information',
  514. * 'feature_list', or 'query_themes'.
  515. * @param object $args Arguments used to query for installer pages from the WordPress.org Themes API.
  516. */
  517. return apply_filters( 'themes_api_result', $res, $action, $args );
  518. }
  519. /**
  520. * Prepare themes for JavaScript.
  521. *
  522. * @since 3.8.0
  523. *
  524. * @param WP_Theme[] $themes Optional. Array of theme objects to prepare.
  525. * Defaults to all allowed themes.
  526. *
  527. * @return array An associative array of theme data, sorted by name.
  528. */
  529. function wp_prepare_themes_for_js( $themes = null ) {
  530. $current_theme = get_stylesheet();
  531. /**
  532. * Filters theme data before it is prepared for JavaScript.
  533. *
  534. * Passing a non-empty array will result in wp_prepare_themes_for_js() returning
  535. * early with that value instead.
  536. *
  537. * @since 4.2.0
  538. *
  539. * @param array $prepared_themes An associative array of theme data. Default empty array.
  540. * @param WP_Theme[]|null $themes An array of theme objects to prepare, if any.
  541. * @param string $current_theme The current theme slug.
  542. */
  543. $prepared_themes = (array) apply_filters( 'pre_prepare_themes_for_js', array(), $themes, $current_theme );
  544. if ( ! empty( $prepared_themes ) ) {
  545. return $prepared_themes;
  546. }
  547. // Make sure the current theme is listed first.
  548. $prepared_themes[ $current_theme ] = array();
  549. if ( null === $themes ) {
  550. $themes = wp_get_themes( array( 'allowed' => true ) );
  551. if ( ! isset( $themes[ $current_theme ] ) ) {
  552. $themes[ $current_theme ] = wp_get_theme();
  553. }
  554. }
  555. $updates = array();
  556. if ( current_user_can( 'update_themes' ) ) {
  557. $updates_transient = get_site_transient( 'update_themes' );
  558. if ( isset( $updates_transient->response ) ) {
  559. $updates = $updates_transient->response;
  560. }
  561. }
  562. WP_Theme::sort_by_name( $themes );
  563. $parents = array();
  564. foreach ( $themes as $theme ) {
  565. $slug = $theme->get_stylesheet();
  566. $encoded_slug = urlencode( $slug );
  567. $parent = false;
  568. if ( $theme->parent() ) {
  569. $parent = $theme->parent();
  570. $parents[ $slug ] = $parent->get_stylesheet();
  571. $parent = $parent->display( 'Name' );
  572. }
  573. $customize_action = null;
  574. if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
  575. $customize_action = esc_url(
  576. add_query_arg(
  577. array(
  578. 'return' => urlencode( esc_url_raw( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ),
  579. ),
  580. wp_customize_url( $slug )
  581. )
  582. );
  583. }
  584. $prepared_themes[ $slug ] = array(
  585. 'id' => $slug,
  586. 'name' => $theme->display( 'Name' ),
  587. 'screenshot' => array( $theme->get_screenshot() ), // @todo Multiple screenshots.
  588. 'description' => $theme->display( 'Description' ),
  589. 'author' => $theme->display( 'Author', false, true ),
  590. 'authorAndUri' => $theme->display( 'Author' ),
  591. 'version' => $theme->display( 'Version' ),
  592. 'tags' => $theme->display( 'Tags' ),
  593. 'parent' => $parent,
  594. 'active' => $slug === $current_theme,
  595. 'hasUpdate' => isset( $updates[ $slug ] ),
  596. 'hasPackage' => isset( $updates[ $slug ] ) && ! empty( $updates[ $slug ]['package'] ),
  597. 'update' => get_theme_update_available( $theme ),
  598. 'actions' => array(
  599. 'activate' => current_user_can( 'switch_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=activate&amp;stylesheet=' . $encoded_slug ), 'switch-theme_' . $slug ) : null,
  600. 'customize' => $customize_action,
  601. 'delete' => current_user_can( 'delete_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=delete&amp;stylesheet=' . $encoded_slug ), 'delete-theme_' . $slug ) : null,
  602. ),
  603. );
  604. }
  605. // Remove 'delete' action if theme has an active child.
  606. if ( ! empty( $parents ) && array_key_exists( $current_theme, $parents ) ) {
  607. unset( $prepared_themes[ $parents[ $current_theme ] ]['actions']['delete'] );
  608. }
  609. /**
  610. * Filters the themes prepared for JavaScript, for themes.php.
  611. *
  612. * Could be useful for changing the order, which is by name by default.
  613. *
  614. * @since 3.8.0
  615. *
  616. * @param array $prepared_themes Array of theme data.
  617. */
  618. $prepared_themes = apply_filters( 'wp_prepare_themes_for_js', $prepared_themes );
  619. $prepared_themes = array_values( $prepared_themes );
  620. return array_filter( $prepared_themes );
  621. }
  622. /**
  623. * Print JS templates for the theme-browsing UI in the Customizer.
  624. *
  625. * @since 4.2.0
  626. */
  627. function customize_themes_print_templates() {
  628. ?>
  629. <script type="text/html" id="tmpl-customize-themes-details-view">
  630. <div class="theme-backdrop"></div>
  631. <div class="theme-wrap wp-clearfix" role="document">
  632. <div class="theme-header">
  633. <button type="button" class="left dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show previous theme' ); ?></span></button>
  634. <button type="button" class="right dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show next theme' ); ?></span></button>
  635. <button type="button" class="close dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Close details dialog' ); ?></span></button>
  636. </div>
  637. <div class="theme-about wp-clearfix">
  638. <div class="theme-screenshots">
  639. <# if ( data.screenshot && data.screenshot[0] ) { #>
  640. <div class="screenshot"><img src="{{ data.screenshot[0] }}" alt="" /></div>
  641. <# } else { #>
  642. <div class="screenshot blank"></div>
  643. <# } #>
  644. </div>
  645. <div class="theme-info">
  646. <# if ( data.active ) { #>
  647. <span class="current-label"><?php _e( 'Current Theme' ); ?></span>
  648. <# } #>
  649. <h2 class="theme-name">{{{ data.name }}}<span class="theme-version">
  650. <?php
  651. /* translators: %s: Theme version. */
  652. printf( __( 'Version: %s' ), '{{ data.version }}' );
  653. ?>
  654. </span></h2>
  655. <h3 class="theme-author">
  656. <?php
  657. /* translators: %s: Theme author link. */
  658. printf( __( 'By %s' ), '{{{ data.authorAndUri }}}' );
  659. ?>
  660. </h3>
  661. <# if ( data.stars && 0 != data.num_ratings ) { #>
  662. <div class="theme-rating">
  663. {{{ data.stars }}}
  664. <a class="num-ratings" target="_blank" href="{{ data.reviews_url }}">
  665. <?php
  666. printf(
  667. '%1$s <span class="screen-reader-text">%2$s</span>',
  668. /* translators: %s: Number of ratings. */
  669. sprintf( __( '(%s ratings)' ), '{{ data.num_ratings }}' ),
  670. /* translators: Accessibility text. */
  671. __( '(opens in a new tab)' )
  672. );
  673. ?>
  674. </a>
  675. </div>
  676. <# } #>
  677. <# if ( data.hasUpdate ) { #>
  678. <div class="notice notice-warning notice-alt notice-large" data-slug="{{ data.id }}">
  679. <h3 class="notice-title"><?php _e( 'Update Available' ); ?></h3>
  680. {{{ data.update }}}
  681. </div>
  682. <# } #>
  683. <# if ( data.parent ) { #>
  684. <p class="parent-theme">
  685. <?php
  686. printf(
  687. /* translators: %s: Theme name. */
  688. __( 'This is a child theme of %s.' ),
  689. '<strong>{{{ data.parent }}}</strong>'
  690. );
  691. ?>
  692. </p>
  693. <# } #>
  694. <p class="theme-description">{{{ data.description }}}</p>
  695. <# if ( data.tags ) { #>
  696. <p class="theme-tags"><span><?php _e( 'Tags:' ); ?></span> {{{ data.tags }}}</p>
  697. <# } #>
  698. </div>
  699. </div>
  700. <div class="theme-actions">
  701. <# if ( data.active ) { #>
  702. <button type="button" class="button button-primary customize-theme"><?php _e( 'Customize' ); ?></button>
  703. <# } else if ( 'installed' === data.type ) { #>
  704. <?php if ( current_user_can( 'delete_themes' ) ) { ?>
  705. <# if ( data.actions && data.actions['delete'] ) { #>
  706. <a href="{{{ data.actions['delete'] }}}" data-slug="{{ data.id }}" class="button button-secondary delete-theme"><?php _e( 'Delete' ); ?></a>
  707. <# } #>
  708. <?php } ?>
  709. <button type="button" class="button button-primary preview-theme" data-slug="{{ data.id }}"><?php _e( 'Live Preview' ); ?></button>
  710. <# } else { #>
  711. <button type="button" class="button theme-install" data-slug="{{ data.id }}"><?php _e( 'Install' ); ?></button>
  712. <button type="button" class="button button-primary theme-install preview" data-slug="{{ data.id }}"><?php _e( 'Install &amp; Preview' ); ?></button>
  713. <# } #>
  714. </div>
  715. </div>
  716. </script>
  717. <?php
  718. }
  719. /**
  720. * Determines whether a theme is technically active but was paused while
  721. * loading.
  722. *
  723. * For more information on this and similar theme functions, check out
  724. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  725. * Conditional Tags} article in the Theme Developer Handbook.
  726. *
  727. * @since 5.2.0
  728. *
  729. * @param string $theme Path to the theme directory relative to the themes directory.
  730. * @return bool True, if in the list of paused themes. False, not in the list.
  731. */
  732. function is_theme_paused( $theme ) {
  733. if ( ! isset( $GLOBALS['_paused_themes'] ) ) {
  734. return false;
  735. }
  736. if ( get_stylesheet() !== $theme && get_template() !== $theme ) {
  737. return false;
  738. }
  739. return array_key_exists( $theme, $GLOBALS['_paused_themes'] );
  740. }
  741. /**
  742. * Gets the error that was recorded for a paused theme.
  743. *
  744. * @since 5.2.0
  745. *
  746. * @param string $theme Path to the theme directory relative to the themes
  747. * directory.
  748. * @return array|false Array of error information as it was returned by
  749. * `error_get_last()`, or false if none was recorded.
  750. */
  751. function wp_get_theme_error( $theme ) {
  752. if ( ! isset( $GLOBALS['_paused_themes'] ) ) {
  753. return false;
  754. }
  755. if ( ! array_key_exists( $theme, $GLOBALS['_paused_themes'] ) ) {
  756. return false;
  757. }
  758. return $GLOBALS['_paused_themes'][ $theme ];
  759. }
  760. /**
  761. * Tries to resume a single theme.
  762. *
  763. * If a redirect was provided and a functions.php file was found, we first ensure that
  764. * functions.php file does not throw fatal errors anymore.
  765. *
  766. * The way it works is by setting the redirection to the error before trying to
  767. * include the file. If the theme fails, then the redirection will not be overwritten
  768. * with the success message and the theme will not be resumed.
  769. *
  770. * @since 5.2.0
  771. *
  772. * @param string $theme Single theme to resume.
  773. * @param string $redirect Optional. URL to redirect to. Default empty string.
  774. * @return bool|WP_Error True on success, false if `$theme` was not paused,
  775. * `WP_Error` on failure.
  776. */
  777. function resume_theme( $theme, $redirect = '' ) {
  778. list( $extension ) = explode( '/', $theme );
  779. /*
  780. * We'll override this later if the theme could be resumed without
  781. * creating a fatal error.
  782. */
  783. if ( ! empty( $redirect ) ) {
  784. $functions_path = '';
  785. if ( strpos( STYLESHEETPATH, $extension ) ) {
  786. $functions_path = STYLESHEETPATH . '/functions.php';
  787. } elseif ( strpos( TEMPLATEPATH, $extension ) ) {
  788. $functions_path = TEMPLATEPATH . '/functions.php';
  789. }
  790. if ( ! empty( $functions_path ) ) {
  791. wp_redirect(
  792. add_query_arg(
  793. '_error_nonce',
  794. wp_create_nonce( 'theme-resume-error_' . $theme ),
  795. $redirect
  796. )
  797. );
  798. // Load the theme's functions.php to test whether it throws a fatal error.
  799. ob_start();
  800. if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
  801. define( 'WP_SANDBOX_SCRAPING', true );
  802. }
  803. include $functions_path;
  804. ob_clean();
  805. }
  806. }
  807. $result = wp_paused_themes()->delete( $extension );
  808. if ( ! $result ) {
  809. return new WP_Error(
  810. 'could_not_resume_theme',
  811. __( 'Could not resume the theme.' )
  812. );
  813. }
  814. return true;
  815. }
  816. /**
  817. * Renders an admin notice in case some themes have been paused due to errors.
  818. *
  819. * @since 5.2.0
  820. */
  821. function paused_themes_notice() {
  822. if ( 'themes.php' === $GLOBALS['pagenow'] ) {
  823. return;
  824. }
  825. if ( ! current_user_can( 'resume_themes' ) ) {
  826. return;
  827. }
  828. if ( ! isset( $GLOBALS['_paused_themes'] ) || empty( $GLOBALS['_paused_themes'] ) ) {
  829. return;
  830. }
  831. printf(
  832. '<div class="notice notice-error"><p><strong>%s</strong><br>%s</p><p><a href="%s">%s</a></p></div>',
  833. __( 'One or more themes failed to load properly.' ),
  834. __( 'You can find more details and make changes on the Themes screen.' ),
  835. esc_url( admin_url( 'themes.php' ) ),
  836. __( 'Go to the Themes screen' )
  837. );
  838. }