]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/theme.php
WordPress 3.9
[autoinstalls/wordpress.git] / wp-includes / theme.php
1 <?php
2 /**
3  * Theme, template, and stylesheet functions.
4  *
5  * @package WordPress
6  * @subpackage Theme
7  */
8
9 /**
10  * Returns an array of WP_Theme objects based on the arguments.
11  *
12  * Despite advances over get_themes(), this function is quite expensive, and grows
13  * linearly with additional themes. Stick to wp_get_theme() if possible.
14  *
15  * @since 3.4.0
16  *
17  * @param array $args The search arguments. Optional.
18  * - errors      mixed  True to return themes with errors, false to return themes without errors, null
19  *                      to return all themes. Defaults to false.
20  * - allowed     mixed  (Multisite) True to return only allowed themes for a site. False to return only
21  *                      disallowed themes for a site. 'site' to return only site-allowed themes. 'network'
22  *                      to return only network-allowed themes. Null to return all themes. Defaults to null.
23  * - blog_id     int    (Multisite) The blog ID used to calculate which themes are allowed. Defaults to 0,
24  *                      synonymous for the current blog.
25  * @return Array of WP_Theme objects.
26  */
27 function wp_get_themes( $args = array() ) {
28         global $wp_theme_directories;
29
30         $defaults = array( 'errors' => false, 'allowed' => null, 'blog_id' => 0 );
31         $args = wp_parse_args( $args, $defaults );
32
33         $theme_directories = search_theme_directories();
34
35         if ( count( $wp_theme_directories ) > 1 ) {
36                 // Make sure the current theme wins out, in case search_theme_directories() picks the wrong
37                 // one in the case of a conflict. (Normally, last registered theme root wins.)
38                 $current_theme = get_stylesheet();
39                 if ( isset( $theme_directories[ $current_theme ] ) ) {
40                         $root_of_current_theme = get_raw_theme_root( $current_theme );
41                         if ( ! in_array( $root_of_current_theme, $wp_theme_directories ) )
42                                 $root_of_current_theme = WP_CONTENT_DIR . $root_of_current_theme;
43                         $theme_directories[ $current_theme ]['theme_root'] = $root_of_current_theme;
44                 }
45         }
46
47         if ( empty( $theme_directories ) )
48                 return array();
49
50         if ( is_multisite() && null !== $args['allowed'] ) {
51                 $allowed = $args['allowed'];
52                 if ( 'network' === $allowed )
53                         $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_network() );
54                 elseif ( 'site' === $allowed )
55                         $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_site( $args['blog_id'] ) );
56                 elseif ( $allowed )
57                         $theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
58                 else
59                         $theme_directories = array_diff_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
60         }
61
62         $themes = array();
63         static $_themes = array();
64
65         foreach ( $theme_directories as $theme => $theme_root ) {
66                 if ( isset( $_themes[ $theme_root['theme_root'] . '/' . $theme ] ) )
67                         $themes[ $theme ] = $_themes[ $theme_root['theme_root'] . '/' . $theme ];
68                 else
69                         $themes[ $theme ] = $_themes[ $theme_root['theme_root'] . '/' . $theme ] = new WP_Theme( $theme, $theme_root['theme_root'] );
70         }
71
72         if ( null !== $args['errors'] ) {
73                 foreach ( $themes as $theme => $wp_theme ) {
74                         if ( $wp_theme->errors() != $args['errors'] )
75                                 unset( $themes[ $theme ] );
76                 }
77         }
78
79         return $themes;
80 }
81
82 /**
83  * Gets a WP_Theme object for a theme.
84  *
85  * @since 3.4.0
86  *
87  * @param string $stylesheet Directory name for the theme. Optional. Defaults to current theme.
88  * @param string $theme_root Absolute path of the theme root to look in. Optional. If not specified, get_raw_theme_root()
89  *      is used to calculate the theme root for the $stylesheet provided (or current theme).
90  * @return WP_Theme Theme object. Be sure to check the object's exists() method if you need to confirm the theme's existence.
91  */
92 function wp_get_theme( $stylesheet = null, $theme_root = null ) {
93         global $wp_theme_directories;
94
95         if ( empty( $stylesheet ) )
96                 $stylesheet = get_stylesheet();
97
98         if ( empty( $theme_root ) ) {
99                 $theme_root = get_raw_theme_root( $stylesheet );
100                 if ( false === $theme_root )
101                         $theme_root = WP_CONTENT_DIR . '/themes';
102                 elseif ( ! in_array( $theme_root, (array) $wp_theme_directories ) )
103                         $theme_root = WP_CONTENT_DIR . $theme_root;
104         }
105
106         return new WP_Theme( $stylesheet, $theme_root );
107 }
108
109 /**
110  * Clears the cache held by get_theme_roots() and WP_Theme.
111  *
112  * @since 3.5.0
113  * @param bool $clear_update_cache Whether to clear the Theme updates cache
114  */
115 function wp_clean_themes_cache( $clear_update_cache = true ) {
116         if ( $clear_update_cache )
117                 delete_site_transient( 'update_themes' );
118         search_theme_directories( true );
119         foreach ( wp_get_themes( array( 'errors' => null ) ) as $theme )
120                 $theme->cache_delete();
121 }
122
123 /**
124  * Whether a child theme is in use.
125  *
126  * @since 3.0.0
127  *
128  * @return bool true if a child theme is in use, false otherwise.
129  **/
130 function is_child_theme() {
131         return ( TEMPLATEPATH !== STYLESHEETPATH );
132 }
133
134 /**
135  * Retrieve name of the current stylesheet.
136  *
137  * The theme name that the administrator has currently set the front end theme
138  * as.
139  *
140  * For all extensive purposes, the template name and the stylesheet name are
141  * going to be the same for most cases.
142  *
143  * @since 1.5.0
144  *
145  * @return string Stylesheet name.
146  */
147 function get_stylesheet() {
148         /**
149          * Filter the name of current stylesheet.
150          *
151          * @since 1.5.0
152          *
153          * @param string $stylesheet Name of the current stylesheet.
154          */
155         return apply_filters( 'stylesheet', get_option( 'stylesheet' ) );
156 }
157
158 /**
159  * Retrieve stylesheet directory path for current theme.
160  *
161  * @since 1.5.0
162  *
163  * @return string Path to current theme directory.
164  */
165 function get_stylesheet_directory() {
166         $stylesheet = get_stylesheet();
167         $theme_root = get_theme_root( $stylesheet );
168         $stylesheet_dir = "$theme_root/$stylesheet";
169
170         /**
171          * Filter the stylesheet directory path for current theme.
172          *
173          * @since 1.5.0
174          *
175          * @param string $stylesheet_dir Absolute path to the current them.
176          * @param string $stylesheet     Directory name of the current theme.
177          * @param string $theme_root     Absolute path to themes directory.
178          */
179         return apply_filters( 'stylesheet_directory', $stylesheet_dir, $stylesheet, $theme_root );
180 }
181
182 /**
183  * Retrieve stylesheet directory URI.
184  *
185  * @since 1.5.0
186  *
187  * @return string
188  */
189 function get_stylesheet_directory_uri() {
190         $stylesheet = str_replace( '%2F', '/', rawurlencode( get_stylesheet() ) );
191         $theme_root_uri = get_theme_root_uri( $stylesheet );
192         $stylesheet_dir_uri = "$theme_root_uri/$stylesheet";
193
194         /**
195          * Filter the stylesheet directory URI.
196          *
197          * @since 1.5.0
198          *
199          * @param string $stylesheet_dir_uri Stylesheet directory URI.
200          * @param string $stylesheet         Name of the activated theme's directory.
201          * @param string $theme_root_uri     Themes root URI.
202          */
203         return apply_filters( 'stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet, $theme_root_uri );
204 }
205
206 /**
207  * Retrieve URI of current theme stylesheet.
208  *
209  * The stylesheet file name is 'style.css' which is appended to {@link
210  * get_stylesheet_directory_uri() stylesheet directory URI} path.
211  *
212  * @since 1.5.0
213  *
214  * @return string
215  */
216 function get_stylesheet_uri() {
217         $stylesheet_dir_uri = get_stylesheet_directory_uri();
218         $stylesheet_uri = $stylesheet_dir_uri . '/style.css';
219         /**
220          * Filter the URI of the current theme stylesheet.
221          *
222          * @since 1.5.0
223          *
224          * @param string $stylesheet_uri     Stylesheet URI for the current theme/child theme.
225          * @param string $stylesheet_dir_uri Stylesheet directory URI for the current theme/child theme.
226          */
227         return apply_filters( 'stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri );
228 }
229
230 /**
231  * Retrieve localized stylesheet URI.
232  *
233  * The stylesheet directory for the localized stylesheet files are located, by
234  * default, in the base theme directory. The name of the locale file will be the
235  * locale followed by '.css'. If that does not exist, then the text direction
236  * stylesheet will be checked for existence, for example 'ltr.css'.
237  *
238  * The theme may change the location of the stylesheet directory by either using
239  * the 'stylesheet_directory_uri' filter or the 'locale_stylesheet_uri' filter.
240  * If you want to change the location of the stylesheet files for the entire
241  * WordPress workflow, then change the former. If you just have the locale in a
242  * separate folder, then change the latter.
243  *
244  * @since 2.1.0
245  *
246  * @return string
247  */
248 function get_locale_stylesheet_uri() {
249         global $wp_locale;
250         $stylesheet_dir_uri = get_stylesheet_directory_uri();
251         $dir = get_stylesheet_directory();
252         $locale = get_locale();
253         if ( file_exists("$dir/$locale.css") )
254                 $stylesheet_uri = "$stylesheet_dir_uri/$locale.css";
255         elseif ( !empty($wp_locale->text_direction) && file_exists("$dir/{$wp_locale->text_direction}.css") )
256                 $stylesheet_uri = "$stylesheet_dir_uri/{$wp_locale->text_direction}.css";
257         else
258                 $stylesheet_uri = '';
259         /**
260          * Filter the localized stylesheet URI.
261          *
262          * @since 2.1.0
263          *
264          * @param string $stylesheet_uri     Localized stylesheet URI.
265          * @param string $stylesheet_dir_uri Stylesheet directory URI.
266          */
267         return apply_filters( 'locale_stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri );
268 }
269
270 /**
271  * Retrieve name of the current theme.
272  *
273  * @since 1.5.0
274  * @uses apply_filters() Calls 'template' filter on template option.
275  *
276  * @return string Template name.
277  */
278 function get_template() {
279         /**
280          * Filter the name of the current theme.
281          *
282          * @since 1.5.0
283          *
284          * @param string $template Current theme's directory name.
285          */
286         return apply_filters( 'template', get_option( 'template' ) );
287 }
288
289 /**
290  * Retrieve current theme directory.
291  *
292  * @since 1.5.0
293  *
294  * @return string Template directory path.
295  */
296 function get_template_directory() {
297         $template = get_template();
298         $theme_root = get_theme_root( $template );
299         $template_dir = "$theme_root/$template";
300
301         /**
302          * Filter the current theme directory path.
303          *
304          * @since 1.5.0
305          *
306          * @param string $template_dir The URI of the current theme directory.
307          * @param string $template     Directory name of the current theme.
308          * @param string $theme_root   Absolute path to the themes directory.
309          */
310         return apply_filters( 'template_directory', $template_dir, $template, $theme_root );
311 }
312
313 /**
314  * Retrieve theme directory URI.
315  *
316  * @since 1.5.0
317  *
318  * @return string Template directory URI.
319  */
320 function get_template_directory_uri() {
321         $template = str_replace( '%2F', '/', rawurlencode( get_template() ) );
322         $theme_root_uri = get_theme_root_uri( $template );
323         $template_dir_uri = "$theme_root_uri/$template";
324
325         /**
326          * Filter the current theme directory URI.
327          *
328          * @since 1.5.0
329          *
330          * @param string $template_dir_uri The URI of the current theme directory.
331          * @param string $template         Directory name of the current theme.
332          * @param string $theme_root_uri   The themes root URI.
333          */
334         return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri );
335 }
336
337 /**
338  * Retrieve theme roots.
339  *
340  * @since 2.9.0
341  *
342  * @return array|string An array of theme roots keyed by template/stylesheet or a single theme root if all themes have the same root.
343  */
344 function get_theme_roots() {
345         global $wp_theme_directories;
346
347         if ( count($wp_theme_directories) <= 1 )
348                 return '/themes';
349
350         $theme_roots = get_site_transient( 'theme_roots' );
351         if ( false === $theme_roots ) {
352                 search_theme_directories( true ); // Regenerate the transient.
353                 $theme_roots = get_site_transient( 'theme_roots' );
354         }
355         return $theme_roots;
356 }
357
358 /**
359  * Register a directory that contains themes.
360  *
361  * @since 2.9.0
362  *
363  * @param string $directory Either the full filesystem path to a theme folder or a folder within WP_CONTENT_DIR
364  * @return bool
365  */
366 function register_theme_directory( $directory ) {
367         global $wp_theme_directories;
368
369         if ( ! file_exists( $directory ) ) {
370                 // Try prepending as the theme directory could be relative to the content directory
371                 $directory = WP_CONTENT_DIR . '/' . $directory;
372                 // If this directory does not exist, return and do not register
373                 if ( ! file_exists( $directory ) )
374                         return false;
375         }
376
377         $wp_theme_directories[] = $directory;
378
379         return true;
380 }
381
382 /**
383  * Search all registered theme directories for complete and valid themes.
384  *
385  * @since 2.9.0
386  *
387  * @param bool $force Optional. Whether to force a new directory scan. Defaults to false.
388  * @return array Valid themes found
389  */
390 function search_theme_directories( $force = false ) {
391         global $wp_theme_directories;
392         if ( empty( $wp_theme_directories ) )
393                 return false;
394
395         static $found_themes;
396         if ( ! $force && isset( $found_themes ) )
397                 return $found_themes;
398
399         $found_themes = array();
400
401         $wp_theme_directories = (array) $wp_theme_directories;
402
403         // Set up maybe-relative, maybe-absolute array of theme directories.
404         // We always want to return absolute, but we need to cache relative
405         // to use in get_theme_root().
406         foreach ( $wp_theme_directories as $theme_root ) {
407                 if ( 0 === strpos( $theme_root, WP_CONTENT_DIR ) )
408                         $relative_theme_roots[ str_replace( WP_CONTENT_DIR, '', $theme_root ) ] = $theme_root;
409                 else
410                         $relative_theme_roots[ $theme_root ] = $theme_root;
411         }
412
413         /**
414          * Filter whether to get the cache of the registered theme directories.
415          *
416          * @since 3.4.0
417          *
418          * @param bool   $cache_expiration Whether to get the cache of the theme directories. Default false.
419          * @param string $cache_directory  Directory to be searched for the cache.
420          */
421         if ( $cache_expiration = apply_filters( 'wp_cache_themes_persistently', false, 'search_theme_directories' ) ) {
422                 $cached_roots = get_site_transient( 'theme_roots' );
423                 if ( is_array( $cached_roots ) ) {
424                         foreach ( $cached_roots as $theme_dir => $theme_root ) {
425                                 // A cached theme root is no longer around, so skip it.
426                                 if ( ! isset( $relative_theme_roots[ $theme_root ] ) )
427                                         continue;
428                                 $found_themes[ $theme_dir ] = array(
429                                         'theme_file' => $theme_dir . '/style.css',
430                                         'theme_root' => $relative_theme_roots[ $theme_root ], // Convert relative to absolute.
431                                 );
432                         }
433                         return $found_themes;
434                 }
435                 if ( ! is_int( $cache_expiration ) )
436                         $cache_expiration = 1800; // half hour
437         } else {
438                 $cache_expiration = 1800; // half hour
439         }
440
441         /* Loop the registered theme directories and extract all themes */
442         foreach ( $wp_theme_directories as $theme_root ) {
443
444                 // Start with directories in the root of the current theme directory.
445                 $dirs = @ scandir( $theme_root );
446                 if ( ! $dirs ) {
447                         trigger_error( "$theme_root is not readable", E_USER_NOTICE );
448                         continue;
449                 }
450                 foreach ( $dirs as $dir ) {
451                         if ( ! is_dir( $theme_root . '/' . $dir ) || $dir[0] == '.' || $dir == 'CVS' )
452                                 continue;
453                         if ( file_exists( $theme_root . '/' . $dir . '/style.css' ) ) {
454                                 // wp-content/themes/a-single-theme
455                                 // wp-content/themes is $theme_root, a-single-theme is $dir
456                                 $found_themes[ $dir ] = array(
457                                         'theme_file' => $dir . '/style.css',
458                                         'theme_root' => $theme_root,
459                                 );
460                         } else {
461                                 $found_theme = false;
462                                 // wp-content/themes/a-folder-of-themes/*
463                                 // wp-content/themes is $theme_root, a-folder-of-themes is $dir, then themes are $sub_dirs
464                                 $sub_dirs = @ scandir( $theme_root . '/' . $dir );
465                                 if ( ! $sub_dirs ) {
466                                         trigger_error( "$theme_root/$dir is not readable", E_USER_NOTICE );
467                                         continue;
468                                 }
469                                 foreach ( $sub_dirs as $sub_dir ) {
470                                         if ( ! is_dir( $theme_root . '/' . $dir . '/' . $sub_dir ) || $dir[0] == '.' || $dir == 'CVS' )
471                                                 continue;
472                                         if ( ! file_exists( $theme_root . '/' . $dir . '/' . $sub_dir . '/style.css' ) )
473                                                 continue;
474                                         $found_themes[ $dir . '/' . $sub_dir ] = array(
475                                                 'theme_file' => $dir . '/' . $sub_dir . '/style.css',
476                                                 'theme_root' => $theme_root,
477                                         );
478                                         $found_theme = true;
479                                 }
480                                 // Never mind the above, it's just a theme missing a style.css.
481                                 // Return it; WP_Theme will catch the error.
482                                 if ( ! $found_theme )
483                                         $found_themes[ $dir ] = array(
484                                                 'theme_file' => $dir . '/style.css',
485                                                 'theme_root' => $theme_root,
486                                         );
487                         }
488                 }
489         }
490
491         asort( $found_themes );
492
493         $theme_roots = array();
494         $relative_theme_roots = array_flip( $relative_theme_roots );
495
496         foreach ( $found_themes as $theme_dir => $theme_data ) {
497                 $theme_roots[ $theme_dir ] = $relative_theme_roots[ $theme_data['theme_root'] ]; // Convert absolute to relative.
498         }
499
500         if ( $theme_roots != get_site_transient( 'theme_roots' ) )
501                 set_site_transient( 'theme_roots', $theme_roots, $cache_expiration );
502
503         return $found_themes;
504 }
505
506 /**
507  * Retrieve path to themes directory.
508  *
509  * Does not have trailing slash.
510  *
511  * @since 1.5.0
512  *
513  * @param string $stylesheet_or_template The stylesheet or template name of the theme
514  * @return string Theme path.
515  */
516 function get_theme_root( $stylesheet_or_template = false ) {
517         global $wp_theme_directories;
518
519         if ( $stylesheet_or_template && $theme_root = get_raw_theme_root( $stylesheet_or_template ) ) {
520                 // Always prepend WP_CONTENT_DIR unless the root currently registered as a theme directory.
521                 // This gives relative theme roots the benefit of the doubt when things go haywire.
522                 if ( ! in_array( $theme_root, (array) $wp_theme_directories ) )
523                         $theme_root = WP_CONTENT_DIR . $theme_root;
524         } else {
525                 $theme_root = WP_CONTENT_DIR . '/themes';
526         }
527
528         /**
529          * Filter the absolute path to the themes directory.
530          *
531          * @since 1.5.0
532          *
533          * @param string $theme_root Absolute path to themes directory.
534          */
535         return apply_filters( 'theme_root', $theme_root );
536 }
537
538 /**
539  * Retrieve URI for themes directory.
540  *
541  * Does not have trailing slash.
542  *
543  * @since 1.5.0
544  *
545  * @param string $stylesheet_or_template Optional. The stylesheet or template name of the theme.
546  *      Default is to leverage the main theme root.
547  * @param string $theme_root Optional. The theme root for which calculations will be based, preventing
548  *      the need for a get_raw_theme_root() call.
549  * @return string Themes URI.
550  */
551 function get_theme_root_uri( $stylesheet_or_template = false, $theme_root = false ) {
552         global $wp_theme_directories;
553
554         if ( $stylesheet_or_template && ! $theme_root )
555                 $theme_root = get_raw_theme_root( $stylesheet_or_template );
556
557         if ( $stylesheet_or_template && $theme_root ) {
558                 if ( in_array( $theme_root, (array) $wp_theme_directories ) ) {
559                         // Absolute path. Make an educated guess. YMMV -- but note the filter below.
560                         if ( 0 === strpos( $theme_root, WP_CONTENT_DIR ) )
561                                 $theme_root_uri = content_url( str_replace( WP_CONTENT_DIR, '', $theme_root ) );
562                         elseif ( 0 === strpos( $theme_root, ABSPATH ) )
563                                 $theme_root_uri = site_url( str_replace( ABSPATH, '', $theme_root ) );
564                         elseif ( 0 === strpos( $theme_root, WP_PLUGIN_DIR ) || 0 === strpos( $theme_root, WPMU_PLUGIN_DIR ) )
565                                 $theme_root_uri = plugins_url( basename( $theme_root ), $theme_root );
566                         else
567                                 $theme_root_uri = $theme_root;
568                 } else {
569                         $theme_root_uri = content_url( $theme_root );
570                 }
571         } else {
572                 $theme_root_uri = content_url( 'themes' );
573         }
574
575         /**
576          * Filter the URI for themes directory.
577          *
578          * @since 1.5.0
579          *
580          * @param string $theme_root_uri         The URI for themes directory.
581          * @param string $siteurl                WordPress web address which is set in General Options.
582          * @param string $stylesheet_or_template Stylesheet or template name of the theme.
583          */
584         return apply_filters( 'theme_root_uri', $theme_root_uri, get_option( 'siteurl' ), $stylesheet_or_template );
585 }
586
587 /**
588  * Get the raw theme root relative to the content directory with no filters applied.
589  *
590  * @since 3.1.0
591  *
592  * @param string $stylesheet_or_template The stylesheet or template name of the theme
593  * @param bool $skip_cache Optional. Whether to skip the cache. Defaults to false, meaning the cache is used.
594  * @return string Theme root
595  */
596 function get_raw_theme_root( $stylesheet_or_template, $skip_cache = false ) {
597         global $wp_theme_directories;
598
599         if ( count($wp_theme_directories) <= 1 )
600                 return '/themes';
601
602         $theme_root = false;
603
604         // If requesting the root for the current theme, consult options to avoid calling get_theme_roots()
605         if ( ! $skip_cache ) {
606                 if ( get_option('stylesheet') == $stylesheet_or_template )
607                         $theme_root = get_option('stylesheet_root');
608                 elseif ( get_option('template') == $stylesheet_or_template )
609                         $theme_root = get_option('template_root');
610         }
611
612         if ( empty($theme_root) ) {
613                 $theme_roots = get_theme_roots();
614                 if ( !empty($theme_roots[$stylesheet_or_template]) )
615                         $theme_root = $theme_roots[$stylesheet_or_template];
616         }
617
618         return $theme_root;
619 }
620
621 /**
622  * Display localized stylesheet link element.
623  *
624  * @since 2.1.0
625  */
626 function locale_stylesheet() {
627         $stylesheet = get_locale_stylesheet_uri();
628         if ( empty($stylesheet) )
629                 return;
630         echo '<link rel="stylesheet" href="' . $stylesheet . '" type="text/css" media="screen" />';
631 }
632
633 /**
634  * Start preview theme output buffer.
635  *
636  * Will only perform task if the user has permissions and template and preview
637  * query variables exist.
638  *
639  * @since 2.6.0
640  */
641 function preview_theme() {
642         if ( ! (isset($_GET['template']) && isset($_GET['preview'])) )
643                 return;
644
645         if ( !current_user_can( 'switch_themes' ) )
646                 return;
647
648         // Admin Thickbox requests
649         if ( isset( $_GET['preview_iframe'] ) )
650                 show_admin_bar( false );
651
652         $_GET['template'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['template']);
653
654         if ( validate_file($_GET['template']) )
655                 return;
656
657         add_filter( 'template', '_preview_theme_template_filter' );
658
659         if ( isset($_GET['stylesheet']) ) {
660                 $_GET['stylesheet'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['stylesheet']);
661                 if ( validate_file($_GET['stylesheet']) )
662                         return;
663                 add_filter( 'stylesheet', '_preview_theme_stylesheet_filter' );
664         }
665
666         // Prevent theme mods to current theme being used on theme being previewed
667         add_filter( 'pre_option_theme_mods_' . get_option( 'stylesheet' ), '__return_empty_array' );
668
669         ob_start( 'preview_theme_ob_filter' );
670 }
671 add_action('setup_theme', 'preview_theme');
672
673 /**
674  * Private function to modify the current template when previewing a theme
675  *
676  * @since 2.9.0
677  * @access private
678  *
679  * @return string
680  */
681 function _preview_theme_template_filter() {
682         return isset($_GET['template']) ? $_GET['template'] : '';
683 }
684
685 /**
686  * Private function to modify the current stylesheet when previewing a theme
687  *
688  * @since 2.9.0
689  * @access private
690  *
691  * @return string
692  */
693 function _preview_theme_stylesheet_filter() {
694         return isset($_GET['stylesheet']) ? $_GET['stylesheet'] : '';
695 }
696
697 /**
698  * Callback function for ob_start() to capture all links in the theme.
699  *
700  * @since 2.6.0
701  * @access private
702  *
703  * @param string $content
704  * @return string
705  */
706 function preview_theme_ob_filter( $content ) {
707         return preg_replace_callback( "|(<a.*?href=([\"']))(.*?)([\"'].*?>)|", 'preview_theme_ob_filter_callback', $content );
708 }
709
710 /**
711  * Manipulates preview theme links in order to control and maintain location.
712  *
713  * Callback function for preg_replace_callback() to accept and filter matches.
714  *
715  * @since 2.6.0
716  * @access private
717  *
718  * @param array $matches
719  * @return string
720  */
721 function preview_theme_ob_filter_callback( $matches ) {
722         if ( strpos($matches[4], 'onclick') !== false )
723                 $matches[4] = preg_replace('#onclick=([\'"]).*?(?<!\\\)\\1#i', '', $matches[4]); //Strip out any onclicks from rest of <a>. (?<!\\\) means to ignore the '" if it's escaped by \  to prevent breaking mid-attribute.
724         if (
725                 ( false !== strpos($matches[3], '/wp-admin/') )
726         ||
727                 ( false !== strpos( $matches[3], '://' ) && 0 !== strpos( $matches[3], home_url() ) )
728         ||
729                 ( false !== strpos($matches[3], '/feed/') )
730         ||
731                 ( false !== strpos($matches[3], '/trackback/') )
732         )
733                 return $matches[1] . "#$matches[2] onclick=$matches[2]return false;" . $matches[4];
734
735         $stylesheet = isset( $_GET['stylesheet'] ) ? $_GET['stylesheet'] : '';
736         $template   = isset( $_GET['template'] )   ? $_GET['template']   : '';
737
738         $link = add_query_arg( array( 'preview' => 1, 'template' => $template, 'stylesheet' => $stylesheet, 'preview_iframe' => 1 ), $matches[3] );
739         if ( 0 === strpos($link, 'preview=1') )
740                 $link = "?$link";
741         return $matches[1] . esc_attr( $link ) . $matches[4];
742 }
743
744 /**
745  * Switches the theme.
746  *
747  * Accepts one argument: $stylesheet of the theme. It also accepts an additional function signature
748  * of two arguments: $template then $stylesheet. This is for backwards compatibility.
749  *
750  * @since 2.5.0
751  *
752  * @param string $stylesheet Stylesheet name
753  */
754 function switch_theme( $stylesheet ) {
755         global $wp_theme_directories, $wp_customize, $sidebars_widgets;
756
757         $_sidebars_widgets = null;
758         if ( 'wp_ajax_customize_save' === current_action() ) {
759                 $_sidebars_widgets = $wp_customize->post_value( $wp_customize->get_setting( 'old_sidebars_widgets_data' ) );
760         } elseif ( is_array( $sidebars_widgets ) ) {
761                 $_sidebars_widgets = $sidebars_widgets;
762         }
763
764         if ( is_array( $_sidebars_widgets ) ) {
765                 set_theme_mod( 'sidebars_widgets', array( 'time' => time(), 'data' => $_sidebars_widgets ) );
766         }
767
768         $old_theme  = wp_get_theme();
769         $new_theme = wp_get_theme( $stylesheet );
770
771         if ( func_num_args() > 1 ) {
772                 $template = $stylesheet;
773                 $stylesheet = func_get_arg( 1 );
774         } else {
775                 $template = $new_theme->get_template();
776         }
777
778         update_option( 'template', $template );
779         update_option( 'stylesheet', $stylesheet );
780
781         if ( count( $wp_theme_directories ) > 1 ) {
782                 update_option( 'template_root', get_raw_theme_root( $template, true ) );
783                 update_option( 'stylesheet_root', get_raw_theme_root( $stylesheet, true ) );
784         } else {
785                 delete_option( 'template_root' );
786                 delete_option( 'stylesheet_root' );
787         }
788
789         $new_name  = $new_theme->get('Name');
790
791         update_option( 'current_theme', $new_name );
792
793         // Migrate from the old mods_{name} option to theme_mods_{slug}.
794         if ( is_admin() && false === get_option( 'theme_mods_' . $stylesheet ) ) {
795                 $default_theme_mods = (array) get_option( 'mods_' . $new_name );
796                 add_option( "theme_mods_$stylesheet", $default_theme_mods );
797         } else {
798                 /*
799                  * Since retrieve_widgets() is called when initializing the customizer theme,
800                  * we need to to remove the theme mods to avoid overwriting changes made via
801                  * the widget customizer when accessing wp-admin/widgets.php.
802                  */
803                 if ( 'wp_ajax_customize_save' === current_action() ) {
804                         remove_theme_mod( 'sidebars_widgets' );
805                 }
806         }
807
808         update_option( 'theme_switched', $old_theme->get_stylesheet() );
809         /**
810          * Fires after the theme is switched.
811          *
812          * @since 1.5.0
813          *
814          * @param string   $new_name  Name of the new theme.
815          * @param WP_Theme $new_theme WP_Theme instance of the new theme.
816          */
817         do_action( 'switch_theme', $new_name, $new_theme );
818 }
819
820 /**
821  * Checks that current theme files 'index.php' and 'style.css' exists.
822  *
823  * Does not check the default theme, which is the fallback and should always exist.
824  * Will switch theme to the fallback theme if current theme does not validate.
825  * You can use the 'validate_current_theme' filter to return false to
826  * disable this functionality.
827  *
828  * @since 1.5.0
829  * @see WP_DEFAULT_THEME
830  *
831  * @return bool
832  */
833 function validate_current_theme() {
834         /**
835          * Filter whether to validate the current theme.
836          *
837          * @since 2.7.0
838          *
839          * @param bool true Validation flag to check the current theme.
840          */
841         if ( defined('WP_INSTALLING') || ! apply_filters( 'validate_current_theme', true ) )
842                 return true;
843
844         if ( get_template() != WP_DEFAULT_THEME && !file_exists(get_template_directory() . '/index.php') ) {
845                 switch_theme( WP_DEFAULT_THEME );
846                 return false;
847         }
848
849         if ( get_stylesheet() != WP_DEFAULT_THEME && !file_exists(get_template_directory() . '/style.css') ) {
850                 switch_theme( WP_DEFAULT_THEME );
851                 return false;
852         }
853
854         if ( is_child_theme() && ! file_exists( get_stylesheet_directory() . '/style.css' ) ) {
855                 switch_theme( WP_DEFAULT_THEME );
856                 return false;
857         }
858
859         return true;
860 }
861
862 /**
863  * Retrieve all theme modifications.
864  *
865  * @since 3.1.0
866  *
867  * @return array Theme modifications.
868  */
869 function get_theme_mods() {
870         $theme_slug = get_option( 'stylesheet' );
871         if ( false === ( $mods = get_option( "theme_mods_$theme_slug" ) ) ) {
872                 $theme_name = get_option( 'current_theme' );
873                 if ( false === $theme_name )
874                         $theme_name = wp_get_theme()->get('Name');
875                 $mods = get_option( "mods_$theme_name" ); // Deprecated location.
876                 if ( is_admin() && false !== $mods ) {
877                         update_option( "theme_mods_$theme_slug", $mods );
878                         delete_option( "mods_$theme_name" );
879                 }
880         }
881         return $mods;
882 }
883
884 /**
885  * Retrieve theme modification value for the current theme.
886  *
887  * If the modification name does not exist, then the $default will be passed
888  * through {@link http://php.net/sprintf sprintf()} PHP function with the first
889  * string the template directory URI and the second string the stylesheet
890  * directory URI.
891  *
892  * @since 2.1.0
893  *
894  * @param string $name Theme modification name.
895  * @param bool|string $default
896  * @return string
897  */
898 function get_theme_mod( $name, $default = false ) {
899         $mods = get_theme_mods();
900
901         if ( isset( $mods[$name] ) ) {
902                 /**
903                  * Filter the theme modification, or 'theme_mod', value.
904                  *
905                  * The dynamic portion of the hook name, $name, refers to
906                  * the key name of the modification array. For example,
907                  * 'header_textcolor', 'header_image', and so on depending
908                  * on the theme options.
909                  *
910                  * @since 2.2.0
911                  *
912                  * @param string $current_mod The value of the current theme modification.
913                  */
914                 return apply_filters( "theme_mod_{$name}", $mods[$name] );
915         }
916
917         if ( is_string( $default ) )
918                 $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
919
920         /** This filter is documented in wp-includes/theme.php */
921         return apply_filters( "theme_mod_{$name}", $default );
922 }
923
924 /**
925  * Update theme modification value for the current theme.
926  *
927  * @since 2.1.0
928  *
929  * @param string $name Theme modification name.
930  * @param string $value theme modification value.
931  */
932 function set_theme_mod( $name, $value ) {
933         $mods = get_theme_mods();
934         $old_value = isset( $mods[ $name ] ) ? $mods[ $name ] : false;
935
936         /**
937          * Filter the theme mod value on save.
938          *
939          * The dynamic portion of the hook name, $name, refers to the key name of
940          * the modification array. For example, 'header_textcolor', 'header_image',
941          * and so on depending on the theme options.
942          *
943          * @since 3.9.0
944          *
945          * @param string $value     The new value of the theme mod.
946          * @param string $old_value The current value of the theme mod.
947          */
948         $mods[ $name ] = apply_filters( "pre_set_theme_mod_$name", $value, $old_value );
949
950         $theme = get_option( 'stylesheet' );
951         update_option( "theme_mods_$theme", $mods );
952 }
953
954 /**
955  * Remove theme modification name from current theme list.
956  *
957  * If removing the name also removes all elements, then the entire option will
958  * be removed.
959  *
960  * @since 2.1.0
961  *
962  * @param string $name Theme modification name.
963  * @return null
964  */
965 function remove_theme_mod( $name ) {
966         $mods = get_theme_mods();
967
968         if ( ! isset( $mods[ $name ] ) )
969                 return;
970
971         unset( $mods[ $name ] );
972
973         if ( empty( $mods ) )
974                 return remove_theme_mods();
975
976         $theme = get_option( 'stylesheet' );
977         update_option( "theme_mods_$theme", $mods );
978 }
979
980 /**
981  * Remove theme modifications option for current theme.
982  *
983  * @since 2.1.0
984  */
985 function remove_theme_mods() {
986         delete_option( 'theme_mods_' . get_option( 'stylesheet' ) );
987
988         // Old style.
989         $theme_name = get_option( 'current_theme' );
990         if ( false === $theme_name )
991                 $theme_name = wp_get_theme()->get('Name');
992         delete_option( 'mods_' . $theme_name );
993 }
994
995 /**
996  * Retrieve text color for custom header.
997  *
998  * @since 2.1.0
999  *
1000  * @return string
1001  */
1002 function get_header_textcolor() {
1003         return get_theme_mod('header_textcolor', get_theme_support( 'custom-header', 'default-text-color' ) );
1004 }
1005
1006 /**
1007  * Display text color for custom header.
1008  *
1009  * @since 2.1.0
1010  */
1011 function header_textcolor() {
1012         echo get_header_textcolor();
1013 }
1014
1015 /**
1016  * Whether to display the header text.
1017  *
1018  * @since 3.4.0
1019  *
1020  * @return bool
1021  */
1022 function display_header_text() {
1023         if ( ! current_theme_supports( 'custom-header', 'header-text' ) )
1024                 return false;
1025
1026         $text_color = get_theme_mod( 'header_textcolor', get_theme_support( 'custom-header', 'default-text-color' ) );
1027         return 'blank' != $text_color;
1028 }
1029
1030 /**
1031  * Retrieve header image for custom header.
1032  *
1033  * @since 2.1.0
1034  *
1035  * @return string
1036  */
1037 function get_header_image() {
1038         $url = get_theme_mod( 'header_image', get_theme_support( 'custom-header', 'default-image' ) );
1039
1040         if ( 'remove-header' == $url )
1041                 return false;
1042
1043         if ( is_random_header_image() )
1044                 $url = get_random_header_image();
1045
1046         return esc_url_raw( set_url_scheme( $url ) );
1047 }
1048
1049 /**
1050  * Get random header image data from registered images in theme.
1051  *
1052  * @since 3.4.0
1053  *
1054  * @access private
1055  *
1056  * @return string Path to header image
1057  */
1058
1059 function _get_random_header_data() {
1060         static $_wp_random_header;
1061
1062         if ( empty( $_wp_random_header ) ) {
1063                 global $_wp_default_headers;
1064                 $header_image_mod = get_theme_mod( 'header_image', '' );
1065                 $headers = array();
1066
1067                 if ( 'random-uploaded-image' == $header_image_mod )
1068                         $headers = get_uploaded_header_images();
1069                 elseif ( ! empty( $_wp_default_headers ) ) {
1070                         if ( 'random-default-image' == $header_image_mod ) {
1071                                 $headers = $_wp_default_headers;
1072                         } else {
1073                                 if ( current_theme_supports( 'custom-header', 'random-default' ) )
1074                                         $headers = $_wp_default_headers;
1075                         }
1076                 }
1077
1078                 if ( empty( $headers ) )
1079                         return new stdClass;
1080
1081                 $_wp_random_header = (object) $headers[ array_rand( $headers ) ];
1082
1083                 $_wp_random_header->url =  sprintf( $_wp_random_header->url, get_template_directory_uri(), get_stylesheet_directory_uri() );
1084                 $_wp_random_header->thumbnail_url =  sprintf( $_wp_random_header->thumbnail_url, get_template_directory_uri(), get_stylesheet_directory_uri() );
1085         }
1086         return $_wp_random_header;
1087 }
1088
1089 /**
1090  * Get random header image url from registered images in theme.
1091  *
1092  * @since 3.2.0
1093  *
1094  * @return string Path to header image
1095  */
1096
1097 function get_random_header_image() {
1098         $random_image = _get_random_header_data();
1099         if ( empty( $random_image->url ) )
1100                 return '';
1101         return $random_image->url;
1102 }
1103
1104 /**
1105  * Check if random header image is in use.
1106  *
1107  * Always true if user expressly chooses the option in Appearance > Header.
1108  * Also true if theme has multiple header images registered, no specific header image
1109  * is chosen, and theme turns on random headers with add_theme_support().
1110  *
1111  * @since 3.2.0
1112  *
1113  * @param string $type The random pool to use. any|default|uploaded
1114  * @return boolean
1115  */
1116 function is_random_header_image( $type = 'any' ) {
1117         $header_image_mod = get_theme_mod( 'header_image', get_theme_support( 'custom-header', 'default-image' ) );
1118
1119         if ( 'any' == $type ) {
1120                 if ( 'random-default-image' == $header_image_mod || 'random-uploaded-image' == $header_image_mod || ( '' != get_random_header_image() && empty( $header_image_mod ) ) )
1121                         return true;
1122         } else {
1123                 if ( "random-$type-image" == $header_image_mod )
1124                         return true;
1125                 elseif ( 'default' == $type && empty( $header_image_mod ) && '' != get_random_header_image() )
1126                         return true;
1127         }
1128
1129         return false;
1130 }
1131
1132 /**
1133  * Display header image URL.
1134  *
1135  * @since 2.1.0
1136  */
1137 function header_image() {
1138         echo esc_url( get_header_image() );
1139 }
1140
1141 /**
1142  * Get the header images uploaded for the current theme.
1143  *
1144  * @since 3.2.0
1145  *
1146  * @return array
1147  */
1148 function get_uploaded_header_images() {
1149         $header_images = array();
1150
1151         // @todo caching
1152         $headers = get_posts( array( 'post_type' => 'attachment', 'meta_key' => '_wp_attachment_is_custom_header', 'meta_value' => get_option('stylesheet'), 'orderby' => 'none', 'nopaging' => true ) );
1153
1154         if ( empty( $headers ) )
1155                 return array();
1156
1157         foreach ( (array) $headers as $header ) {
1158                 $url = esc_url_raw( wp_get_attachment_url( $header->ID ) );
1159                 $header_data = wp_get_attachment_metadata( $header->ID );
1160                 $header_index = basename($url);
1161                 $header_images[$header_index] = array();
1162                 $header_images[$header_index]['attachment_id'] =  $header->ID;
1163                 $header_images[$header_index]['url'] =  $url;
1164                 $header_images[$header_index]['thumbnail_url'] =  $url;
1165                 if ( isset( $header_data['width'] ) )
1166                         $header_images[$header_index]['width'] = $header_data['width'];
1167                 if ( isset( $header_data['height'] ) )
1168                         $header_images[$header_index]['height'] = $header_data['height'];
1169         }
1170
1171         return $header_images;
1172 }
1173
1174 /**
1175  * Get the header image data.
1176  *
1177  * @since 3.4.0
1178  *
1179  * @return object
1180  */
1181 function get_custom_header() {
1182         global $_wp_default_headers;
1183
1184         if ( is_random_header_image() ) {
1185                 $data = _get_random_header_data();
1186         } else {
1187                 $data = get_theme_mod( 'header_image_data' );
1188                 if ( ! $data && current_theme_supports( 'custom-header', 'default-image' ) ) {
1189                         $directory_args = array( get_template_directory_uri(), get_stylesheet_directory_uri() );
1190                         $data = array();
1191                         $data['url'] = $data['thumbnail_url'] = vsprintf( get_theme_support( 'custom-header', 'default-image' ), $directory_args );
1192                         if ( ! empty( $_wp_default_headers ) ) {
1193                                 foreach ( (array) $_wp_default_headers as $default_header ) {
1194                                         $url = vsprintf( $default_header['url'], $directory_args );
1195                                         if ( $data['url'] == $url ) {
1196                                                 $data = $default_header;
1197                                                 $data['url'] = $url;
1198                                                 $data['thumbnail_url'] = vsprintf( $data['thumbnail_url'], $directory_args );
1199                                                 break;
1200                                         }
1201                                 }
1202                         }
1203                 }
1204         }
1205
1206         $default = array(
1207                 'url'           => '',
1208                 'thumbnail_url' => '',
1209                 'width'         => get_theme_support( 'custom-header', 'width' ),
1210                 'height'        => get_theme_support( 'custom-header', 'height' ),
1211         );
1212         return (object) wp_parse_args( $data, $default );
1213 }
1214
1215 /**
1216  * Register a selection of default headers to be displayed by the custom header admin UI.
1217  *
1218  * @since 3.0.0
1219  *
1220  * @param array $headers Array of headers keyed by a string id. The ids point to arrays containing 'url', 'thumbnail_url', and 'description' keys.
1221  */
1222 function register_default_headers( $headers ) {
1223         global $_wp_default_headers;
1224
1225         $_wp_default_headers = array_merge( (array) $_wp_default_headers, (array) $headers );
1226 }
1227
1228 /**
1229  * Unregister default headers.
1230  *
1231  * This function must be called after register_default_headers() has already added the
1232  * header you want to remove.
1233  *
1234  * @see register_default_headers()
1235  * @since 3.0.0
1236  *
1237  * @param string|array $header The header string id (key of array) to remove, or an array thereof.
1238  * @return bool|void A single header returns true on success, false on failure.
1239  *                   There is currently no return value for multiple headers.
1240  */
1241 function unregister_default_headers( $header ) {
1242         global $_wp_default_headers;
1243         if ( is_array( $header ) ) {
1244                 array_map( 'unregister_default_headers', $header );
1245         } elseif ( isset( $_wp_default_headers[ $header ] ) ) {
1246                 unset( $_wp_default_headers[ $header ] );
1247                 return true;
1248         } else {
1249                 return false;
1250         }
1251 }
1252
1253 /**
1254  * Retrieve background image for custom background.
1255  *
1256  * @since 3.0.0
1257  *
1258  * @return string
1259  */
1260 function get_background_image() {
1261         return get_theme_mod('background_image', get_theme_support( 'custom-background', 'default-image' ) );
1262 }
1263
1264 /**
1265  * Display background image path.
1266  *
1267  * @since 3.0.0
1268  */
1269 function background_image() {
1270         echo get_background_image();
1271 }
1272
1273 /**
1274  * Retrieve value for custom background color.
1275  *
1276  * @since 3.0.0
1277  *
1278  * @return string
1279  */
1280 function get_background_color() {
1281         return get_theme_mod('background_color', get_theme_support( 'custom-background', 'default-color' ) );
1282 }
1283
1284 /**
1285  * Display background color value.
1286  *
1287  * @since 3.0.0
1288  */
1289 function background_color() {
1290         echo get_background_color();
1291 }
1292
1293 /**
1294  * Default custom background callback.
1295  *
1296  * @since 3.0.0
1297  * @access protected
1298  */
1299 function _custom_background_cb() {
1300         // $background is the saved custom image, or the default image.
1301         $background = set_url_scheme( get_background_image() );
1302
1303         // $color is the saved custom color.
1304         // A default has to be specified in style.css. It will not be printed here.
1305         $color = get_background_color();
1306
1307         if ( $color === get_theme_support( 'custom-background', 'default-color' ) ) {
1308                 $color = false;
1309         }
1310
1311         if ( ! $background && ! $color )
1312                 return;
1313
1314         $style = $color ? "background-color: #$color;" : '';
1315
1316         if ( $background ) {
1317                 $image = " background-image: url('$background');";
1318
1319                 $repeat = get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) );
1320                 if ( ! in_array( $repeat, array( 'no-repeat', 'repeat-x', 'repeat-y', 'repeat' ) ) )
1321                         $repeat = 'repeat';
1322                 $repeat = " background-repeat: $repeat;";
1323
1324                 $position = get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );
1325                 if ( ! in_array( $position, array( 'center', 'right', 'left' ) ) )
1326                         $position = 'left';
1327                 $position = " background-position: top $position;";
1328
1329                 $attachment = get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) );
1330                 if ( ! in_array( $attachment, array( 'fixed', 'scroll' ) ) )
1331                         $attachment = 'scroll';
1332                 $attachment = " background-attachment: $attachment;";
1333
1334                 $style .= $image . $repeat . $position . $attachment;
1335         }
1336 ?>
1337 <style type="text/css" id="custom-background-css">
1338 body.custom-background { <?php echo trim( $style ); ?> }
1339 </style>
1340 <?php
1341 }
1342
1343 /**
1344  * Add callback for custom TinyMCE editor stylesheets.
1345  *
1346  * The parameter $stylesheet is the name of the stylesheet, relative to
1347  * the theme root. It also accepts an array of stylesheets.
1348  * It is optional and defaults to 'editor-style.css'.
1349  *
1350  * This function automatically adds another stylesheet with -rtl prefix, e.g. editor-style-rtl.css.
1351  * If that file doesn't exist, it is removed before adding the stylesheet(s) to TinyMCE.
1352  * If an array of stylesheets is passed to add_editor_style(),
1353  * RTL is only added for the first stylesheet.
1354  *
1355  * Since version 3.4 the TinyMCE body has .rtl CSS class.
1356  * It is a better option to use that class and add any RTL styles to the main stylesheet.
1357  *
1358  * @since 3.0.0
1359  *
1360  * @param mixed $stylesheet Optional. Stylesheet name or array thereof, relative to theme root.
1361  *      Defaults to 'editor-style.css'
1362  */
1363 function add_editor_style( $stylesheet = 'editor-style.css' ) {
1364
1365         add_theme_support( 'editor-style' );
1366
1367         if ( ! is_admin() )
1368                 return;
1369
1370         global $editor_styles;
1371         $editor_styles = (array) $editor_styles;
1372         $stylesheet    = (array) $stylesheet;
1373         if ( is_rtl() ) {
1374                 $rtl_stylesheet = str_replace('.css', '-rtl.css', $stylesheet[0]);
1375                 $stylesheet[] = $rtl_stylesheet;
1376         }
1377
1378         $editor_styles = array_merge( $editor_styles, $stylesheet );
1379 }
1380
1381 /**
1382  * Removes all visual editor stylesheets.
1383  *
1384  * @since 3.1.0
1385  *
1386  * @return bool True on success, false if there were no stylesheets to remove.
1387  */
1388 function remove_editor_styles() {
1389         if ( ! current_theme_supports( 'editor-style' ) )
1390                 return false;
1391         _remove_theme_support( 'editor-style' );
1392         if ( is_admin() )
1393                 $GLOBALS['editor_styles'] = array();
1394         return true;
1395 }
1396
1397 /**
1398  * Allows a theme to register its support of a certain feature
1399  *
1400  * Must be called in the theme's functions.php file to work.
1401  * If attached to a hook, it must be after_setup_theme.
1402  * The init hook may be too late for some features.
1403  *
1404  * @since 2.9.0
1405  *
1406  * @param string $feature The feature being added.
1407  * @return void|bool False on failure, void otherwise.
1408  */
1409 function add_theme_support( $feature ) {
1410         global $_wp_theme_features;
1411
1412         if ( func_num_args() == 1 )
1413                 $args = true;
1414         else
1415                 $args = array_slice( func_get_args(), 1 );
1416
1417         switch ( $feature ) {
1418                 case 'post-formats' :
1419                         if ( is_array( $args[0] ) )
1420                                 $args[0] = array_intersect( $args[0], array_keys( get_post_format_slugs() ) );
1421                         break;
1422
1423                 case 'html5' :
1424                         // You can't just pass 'html5', you need to pass an array of types.
1425                         if ( empty( $args[0] ) ) {
1426                                 // Build an array of types for back-compat.
1427                                 $args = array( 0 => array( 'comment-list', 'comment-form', 'search-form' ) );
1428                         } elseif ( ! is_array( $args[0] ) ) {
1429                                 _doing_it_wrong( "add_theme_support( 'html5' )", 'You need to pass an array of types.', '3.6.1' );
1430                                 return false;
1431                         }
1432
1433                         // Calling 'html5' again merges, rather than overwrites.
1434                         if ( isset( $_wp_theme_features['html5'] ) )
1435                                 $args[0] = array_merge( $_wp_theme_features['html5'][0], $args[0] );
1436                         break;
1437
1438                 case 'custom-header-uploads' :
1439                         return add_theme_support( 'custom-header', array( 'uploads' => true ) );
1440                         break;
1441
1442                 case 'custom-header' :
1443                         if ( ! is_array( $args ) )
1444                                 $args = array( 0 => array() );
1445
1446                         $defaults = array(
1447                                 'default-image' => '',
1448                                 'random-default' => false,
1449                                 'width' => 0,
1450                                 'height' => 0,
1451                                 'flex-height' => false,
1452                                 'flex-width' => false,
1453                                 'default-text-color' => '',
1454                                 'header-text' => true,
1455                                 'uploads' => true,
1456                                 'wp-head-callback' => '',
1457                                 'admin-head-callback' => '',
1458                                 'admin-preview-callback' => '',
1459                         );
1460
1461                         $jit = isset( $args[0]['__jit'] );
1462                         unset( $args[0]['__jit'] );
1463
1464                         // Merge in data from previous add_theme_support() calls.
1465                         // The first value registered wins. (A child theme is set up first.)
1466                         if ( isset( $_wp_theme_features['custom-header'] ) )
1467                                 $args[0] = wp_parse_args( $_wp_theme_features['custom-header'][0], $args[0] );
1468
1469                         // Load in the defaults at the end, as we need to insure first one wins.
1470                         // This will cause all constants to be defined, as each arg will then be set to the default.
1471                         if ( $jit )
1472                                 $args[0] = wp_parse_args( $args[0], $defaults );
1473
1474                         // If a constant was defined, use that value. Otherwise, define the constant to ensure
1475                         // the constant is always accurate (and is not defined later,  overriding our value).
1476                         // As stated above, the first value wins.
1477                         // Once we get to wp_loaded (just-in-time), define any constants we haven't already.
1478                         // Constants are lame. Don't reference them. This is just for backwards compatibility.
1479
1480                         if ( defined( 'NO_HEADER_TEXT' ) )
1481                                 $args[0]['header-text'] = ! NO_HEADER_TEXT;
1482                         elseif ( isset( $args[0]['header-text'] ) )
1483                                 define( 'NO_HEADER_TEXT', empty( $args[0]['header-text'] ) );
1484
1485                         if ( defined( 'HEADER_IMAGE_WIDTH' ) )
1486                                 $args[0]['width'] = (int) HEADER_IMAGE_WIDTH;
1487                         elseif ( isset( $args[0]['width'] ) )
1488                                 define( 'HEADER_IMAGE_WIDTH', (int) $args[0]['width'] );
1489
1490                         if ( defined( 'HEADER_IMAGE_HEIGHT' ) )
1491                                 $args[0]['height'] = (int) HEADER_IMAGE_HEIGHT;
1492                         elseif ( isset( $args[0]['height'] ) )
1493                                 define( 'HEADER_IMAGE_HEIGHT', (int) $args[0]['height'] );
1494
1495                         if ( defined( 'HEADER_TEXTCOLOR' ) )
1496                                 $args[0]['default-text-color'] = HEADER_TEXTCOLOR;
1497                         elseif ( isset( $args[0]['default-text-color'] ) )
1498                                 define( 'HEADER_TEXTCOLOR', $args[0]['default-text-color'] );
1499
1500                         if ( defined( 'HEADER_IMAGE' ) )
1501                                 $args[0]['default-image'] = HEADER_IMAGE;
1502                         elseif ( isset( $args[0]['default-image'] ) )
1503                                 define( 'HEADER_IMAGE', $args[0]['default-image'] );
1504
1505                         if ( $jit && ! empty( $args[0]['default-image'] ) )
1506                                 $args[0]['random-default'] = false;
1507
1508                         // If headers are supported, and we still don't have a defined width or height,
1509                         // we have implicit flex sizes.
1510                         if ( $jit ) {
1511                                 if ( empty( $args[0]['width'] ) && empty( $args[0]['flex-width'] ) )
1512                                         $args[0]['flex-width'] = true;
1513                                 if ( empty( $args[0]['height'] ) && empty( $args[0]['flex-height'] ) )
1514                                         $args[0]['flex-height'] = true;
1515                         }
1516
1517                         break;
1518
1519                 case 'custom-background' :
1520                         if ( ! is_array( $args ) )
1521                                 $args = array( 0 => array() );
1522
1523                         $defaults = array(
1524                                 'default-image'          => '',
1525                                 'default-repeat'         => 'repeat',
1526                                 'default-position-x'     => 'left',
1527                                 'default-attachment'     => 'scroll',
1528                                 'default-color'          => '',
1529                                 'wp-head-callback'       => '_custom_background_cb',
1530                                 'admin-head-callback'    => '',
1531                                 'admin-preview-callback' => '',
1532                         );
1533
1534                         $jit = isset( $args[0]['__jit'] );
1535                         unset( $args[0]['__jit'] );
1536
1537                         // Merge in data from previous add_theme_support() calls. The first value registered wins.
1538                         if ( isset( $_wp_theme_features['custom-background'] ) )
1539                                 $args[0] = wp_parse_args( $_wp_theme_features['custom-background'][0], $args[0] );
1540
1541                         if ( $jit )
1542                                 $args[0] = wp_parse_args( $args[0], $defaults );
1543
1544                         if ( defined( 'BACKGROUND_COLOR' ) )
1545                                 $args[0]['default-color'] = BACKGROUND_COLOR;
1546                         elseif ( isset( $args[0]['default-color'] ) || $jit )
1547                                 define( 'BACKGROUND_COLOR', $args[0]['default-color'] );
1548
1549                         if ( defined( 'BACKGROUND_IMAGE' ) )
1550                                 $args[0]['default-image'] = BACKGROUND_IMAGE;
1551                         elseif ( isset( $args[0]['default-image'] ) || $jit )
1552                                 define( 'BACKGROUND_IMAGE', $args[0]['default-image'] );
1553
1554                         break;
1555         }
1556
1557         $_wp_theme_features[ $feature ] = $args;
1558 }
1559
1560 /**
1561  * Registers the internal custom header and background routines.
1562  *
1563  * @since 3.4.0
1564  * @access private
1565  */
1566 function _custom_header_background_just_in_time() {
1567         global $custom_image_header, $custom_background;
1568
1569         if ( current_theme_supports( 'custom-header' ) ) {
1570                 // In case any constants were defined after an add_custom_image_header() call, re-run.
1571                 add_theme_support( 'custom-header', array( '__jit' => true ) );
1572
1573                 $args = get_theme_support( 'custom-header' );
1574                 if ( $args[0]['wp-head-callback'] )
1575                         add_action( 'wp_head', $args[0]['wp-head-callback'] );
1576
1577                 if ( is_admin() ) {
1578                         require_once( ABSPATH . 'wp-admin/custom-header.php' );
1579                         $custom_image_header = new Custom_Image_Header( $args[0]['admin-head-callback'], $args[0]['admin-preview-callback'] );
1580                 }
1581         }
1582
1583         if ( current_theme_supports( 'custom-background' ) ) {
1584                 // In case any constants were defined after an add_custom_background() call, re-run.
1585                 add_theme_support( 'custom-background', array( '__jit' => true ) );
1586
1587                 $args = get_theme_support( 'custom-background' );
1588                 add_action( 'wp_head', $args[0]['wp-head-callback'] );
1589
1590                 if ( is_admin() ) {
1591                         require_once( ABSPATH . 'wp-admin/custom-background.php' );
1592                         $custom_background = new Custom_Background( $args[0]['admin-head-callback'], $args[0]['admin-preview-callback'] );
1593                 }
1594         }
1595 }
1596 add_action( 'wp_loaded', '_custom_header_background_just_in_time' );
1597
1598 /**
1599  * Gets the theme support arguments passed when registering that support
1600  *
1601  * @since 3.1.0
1602  *
1603  * @param string $feature the feature to check
1604  * @return array The array of extra arguments
1605  */
1606 function get_theme_support( $feature ) {
1607         global $_wp_theme_features;
1608         if ( ! isset( $_wp_theme_features[ $feature ] ) )
1609                 return false;
1610
1611         if ( func_num_args() <= 1 )
1612                 return $_wp_theme_features[ $feature ];
1613
1614         $args = array_slice( func_get_args(), 1 );
1615         switch ( $feature ) {
1616                 case 'custom-header' :
1617                 case 'custom-background' :
1618                         if ( isset( $_wp_theme_features[ $feature ][0][ $args[0] ] ) )
1619                                 return $_wp_theme_features[ $feature ][0][ $args[0] ];
1620                         return false;
1621                         break;
1622                 default :
1623                         return $_wp_theme_features[ $feature ];
1624                         break;
1625         }
1626 }
1627
1628 /**
1629  * Allows a theme to de-register its support of a certain feature
1630  *
1631  * Should be called in the theme's functions.php file. Generally would
1632  * be used for child themes to override support from the parent theme.
1633  *
1634  * @since 3.0.0
1635  * @see add_theme_support()
1636  * @param string $feature the feature being added
1637  * @return bool Whether feature was removed.
1638  */
1639 function remove_theme_support( $feature ) {
1640         // Blacklist: for internal registrations not used directly by themes.
1641         if ( in_array( $feature, array( 'editor-style', 'widgets', 'menus' ) ) )
1642                 return false;
1643
1644         return _remove_theme_support( $feature );
1645 }
1646
1647 /**
1648  * Do not use. Removes theme support internally, ignorant of the blacklist.
1649  *
1650  * @access private
1651  * @since 3.1.0
1652  */
1653 function _remove_theme_support( $feature ) {
1654         global $_wp_theme_features;
1655
1656         switch ( $feature ) {
1657                 case 'custom-header-uploads' :
1658                         if ( ! isset( $_wp_theme_features['custom-header'] ) )
1659                                 return false;
1660                         add_theme_support( 'custom-header', array( 'uploads' => false ) );
1661                         return; // Do not continue - custom-header-uploads no longer exists.
1662         }
1663
1664         if ( ! isset( $_wp_theme_features[ $feature ] ) )
1665                 return false;
1666
1667         switch ( $feature ) {
1668                 case 'custom-header' :
1669                         if ( ! did_action( 'wp_loaded' ) )
1670                                 break;
1671                         $support = get_theme_support( 'custom-header' );
1672                         if ( $support[0]['wp-head-callback'] )
1673                                 remove_action( 'wp_head', $support[0]['wp-head-callback'] );
1674                         remove_action( 'admin_menu', array( $GLOBALS['custom_image_header'], 'init' ) );
1675                         unset( $GLOBALS['custom_image_header'] );
1676                         break;
1677
1678                 case 'custom-background' :
1679                         if ( ! did_action( 'wp_loaded' ) )
1680                                 break;
1681                         $support = get_theme_support( 'custom-background' );
1682                         remove_action( 'wp_head', $support[0]['wp-head-callback'] );
1683                         remove_action( 'admin_menu', array( $GLOBALS['custom_background'], 'init' ) );
1684                         unset( $GLOBALS['custom_background'] );
1685                         break;
1686         }
1687
1688         unset( $_wp_theme_features[ $feature ] );
1689         return true;
1690 }
1691
1692 /**
1693  * Checks a theme's support for a given feature
1694  *
1695  * @since 2.9.0
1696  * @param string $feature the feature being checked
1697  * @return boolean
1698  */
1699 function current_theme_supports( $feature ) {
1700         global $_wp_theme_features;
1701
1702         if ( 'custom-header-uploads' == $feature )
1703                 return current_theme_supports( 'custom-header', 'uploads' );
1704
1705         if ( !isset( $_wp_theme_features[$feature] ) )
1706                 return false;
1707
1708         // If no args passed then no extra checks need be performed
1709         if ( func_num_args() <= 1 )
1710                 return true;
1711
1712         $args = array_slice( func_get_args(), 1 );
1713
1714         switch ( $feature ) {
1715                 case 'post-thumbnails':
1716                         // post-thumbnails can be registered for only certain content/post types by passing
1717                         // an array of types to add_theme_support(). If no array was passed, then
1718                         // any type is accepted
1719                         if ( true === $_wp_theme_features[$feature] )  // Registered for all types
1720                                 return true;
1721                         $content_type = $args[0];
1722                         return in_array( $content_type, $_wp_theme_features[$feature][0] );
1723                         break;
1724
1725                 case 'html5':
1726                 case 'post-formats':
1727                         // specific post formats can be registered by passing an array of types to
1728                         // add_theme_support()
1729
1730                         // Specific areas of HTML5 support *must* be passed via an array to add_theme_support()
1731
1732                         $type = $args[0];
1733                         return in_array( $type, $_wp_theme_features[$feature][0] );
1734                         break;
1735
1736                 case 'custom-header':
1737                 case 'custom-background' :
1738                         // specific custom header and background capabilities can be registered by passing
1739                         // an array to add_theme_support()
1740                         $header_support = $args[0];
1741                         return ( isset( $_wp_theme_features[$feature][0][$header_support] ) && $_wp_theme_features[$feature][0][$header_support] );
1742                         break;
1743         }
1744
1745         /**
1746          * Filter whether the current theme supports a specific feature.
1747          *
1748          * The dynamic portion of the hook name, $feature, refers to
1749          * the specific theme feature. Possible values include 'post-formats',
1750          * 'post-thumbnails', 'custom-background', 'custom-header', 'menus',
1751          * 'automatic-feed-links', and 'html5'.
1752          *
1753          * @since 3.4.0
1754          *
1755          * @param bool   true     Whether the current theme supports the given feature. Default true.
1756          * @param array  $args    Array of arguments for the feature.
1757          * @param string $feature The theme feature.
1758          */
1759         return apply_filters( "current_theme_supports-{$feature}", true, $args, $_wp_theme_features[$feature] );
1760 }
1761
1762 /**
1763  * Checks a theme's support for a given feature before loading the functions which implement it.
1764  *
1765  * @since 2.9.0
1766  *
1767  * @param string $feature The feature being checked.
1768  * @param string $include Path to the file.
1769  * @return bool True if the current theme supports the supplied feature, false otherwise.
1770  */
1771 function require_if_theme_supports( $feature, $include ) {
1772         if ( current_theme_supports( $feature ) ) {
1773                 require ( $include );
1774                 return true;
1775         }
1776         return false;
1777 }
1778
1779 /**
1780  * Checks an attachment being deleted to see if it's a header or background image.
1781  *
1782  * If true it removes the theme modification which would be pointing at the deleted
1783  * attachment
1784  *
1785  * @access private
1786  * @since 3.0.0
1787  * @param int $id the attachment id
1788  */
1789 function _delete_attachment_theme_mod( $id ) {
1790         $attachment_image = wp_get_attachment_url( $id );
1791         $header_image = get_header_image();
1792         $background_image = get_background_image();
1793
1794         if ( $header_image && $header_image == $attachment_image )
1795                 remove_theme_mod( 'header_image' );
1796
1797         if ( $background_image && $background_image == $attachment_image )
1798                 remove_theme_mod( 'background_image' );
1799 }
1800
1801 add_action( 'delete_attachment', '_delete_attachment_theme_mod' );
1802
1803 /**
1804  * Checks if a theme has been changed and runs 'after_switch_theme' hook on the next WP load
1805  *
1806  * @since 3.3.0
1807  */
1808 function check_theme_switched() {
1809         if ( $stylesheet = get_option( 'theme_switched' ) ) {
1810                 $old_theme = wp_get_theme( $stylesheet );
1811
1812                 // Prevent retrieve_widgets() from running since Customizer already called it up front
1813                 if ( get_option( 'theme_switched_via_customizer' ) ) {
1814                         remove_action( 'after_switch_theme', '_wp_sidebars_changed' );
1815                         update_option( 'theme_switched_via_customizer', false );
1816                 }
1817
1818                 if ( $old_theme->exists() ) {
1819                         /**
1820                          * Fires on the first WP load after a theme switch if the old theme still exists.
1821                          *
1822                          * This action fires multiple times and the parameters differs
1823                          * according to the context, if the old theme exists or not.
1824                          * If the old theme is missing, the parameter will be the slug
1825                          * of the old theme.
1826                          *
1827                          * @since 3.3.0
1828                          *
1829                          * @param string   $old_name  Old theme name.
1830                          * @param WP_Theme $old_theme WP_Theme instance of the old theme.
1831                          */
1832                         do_action( 'after_switch_theme', $old_theme->get( 'Name' ), $old_theme );
1833                 } else {
1834                         /** This action is documented in wp-includes/theme.php */
1835                         do_action( 'after_switch_theme', $stylesheet );
1836                 }
1837
1838                 update_option( 'theme_switched', false );
1839         }
1840 }
1841
1842 /**
1843  * Includes and instantiates the WP_Customize_Manager class.
1844  *
1845  * Fires when ?wp_customize=on or on wp-admin/customize.php.
1846  *
1847  * @since 3.4.0
1848  */
1849 function _wp_customize_include() {
1850         if ( ! ( ( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
1851                 || ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) )
1852         ) )
1853                 return;
1854
1855         require( ABSPATH . WPINC . '/class-wp-customize-manager.php' );
1856         // Init Customize class
1857         $GLOBALS['wp_customize'] = new WP_Customize_Manager;
1858 }
1859 add_action( 'plugins_loaded', '_wp_customize_include' );
1860
1861 /**
1862  * Adds settings for the customize-loader script.
1863  *
1864  * @since 3.4.0
1865  */
1866 function _wp_customize_loader_settings() {
1867         global $wp_scripts;
1868
1869         $admin_origin = parse_url( admin_url() );
1870         $home_origin  = parse_url( home_url() );
1871         $cross_domain = ( strtolower( $admin_origin[ 'host' ] ) != strtolower( $home_origin[ 'host' ] ) );
1872
1873         $browser = array(
1874                 'mobile' => wp_is_mobile(),
1875                 'ios'    => wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] ),
1876         );
1877
1878         $settings = array(
1879                 'url'           => esc_url( admin_url( 'customize.php' ) ),
1880                 'isCrossDomain' => $cross_domain,
1881                 'browser'       => $browser,
1882         );
1883
1884         $script = 'var _wpCustomizeLoaderSettings = ' . json_encode( $settings ) . ';';
1885
1886         $data = $wp_scripts->get_data( 'customize-loader', 'data' );
1887         if ( $data )
1888                 $script = "$data\n$script";
1889
1890         $wp_scripts->add_data( 'customize-loader', 'data', $script );
1891 }
1892 add_action( 'admin_enqueue_scripts', '_wp_customize_loader_settings' );
1893
1894 /**
1895  * Returns a URL to load the theme customizer.
1896  *
1897  * @since 3.4.0
1898  *
1899  * @param string $stylesheet Optional. Theme to customize. Defaults to current theme.
1900  *      The theme's stylesheet will be urlencoded if necessary.
1901  */
1902 function wp_customize_url( $stylesheet = null ) {
1903         $url = admin_url( 'customize.php' );
1904         if ( $stylesheet )
1905                 $url .= '?theme=' . urlencode( $stylesheet );
1906         return esc_url( $url );
1907 }
1908
1909 /**
1910  * Prints a script to check whether or not the customizer is supported,
1911  * and apply either the no-customize-support or customize-support class
1912  * to the body.
1913  *
1914  * This function MUST be called inside the body tag.
1915  *
1916  * Ideally, call this function immediately after the body tag is opened.
1917  * This prevents a flash of unstyled content.
1918  *
1919  * It is also recommended that you add the "no-customize-support" class
1920  * to the body tag by default.
1921  *
1922  * @since 3.4.0
1923  */
1924 function wp_customize_support_script() {
1925         $admin_origin = parse_url( admin_url() );
1926         $home_origin  = parse_url( home_url() );
1927         $cross_domain = ( strtolower( $admin_origin[ 'host' ] ) != strtolower( $home_origin[ 'host' ] ) );
1928
1929         ?>
1930         <script type="text/javascript">
1931                 (function() {
1932                         var request, b = document.body, c = 'className', cs = 'customize-support', rcs = new RegExp('(^|\\s+)(no-)?'+cs+'(\\s+|$)');
1933
1934 <?php           if ( $cross_domain ): ?>
1935                         request = (function(){ var xhr = new XMLHttpRequest(); return ('withCredentials' in xhr); })();
1936 <?php           else: ?>
1937                         request = true;
1938 <?php           endif; ?>
1939
1940                         b[c] = b[c].replace( rcs, ' ' );
1941                         b[c] += ( window.postMessage && request ? ' ' : ' no-' ) + cs;
1942                 }());
1943         </script>
1944         <?php
1945 }