PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 13.2.2
Jetpack – WP Security, Backup, Speed, & Growth v13.2.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / custom-css / custom-css.php
custom-css.php
1,203 lines 36.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3 // phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move classes to appropriately-named class files.
4
5 use Automattic\Jetpack\Assets;
6
7 /**
8 * Alternate Custom CSS source for 4.7 compat.
9 *
10 * @since 4.4.2
11 *
12 * @package automattic/jetpack
13 */
14
15 /**
16 * Class Jetpack_Custom_CSS_Enhancements
17 */
18 class Jetpack_Custom_CSS_Enhancements {
19
20 /**
21 * Set up the actions and filters needed for our compatability layer on top of core's Custom CSS implementation.
22 */
23 public static function add_hooks() {
24 add_action( 'init', array( __CLASS__, 'init' ) );
25 add_action( 'customize_controls_enqueue_scripts', array( __CLASS__, 'customize_controls_enqueue_scripts' ) );
26 add_action( 'customize_register', array( __CLASS__, 'customize_register' ) );
27 add_filter( 'map_meta_cap', array( __CLASS__, 'map_meta_cap' ), 20, 2 );
28 add_action( 'customize_preview_init', array( __CLASS__, 'customize_preview_init' ) );
29 add_filter( '_wp_post_revision_fields', array( __CLASS__, 'wp_post_revision_fields' ), 10, 2 );
30 add_action( 'load-revision.php', array( __CLASS__, 'load_revision_php' ) );
31
32 add_action( 'wp_enqueue_scripts', array( __CLASS__, 'wp_enqueue_scripts' ) );
33
34 // Handle Sass/LESS.
35 add_filter( 'customize_value_custom_css', array( __CLASS__, 'customize_value_custom_css' ), 10, 2 );
36 add_filter( 'customize_update_custom_css_post_content_args', array( __CLASS__, 'customize_update_custom_css_post_content_args' ), 10, 3 );
37 add_filter( 'update_custom_css_data', array( __CLASS__, 'update_custom_css_data' ), 10, 2 );
38
39 // Stuff for stripping out the theme's default stylesheet...
40 add_filter( 'stylesheet_uri', array( __CLASS__, 'style_filter' ) );
41 add_filter( 'safecss_skip_stylesheet', array( __CLASS__, 'preview_skip_stylesheet' ) );
42
43 // Stuff for overriding content width...
44 add_action( 'customize_preview_init', array( __CLASS__, 'preview_content_width' ) );
45 add_filter( 'jetpack_content_width', array( __CLASS__, 'jetpack_content_width' ) );
46 add_filter( 'editor_max_image_size', array( __CLASS__, 'editor_max_image_size' ), 10, 3 );
47 add_action( 'template_redirect', array( __CLASS__, 'set_content_width' ) );
48 add_action( 'admin_init', array( __CLASS__, 'set_content_width' ) );
49 }
50
51 /**
52 * Things that we do on init.
53 */
54 public static function init() {
55
56 wp_register_style( 'jetpack-codemirror', plugins_url( 'custom-css/css/codemirror.css', __FILE__ ), array(), '20120905' );
57 wp_register_style( 'jetpack-customizer-css', plugins_url( 'custom-css/css/customizer-control.css', __FILE__ ), array(), '20140728' );
58 wp_register_script( 'jetpack-codemirror', plugins_url( 'custom-css/js/codemirror.min.js', __FILE__ ), array(), '3.16', true );
59
60 $src = Assets::get_file_url_for_environment(
61 '_inc/build/custom-css/custom-css/js/core-customizer-css.core-4.9.min.js',
62 'modules/custom-css/custom-css/js/core-customizer-css.core-4.9.js'
63 );
64 wp_register_script(
65 'jetpack-customizer-css',
66 $src,
67 array(
68 'jquery',
69 'customize-controls',
70 'underscore',
71 ),
72 JETPACK__VERSION,
73 true
74 );
75
76 wp_register_script(
77 'jetpack-customizer-css-preview',
78 Assets::get_file_url_for_environment(
79 '_inc/build/custom-css/custom-css/js/core-customizer-css-preview.min.js',
80 'modules/custom-css/custom-css/js/core-customizer-css-preview.js'
81 ),
82 array( 'jquery', 'customize-selective-refresh' ),
83 JETPACK__VERSION,
84 true
85 );
86
87 remove_action( 'wp_head', 'wp_custom_css_cb', 11 ); // 4.7.0 had it at 11, 4.7.1 moved it to 101.
88 remove_action( 'wp_head', 'wp_custom_css_cb', 101 );
89 add_action( 'wp_head', array( __CLASS__, 'wp_custom_css_cb' ), 101 );
90
91 if ( isset( $_GET['custom-css'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
92 self::print_linked_custom_css();
93 }
94 }
95
96 /**
97 * Things that we do on init when the Customize Preview is loading.
98 */
99 public static function customize_preview_init() {
100 add_filter( 'wp_get_custom_css', array( __CLASS__, 'customize_preview_wp_get_custom_css' ) );
101 }
102
103 /**
104 * Print the current Custom CSS. This is for linking instead of printing directly.
105 */
106 public static function print_linked_custom_css() {
107 header( 'Content-type: text/css' );
108 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + YEAR_IN_SECONDS ) . ' GMT' );
109 echo wp_get_custom_css(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
110 exit;
111 }
112
113 /**
114 * Re-map the Edit CSS capability.
115 *
116 * Core, by default, restricts this to users that have `unfiltered_html` which
117 * would make the feature unusable in multi-site by non-super-admins, due to Core
118 * not shipping any solid sanitization.
119 *
120 * We're expanding who can use it, and then conditionally applying CSSTidy
121 * sanitization to users that do not have the `unfiltered_html` capability.
122 *
123 * @param array $caps Returns the user's actual capabilities.
124 * @param string $cap Capability name.
125 *
126 * @return array $caps
127 */
128 public static function map_meta_cap( $caps, $cap ) {
129 if ( 'edit_css' === $cap ) {
130 $caps = array( 'edit_theme_options' );
131 }
132 return $caps;
133 }
134
135 /**
136 * Shows Preprocessor code in the Revisions screen, and ensures that post_content_filtered
137 * is maintained on revisions
138 *
139 * @param array $fields Post fields pertinent to revisions.
140 * @param array $post A post array being processed for insertion as a post revision.
141 *
142 * @return array $fields Modified array to include post_content_filtered.
143 */
144 public static function wp_post_revision_fields( $fields, $post ) {
145 // None of the fields in $post are required to be passed in this filter.
146 if ( ! isset( $post['post_type'] ) || ! isset( $post['ID'] ) ) {
147 return $fields;
148 }
149
150 // If we're passed in a revision, go get the main post instead.
151 if ( 'revision' === $post['post_type'] ) {
152 $main_post_id = wp_is_post_revision( $post['ID'] );
153 $post = get_post( $main_post_id, ARRAY_A );
154 }
155 if ( 'custom_css' === $post['post_type'] ) {
156 $fields['post_content'] = __( 'CSS', 'jetpack' );
157 $fields['post_content_filtered'] = __( 'Preprocessor', 'jetpack' );
158 }
159 return $fields;
160 }
161
162 /**
163 * Get the published custom CSS post.
164 *
165 * @param string $stylesheet Optional. A theme object stylesheet name. Defaults to the current theme.
166 * @return WP_Post|null
167 */
168 public static function get_css_post( $stylesheet = '' ) {
169 return wp_get_custom_css_post( $stylesheet );
170 }
171
172 /**
173 * Override Core's `wp_custom_css_cb` method to provide linking to custom css.
174 */
175 public static function wp_custom_css_cb() {
176 $styles = wp_get_custom_css();
177 if ( ! $styles ) {
178 return;
179 }
180
181 $should_embed = strlen( $styles ) < 2000;
182 /** This filter is documented in projects/plugins/jetpack/modules/custom-css/custom-css.php */
183 $should_embed = apply_filters( 'safecss_embed_style', $should_embed, $styles );
184
185 if ( $should_embed || is_customize_preview() ) {
186 printf(
187 '<style type="text/css" id="wp-custom-css">%1$s</style>',
188 wp_strip_all_tags( $styles ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
189 );
190 } else {
191 // Add a cache buster to the url.
192 $url = home_url( '/' );
193 $url = add_query_arg( 'custom-css', substr( md5( $styles ), -10 ), $url );
194
195 printf(
196 '<link rel="stylesheet" type="text/css" id="wp-custom-css" href="%1$s" />', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
197 esc_url( $url )
198 );
199 }
200 }
201
202 /**
203 * Get the ID of a Custom CSS post tying to a given stylesheet.
204 *
205 * @param string $stylesheet Stylesheet name.
206 *
207 * @return int $post_id Post ID.
208 */
209 public static function post_id( $stylesheet = '' ) {
210 $post = self::get_css_post( $stylesheet );
211 if ( $post instanceof WP_Post ) {
212 return $post->ID;
213 }
214 return 0;
215 }
216
217 /**
218 * Partial for use in the Customizer.
219 */
220 public static function echo_custom_css_partial() {
221 echo wp_get_custom_css(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
222 }
223
224 /**
225 * Admin page!
226 *
227 * This currently has two main uses -- firstly to display the css for an inactive
228 * theme if there are no revisions attached it to a legacy bug, and secondly to
229 * handle folks that have bookmarkes in their browser going to the old page for
230 * managing Custom CSS in Jetpack.
231 *
232 * If we ever add back in a non-Customizer CSS editor, this would be the place.
233 */
234 public static function admin_page() {
235 $post = null;
236 $stylesheet = null;
237 if ( isset( $_GET['id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
238 $post_id = absint( $_GET['id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site
239 $post = get_post( $post_id );
240 if ( $post instanceof WP_Post && 'custom_css' === $post->post_type ) {
241 $stylesheet = $post->post_title;
242 }
243 }
244 ?>
245 <div class="wrap">
246 <?php self::revisions_switcher_box( $stylesheet ); ?>
247 <h1>
248 <?php
249 if ( $post ) {
250 printf( 'Custom CSS for &#8220;%1$s&#8221;', wp_get_theme( $stylesheet )->Name ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
251 } else {
252 esc_html_e( 'Custom CSS', 'jetpack' );
253 }
254 if ( current_user_can( 'customize' ) ) {
255 printf(
256 ' <a class="page-title-action hide-if-no-customize" href="%1$s">%2$s</a>',
257 esc_url( self::customizer_link() ),
258 esc_html__( 'Manage with Live Preview', 'jetpack' )
259 );
260 }
261 ?>
262 </h1>
263 <p><?php esc_html_e( 'Custom CSS is now managed in the Customizer.', 'jetpack' ); ?></p>
264 <?php if ( $post ) : ?>
265 <div class="revisions">
266 <h3><?php esc_html_e( 'CSS', 'jetpack' ); ?></h3>
267 <textarea class="widefat" readonly><?php echo esc_textarea( $post->post_content ); ?></textarea>
268 <?php if ( $post->post_content_filtered ) : ?>
269 <h3><?php esc_html_e( 'Preprocessor', 'jetpack' ); ?></h3>
270 <textarea class="widefat" readonly><?php echo esc_textarea( $post->post_content_filtered ); ?></textarea>
271 <?php endif; ?>
272 </div>
273 <?php endif; ?>
274 </div>
275
276 <style>
277 .other-themes-wrap {
278 float: right;
279 background-color: #fff;
280 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
281 box-shadow: 0 1px 3px rgba(0,0,0,0.1);
282 padding: 5px 10px;
283 margin-bottom: 10px;
284 }
285 .other-themes-wrap label {
286 display: block;
287 margin-bottom: 10px;
288 }
289 .other-themes-wrap select {
290 float: left;
291 width: 77%;
292 }
293 .other-themes-wrap button {
294 float: right;
295 width: 20%;
296 }
297 .revisions {
298 clear: both;
299 }
300 .revisions textarea {
301 min-height: 300px;
302 background: #fff;
303 }
304 </style>
305 <script>
306 (function($){
307 var $switcher = $('.other-themes-wrap');
308 $switcher.find('button').on('click', function(e){
309 e.preventDefault();
310 if ( $switcher.find('select').val() ) {
311 window.location.href = $switcher.find('select').val();
312 }
313 });
314 })(jQuery);
315 </script>
316 <?php
317 }
318
319 /**
320 * Build the URL to deep link to the Customizer.
321 *
322 * You can modify the return url via $args.
323 *
324 * @param array $args Array of parameters.
325 * @return string
326 */
327 public static function customizer_link( $args = array() ) {
328 $args = wp_parse_args(
329 $args,
330 array(
331 'return_url' => isset( $_SERVER['REQUEST_URI'] ) ? rawurlencode( filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) : '',
332 )
333 );
334
335 return add_query_arg(
336 array(
337 array(
338 'autofocus' => array(
339 'section' => 'custom_css',
340 ),
341 ),
342 'return' => $args['return_url'],
343 ),
344 admin_url( 'customize.php' )
345 );
346 }
347
348 /**
349 * Handle the enqueueing and localizing for scripts to be used in the Customizer.
350 */
351 public static function customize_controls_enqueue_scripts() {
352 wp_enqueue_style( 'jetpack-customizer-css' );
353 wp_enqueue_script( 'jetpack-customizer-css' );
354
355 $content_help = __( 'Set a different media width for full size images.', 'jetpack' );
356 if ( ! empty( $GLOBALS['content_width'] ) ) {
357 $content_help .= sprintf(
358 // translators: the theme name and then the default width.
359 _n( ' The default media width for the <strong>%1$s</strong> theme is %2$d pixel.', ' The default media width for the <strong>%1$s</strong> theme is %2$d pixels.', (int) $GLOBALS['content_width'], 'jetpack' ),
360 wp_get_theme()->Name,
361 (int) $GLOBALS['content_width']
362 );
363 }
364
365 wp_localize_script(
366 'jetpack-customizer-css',
367 '_jp_css_settings',
368 array(
369 /** This filter is documented in modules/custom-css/custom-css.php */
370 'useRichEditor' => ! jetpack_is_mobile() && apply_filters( 'safecss_use_ace', true ),
371 'areThereCssRevisions' => self::are_there_css_revisions(),
372 'revisionsUrl' => self::get_revisions_url(),
373 'cssHelpUrl' => '//en.support.wordpress.com/custom-design/editing-css/',
374 'l10n' => array(
375 'mode' => __( 'Start Fresh', 'jetpack' ),
376 'mobile' => __( 'On Mobile', 'jetpack' ),
377 'contentWidth' => $content_help,
378 'revisions' => _x( 'See full history', 'Toolbar button to see full CSS revision history', 'jetpack' ),
379 'css_help_title' => _x( 'Help', 'Toolbar button to get help with custom CSS', 'jetpack' ),
380 ),
381 )
382 );
383 }
384
385 /**
386 * Check whether there are CSS Revisions for a given theme.
387 *
388 * Going forward, there should always be, but this was necessitated
389 * early on by https://core.trac.wordpress.org/ticket/30854
390 *
391 * @param string $stylesheet Stylesheet name.
392 *
393 * @return bool|null|WP_Post
394 */
395 public static function are_there_css_revisions( $stylesheet = '' ) {
396 $post = wp_get_custom_css_post( $stylesheet );
397 if ( empty( $post ) ) {
398 return $post;
399 }
400 return (bool) wp_get_post_revisions( $post );
401 }
402
403 /**
404 * Core doesn't have a function to get the revisions url for a given post ID.
405 *
406 * @param string $stylesheet Stylesheet name.
407 *
408 * @return null|string|void
409 */
410 public static function get_revisions_url( $stylesheet = '' ) {
411 $post = wp_get_custom_css_post( $stylesheet );
412
413 // If we have any currently saved customizations...
414 if ( $post instanceof WP_Post ) {
415 $revisions = wp_get_post_revisions( $post->ID, array( 'posts_per_page' => 1 ) );
416 if ( empty( $revisions ) || is_wp_error( $revisions ) ) {
417 return admin_url( 'themes.php?page=editcss' );
418 }
419 $revision = reset( $revisions );
420 return get_edit_post_link( $revision->ID );
421 }
422
423 return admin_url( 'themes.php?page=editcss' );
424 }
425
426 /**
427 * Get a map of all theme names and theme stylesheets for mapping stuff.
428 *
429 * @return array
430 */
431 public static function get_themes() {
432 $themes = wp_get_themes( array( 'errors' => null ) );
433 $all = array();
434 foreach ( $themes as $theme ) {
435 $all[ $theme->name ] = $theme->stylesheet;
436 }
437 return $all;
438 }
439
440 /**
441 * When we need to get all themes that have Custom CSS saved.
442 *
443 * @return array
444 */
445 public static function get_all_themes_with_custom_css() {
446 $themes = self::get_themes();
447 $custom_css = get_posts(
448 array(
449 'post_type' => 'custom_css',
450 'post_status' => get_post_stati(),
451 'number' => -1,
452 'order' => 'DESC',
453 'orderby' => 'modified',
454 )
455 );
456 $return = array();
457
458 foreach ( $custom_css as $post ) {
459 $stylesheet = $post->post_title;
460 $label = array_search( $stylesheet, $themes, true );
461
462 if ( ! $label ) {
463 continue;
464 }
465
466 $return[ $stylesheet ] = array(
467 'label' => $label,
468 'post' => $post,
469 );
470 }
471
472 return $return;
473 }
474
475 /**
476 * Handle the enqueueing of scripts for customize previews.
477 */
478 public static function wp_enqueue_scripts() {
479 if ( is_customize_preview() ) {
480 wp_enqueue_script( 'jetpack-customizer-css-preview' );
481 wp_localize_script(
482 'jetpack-customizer-css-preview',
483 'jpCustomizerCssPreview',
484 array(
485 /** This filter is documented in modules/custom-css/custom-css.php */
486 'preprocessors' => apply_filters( 'jetpack_custom_css_preprocessors', array() ),
487 )
488 );
489 }
490 }
491
492 /**
493 * Sanitize the CSS for users without `unfiltered_html`.
494 *
495 * @param string $css Input CSS.
496 * @param array $args Array of CSS options.
497 *
498 * @return mixed|string
499 */
500 public static function sanitize_css( $css, $args = array() ) {
501 $args = wp_parse_args(
502 $args,
503 array(
504 'force' => false,
505 'preprocessor' => null,
506 )
507 );
508
509 if ( $args['force'] || ! current_user_can( 'unfiltered_html' ) ) {
510
511 $warnings = array();
512
513 safecss_class();
514 $csstidy = new csstidy();
515 $csstidy->optimise = new safecss( $csstidy );
516
517 $csstidy->set_cfg( 'remove_bslash', false );
518 $csstidy->set_cfg( 'compress_colors', false );
519 $csstidy->set_cfg( 'compress_font-weight', false );
520 $csstidy->set_cfg( 'optimise_shorthands', 0 );
521 $csstidy->set_cfg( 'remove_last_;', false );
522 $csstidy->set_cfg( 'case_properties', false );
523 $csstidy->set_cfg( 'discard_invalid_properties', true );
524 $csstidy->set_cfg( 'css_level', 'CSS3.0' );
525 $csstidy->set_cfg( 'preserve_css', true );
526 $csstidy->set_cfg( 'template', __DIR__ . '/csstidy/wordpress-standard.tpl' );
527
528 // Test for some preg_replace stuff.
529 $prev = $css;
530 $css = preg_replace( '/\\\\([0-9a-fA-F]{4})/', '\\\\\\\\$1', $css );
531 // prevent content: '\3434' from turning into '\\3434'.
532 $css = str_replace( array( '\'\\\\', '"\\\\' ), array( '\'\\', '"\\' ), $css );
533 if ( $css !== $prev ) {
534 $warnings[] = 'preg_replace found stuff';
535 }
536
537 // Some people put weird stuff in their CSS, KSES tends to be greedy.
538 $css = str_replace( '<=', '&lt;=', $css );
539
540 // Test for some kses stuff.
541 $prev = $css;
542 // Why KSES instead of strip_tags? Who knows?
543 $css = wp_kses_split( $css, array(), array() );
544 $css = str_replace( '&gt;', '>', $css ); // kses replaces lone '>' with &gt;
545 // Why both KSES and strip_tags? Because we just added some '>'.
546 $css = strip_tags( $css ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- scared to update this to wp_strip_all_tags since we're building a CSS file here.
547
548 if ( $css !== $prev ) {
549 $warnings[] = 'kses found stuff';
550 }
551
552 // if we're not using a preprocessor.
553 if ( ! $args['preprocessor'] ) {
554
555 /** This action is documented in modules/custom-css/custom-css.php */
556 do_action( 'safecss_parse_pre', $csstidy, $css, $args );
557
558 $csstidy->parse( $css );
559
560 /** This action is documented in modules/custom-css/custom-css.php */
561 do_action( 'safecss_parse_post', $csstidy, $warnings, $args );
562
563 $css = $csstidy->print->plain();
564 }
565 }
566 return $css;
567 }
568
569 /**
570 * Override $content_width in customizer previews.
571 */
572 public static function preview_content_width() {
573 global $wp_customize;
574 if ( ! is_customize_preview() ) {
575 return;
576 }
577
578 $setting = $wp_customize->get_setting( 'jetpack_custom_css[content_width]' );
579 if ( ! $setting ) {
580 return;
581 }
582
583 $customized_content_width = (int) $setting->post_value();
584 if ( ! empty( $customized_content_width ) ) {
585 $GLOBALS['content_width'] = $customized_content_width;
586 }
587 }
588
589 /**
590 * Filter the current theme's stylesheet for potentially nullifying it.
591 *
592 * @param string $current Stylesheet URI for the current theme/child theme.
593 *
594 * @return mixed|void
595 */
596 public static function style_filter( $current ) {
597 if ( is_admin() ) {
598 return $current;
599 } elseif ( self::is_freetrial() && ( ! self::is_preview() || ! current_user_can( 'switch_themes' ) ) ) {
600 return $current;
601 } elseif ( self::skip_stylesheet() ) {
602 /** This filter is documented in modules/custom-css/custom-css.php */
603 return apply_filters( 'safecss_style_filter_url', plugins_url( 'custom-css/css/blank.css', __FILE__ ) );
604 }
605
606 return $current;
607 }
608
609 /**
610 * Determine whether or not we should have the theme skip its main stylesheet.
611 *
612 * @return mixed The truthiness of this value determines whether the stylesheet should be skipped.
613 */
614 public static function skip_stylesheet() {
615 /** This filter is documented in modules/custom-css/custom-css.php */
616 $skip_stylesheet = apply_filters( 'safecss_skip_stylesheet', null );
617 if ( $skip_stylesheet !== null ) {
618 return $skip_stylesheet;
619 }
620
621 $jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
622 if ( isset( $jetpack_custom_css['replace'] ) ) {
623 return $jetpack_custom_css['replace'];
624 }
625
626 return false;
627 }
628
629 /**
630 * Override $content_width in customizer previews.
631 *
632 * Runs on `safecss_skip_stylesheet` filter.
633 *
634 * @param bool $skip_value Should the stylesheet be skipped.
635 *
636 * @return null|bool
637 */
638 public static function preview_skip_stylesheet( $skip_value ) {
639 global $wp_customize;
640 if ( ! is_customize_preview() ) {
641 return $skip_value;
642 }
643
644 $setting = $wp_customize->get_setting( 'jetpack_custom_css[replace]' );
645 if ( ! $setting ) {
646 return $skip_value;
647 }
648
649 $customized_replace = $setting->post_value();
650 if ( null !== $customized_replace ) {
651 return $customized_replace;
652 }
653
654 return $skip_value;
655 }
656
657 /**
658 * Add Custom CSS section and controls.
659 *
660 * @param WP_Customize_Manager $wp_customize WP_Customize_Manager instance.
661 */
662 public static function customize_register( $wp_customize ) {
663
664 /**
665 * SETTINGS.
666 */
667
668 $wp_customize->add_setting(
669 'jetpack_custom_css[preprocessor]',
670 array(
671 'default' => '',
672 'transport' => 'postMessage',
673 'sanitize_callback' => array( __CLASS__, 'sanitize_preprocessor' ),
674 )
675 );
676
677 $wp_customize->add_setting(
678 'jetpack_custom_css[replace]',
679 array(
680 'default' => false,
681 'transport' => 'refresh',
682 )
683 );
684
685 $wp_customize->add_setting(
686 'jetpack_custom_css[content_width]',
687 array(
688 'default' => '',
689 'transport' => 'refresh',
690 'sanitize_callback' => array( __CLASS__, 'intval_base10' ),
691 )
692 );
693
694 // Add custom sanitization to the core css customizer setting.
695 foreach ( $wp_customize->settings() as $setting ) {
696 if ( $setting instanceof WP_Customize_Custom_CSS_Setting ) {
697 add_filter( "customize_sanitize_{$setting->id}", array( __CLASS__, 'sanitize_css_callback' ), 10, 2 );
698 }
699 }
700
701 /**
702 * CONTROLS.
703 */
704
705 // Overwrite or Tweak the Core Control.
706 $core_custom_css = $wp_customize->get_control( 'custom_css' );
707 if ( $core_custom_css ) {
708 if ( $core_custom_css instanceof WP_Customize_Code_Editor_Control ) {
709 // In WP 4.9, we let the Core CodeMirror control keep running the show, but hook into it to tweak stuff.
710 $types = array(
711 'default' => 'text/css',
712 'less' => 'text/x-less',
713 'sass' => 'text/x-scss',
714 );
715 $preprocessor = $wp_customize->get_setting( 'jetpack_custom_css[preprocessor]' )->value();
716 if ( isset( $types[ $preprocessor ] ) ) {
717 $core_custom_css->code_type = $types[ $preprocessor ];
718 }
719 } else {
720 // Core < 4.9 Fallback
721 $core_custom_css->type = 'jetpackCss';
722 }
723 }
724
725 $wp_customize->selective_refresh->add_partial(
726 'custom_css',
727 array(
728 'type' => 'custom_css',
729 'selector' => '#wp-custom-css',
730 'container_inclusive' => false,
731 'fallback_refresh' => false,
732 'settings' => array(
733 'custom_css[' . $wp_customize->get_stylesheet() . ']',
734 'jetpack_custom_css[preprocessor]',
735 ),
736 'render_callback' => array( __CLASS__, 'echo_custom_css_partial' ),
737 )
738 );
739
740 $wp_customize->add_control(
741 'wpcom_custom_css_content_width_control',
742 array(
743 'type' => 'text',
744 'label' => __( 'Media Width', 'jetpack' ),
745 'section' => 'custom_css',
746 'settings' => 'jetpack_custom_css[content_width]',
747 )
748 );
749
750 $wp_customize->add_control(
751 'jetpack_css_mode_control',
752 array(
753 'type' => 'checkbox',
754 'label' => __( 'Don\'t use the theme\'s original CSS.', 'jetpack' ),
755 'section' => 'custom_css',
756 'settings' => 'jetpack_custom_css[replace]',
757 )
758 );
759
760 /**
761 * An action to grab on to if another Jetpack Module would like to add its own controls.
762 *
763 * @module custom-css
764 *
765 * @since 4.4.2
766 *
767 * @param $wp_customize The WP_Customize object.
768 */
769 do_action( 'jetpack_custom_css_customizer_controls', $wp_customize );
770
771 /** This filter is documented in modules/custom-css/custom-css.php */
772 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
773 if ( ! empty( $preprocessors ) ) {
774 $preprocessor_choices = array(
775 '' => __( 'None', 'jetpack' ),
776 );
777
778 foreach ( $preprocessors as $preprocessor_key => $processor ) {
779 $preprocessor_choices[ $preprocessor_key ] = $processor['name'];
780 }
781
782 $wp_customize->add_control(
783 'jetpack_css_preprocessors_control',
784 array(
785 'type' => 'select',
786 'choices' => $preprocessor_choices,
787 'label' => __( 'Preprocessor', 'jetpack' ),
788 'section' => 'custom_css',
789 'settings' => 'jetpack_custom_css[preprocessor]',
790 )
791 );
792 }
793 }
794
795 /**
796 * The callback to handle sanitizing the CSS. Takes different arguments, hence the proxy function.
797 *
798 * @param mixed $css Value of the setting.
799 *
800 * @return mixed|string
801 */
802 public static function sanitize_css_callback( $css ) {
803 global $wp_customize;
804 return self::sanitize_css(
805 $css,
806 array(
807 'preprocessor' => $wp_customize->get_setting( 'jetpack_custom_css[preprocessor]' )->value(),
808 )
809 );
810 }
811
812 /**
813 * Flesh out for wpcom.
814 *
815 * @todo
816 *
817 * @return bool
818 */
819 public static function is_freetrial() {
820 return false;
821 }
822
823 /**
824 * Flesh out for wpcom.
825 *
826 * @todo
827 *
828 * @return bool
829 */
830 public static function is_preview() {
831 return false;
832 }
833
834 /**
835 * Output the custom css for customize preview.
836 *
837 * @param string $css Custom CSS content.
838 *
839 * @return mixed
840 */
841 public static function customize_preview_wp_get_custom_css( $css ) {
842 global $wp_customize;
843
844 $preprocessor = $wp_customize->get_setting( 'jetpack_custom_css[preprocessor]' )->value();
845
846 // If it's empty, just return.
847 if ( empty( $preprocessor ) ) {
848 return $css;
849 }
850
851 /** This filter is documented in modules/custom-css/custom-css.php */
852 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
853 if ( isset( $preprocessors[ $preprocessor ] ) ) {
854 return call_user_func( $preprocessors[ $preprocessor ]['callback'], $css );
855 }
856
857 return $css;
858 }
859
860 /**
861 * Add CSS preprocessing to our CSS if it is supported.
862 *
863 * @param mixed $css Value of the setting.
864 * @param WP_Customize_Setting $setting WP_Customize_Setting instance.
865 *
866 * @return string
867 */
868 public static function customize_value_custom_css( $css, $setting ) {
869 // Find the current preprocessor.
870 $preprocessor = null;
871 $jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
872 if ( isset( $jetpack_custom_css['preprocessor'] ) ) {
873 $preprocessor = $jetpack_custom_css['preprocessor'];
874 }
875
876 // If it's not supported, just return.
877 /** This filter is documented in modules/custom-css/custom-css.php */
878 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
879 if ( ! isset( $preprocessors[ $preprocessor ] ) ) {
880 return $css;
881 }
882
883 // Swap it for the `post_content_filtered` instead.
884 $post = wp_get_custom_css_post( $setting->stylesheet );
885 if ( $post && ! empty( $post->post_content_filtered ) ) {
886 $css = $post->post_content_filtered;
887 }
888
889 return $css;
890 }
891
892 /**
893 * Store the original pre-processed CSS in `post_content_filtered`
894 * and then store processed CSS in `post_content`.
895 *
896 * @param array $args Content post args.
897 * @param string $css Original CSS being updated.
898 *
899 * @return mixed
900 */
901 public static function customize_update_custom_css_post_content_args( $args, $css ) {
902 // Find the current preprocessor.
903 $jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
904 if ( empty( $jetpack_custom_css['preprocessor'] ) ) {
905 return $args;
906 }
907
908 $preprocessor = $jetpack_custom_css['preprocessor'];
909 /** This filter is documented in modules/custom-css/custom-css.php */
910 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
911
912 // If it's empty, just return.
913 if ( empty( $preprocessor ) ) {
914 return $args;
915 }
916
917 if ( isset( $preprocessors[ $preprocessor ] ) ) {
918 $args['post_content_filtered'] = $css;
919 $args['post_content'] = call_user_func( $preprocessors[ $preprocessor ]['callback'], $css );
920 }
921
922 return $args;
923 }
924
925 /**
926 * Filter to handle the processing of preprocessed css on save.
927 *
928 * @param array $args Custom CSS options.
929 *
930 * @return mixed
931 */
932 public static function update_custom_css_data( $args ) {
933 // Find the current preprocessor.
934 $jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
935 if ( empty( $jetpack_custom_css['preprocessor'] ) ) {
936 return $args;
937 }
938
939 /** This filter is documented in modules/custom-css/custom-css.php */
940 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
941 $preprocessor = $jetpack_custom_css['preprocessor'];
942
943 // If we have a preprocessor specified ...
944 if ( isset( $preprocessors[ $preprocessor ] ) ) {
945 // And no other preprocessor has run ...
946 if ( empty( $args['preprocessed'] ) ) {
947 $args['preprocessed'] = $args['css'];
948 $args['css'] = call_user_func( $preprocessors[ $preprocessor ]['callback'], $args['css'] );
949 } else {
950 trigger_error( 'Jetpack CSS Preprocessor specified, but something else has already modified the argument.', E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
951 }
952 }
953
954 return $args;
955 }
956
957 /**
958 * When on the edit screen, make sure the custom content width
959 * setting is applied to the large image size.
960 *
961 * @param array $dims Array of image dimensions (width and height).
962 * @param string $size Size of the resulting image.
963 * @param null $context Context the image is being resized for. `edit` or `display`.
964 *
965 * @return array
966 */
967 public static function editor_max_image_size( $dims, $size = 'medium', $context = null ) {
968 list( $width, $height ) = $dims;
969
970 if ( 'large' === $size && 'edit' === $context ) {
971 $width = Jetpack::get_content_width();
972 }
973
974 return array( $width, $height );
975 }
976
977 /**
978 * Override the content_width with a custom value if one is set.
979 *
980 * @param int $content_width Content Width value to be updated.
981 *
982 * @return int
983 */
984 public static function jetpack_content_width( $content_width ) {
985 $custom_content_width = 0;
986
987 $jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
988 if ( isset( $jetpack_custom_css['content_width'] ) ) {
989 $custom_content_width = $jetpack_custom_css['content_width'];
990 }
991
992 if ( $custom_content_width > 0 ) {
993 return $custom_content_width;
994 }
995
996 return $content_width;
997 }
998
999 /**
1000 * Currently this filter function gets called on
1001 * 'template_redirect' action and
1002 * 'admin_init' action
1003 */
1004 public static function set_content_width() {
1005 // Don't apply this filter on the Edit CSS page.
1006 if ( isset( $_GET['page'] ) && 'editcss' === $_GET['page'] && is_admin() ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nothing is changed on the site.
1007 return;
1008 }
1009
1010 $GLOBALS['content_width'] = Jetpack::get_content_width();
1011 }
1012
1013 /**
1014 * Make sure the preprocessor we're saving is one we know about.
1015 *
1016 * @param string $preprocessor The preprocessor to sanitize.
1017 *
1018 * @return null|string
1019 */
1020 public static function sanitize_preprocessor( $preprocessor ) {
1021 /** This filter is documented in modules/custom-css/custom-css.php */
1022 $preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
1023 if ( empty( $preprocessor ) || array_key_exists( $preprocessor, $preprocessors ) ) {
1024 return $preprocessor;
1025 }
1026 return null;
1027 }
1028
1029 /**
1030 * Get the base10 intval.
1031 *
1032 * This is used as a setting's sanitize_callback; we can't use just plain
1033 * intval because the second argument is not what intval() expects.
1034 *
1035 * @access public
1036 *
1037 * @param mixed $value Number to convert.
1038 * @return int Integer.
1039 */
1040 public static function intval_base10( $value ) {
1041 return (int) $value;
1042 }
1043
1044 /**
1045 * Add a footer action on revision.php to print some customizations for the theme switcher.
1046 */
1047 public static function load_revision_php() {
1048 add_action( 'admin_footer', array( __CLASS__, 'revision_admin_footer' ) );
1049 }
1050
1051 /**
1052 * Print the theme switcher on revision.php and move it into place.
1053 */
1054 public static function revision_admin_footer() {
1055 $post = get_post();
1056 if ( 'custom_css' !== $post->post_type ) {
1057 return;
1058 }
1059 $stylesheet = $post->post_title;
1060 ?>
1061 <script type="text/html" id="tmpl-other-themes-switcher">
1062 <?php self::revisions_switcher_box( $stylesheet ); ?>
1063 </script>
1064 <style>
1065 .other-themes-wrap {
1066 float: right;
1067 background-color: #fff;
1068 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
1069 box-shadow: 0 1px 3px rgba(0,0,0,0.1);
1070 padding: 5px 10px;
1071 margin-bottom: 10px;
1072 }
1073 .other-themes-wrap label {
1074 display: block;
1075 margin-bottom: 10px;
1076 }
1077 .other-themes-wrap select {
1078 float: left;
1079 width: 77%;
1080 }
1081 .other-themes-wrap button {
1082 float: right;
1083 width: 20%;
1084 }
1085 .revisions {
1086 clear: both;
1087 }
1088 /* Hide the back-to-post link */
1089 .long-header + a {
1090 display: none;
1091 }
1092 </style>
1093 <script>
1094 (function($){
1095 var switcher = $('#tmpl-other-themes-switcher').html(),
1096 qty = $( switcher ).find('select option').length,
1097 $switcher;
1098
1099 if ( qty >= 3 ) {
1100 $('h1.long-header').before( switcher );
1101 $switcher = $('.other-themes-wrap');
1102 $switcher.find('button').on('click', function(e){
1103 e.preventDefault();
1104 if ( $switcher.find('select').val() ) {
1105 window.location.href = $switcher.find('select').val();
1106 }
1107 })
1108 }
1109 })(jQuery);
1110 </script>
1111 <?php
1112 }
1113
1114 /**
1115 * The HTML for the theme revision switcher box.
1116 *
1117 * @param string $stylesheet Stylesheet name.
1118 */
1119 public static function revisions_switcher_box( $stylesheet = '' ) {
1120 $themes = self::get_all_themes_with_custom_css();
1121 ?>
1122 <div class="other-themes-wrap">
1123 <label for="other-themes"><?php esc_html_e( 'Select another theme to view its custom CSS.', 'jetpack' ); ?></label>
1124 <select id="other-themes">
1125 <option value=""><?php esc_html_e( 'Select a theme&hellip;', 'jetpack' ); ?></option>
1126 <?php
1127 foreach ( $themes as $theme_stylesheet => $data ) {
1128 $revisions = wp_get_post_revisions( $data['post']->ID, array( 'posts_per_page' => 1 ) );
1129 if ( ! $revisions ) {
1130 ?>
1131 <option value="<?php echo esc_url( add_query_arg( 'id', $data['post']->ID, menu_page_url( 'editcss', 0 ) ) ); ?>" <?php disabled( $stylesheet, $theme_stylesheet ); ?>>
1132 <?php echo esc_html( $data['label'] ); ?>
1133 <?php
1134 // translators: how long ago the stylesheet was modified.
1135 printf( esc_html__( '(modified %s ago)', 'jetpack' ), human_time_diff( strtotime( $data['post']->post_modified_gmt ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1136 ?>
1137 </option>
1138 <?php
1139 continue;
1140 }
1141 $revision = array_shift( $revisions );
1142 ?>
1143 <option value="<?php echo esc_url( get_edit_post_link( $revision->ID ) ); ?>" <?php disabled( $stylesheet, $theme_stylesheet ); ?>>
1144 <?php echo esc_html( $data['label'] ); ?>
1145 <?php
1146 // translators: how long ago the stylesheet was modified.
1147 printf( esc_html__( '(modified %s ago)', 'jetpack' ), human_time_diff( strtotime( $data['post']->post_modified_gmt ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1148 ?>
1149 </option>
1150 <?php
1151 }
1152 ?>
1153 </select>
1154 <button class="button" id="other_theme_custom_css_switcher"><?php esc_html_e( 'Switch', 'jetpack' ); ?></button>
1155 </div>
1156 <?php
1157 }
1158 }
1159
1160 Jetpack_Custom_CSS_Enhancements::add_hooks();
1161
1162 if ( ! function_exists( 'safecss_class' ) ) :
1163 /**
1164 * Load in the class only when needed. Makes lighter load by having one less class in memory.
1165 */
1166 function safecss_class() {
1167 // Wrapped so we don't need the parent class just to load the plugin.
1168 if ( class_exists( 'safecss' ) ) {
1169 return;
1170 }
1171
1172 require_once __DIR__ . '/csstidy/class.csstidy.php';
1173
1174 /**
1175 * Class safecss
1176 */
1177 class safecss extends csstidy_optimise { // phpcs:ignore
1178
1179 /**
1180 * Optimises $css after parsing.
1181 */
1182 public function postparse() { // phpcs:ignore MediaWiki.Usage.NestedFunctions.NestedFunction
1183
1184 /** This action is documented in modules/custom-css/custom-css.php */
1185 do_action( 'csstidy_optimize_postparse', $this );
1186
1187 return parent::postparse();
1188 }
1189
1190 /**
1191 * Optimises a sub-value.
1192 */
1193 public function subvalue() { // phpcs:ignore MediaWiki.Usage.NestedFunctions.NestedFunction
1194
1195 /** This action is documented in modules/custom-css/custom-css.php */
1196 do_action( 'csstidy_optimize_subvalue', $this );
1197
1198 return parent::subvalue();
1199 }
1200 }
1201 }
1202 endif;
1203