1<?php
2/**
3 * WordPress Theme Administration API
4 *
5 * @package WordPress
6 * @subpackage Administration
7 */
8
9/**
10 * Remove a theme
11 *
12 * @since 2.8.0
13 *
14 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
15 *
16 * @param string $stylesheet Stylesheet of the theme to delete.
17 * @param string $redirect   Redirect to page when complete.
18 * @return bool|null|WP_Error True on success, false if `$stylesheet` is empty, WP_Error on failure.
19 *                            Null if filesystem credentials are required to proceed.
20 */
21function delete_theme( $stylesheet, $redirect = '' ) {
22	global $wp_filesystem;
23
24	if ( empty( $stylesheet ) ) {
25		return false;
26	}
27
28	if ( empty( $redirect ) ) {
29		$redirect = wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet );
30	}
31
32	ob_start();
33	$credentials = request_filesystem_credentials( $redirect );
34	$data        = ob_get_clean();
35
36	if ( false === $credentials ) {
37		if ( ! empty( $data ) ) {
38			require_once ABSPATH . 'wp-admin/admin-header.php';
39			echo $data;
40			require_once ABSPATH . 'wp-admin/admin-footer.php';
41			exit;
42		}
43		return;
44	}
45
46	if ( ! WP_Filesystem( $credentials ) ) {
47		ob_start();
48		// Failed to connect. Error and request again.
49		request_filesystem_credentials( $redirect, '', true );
50		$data = ob_get_clean();
51
52		if ( ! empty( $data ) ) {
53			require_once ABSPATH . 'wp-admin/admin-header.php';
54			echo $data;
55			require_once ABSPATH . 'wp-admin/admin-footer.php';
56			exit;
57		}
58		return;
59	}
60
61	if ( ! is_object( $wp_filesystem ) ) {
62		return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
63	}
64
65	if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
66		return new WP_Error( 'fs_error', __( 'Filesystem error.' ), $wp_filesystem->errors );
67	}
68
69	// Get the base plugin folder.
70	$themes_dir = $wp_filesystem->wp_themes_dir();
71	if ( empty( $themes_dir ) ) {
72		return new WP_Error( 'fs_no_themes_dir', __( 'Unable to locate WordPress theme directory.' ) );
73	}
74
75	/**
76	 * Fires immediately before a theme deletion attempt.
77	 *
78	 * @since 5.8.0
79	 *
80	 * @param string $stylesheet Stylesheet of the theme to delete.
81	 */
82	do_action( 'delete_theme', $stylesheet );
83
84	$themes_dir = trailingslashit( $themes_dir );
85	$theme_dir  = trailingslashit( $themes_dir . $stylesheet );
86	$deleted    = $wp_filesystem->delete( $theme_dir, true );
87
88	/**
89	 * Fires immediately after a theme deletion attempt.
90	 *
91	 * @since 5.8.0
92	 *
93	 * @param string $stylesheet Stylesheet of the theme to delete.
94	 * @param bool   $deleted    Whether the theme deletion was successful.
95	 */
96	do_action( 'deleted_theme', $stylesheet, $deleted );
97
98	if ( ! $deleted ) {
99		return new WP_Error(
100			'could_not_remove_theme',
101			/* translators: %s: Theme name. */
102			sprintf( __( 'Could not fully remove the theme %s.' ), $stylesheet )
103		);
104	}
105
106	$theme_translations = wp_get_installed_translations( 'themes' );
107
108	// Remove language files, silently.
109	if ( ! empty( $theme_translations[ $stylesheet ] ) ) {
110		$translations = $theme_translations[ $stylesheet ];
111
112		foreach ( $translations as $translation => $data ) {
113			$wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.po' );
114			$wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.mo' );
115
116			$json_translation_files = glob( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '-*.json' );
117			if ( $json_translation_files ) {
118				array_map( array( $wp_filesystem, 'delete' ), $json_translation_files );
119			}
120		}
121	}
122
123	// Remove the theme from allowed themes on the network.
124	if ( is_multisite() ) {
125		WP_Theme::network_disable_theme( $stylesheet );
126	}
127
128	// Force refresh of theme update information.
129	delete_site_transient( 'update_themes' );
130
131	return true;
132}
133
134/**
135 * Gets the page templates available in this theme.
136 *
137 * @since 1.5.0
138 * @since 4.7.0 Added the `$post_type` parameter.
139 *
140 * @param WP_Post|null $post      Optional. The post being edited, provided for context.
141 * @param string       $post_type Optional. Post type to get the templates for. Default 'page'.
142 * @return string[] Array of template file names keyed by the template header name.
143 */
144function get_page_templates( $post = null, $post_type = 'page' ) {
145	return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) );
146}
147
148/**
149 * Tidies a filename for url display by the theme editor.
150 *
151 * @since 2.9.0
152 * @access private
153 *
154 * @param string $fullpath Full path to the theme file
155 * @param string $containingfolder Path of the theme parent folder
156 * @return string
157 */
158function _get_template_edit_filename( $fullpath, $containingfolder ) {
159	return str_replace( dirname( dirname( $containingfolder ) ), '', $fullpath );
160}
161
162/**
163 * Check if there is an update for a theme available.
164 *
165 * Will display link, if there is an update available.
166 *
167 * @since 2.7.0
168 *
169 * @see get_theme_update_available()
170 *
171 * @param WP_Theme $theme Theme data object.
172 */
173function theme_update_available( $theme ) {
174	echo get_theme_update_available( $theme );
175}
176
177/**
178 * Retrieve the update link if there is a theme update available.
179 *
180 * Will return a link if there is an update available.
181 *
182 * @since 3.8.0
183 *
184 * @param WP_Theme $theme WP_Theme object.
185 * @return string|false HTML for the update link, or false if invalid info was passed.
186 */
187function get_theme_update_available( $theme ) {
188	static $themes_update = null;
189
190	if ( ! current_user_can( 'update_themes' ) ) {
191		return false;
192	}
193
194	if ( ! isset( $themes_update ) ) {
195		$themes_update = get_site_transient( 'update_themes' );
196	}
197
198	if ( ! ( $theme instanceof WP_Theme ) ) {
199		return false;
200	}
201
202	$stylesheet = $theme->get_stylesheet();
203
204	$html = '';
205
206	if ( isset( $themes_update->response[ $stylesheet ] ) ) {
207		$update      = $themes_update->response[ $stylesheet ];
208		$theme_name  = $theme->display( 'Name' );
209		$details_url = add_query_arg(
210			array(
211				'TB_iframe' => 'true',
212				'width'     => 1024,
213				'height'    => 800,
214			),
215			$update['url']
216		); // Theme browser inside WP? Replace this. Also, theme preview JS will override this on the available list.
217		$update_url  = wp_nonce_url( admin_url( 'update.php?action=upgrade-theme&amp;theme=' . urlencode( $stylesheet ) ), 'upgrade-theme_' . $stylesheet );
218
219		if ( ! is_multisite() ) {
220			if ( ! current_user_can( 'update_themes' ) ) {
221				$html = sprintf(
222					/* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */
223					'<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>',
224					$theme_name,
225					esc_url( $details_url ),
226					sprintf(
227						'class="thickbox open-plugin-details-modal" aria-label="%s"',
228						/* translators: 1: Theme name, 2: Version number. */
229						esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
230					),
231					$update['new_version']
232				);
233			} elseif ( empty( $update['package'] ) ) {
234				$html = sprintf(
235					/* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */
236					'<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>',
237					$theme_name,
238					esc_url( $details_url ),
239					sprintf(
240						'class="thickbox open-plugin-details-modal" aria-label="%s"',
241						/* translators: 1: Theme name, 2: Version number. */
242						esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
243					),
244					$update['new_version']
245				);
246			} else {
247				$html = sprintf(
248					/* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number, 5: Update URL, 6: Additional link attributes. */
249					'<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>',
250					$theme_name,
251					esc_url( $details_url ),
252					sprintf(
253						'class="thickbox open-plugin-details-modal" aria-label="%s"',
254						/* translators: 1: Theme name, 2: Version number. */
255						esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) )
256					),
257					$update['new_version'],
258					$update_url,
259					sprintf(
260						'aria-label="%s" id="update-theme" data-slug="%s"',
261						/* translators: %s: Theme name. */
262						esc_attr( sprintf( _x( 'Update %s now', 'theme' ), $theme_name ) ),
263						$stylesheet
264					)
265				);
266			}
267		}
268	}
269
270	return $html;
271}
272
273/**
274 * Retrieve list of WordPress theme features (aka theme tags).
275 *
276 * @since 3.1.0
277 * @since 3.2.0 Added 'Gray' color and 'Featured Image Header', 'Featured Images',
278 *              'Full Width Template', and 'Post Formats' features.
279 * @since 3.5.0 Added 'Flexible Header' feature.
280 * @since 3.8.0 Renamed 'Width' filter to 'Layout'.
281 * @since 3.8.0 Renamed 'Fixed Width' and 'Flexible Width' options
282 *              to 'Fixed Layout' and 'Fluid Layout'.
283 * @since 3.8.0 Added 'Accessibility Ready' feature and 'Responsive Layout' option.
284 * @since 3.9.0 Combined 'Layout' and 'Columns' filters.
285 * @since 4.6.0 Removed 'Colors' filter.
286 * @since 4.6.0 Added 'Grid Layout' option.
287 *              Removed 'Fixed Layout', 'Fluid Layout', and 'Responsive Layout' options.
288 * @since 4.6.0 Added 'Custom Logo' and 'Footer Widgets' features.
289 *              Removed 'Blavatar' feature.
290 * @since 4.6.0 Added 'Blog', 'E-Commerce', 'Education', 'Entertainment', 'Food & Drink',
291 *              'Holiday', 'News', 'Photography', and 'Portfolio' subjects.
292 *              Removed 'Photoblogging' and 'Seasonal' subjects.
293 * @since 4.9.0 Reordered the filters from 'Layout', 'Features', 'Subject'
294 *              to 'Subject', 'Features', 'Layout'.
295 * @since 4.9.0 Removed 'BuddyPress', 'Custom Menu', 'Flexible Header',
296 *              'Front Page Posting', 'Microformats', 'RTL Language Support',
297 *              'Threaded Comments', and 'Translation Ready' features.
298 * @since 5.5.0 Added 'Block Editor Patterns', 'Block Editor Styles',
299 *              and 'Full Site Editing' features.
300 * @since 5.5.0 Added 'Wide Blocks' layout option.
301 * @since 5.8.1 Added 'Template Editing' feature.
302 *
303 * @param bool $api Optional. Whether try to fetch tags from the WordPress.org API. Defaults to true.
304 * @return array Array of features keyed by category with translations keyed by slug.
305 */
306function get_theme_feature_list( $api = true ) {
307	// Hard-coded list is used if API is not accessible.
308	$features = array(
309
310		__( 'Subject' )  => array(
311			'blog'           => __( 'Blog' ),
312			'e-commerce'     => __( 'E-Commerce' ),
313			'education'      => __( 'Education' ),
314			'entertainment'  => __( 'Entertainment' ),
315			'food-and-drink' => __( 'Food & Drink' ),
316			'holiday'        => __( 'Holiday' ),
317			'news'           => __( 'News' ),
318			'photography'    => __( 'Photography' ),
319			'portfolio'      => __( 'Portfolio' ),
320		),
321
322		__( 'Features' ) => array(
323			'accessibility-ready'   => __( 'Accessibility Ready' ),
324			'block-patterns'        => __( 'Block Editor Patterns' ),
325			'block-styles'          => __( 'Block Editor Styles' ),
326			'custom-background'     => __( 'Custom Background' ),
327			'custom-colors'         => __( 'Custom Colors' ),
328			'custom-header'         => __( 'Custom Header' ),
329			'custom-logo'           => __( 'Custom Logo' ),
330			'editor-style'          => __( 'Editor Style' ),
331			'featured-image-header' => __( 'Featured Image Header' ),
332			'featured-images'       => __( 'Featured Images' ),
333			'footer-widgets'        => __( 'Footer Widgets' ),
334			'full-site-editing'     => __( 'Full Site Editing' ),
335			'full-width-template'   => __( 'Full Width Template' ),
336			'post-formats'          => __( 'Post Formats' ),
337			'sticky-post'           => __( 'Sticky Post' ),
338			'template-editing'      => __( 'Template Editing' ),
339			'theme-options'         => __( 'Theme Options' ),
340		),
341
342		__( 'Layout' )   => array(
343			'grid-layout'   => __( 'Grid Layout' ),
344			'one-column'    => __( 'One Column' ),
345			'two-columns'   => __( 'Two Columns' ),
346			'three-columns' => __( 'Three Columns' ),
347			'four-columns'  => __( 'Four Columns' ),
348			'left-sidebar'  => __( 'Left Sidebar' ),
349			'right-sidebar' => __( 'Right Sidebar' ),
350			'wide-blocks'   => __( 'Wide Blocks' ),
351		),
352
353	);
354
355	if ( ! $api || ! current_user_can( 'install_themes' ) ) {
356		return $features;
357	}
358
359	$feature_list = get_site_transient( 'wporg_theme_feature_list' );
360	if ( ! $feature_list ) {
361		set_site_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS );
362	}
363
364	if ( ! $feature_list ) {
365		$feature_list = themes_api( 'feature_list', array() );
366		if ( is_wp_error( $feature_list ) ) {
367			return $features;
368		}
369	}
370
371	if ( ! $feature_list ) {
372		return $features;
373	}
374
375	set_site_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS );
376
377	$category_translations = array(
378		'Layout'   => __( 'Layout' ),
379		'Features' => __( 'Features' ),
380		'Subject'  => __( 'Subject' ),
381	);
382
383	$wporg_features = array();
384
385	// Loop over the wp.org canonical list and apply translations.
386	foreach ( (array) $feature_list as $feature_category => $feature_items ) {
387		if ( isset( $category_translations[ $feature_category ] ) ) {
388			$feature_category = $category_translations[ $feature_category ];
389		}
390
391		$wporg_features[ $feature_category ] = array();
392
393		foreach ( $feature_items as $feature ) {
394			if ( isset( $features[ $feature_category ][ $feature ] ) ) {
395				$wporg_features[ $feature_category ][ $feature ] = $features[ $feature_category ][ $feature ];
396			} else {
397				$wporg_features[ $feature_category ][ $feature ] = $feature;
398			}
399		}
400	}
401
402	return $wporg_features;
403}
404
405/**
406 * Retrieves theme installer pages from the WordPress.org Themes API.
407 *
408 * It is possible for a theme to override the Themes API result with three
409 * filters. Assume this is for themes, which can extend on the Theme Info to
410 * offer more choices. This is very powerful and must be used with care, when
411 * overriding the filters.
412 *
413 * The first filter, {@see 'themes_api_args'}, is for the args and gives the action
414 * as the second parameter. The hook for {@see 'themes_api_args'} must ensure that
415 * an object is returned.
416 *
417 * The second filter, {@see 'themes_api'}, allows a plugin to override the WordPress.org
418 * Theme API entirely. If `$action` is 'query_themes', 'theme_information', or 'feature_list',
419 * an object MUST be passed. If `$action` is 'hot_tags', an array should be passed.
420 *
421 * Finally, the third filter, {@see 'themes_api_result'}, makes it possible to filter the
422 * response object or array, depending on the `$action` type.
423 *
424 * Supported arguments per action:
425 *
426 * | Argument Name      | 'query_themes' | 'theme_information' | 'hot_tags' | 'feature_list'   |
427 * | -------------------| :------------: | :-----------------: | :--------: | :--------------: |
428 * | `$slug`            | No             |  Yes                | No         | No               |
429 * | `$per_page`        | Yes            |  No                 | No         | No               |
430 * | `$page`            | Yes            |  No                 | No         | No               |
431 * | `$number`          | No             |  No                 | Yes        | No               |
432 * | `$search`          | Yes            |  No                 | No         | No               |
433 * | `$tag`             | Yes            |  No                 | No         | No               |
434 * | `$author`          | Yes            |  No                 | No         | No               |
435 * | `$user`            | Yes            |  No                 | No         | No               |
436 * | `$browse`          | Yes            |  No                 | No         | No               |
437 * | `$locale`          | Yes            |  Yes                | No         | No               |
438 * | `$fields`          | Yes            |  Yes                | No         | No               |
439 *
440 * @since 2.8.0
441 *
442 * @param string       $action API action to perform: 'query_themes', 'theme_information',
443 *                             'hot_tags' or 'feature_list'.
444 * @param array|object $args   {
445 *     Optional. Array or object of arguments to serialize for the Themes API.
446 *
447 *     @type string  $slug     The theme slug. Default empty.
448 *     @type int     $per_page Number of themes per page. Default 24.
449 *     @type int     $page     Number of current page. Default 1.
450 *     @type int     $number   Number of tags to be queried.
451 *     @type string  $search   A search term. Default empty.
452 *     @type string  $tag      Tag to filter themes. Default empty.
453 *     @type string  $author   Username of an author to filter themes. Default empty.
454 *     @type string  $user     Username to query for their favorites. Default empty.
455 *     @type string  $browse   Browse view: 'featured', 'popular', 'updated', 'favorites'.
456 *     @type string  $locale   Locale to provide context-sensitive results. Default is the value of get_locale().
457 *     @type array   $fields   {
458 *         Array of fields which should or should not be returned.
459 *
460 *         @type bool $description        Whether to return the theme full description. Default false.
461 *         @type bool $sections           Whether to return the theme readme sections: description, installation,
462 *                                        FAQ, screenshots, other notes, and changelog. Default false.
463 *         @type bool $rating             Whether to return the rating in percent and total number of ratings.
464 *                                        Default false.
465 *         @type bool $ratings            Whether to return the number of rating for each star (1-5). Default false.
466 *         @type bool $downloaded         Whether to return the download count. Default false.
467 *         @type bool $downloadlink       Whether to return the download link for the package. Default false.
468 *         @type bool $last_updated       Whether to return the date of the last update. Default false.
469 *         @type bool $tags               Whether to return the assigned tags. Default false.
470 *         @type bool $homepage           Whether to return the theme homepage link. Default false.
471 *         @type bool $screenshots        Whether to return the screenshots. Default false.
472 *         @type int  $screenshot_count   Number of screenshots to return. Default 1.
473 *         @type bool $screenshot_url     Whether to return the URL of the first screenshot. Default false.
474 *         @type bool $photon_screenshots Whether to return the screenshots via Photon. Default false.
475 *         @type bool $template           Whether to return the slug of the parent theme. Default false.
476 *         @type bool $parent             Whether to return the slug, name and homepage of the parent theme. Default false.
477 *         @type bool $versions           Whether to return the list of all available versions. Default false.
478 *         @type bool $theme_url          Whether to return theme's URL. Default false.
479 *         @type bool $extended_author    Whether to return nicename or nicename and display name. Default false.
480 *     }
481 * }
482 * @return object|array|WP_Error Response object or array on success, WP_Error on failure. See the
483 *         {@link https://developer.wordpress.org/reference/functions/themes_api/ function reference article}
484 *         for more information on the make-up of possible return objects depending on the value of `$action`.
485 */
486function themes_api( $action, $args = array() ) {
487	// Include an unmodified $wp_version.
488	require ABSPATH . WPINC . '/version.php';
489
490	if ( is_array( $args ) ) {
491		$args = (object) $args;
492	}
493
494	if ( 'query_themes' === $action ) {
495		if ( ! isset( $args->per_page ) ) {
496			$args->per_page = 24;
497		}
498	}
499
500	if ( ! isset( $args->locale ) ) {
501		$args->locale = get_user_locale();
502	}
503
504	if ( ! isset( $args->wp_version ) ) {
505		$args->wp_version = substr( $wp_version, 0, 3 ); // x.y
506	}
507
508	/**
509	 * Filters arguments used to query for installer pages from the WordPress.org Themes API.
510	 *
511	 * Important: An object MUST be returned to this filter.
512	 *
513	 * @since 2.8.0
514	 *
515	 * @param object $args   Arguments used to query for installer pages from the WordPress.org Themes API.
516	 * @param string $action Requested action. Likely values are 'theme_information',
517	 *                       'feature_list', or 'query_themes'.
518	 */
519	$args = apply_filters( 'themes_api_args', $args, $action );
520
521	/**
522	 * Filters whether to override the WordPress.org Themes API.
523	 *
524	 * Passing a non-false value will effectively short-circuit the WordPress.org API request.
525	 *
526	 * If `$action` is 'query_themes', 'theme_information', or 'feature_list', an object MUST
527	 * be passed. If `$action` is 'hot_tags', an array should be passed.
528	 *
529	 * @since 2.8.0
530	 *
531	 * @param false|object|array $override Whether to override the WordPress.org Themes API. Default false.
532	 * @param string             $action   Requested action. Likely values are 'theme_information',
533	 *                                    'feature_list', or 'query_themes'.
534	 * @param object             $args     Arguments used to query for installer pages from the Themes API.
535	 */
536	$res = apply_filters( 'themes_api', false, $action, $args );
537
538	if ( ! $res ) {
539		$url = 'http://api.wordpress.org/themes/info/1.2/';
540		$url = add_query_arg(
541			array(
542				'action'  => $action,
543				'request' => $args,
544			),
545			$url
546		);
547
548		$http_url = $url;
549		$ssl      = wp_http_supports( array( 'ssl' ) );
550		if ( $ssl ) {
551			$url = set_url_scheme( $url, 'https' );
552		}
553
554		$http_args = array(
555			'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ),
556		);
557		$request   = wp_remote_get( $url, $http_args );
558
559		if ( $ssl && is_wp_error( $request ) ) {
560			if ( ! wp_doing_ajax() ) {
561				trigger_error(
562					sprintf(
563						/* translators: %s: Support forums URL. */
564						__( '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>.' ),
565						__( 'https://wordpress.org/support/forums/' )
566					) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ),
567					headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE
568				);
569			}
570			$request = wp_remote_get( $http_url, $http_args );
571		}
572
573		if ( is_wp_error( $request ) ) {
574			$res = new WP_Error(
575				'themes_api_failed',
576				sprintf(
577					/* translators: %s: Support forums URL. */
578					__( '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>.' ),
579					__( 'https://wordpress.org/support/forums/' )
580				),
581				$request->get_error_message()
582			);
583		} else {
584			$res = json_decode( wp_remote_retrieve_body( $request ), true );
585			if ( is_array( $res ) ) {
586				// Object casting is required in order to match the info/1.0 format.
587				$res = (object) $res;
588			} elseif ( null === $res ) {
589				$res = new WP_Error(
590					'themes_api_failed',
591					sprintf(
592						/* translators: %s: Support forums URL. */
593						__( '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>.' ),
594						__( 'https://wordpress.org/support/forums/' )
595					),
596					wp_remote_retrieve_body( $request )
597				);
598			}
599
600			if ( isset( $res->error ) ) {
601				$res = new WP_Error( 'themes_api_failed', $res->error );
602			}
603		}
604
605		// Back-compat for info/1.2 API, upgrade the theme objects in query_themes to objects.
606		if ( 'query_themes' === $action ) {
607			foreach ( $res->themes as $i => $theme ) {
608				$res->themes[ $i ] = (object) $theme;
609			}
610		}
611		// Back-compat for info/1.2 API, downgrade the feature_list result back to an array.
612		if ( 'feature_list' === $action ) {
613			$res = (array) $res;
614		}
615	}
616
617	/**
618	 * Filters the returned WordPress.org Themes API response.
619	 *
620	 * @since 2.8.0
621	 *
622	 * @param array|object|WP_Error $res    WordPress.org Themes API response.
623	 * @param string                $action Requested action. Likely values are 'theme_information',
624	 *                                      'feature_list', or 'query_themes'.
625	 * @param object                $args   Arguments used to query for installer pages from the WordPress.org Themes API.
626	 */
627	return apply_filters( 'themes_api_result', $res, $action, $args );
628}
629
630/**
631 * Prepare themes for JavaScript.
632 *
633 * @since 3.8.0
634 *
635 * @param WP_Theme[] $themes Optional. Array of theme objects to prepare.
636 *                           Defaults to all allowed themes.
637 *
638 * @return array An associative array of theme data, sorted by name.
639 */
640function wp_prepare_themes_for_js( $themes = null ) {
641	$current_theme = get_stylesheet();
642
643	/**
644	 * Filters theme data before it is prepared for JavaScript.
645	 *
646	 * Passing a non-empty array will result in wp_prepare_themes_for_js() returning
647	 * early with that value instead.
648	 *
649	 * @since 4.2.0
650	 *
651	 * @param array           $prepared_themes An associative array of theme data. Default empty array.
652	 * @param WP_Theme[]|null $themes          An array of theme objects to prepare, if any.
653	 * @param string          $current_theme   The current theme slug.
654	 */
655	$prepared_themes = (array) apply_filters( 'pre_prepare_themes_for_js', array(), $themes, $current_theme );
656
657	if ( ! empty( $prepared_themes ) ) {
658		return $prepared_themes;
659	}
660
661	// Make sure the current theme is listed first.
662	$prepared_themes[ $current_theme ] = array();
663
664	if ( null === $themes ) {
665		$themes = wp_get_themes( array( 'allowed' => true ) );
666		if ( ! isset( $themes[ $current_theme ] ) ) {
667			$themes[ $current_theme ] = wp_get_theme();
668		}
669	}
670
671	$updates    = array();
672	$no_updates = array();
673	if ( ! is_multisite() && current_user_can( 'update_themes' ) ) {
674		$updates_transient = get_site_transient( 'update_themes' );
675		if ( isset( $updates_transient->response ) ) {
676			$updates = $updates_transient->response;
677		}
678		if ( isset( $updates_transient->no_update ) ) {
679			$no_updates = $updates_transient->no_update;
680		}
681	}
682
683	WP_Theme::sort_by_name( $themes );
684
685	$parents = array();
686
687	$auto_updates = (array) get_site_option( 'auto_update_themes', array() );
688
689	foreach ( $themes as $theme ) {
690		$slug         = $theme->get_stylesheet();
691		$encoded_slug = urlencode( $slug );
692
693		$parent = false;
694		if ( $theme->parent() ) {
695			$parent           = $theme->parent();
696			$parents[ $slug ] = $parent->get_stylesheet();
697			$parent           = $parent->display( 'Name' );
698		}
699
700		$customize_action = null;
701		if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
702			$customize_action = esc_url(
703				add_query_arg(
704					array(
705						'return' => urlencode( esc_url_raw( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ),
706					),
707					wp_customize_url( $slug )
708				)
709			);
710		}
711
712		$update_requires_wp  = isset( $updates[ $slug ]['requires'] ) ? $updates[ $slug ]['requires'] : null;
713		$update_requires_php = isset( $updates[ $slug ]['requires_php'] ) ? $updates[ $slug ]['requires_php'] : null;
714
715		$auto_update        = in_array( $slug, $auto_updates, true );
716		$auto_update_action = $auto_update ? 'disable-auto-update' : 'enable-auto-update';
717
718		if ( isset( $updates[ $slug ] ) ) {
719			$auto_update_supported      = true;
720			$auto_update_filter_payload = (object) $updates[ $slug ];
721		} elseif ( isset( $no_updates[ $slug ] ) ) {
722			$auto_update_supported      = true;
723			$auto_update_filter_payload = (object) $no_updates[ $slug ];
724		} else {
725			$auto_update_supported = false;
726			/*
727			 * Create the expected payload for the auto_update_theme filter, this is the same data
728			 * as contained within $updates or $no_updates but used when the Theme is not known.
729			 */
730			$auto_update_filter_payload = (object) array(
731				'theme'        => $slug,
732				'new_version'  => $theme->get( 'Version' ),
733				'url'          => '',
734				'package'      => '',
735				'requires'     => $theme->get( 'RequiresWP' ),
736				'requires_php' => $theme->get( 'RequiresPHP' ),
737			);
738		}
739
740		$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, $auto_update_filter_payload );
741
742		$prepared_themes[ $slug ] = array(
743			'id'             => $slug,
744			'name'           => $theme->display( 'Name' ),
745			'screenshot'     => array( $theme->get_screenshot() ), // @todo Multiple screenshots.
746			'description'    => $theme->display( 'Description' ),
747			'author'         => $theme->display( 'Author', false, true ),
748			'authorAndUri'   => $theme->display( 'Author' ),
749			'tags'           => $theme->display( 'Tags' ),
750			'version'        => $theme->get( 'Version' ),
751			'compatibleWP'   => is_wp_version_compatible( $theme->get( 'RequiresWP' ) ),
752			'compatiblePHP'  => is_php_version_compatible( $theme->get( 'RequiresPHP' ) ),
753			'updateResponse' => array(
754				'compatibleWP'  => is_wp_version_compatible( $update_requires_wp ),
755				'compatiblePHP' => is_php_version_compatible( $update_requires_php ),
756			),
757			'parent'         => $parent,
758			'active'         => $slug === $current_theme,
759			'hasUpdate'      => isset( $updates[ $slug ] ),
760			'hasPackage'     => isset( $updates[ $slug ] ) && ! empty( $updates[ $slug ]['package'] ),
761			'update'         => get_theme_update_available( $theme ),
762			'autoupdate'     => array(
763				'enabled'   => $auto_update || $auto_update_forced,
764				'supported' => $auto_update_supported,
765				'forced'    => $auto_update_forced,
766			),
767			'actions'        => array(
768				'activate'   => current_user_can( 'switch_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=activate&amp;stylesheet=' . $encoded_slug ), 'switch-theme_' . $slug ) : null,
769				'customize'  => $customize_action,
770				'delete'     => ( ! is_multisite() && current_user_can( 'delete_themes' ) ) ? wp_nonce_url( admin_url( 'themes.php?action=delete&amp;stylesheet=' . $encoded_slug ), 'delete-theme_' . $slug ) : null,
771				'autoupdate' => wp_is_auto_update_enabled_for_type( 'theme' ) && ! is_multisite() && current_user_can( 'update_themes' )
772					? wp_nonce_url( admin_url( 'themes.php?action=' . $auto_update_action . '&amp;stylesheet=' . $encoded_slug ), 'updates' )
773					: null,
774			),
775		);
776	}
777
778	// Remove 'delete' action if theme has an active child.
779	if ( ! empty( $parents ) && array_key_exists( $current_theme, $parents ) ) {
780		unset( $prepared_themes[ $parents[ $current_theme ] ]['actions']['delete'] );
781	}
782
783	/**
784	 * Filters the themes prepared for JavaScript, for themes.php.
785	 *
786	 * Could be useful for changing the order, which is by name by default.
787	 *
788	 * @since 3.8.0
789	 *
790	 * @param array $prepared_themes Array of theme data.
791	 */
792	$prepared_themes = apply_filters( 'wp_prepare_themes_for_js', $prepared_themes );
793	$prepared_themes = array_values( $prepared_themes );
794	return array_filter( $prepared_themes );
795}
796
797/**
798 * Print JS templates for the theme-browsing UI in the Customizer.
799 *
800 * @since 4.2.0
801 */
802function customize_themes_print_templates() {
803	?>
804	<script type="text/html" id="tmpl-customize-themes-details-view">
805		<div class="theme-backdrop"></div>
806		<div class="theme-wrap wp-clearfix" role="document">
807			<div class="theme-header">
808				<button type="button" class="left dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show previous theme' ); ?></span></button>
809				<button type="button" class="right dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show next theme' ); ?></span></button>
810				<button type="button" class="close dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Close details dialog' ); ?></span></button>
811			</div>
812			<div class="theme-about wp-clearfix">
813				<div class="theme-screenshots">
814				<# if ( data.screenshot && data.screenshot[0] ) { #>
815					<div class="screenshot"><img src="{{ data.screenshot[0] }}" alt="" /></div>
816				<# } else { #>
817					<div class="screenshot blank"></div>
818				<# } #>
819				</div>
820
821				<div class="theme-info">
822					<# if ( data.active ) { #>
823						<span class="current-label"><?php _e( 'Current Theme' ); ?></span>
824					<# } #>
825					<h2 class="theme-name">{{{ data.name }}}<span class="theme-version">
826						<?php
827						/* translators: %s: Theme version. */
828						printf( __( 'Version: %s' ), '{{ data.version }}' );
829						?>
830					</span></h2>
831					<h3 class="theme-author">
832						<?php
833						/* translators: %s: Theme author link. */
834						printf( __( 'By %s' ), '{{{ data.authorAndUri }}}' );
835						?>
836					</h3>
837
838					<# if ( data.stars && 0 != data.num_ratings ) { #>
839						<div class="theme-rating">
840							{{{ data.stars }}}
841							<a class="num-ratings" target="_blank" href="{{ data.reviews_url }}">
842								<?php
843								printf(
844									'%1$s <span class="screen-reader-text">%2$s</span>',
845									/* translators: %s: Number of ratings. */
846									sprintf( __( '(%s ratings)' ), '{{ data.num_ratings }}' ),
847									/* translators: Accessibility text. */
848									__( '(opens in a new tab)' )
849								);
850								?>
851							</a>
852						</div>
853					<# } #>
854
855					<# if ( data.hasUpdate ) { #>
856						<# if ( data.updateResponse.compatibleWP && data.updateResponse.compatiblePHP ) { #>
857							<div class="notice notice-warning notice-alt notice-large" data-slug="{{ data.id }}">
858								<h3 class="notice-title"><?php _e( 'Update Available' ); ?></h3>
859								{{{ data.update }}}
860							</div>
861						<# } else { #>
862							<div class="notice notice-error notice-alt notice-large" data-slug="{{ data.id }}">
863								<h3 class="notice-title"><?php _e( 'Update Incompatible' ); ?></h3>
864								<p>
865									<# if ( ! data.updateResponse.compatibleWP && ! data.updateResponse.compatiblePHP ) { #>
866										<?php
867										printf(
868											/* translators: %s: Theme name. */
869											__( 'There is a new version of %s available, but it doesn&#8217;t work with your versions of WordPress and PHP.' ),
870											'{{{ data.name }}}'
871										);
872										if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) {
873											printf(
874												/* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */
875												' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ),
876												self_admin_url( 'update-core.php' ),
877												esc_url( wp_get_update_php_url() )
878											);
879											wp_update_php_annotation( '</p><p><em>', '</em>' );
880										} elseif ( current_user_can( 'update_core' ) ) {
881											printf(
882												/* translators: %s: URL to WordPress Updates screen. */
883												' ' . __( '<a href="%s">Please update WordPress</a>.' ),
884												self_admin_url( 'update-core.php' )
885											);
886										} elseif ( current_user_can( 'update_php' ) ) {
887											printf(
888												/* translators: %s: URL to Update PHP page. */
889												' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
890												esc_url( wp_get_update_php_url() )
891											);
892											wp_update_php_annotation( '</p><p><em>', '</em>' );
893										}
894										?>
895									<# } else if ( ! data.updateResponse.compatibleWP ) { #>
896										<?php
897										printf(
898											/* translators: %s: Theme name. */
899											__( 'There is a new version of %s available, but it doesn&#8217;t work with your version of WordPress.' ),
900											'{{{ data.name }}}'
901										);
902										if ( current_user_can( 'update_core' ) ) {
903											printf(
904												/* translators: %s: URL to WordPress Updates screen. */
905												' ' . __( '<a href="%s">Please update WordPress</a>.' ),
906												self_admin_url( 'update-core.php' )
907											);
908										}
909										?>
910									<# } else if ( ! data.updateResponse.compatiblePHP ) { #>
911										<?php
912										printf(
913											/* translators: %s: Theme name. */
914											__( 'There is a new version of %s available, but it doesn&#8217;t work with your version of PHP.' ),
915											'{{{ data.name }}}'
916										);
917										if ( current_user_can( 'update_php' ) ) {
918											printf(
919												/* translators: %s: URL to Update PHP page. */
920												' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
921												esc_url( wp_get_update_php_url() )
922											);
923											wp_update_php_annotation( '</p><p><em>', '</em>' );
924										}
925										?>
926									<# } #>
927								</p>
928							</div>
929						<# } #>
930					<# } #>
931
932					<# if ( data.parent ) { #>
933						<p class="parent-theme">
934							<?php
935							printf(
936								/* translators: %s: Theme name. */
937								__( 'This is a child theme of %s.' ),
938								'<strong>{{{ data.parent }}}</strong>'
939							);
940							?>
941						</p>
942					<# } #>
943
944					<# if ( ! data.compatibleWP || ! data.compatiblePHP ) { #>
945						<div class="notice notice-error notice-alt notice-large"><p>
946							<# if ( ! data.compatibleWP && ! data.compatiblePHP ) { #>
947								<?php
948								_e( 'This theme doesn&#8217;t work with your versions of WordPress and PHP.' );
949								if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) {
950									printf(
951										/* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */
952										' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ),
953										self_admin_url( 'update-core.php' ),
954										esc_url( wp_get_update_php_url() )
955									);
956									wp_update_php_annotation( '</p><p><em>', '</em>' );
957								} elseif ( current_user_can( 'update_core' ) ) {
958									printf(
959										/* translators: %s: URL to WordPress Updates screen. */
960										' ' . __( '<a href="%s">Please update WordPress</a>.' ),
961										self_admin_url( 'update-core.php' )
962									);
963								} elseif ( current_user_can( 'update_php' ) ) {
964									printf(
965										/* translators: %s: URL to Update PHP page. */
966										' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
967										esc_url( wp_get_update_php_url() )
968									);
969									wp_update_php_annotation( '</p><p><em>', '</em>' );
970								}
971								?>
972							<# } else if ( ! data.compatibleWP ) { #>
973								<?php
974								_e( 'This theme doesn&#8217;t work with your version of WordPress.' );
975								if ( current_user_can( 'update_core' ) ) {
976									printf(
977										/* translators: %s: URL to WordPress Updates screen. */
978										' ' . __( '<a href="%s">Please update WordPress</a>.' ),
979										self_admin_url( 'update-core.php' )
980									);
981								}
982								?>
983							<# } else if ( ! data.compatiblePHP ) { #>
984								<?php
985								_e( 'This theme doesn&#8217;t work with your version of PHP.' );
986								if ( current_user_can( 'update_php' ) ) {
987									printf(
988										/* translators: %s: URL to Update PHP page. */
989										' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
990										esc_url( wp_get_update_php_url() )
991									);
992									wp_update_php_annotation( '</p><p><em>', '</em>' );
993								}
994								?>
995							<# } #>
996						</p></div>
997					<# } #>
998
999					<p class="theme-description">{{{ data.description }}}</p>
1000
1001					<# if ( data.tags ) { #>
1002						<p class="theme-tags"><span><?php _e( 'Tags:' ); ?></span> {{{ data.tags }}}</p>
1003					<# } #>
1004				</div>
1005			</div>
1006
1007			<div class="theme-actions">
1008				<# if ( data.active ) { #>
1009					<button type="button" class="button button-primary customize-theme"><?php _e( 'Customize' ); ?></button>
1010				<# } else if ( 'installed' === data.type ) { #>
1011					<?php if ( current_user_can( 'delete_themes' ) ) { ?>
1012						<# if ( data.actions && data.actions['delete'] ) { #>
1013							<a href="{{{ data.actions['delete'] }}}" data-slug="{{ data.id }}" class="button button-secondary delete-theme"><?php _e( 'Delete' ); ?></a>
1014						<# } #>
1015					<?php } ?>
1016
1017					<# if ( data.compatibleWP && data.compatiblePHP ) { #>
1018						<button type="button" class="button button-primary preview-theme" data-slug="{{ data.id }}"><?php _e( 'Live Preview' ); ?></button>
1019					<# } else { #>
1020						<button class="button button-primary disabled"><?php _e( 'Live Preview' ); ?></button>
1021					<# } #>
1022				<# } else { #>
1023					<# if ( data.compatibleWP && data.compatiblePHP ) { #>
1024						<button type="button" class="button theme-install" data-slug="{{ data.id }}"><?php _e( 'Install' ); ?></button>
1025						<button type="button" class="button button-primary theme-install preview" data-slug="{{ data.id }}"><?php _e( 'Install &amp; Preview' ); ?></button>
1026					<# } else { #>
1027						<button type="button" class="button disabled"><?php _ex( 'Cannot Install', 'theme' ); ?></button>
1028						<button type="button" class="button button-primary disabled"><?php _e( 'Install &amp; Preview' ); ?></button>
1029					<# } #>
1030				<# } #>
1031			</div>
1032		</div>
1033	</script>
1034	<?php
1035}
1036
1037/**
1038 * Determines whether a theme is technically active but was paused while
1039 * loading.
1040 *
1041 * For more information on this and similar theme functions, check out
1042 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1043 * Conditional Tags} article in the Theme Developer Handbook.
1044 *
1045 * @since 5.2.0
1046 *
1047 * @param string $theme Path to the theme directory relative to the themes directory.
1048 * @return bool True, if in the list of paused themes. False, not in the list.
1049 */
1050function is_theme_paused( $theme ) {
1051	if ( ! isset( $GLOBALS['_paused_themes'] ) ) {
1052		return false;
1053	}
1054
1055	if ( get_stylesheet() !== $theme && get_template() !== $theme ) {
1056		return false;
1057	}
1058
1059	return array_key_exists( $theme, $GLOBALS['_paused_themes'] );
1060}
1061
1062/**
1063 * Gets the error that was recorded for a paused theme.
1064 *
1065 * @since 5.2.0
1066 *
1067 * @param string $theme Path to the theme directory relative to the themes
1068 *                      directory.
1069 * @return array|false Array of error information as it was returned by
1070 *                     `error_get_last()`, or false if none was recorded.
1071 */
1072function wp_get_theme_error( $theme ) {
1073	if ( ! isset( $GLOBALS['_paused_themes'] ) ) {
1074		return false;
1075	}
1076
1077	if ( ! array_key_exists( $theme, $GLOBALS['_paused_themes'] ) ) {
1078		return false;
1079	}
1080
1081	return $GLOBALS['_paused_themes'][ $theme ];
1082}
1083
1084/**
1085 * Tries to resume a single theme.
1086 *
1087 * If a redirect was provided and a functions.php file was found, we first ensure that
1088 * functions.php file does not throw fatal errors anymore.
1089 *
1090 * The way it works is by setting the redirection to the error before trying to
1091 * include the file. If the theme fails, then the redirection will not be overwritten
1092 * with the success message and the theme will not be resumed.
1093 *
1094 * @since 5.2.0
1095 *
1096 * @param string $theme    Single theme to resume.
1097 * @param string $redirect Optional. URL to redirect to. Default empty string.
1098 * @return bool|WP_Error True on success, false if `$theme` was not paused,
1099 *                       `WP_Error` on failure.
1100 */
1101function resume_theme( $theme, $redirect = '' ) {
1102	list( $extension ) = explode( '/', $theme );
1103
1104	/*
1105	 * We'll override this later if the theme could be resumed without
1106	 * creating a fatal error.
1107	 */
1108	if ( ! empty( $redirect ) ) {
1109		$functions_path = '';
1110		if ( strpos( STYLESHEETPATH, $extension ) ) {
1111			$functions_path = STYLESHEETPATH . '/functions.php';
1112		} elseif ( strpos( TEMPLATEPATH, $extension ) ) {
1113			$functions_path = TEMPLATEPATH . '/functions.php';
1114		}
1115
1116		if ( ! empty( $functions_path ) ) {
1117			wp_redirect(
1118				add_query_arg(
1119					'_error_nonce',
1120					wp_create_nonce( 'theme-resume-error_' . $theme ),
1121					$redirect
1122				)
1123			);
1124
1125			// Load the theme's functions.php to test whether it throws a fatal error.
1126			ob_start();
1127			if ( ! defined( 'WP_SANDBOX_SCRAPING' ) ) {
1128				define( 'WP_SANDBOX_SCRAPING', true );
1129			}
1130			include $functions_path;
1131			ob_clean();
1132		}
1133	}
1134
1135	$result = wp_paused_themes()->delete( $extension );
1136
1137	if ( ! $result ) {
1138		return new WP_Error(
1139			'could_not_resume_theme',
1140			__( 'Could not resume the theme.' )
1141		);
1142	}
1143
1144	return true;
1145}
1146
1147/**
1148 * Renders an admin notice in case some themes have been paused due to errors.
1149 *
1150 * @since 5.2.0
1151 *
1152 * @global string $pagenow
1153 */
1154function paused_themes_notice() {
1155	if ( 'themes.php' === $GLOBALS['pagenow'] ) {
1156		return;
1157	}
1158
1159	if ( ! current_user_can( 'resume_themes' ) ) {
1160		return;
1161	}
1162
1163	if ( ! isset( $GLOBALS['_paused_themes'] ) || empty( $GLOBALS['_paused_themes'] ) ) {
1164		return;
1165	}
1166
1167	printf(
1168		'<div class="notice notice-error"><p><strong>%s</strong><br>%s</p><p><a href="%s">%s</a></p></div>',
1169		__( 'One or more themes failed to load properly.' ),
1170		__( 'You can find more details and make changes on the Themes screen.' ),
1171		esc_url( admin_url( 'themes.php' ) ),
1172		__( 'Go to the Themes screen' )
1173	);
1174}
1175