WordPress 4.2
[autoinstalls/wordpress.git] / wp-admin / includes / theme.php
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  * @param string $stylesheet Stylesheet of the theme to delete
15  * @param string $redirect Redirect to page when complete.
16  * @return mixed
17  */
18 function delete_theme($stylesheet, $redirect = '') {
19         global $wp_filesystem;
20
21         if ( empty($stylesheet) )
22                 return false;
23
24         ob_start();
25         if ( empty( $redirect ) )
26                 $redirect = wp_nonce_url('themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet);
27         if ( false === ($credentials = request_filesystem_credentials($redirect)) ) {
28                 $data = ob_get_contents();
29                 ob_end_clean();
30                 if ( ! empty($data) ){
31                         include_once( ABSPATH . 'wp-admin/admin-header.php');
32                         echo $data;
33                         include( ABSPATH . 'wp-admin/admin-footer.php');
34                         exit;
35                 }
36                 return;
37         }
38
39         if ( ! WP_Filesystem($credentials) ) {
40                 request_filesystem_credentials($redirect, '', true); // Failed to connect, Error and request again
41                 $data = ob_get_contents();
42                 ob_end_clean();
43                 if ( ! empty($data) ) {
44                         include_once( ABSPATH . 'wp-admin/admin-header.php');
45                         echo $data;
46                         include( ABSPATH . 'wp-admin/admin-footer.php');
47                         exit;
48                 }
49                 return;
50         }
51
52         if ( ! is_object($wp_filesystem) )
53                 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
54
55         if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
56                 return new WP_Error('fs_error', __('Filesystem error.'), $wp_filesystem->errors);
57
58         // Get the base plugin folder.
59         $themes_dir = $wp_filesystem->wp_themes_dir();
60         if ( empty( $themes_dir ) ) {
61                 return new WP_Error( 'fs_no_themes_dir', __( 'Unable to locate WordPress theme directory.' ) );
62         }
63
64         $themes_dir = trailingslashit( $themes_dir );
65         $theme_dir = trailingslashit( $themes_dir . $stylesheet );
66         $deleted = $wp_filesystem->delete( $theme_dir, true );
67
68         if ( ! $deleted ) {
69                 return new WP_Error( 'could_not_remove_theme', sprintf( __( 'Could not fully remove the theme %s.' ), $stylesheet ) );
70         }
71
72         $theme_translations = wp_get_installed_translations( 'themes' );
73
74         // Remove language files, silently.
75         if ( ! empty( $theme_translations[ $stylesheet ] ) ) {
76                 $translations = $theme_translations[ $stylesheet ];
77
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                 }
82         }
83
84         // Force refresh of theme update information.
85         delete_site_transient( 'update_themes' );
86
87         return true;
88 }
89
90 /**
91  * Get the Page Templates available in this theme
92  *
93  * @since 1.5.0
94  *
95  * @param WP_Post|null $post Optional. The post being edited, provided for context.
96  * @return array Key is the template name, value is the filename of the template
97  */
98 function get_page_templates( $post = null ) {
99         return array_flip( wp_get_theme()->get_page_templates( $post ) );
100 }
101
102 /**
103  * Tidies a filename for url display by the theme editor.
104  *
105  * @since 2.9.0
106  * @access private
107  *
108  * @param string $fullpath Full path to the theme file
109  * @param string $containingfolder Path of the theme parent folder
110  * @return string
111  */
112 function _get_template_edit_filename($fullpath, $containingfolder) {
113         return str_replace(dirname(dirname( $containingfolder )) , '', $fullpath);
114 }
115
116 /**
117  * Check if there is an update for a theme available.
118  *
119  * Will display link, if there is an update available.
120  *
121  * @since 2.7.0
122  * @see get_theme_update_available()
123  *
124  * @param object $theme Theme data object.
125  */
126 function theme_update_available( $theme ) {
127         echo get_theme_update_available( $theme );
128 }
129
130 /**
131  * Retrieve the update link if there is a theme update available.
132  *
133  * Will return a link if there is an update available.
134  *
135  * @since 3.8.0
136  *
137  * @param WP_Theme $theme WP_Theme object.
138  * @return false|string HTML for the update link, or false if invalid info was passed.
139  */
140 function get_theme_update_available( $theme ) {
141         static $themes_update;
142
143         if ( !current_user_can('update_themes' ) )
144                 return false;
145
146         if ( !isset($themes_update) )
147                 $themes_update = get_site_transient('update_themes');
148
149         if ( ! ( $theme instanceof WP_Theme ) ) {
150                 return false;
151         }
152
153         $stylesheet = $theme->get_stylesheet();
154
155         $html = '';
156
157         if ( isset($themes_update->response[ $stylesheet ]) ) {
158                 $update = $themes_update->response[ $stylesheet ];
159                 $theme_name = $theme->display('Name');
160                 $details_url = add_query_arg(array('TB_iframe' => 'true', 'width' => 1024, 'height' => 800), $update['url']); //Theme browser inside WP? replace this, Also, theme preview JS will override this on the available list.
161                 $update_url = wp_nonce_url( admin_url( 'update.php?action=upgrade-theme&amp;theme=' . urlencode( $stylesheet ) ), 'upgrade-theme_' . $stylesheet );
162                 $update_onclick = 'onclick="if ( confirm(\'' . esc_js( __("Updating this theme will lose any customizations you have made. 'Cancel' to stop, 'OK' to update.") ) . '\') ) {return true;}return false;"';
163
164                 if ( !is_multisite() ) {
165                         if ( ! current_user_can('update_themes') ) {
166                                 $html = sprintf( '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>.' ) . '</strong></p>',
167                                         $theme_name, esc_url( $details_url ), esc_attr( $theme['Name'] ), $update['new_version'] );
168                         } elseif ( empty( $update['package'] ) ) {
169                                 $html = sprintf( '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' ) . '</strong></p>',
170                                         $theme_name, esc_url( $details_url ), esc_attr( $theme['Name'] ), $update['new_version'] );
171                         } else {
172                                 $html = sprintf( '<p><strong>' . __( 'There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a> or <a href="%5$s">update now</a>.' ) . '</strong></p>',
173                                         $theme_name, esc_url( $details_url ), esc_attr( $theme['Name'] ), $update['new_version'], $update_url, $update_onclick );
174                         }
175                 }
176         }
177
178         return $html;
179 }
180
181 /**
182  * Retrieve list of WordPress theme features (aka theme tags)
183  *
184  * @since 3.1.0
185  *
186  * @param bool $api Optional. Whether try to fetch tags from the WP.org API. Defaults to true.
187  * @return array Array of features keyed by category with translations keyed by slug.
188  */
189 function get_theme_feature_list( $api = true ) {
190         // Hard-coded list is used if api not accessible.
191         $features = array(
192                         __( 'Colors' ) => array(
193                                 'black'   => __( 'Black' ),
194                                 'blue'    => __( 'Blue' ),
195                                 'brown'   => __( 'Brown' ),
196                                 'gray'    => __( 'Gray' ),
197                                 'green'   => __( 'Green' ),
198                                 'orange'  => __( 'Orange' ),
199                                 'pink'    => __( 'Pink' ),
200                                 'purple'  => __( 'Purple' ),
201                                 'red'     => __( 'Red' ),
202                                 'silver'  => __( 'Silver' ),
203                                 'tan'     => __( 'Tan' ),
204                                 'white'   => __( 'White' ),
205                                 'yellow'  => __( 'Yellow' ),
206                                 'dark'    => __( 'Dark' ),
207                                 'light'   => __( 'Light' ),
208                         ),
209
210                 __( 'Layout' ) => array(
211                         'fixed-layout'      => __( 'Fixed Layout' ),
212                         'fluid-layout'      => __( 'Fluid Layout' ),
213                         'responsive-layout' => __( 'Responsive Layout' ),
214                         'one-column'    => __( 'One Column' ),
215                         'two-columns'   => __( 'Two Columns' ),
216                         'three-columns' => __( 'Three Columns' ),
217                         'four-columns'  => __( 'Four Columns' ),
218                         'left-sidebar'  => __( 'Left Sidebar' ),
219                         'right-sidebar' => __( 'Right Sidebar' ),
220                 ),
221
222                 __( 'Features' ) => array(
223                         'accessibility-ready'   => __( 'Accessibility Ready' ),
224                         'blavatar'              => __( 'Blavatar' ),
225                         'buddypress'            => __( 'BuddyPress' ),
226                         'custom-background'     => __( 'Custom Background' ),
227                         'custom-colors'         => __( 'Custom Colors' ),
228                         'custom-header'         => __( 'Custom Header' ),
229                         'custom-menu'           => __( 'Custom Menu' ),
230                         'editor-style'          => __( 'Editor Style' ),
231                         'featured-image-header' => __( 'Featured Image Header' ),
232                         'featured-images'       => __( 'Featured Images' ),
233                         'flexible-header'       => __( 'Flexible Header' ),
234                         'front-page-post-form'  => __( 'Front Page Posting' ),
235                         'full-width-template'   => __( 'Full Width Template' ),
236                         'microformats'          => __( 'Microformats' ),
237                         'post-formats'          => __( 'Post Formats' ),
238                         'rtl-language-support'  => __( 'RTL Language Support' ),
239                         'sticky-post'           => __( 'Sticky Post' ),
240                         'theme-options'         => __( 'Theme Options' ),
241                         'threaded-comments'     => __( 'Threaded Comments' ),
242                         'translation-ready'     => __( 'Translation Ready' ),
243                 ),
244
245                 __( 'Subject' )  => array(
246                         'holiday'       => __( 'Holiday' ),
247                         'photoblogging' => __( 'Photoblogging' ),
248                         'seasonal'      => __( 'Seasonal' ),
249                 )
250         );
251
252         if ( ! $api || ! current_user_can( 'install_themes' ) )
253                 return $features;
254
255         if ( !$feature_list = get_site_transient( 'wporg_theme_feature_list' ) )
256                 set_site_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS );
257
258         if ( !$feature_list ) {
259                 $feature_list = themes_api( 'feature_list', array() );
260                 if ( is_wp_error( $feature_list ) )
261                         return $features;
262         }
263
264         if ( !$feature_list )
265                 return $features;
266
267         set_site_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS );
268
269         $category_translations = array(
270                 'Colors'   => __( 'Colors' ),
271                 'Layout'   => __( 'Layout' ),
272                 'Features' => __( 'Features' ),
273                 'Subject'  => __( 'Subject' )
274         );
275
276         // Loop over the wporg canonical list and apply translations
277         $wporg_features = array();
278         foreach ( (array) $feature_list as $feature_category => $feature_items ) {
279                 if ( isset($category_translations[$feature_category]) )
280                         $feature_category = $category_translations[$feature_category];
281                 $wporg_features[$feature_category] = array();
282
283                 foreach ( $feature_items as $feature ) {
284                         if ( isset($features[$feature_category][$feature]) )
285                                 $wporg_features[$feature_category][$feature] = $features[$feature_category][$feature];
286                         else
287                                 $wporg_features[$feature_category][$feature] = $feature;
288                 }
289         }
290
291         return $wporg_features;
292 }
293
294 /**
295  * Retrieve theme installer pages from WordPress Themes API.
296  *
297  * It is possible for a theme to override the Themes API result with three
298  * filters. Assume this is for themes, which can extend on the Theme Info to
299  * offer more choices. This is very powerful and must be used with care, when
300  * overriding the filters.
301  *
302  * The first filter, 'themes_api_args', is for the args and gives the action as
303  * the second parameter. The hook for 'themes_api_args' must ensure that an
304  * object is returned.
305  *
306  * The second filter, 'themes_api', is the result that would be returned.
307  *
308  * @since 2.8.0
309  *
310  * @param string       $action The requested action. Likely values are 'theme_information',
311  *                             'feature_list', or 'query_themes'.
312  * @param array|object $args   Optional. Arguments to serialize for the Theme Info API.
313  * @return mixed
314  */
315 function themes_api( $action, $args = null ) {
316
317         if ( is_array( $args ) ) {
318                 $args = (object) $args;
319         }
320
321         if ( ! isset( $args->per_page ) ) {
322                 $args->per_page = 24;
323         }
324
325         if ( ! isset( $args->locale ) ) {
326                 $args->locale = get_locale();
327         }
328
329         /**
330          * Filter arguments used to query for installer pages from the WordPress.org Themes API.
331          *
332          * Important: An object MUST be returned to this filter.
333          *
334          * @since 2.8.0
335          *
336          * @param object $args   Arguments used to query for installer pages from the WordPress.org Themes API.
337          * @param string $action Requested action. Likely values are 'theme_information',
338          *                       'feature_list', or 'query_themes'.
339          */
340         $args = apply_filters( 'themes_api_args', $args, $action );
341
342         /**
343          * Filter whether to override the WordPress.org Themes API.
344          *
345          * Returning a value of true to this filter allows a theme to completely
346          * override the built-in WordPress.org API.
347          *
348          * @since 2.8.0
349          *
350          * @param bool   $bool   Whether to override the WordPress.org Themes API. Default false.
351          * @param string $action Requested action. Likely values are 'theme_information',
352          *                       'feature_list', or 'query_themes'.
353          * @param object $args   Arguments used to query for installer pages from the Themes API.
354          */
355         $res = apply_filters( 'themes_api', false, $action, $args );
356
357         if ( ! $res ) {
358                 $url = $http_url = 'http://api.wordpress.org/themes/info/1.0/';
359                 if ( $ssl = wp_http_supports( array( 'ssl' ) ) )
360                         $url = set_url_scheme( $url, 'https' );
361
362                 $http_args = array(
363                         'body' => array(
364                                 'action' => $action,
365                                 'request' => serialize( $args )
366                         )
367                 );
368                 $request = wp_remote_post( $url, $http_args );
369
370                 if ( $ssl && is_wp_error( $request ) ) {
371                         if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
372                                 trigger_error( __( '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="https://wordpress.org/support/">support forums</a>.' ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE );
373                         }
374                         $request = wp_remote_post( $http_url, $http_args );
375                 }
376
377                 if ( is_wp_error($request) ) {
378                         $res = new WP_Error('themes_api_failed', __( '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="https://wordpress.org/support/">support forums</a>.' ), $request->get_error_message() );
379                 } else {
380                         $res = maybe_unserialize( wp_remote_retrieve_body( $request ) );
381                         if ( ! is_object( $res ) && ! is_array( $res ) )
382                                 $res = new WP_Error('themes_api_failed', __( '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="https://wordpress.org/support/">support forums</a>.' ), wp_remote_retrieve_body( $request ) );
383                 }
384         }
385
386         /**
387          * Filter the returned WordPress.org Themes API response.
388          *
389          * @since 2.8.0
390          *
391          * @param array|object $res    WordPress.org Themes API response.
392          * @param string       $action Requested action. Likely values are 'theme_information',
393          *                             'feature_list', or 'query_themes'.
394          * @param object       $args   Arguments used to query for installer pages from the WordPress.org Themes API.
395          */
396         return apply_filters( 'themes_api_result', $res, $action, $args );
397 }
398
399 /**
400  * Prepare themes for JavaScript.
401  *
402  * @since 3.8.0
403  *
404  * @param array $themes Optional. Array of WP_Theme objects to prepare.
405  *                      Defaults to all allowed themes.
406  *
407  * @return array An associative array of theme data, sorted by name.
408  */
409 function wp_prepare_themes_for_js( $themes = null ) {
410         $current_theme = get_stylesheet();
411
412         /**
413          * Filter theme data before it is prepared for JavaScript.
414          *
415          * Passing a non-empty array will result in wp_prepare_themes_for_js() returning
416          * early with that value instead.
417          *
418          * @since 4.2.0
419          *
420          * @param array      $prepared_themes An associative array of theme data. Default empty array.
421          * @param null|array $themes          An array of WP_Theme objects to prepare, if any.
422          * @param string     $current_theme   The current theme slug.
423          */
424         $prepared_themes = (array) apply_filters( 'pre_prepare_themes_for_js', array(), $themes, $current_theme );
425
426         if ( ! empty( $prepared_themes ) ) {
427                 return $prepared_themes;
428         }
429
430         // Make sure the current theme is listed first.
431         $prepared_themes[ $current_theme ] = array();
432
433         if ( null === $themes ) {
434                 $themes = wp_get_themes( array( 'allowed' => true ) );
435                 if ( ! isset( $themes[ $current_theme ] ) ) {
436                         $themes[ $current_theme ] = wp_get_theme();
437                 }
438         }
439
440         $updates = array();
441         if ( current_user_can( 'update_themes' ) ) {
442                 $updates_transient = get_site_transient( 'update_themes' );
443                 if ( isset( $updates_transient->response ) ) {
444                         $updates = $updates_transient->response;
445                 }
446         }
447
448         WP_Theme::sort_by_name( $themes );
449
450         $parents = array();
451
452         foreach ( $themes as $theme ) {
453                 $slug = $theme->get_stylesheet();
454                 $encoded_slug = urlencode( $slug );
455
456                 $parent = false;
457                 if ( $theme->parent() ) {
458                         $parent = $theme->parent()->display( 'Name' );
459                         $parents[ $slug ] = $theme->parent()->get_stylesheet();
460                 }
461
462                 $prepared_themes[ $slug ] = array(
463                         'id'           => $slug,
464                         'name'         => $theme->display( 'Name' ),
465                         'screenshot'   => array( $theme->get_screenshot() ), // @todo multiple
466                         'description'  => $theme->display( 'Description' ),
467                         'author'       => $theme->display( 'Author', false, true ),
468                         'authorAndUri' => $theme->display( 'Author' ),
469                         'version'      => $theme->display( 'Version' ),
470                         'tags'         => $theme->display( 'Tags' ),
471                         'parent'       => $parent,
472                         'active'       => $slug === $current_theme,
473                         'hasUpdate'    => isset( $updates[ $slug ] ),
474                         'update'       => get_theme_update_available( $theme ),
475                         'actions'      => array(
476                                 'activate' => current_user_can( 'switch_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=activate&amp;stylesheet=' . $encoded_slug ), 'switch-theme_' . $slug ) : null,
477                                 'customize' => ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) ? wp_customize_url( $slug ) : null,
478                                 'preview'   => add_query_arg( array(
479                                         'preview'        => 1,
480                                         'template'       => urlencode( $theme->get_template() ),
481                                         'stylesheet'     => urlencode( $slug ),
482                                         'preview_iframe' => true,
483                                         'TB_iframe'      => true,
484                                 ), home_url( '/' ) ),
485                                 'delete'   => current_user_can( 'delete_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=delete&amp;stylesheet=' . $encoded_slug ), 'delete-theme_' . $slug ) : null,
486                         ),
487                 );
488         }
489
490         // Remove 'delete' action if theme has an active child
491         if ( ! empty( $parents ) && array_key_exists( $current_theme, $parents ) ) {
492                 unset( $prepared_themes[ $parents[ $current_theme ] ]['actions']['delete'] );
493         }
494
495         /**
496          * Filter the themes prepared for JavaScript, for themes.php.
497          *
498          * Could be useful for changing the order, which is by name by default.
499          *
500          * @since 3.8.0
501          *
502          * @param array $prepared_themes Array of themes.
503          */
504         $prepared_themes = apply_filters( 'wp_prepare_themes_for_js', $prepared_themes );
505         $prepared_themes = array_values( $prepared_themes );
506         return array_filter( $prepared_themes );
507 }
508
509 /**
510  * Print JS templates for the theme-browsing UI in the Customizer.
511  *
512  * @since 4.2.0
513  */
514 function customize_themes_print_templates() {
515         $preview_url = esc_url( add_query_arg( 'theme', '__THEME__' ) ); // Token because esc_url() strips curly braces.
516         $preview_url = str_replace( '__THEME__', '{{ data.id }}', $preview_url );
517         ?>
518         <script type="text/html" id="tmpl-customize-themes-details-view">
519                 <div class="theme-backdrop"></div>
520                 <div class="theme-wrap">
521                         <div class="theme-header">
522                                 <button type="button" class="left dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show previous theme' ); ?></span></button>
523                                 <button type="button" class="right dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Show next theme' ); ?></span></button>
524                                 <button type="button" class="close dashicons dashicons-no"><span class="screen-reader-text"><?php _e( 'Close details dialog' ); ?></span></button>
525                         </div>
526                         <div class="theme-about">
527                                 <div class="theme-screenshots">
528                                 <# if ( data.screenshot[0] ) { #>
529                                         <div class="screenshot"><img src="{{ data.screenshot[0] }}" alt="" /></div>
530                                 <# } else { #>
531                                         <div class="screenshot blank"></div>
532                                 <# } #>
533                                 </div>
534
535                                 <div class="theme-info">
536                                         <# if ( data.active ) { #>
537                                                 <span class="current-label"><?php _e( 'Current Theme' ); ?></span>
538                                         <# } #>
539                                         <h3 class="theme-name">{{{ data.name }}}<span class="theme-version"><?php printf( __( 'Version: %s' ), '{{ data.version }}' ); ?></span></h3>
540                                         <h4 class="theme-author"><?php printf( __( 'By %s' ), '{{{ data.authorAndUri }}}' ); ?></h4>
541                                         <p class="theme-description">{{{ data.description }}}</p>
542
543                                         <# if ( data.parent ) { #>
544                                                 <p class="parent-theme"><?php printf( __( 'This is a child theme of %s.' ), '<strong>{{{ data.parent }}}</strong>' ); ?></p>
545                                         <# } #>
546
547                                         <# if ( data.tags ) { #>
548                                                 <p class="theme-tags"><span><?php _e( 'Tags:' ); ?></span> {{ data.tags }}</p>
549                                         <# } #>
550                                 </div>
551                         </div>
552
553                         <# if ( ! data.active ) { #>
554                                 <div class="theme-actions">
555                                         <div class="inactive-theme">
556                                                 <a href="<?php echo $preview_url; ?>" target="_top" class="button button-primary"><?php _e( 'Live Preview' ); ?></a>
557                                         </div>
558                                 </div>
559                         <# } #>
560                 </div>
561         </script>
562         <?php
563 }
564 add_action( 'customize_controls_print_footer_scripts', 'customize_themes_print_templates' );