Completed
Push — core/custom-css-4.7 ( a763b1...39aaf0 )
by George
06:52
created

prettify_post_revisions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Class Jetpack_Custom_CSS_Enhancements
5
 */
6
class Jetpack_Custom_CSS_Enhancements {
7
	/**
8
	 * Set up the actions and filters needed for our compatability layer on top of core's Custom CSS implementation.
9
	 */
10
	public static function add_hooks() {
11
		add_action( 'init', array( __CLASS__, 'init' ) );
12
		add_action( 'admin_menu', array( __CLASS__, 'admin_menu' ) );
13
		add_action( 'customize_controls_enqueue_scripts', array( __CLASS__, 'customize_controls_enqueue_scripts' ) );
14
		add_action( 'customize_register', array( __CLASS__, 'customize_register' ) );
15
		add_filter( 'map_meta_cap', array( __CLASS__, 'map_meta_cap' ), 20, 2 );
16
		add_action( 'customize_preview_init', array( __CLASS__, 'customize_preview_init' ) );
17
		add_filter( '_wp_post_revision_fields', array( __CLASS__, '_wp_post_revision_fields' ), 10, 2 );
18
		add_action( 'load-revision.php', array( __CLASS__, 'load_revision_php' ) );
19
20
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'wp_enqueue_scripts' ) );
21
22
		// Handle Sass/LESS
23
		add_filter( 'customize_value_custom_css', array( __CLASS__, 'customize_value_custom_css' ), 10, 2 );
24
		add_filter( 'customize_update_custom_css_post_content_args', array( __CLASS__, 'customize_update_custom_css_post_content_args' ), 10, 3 );
25
		add_filter( 'update_custom_css_data', array( __CLASS__, 'update_custom_css_data' ), 10, 2 );
26
27
		// Handle Sass/LESS
28
		add_filter( 'customize_value_custom_css', array( __CLASS__, 'customize_value_custom_css' ), 10, 2 );
29
		add_filter( 'customize_update_custom_css_post_content_args', array( __CLASS__, 'customize_update_custom_css_post_content_args' ), 10, 3 );
30
31
		// Stuff for stripping out the theme's default stylesheet...
32
		add_filter( 'stylesheet_uri', array( __CLASS__, 'style_filter' ) );
33
		add_filter( 'safecss_skip_stylesheet', array( __CLASS__, 'preview_skip_stylesheet' ) );
34
35
		// Stuff for overriding content width...
36
		add_action( 'customize_preview_init', array( __CLASS__, 'preview_content_width' ) );
37
		add_filter( 'jetpack_content_width', array( __CLASS__, 'jetpack_content_width' ) );
38
		add_filter( 'editor_max_image_size', array( __CLASS__, 'editor_max_image_size' ), 10, 3 );
39
		add_action( 'template_redirect', array( __CLASS__, 'set_content_width' ) );
40
		add_action( 'admin_init', array( __CLASS__, 'set_content_width' ) );
41
42
		// Stuff?
43
	}
44
45
	/**
46
	 * Things that we do on init.
47
	 */
48
	public static function init() {
49
		$min = '.min';
0 ignored issues
show
Unused Code introduced by
$min is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
50
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
51
			$min = '';
0 ignored issues
show
Unused Code introduced by
$min is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
		}
53
54
		wp_register_style( 'jetpack-codemirror',      plugins_url( "custom-css/css/codemirror.css", __FILE__ ), array(), '20120905' );
55
		wp_register_style( 'jetpack-customizer-css',  plugins_url( 'custom-css/css/customizer-control.css', __FILE__ ), array( 'jetpack-codemirror' ), '20140728' );
56
		wp_register_script( 'jetpack-codemirror',     plugins_url( "custom-css/js/codemirror.min.js", __FILE__ ), array(), '3.16', true );
57
		wp_register_script( 'jetpack-customizer-css', plugins_url( 'custom-css/js/core-customizer-css.js', __FILE__ ), array(  'customize-controls', 'underscore', 'jetpack-codemirror' ), JETPACK__VERSION, true );
58
59
		wp_register_script( 'jetpack-customizer-css-preview', plugins_url( 'custom-css/js/core-customizer-css-preview.js', __FILE__ ), array( 'customize-selective-refresh' ), JETPACK__VERSION, true );
60
	}
61
62
	/**
63
	 * Things that we do on init when the Customize Preview is loading.
64
	 */
65
	public static function customize_preview_init() {
66
		add_filter( 'wp_get_custom_css', array( __CLASS__, 'customize_preview_wp_get_custom_css' ) );
67
	}
68
69
	/**
70
	 * Re-map the Edit CSS capability.
71
	 *
72
	 * Core, by default, restricts this to users that have `unfiltered_html` which
73
	 * would make the feature unusable in multi-site by non-super-admins, due to Core
74
	 * not shipping any solid sanitization.
75
	 *
76
	 * We're expanding who can use it, and then conditionally applying CSSTidy
77
	 * sanitization to users that do not have the `unfiltered_html` capability.
78
	 *
79
	 * @param $caps
80
	 * @param $cap
81
	 * @return array
82
	 */
83
	public static function map_meta_cap( $caps, $cap ) {
84
		if ( 'edit_css' === $cap ) {
85
			$caps = array( 'edit_theme_options' );
86
		}
87
		return $caps;
88
	}
89
90
	/**
91
	 * Handle our admin menu item and legacy page declaration.
92
	 */
93
	public static function admin_menu() {
94
		// Add in our legacy page to support old bookmarks and such.
95
		add_submenu_page( null, __( 'CSS', 'jetpack' ), __( 'Edit CSS', 'jetpack' ), 'edit_theme_options', 'editcss', array( __CLASS__, 'admin_page' ) );
96
97
		// Add in our new page slug that will redirect to the customizer.
98
		$hook = add_theme_page( __( 'CSS', 'jetpack' ), __( 'Edit CSS', 'jetpack' ), 'edit_theme_options', 'editcss-customizer-redirect', array( __CLASS__, 'admin_page' ) );
99
		add_action( "load-{$hook}", array( __CLASS__, 'customizer_redirect' ) );
100
	}
101
102
	/**
103
	 * Handle the redirect for the customizer.  This is necessary because
104
	 * we can't directly add customizer links to the admin menu.
105
	 *
106
	 * There is a core patch in trac that would make this unnecessary.
107
	 *
108
	 * @link https://core.trac.wordpress.org/ticket/39050
109
	 */
110
	public static function customizer_redirect() {
111
		wp_safe_redirect( self::customizer_link( array(
112
			'return_url' => wp_get_referer(),
113
		) ) );
114
	}
115
116
	/**
117
	 * Shows Preprocessor code in the Revisions screen, and ensures that post_content_filtered
118
	 * is maintained on revisions
119
	 *
120
	 * @param  array $fields  Post fields pertinent to revisions
121
	 * @return array          Modified array to include post_content_filtered
122
	 */
123
	public static function _wp_post_revision_fields( $fields, $post ) {
124
		// If we're passed in a revision, go get the main post instead.
125
		if ( 'revision' === $post['post_type'] ) {
126
			$main_post_id = wp_is_post_revision( $post['ID'] );
127
			$post = get_post( $main_post_id, ARRAY_A );
128
		}
129
		if ( 'custom_css' === $post['post_type'] ) {
130
			$fields['post_content'] = __( 'CSS', 'jetpack' );
131
			$fields['post_content_filtered'] = __( 'Preprocessor', 'jetpack' );
132
		}
133
		return $fields;
134
	}
135
136
	/**
137
	 * Get the published custom CSS post.
138
	 *
139
	 * @param string $stylesheet Optional. A theme object stylesheet name. Defaults to the current theme.
140
	 * @return WP_Post|null
141
	 */
142
	public static function get_css_post( $stylesheet = '' ) {
143
		return wp_get_custom_css_post( $stylesheet );
144
	}
145
146
	/**
147
	 * Get the ID of a Custom CSS post tying to a given stylesheet.
148
	 *
149
	 * @param string $stylesheet
150
	 * @return int
151
	 */
152
	public static function post_id( $stylesheet = '' ) {
153
		$post = self::get_css_post( $stylesheet );
154
		if ( $post instanceof WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
155
			return $post->ID;
156
		}
157
		return 0;
158
	}
159
160
	/**
161
	 * Partial for use in the Customizer.
162
	 */
163
	public static function echo_custom_css_partial() {
164
		echo wp_get_custom_css();
165
	}
166
167
	/**
168
	 * Admin page!
169
	 *
170
	 * This currently has two main uses -- firstly to display the css for an inactive
171
	 * theme if there are no revisions attached it to a legacy bug, and secondly to
172
	 * handle folks that have bookmarkes in their browser going to the old page for
173
	 * managing Custom CSS in Jetpack.
174
	 *
175
	 * If we ever add back in a non-Customizer CSS editor, this would be the place.
176
	 */
177
	public static function admin_page() {
178
		$post = null;
179
		$stylesheet = null;
180
		if ( isset( $_GET['id'] ) ) {
181
			$post_id = absint( $_GET['id'] );
182
			$post = get_post( $post_id );
183
			if ( $post instanceof WP_Post && 'custom_css' === $post->post_type ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
184
				$stylesheet = $post->post_title;
185
			}
186
		}
187
		?>
188
		<div class="wrap">
189
			<?php self::revisions_switcher_box( $stylesheet ); ?>
190
			<h1>
191
				<?php
192
				if ( $post ) {
193
					printf( 'Custom CSS for &#8220;%1$s&#8221;', wp_get_theme( $stylesheet )->Name );
194
				} else {
195
					esc_html_e( 'Custom CSS', 'jetpack' );
196
				}
197
				if ( current_user_can( 'customize' ) ) {
198
					printf(
199
						' <a class="page-title-action hide-if-no-customize" href="%1$s">%2$s</a>',
200
						esc_url( self::customizer_link() ),
201
						__( 'Manage with Live Preview', 'jetpack' )
202
					);
203
				}
204
				?>
205
			</h1>
206
			<p><?php esc_html_e( 'Custom CSS is now managed in the Customizer.', 'jetpack' ); ?></p>
207
			<?php if ( $post ) : ?>
208
				<div class="revisions">
209
					<h3><?php esc_html_e( 'CSS', 'jetpack' ); ?></h3>
210
					<textarea class="widefat" readonly><?php echo esc_textarea( $post->post_content ); ?></textarea>
211
					<?php if ( $post->post_content_filtered ) : ?>
212
						<h3><?php esc_html_e( 'Preprocessor', 'jetpack' ); ?></h3>
213
						<textarea class="widefat" readonly><?php echo esc_textarea( $post->post_content_filtered ); ?></textarea>
214
					<?php endif; ?>
215
				</div>
216
			<?php endif; ?>
217
		</div>
218
219
		<style>
220
			.other-themes-wrap {
221
				float: right;
222
				background-color: #fff;
223
				-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
224
				box-shadow: 0 1px 3px rgba(0,0,0,0.1);
225
				padding: 5px 10px;
226
				margin-bottom: 10px;
227
			}
228
			.other-themes-wrap label {
229
				display: block;
230
				margin-bottom: 10px;
231
			}
232
			.other-themes-wrap select {
233
				float: left;
234
				width: 77%;
235
			}
236
			.other-themes-wrap button {
237
				float: right;
238
				width: 20%;
239
			}
240
			.revisions {
241
				clear: both;
242
			}
243
			.revisions textarea {
244
				min-height: 300px;
245
				background: #fff;
246
			}
247
		</style>
248
		<script>
249
			(function($){
250
				var $switcher = $('.other-themes-wrap');
251
				$switcher.find('button').on('click', function(e){
252
					e.preventDefault();
253
					if ( $switcher.find('select').val() ) {
254
						window.location.href = $switcher.find('select').val();
255
					}
256
				});
257
			})(jQuery);
258
		</script>
259
		<?php
260
	}
261
262
	/**
263
	 * Build the URL to deep link to the Customizer.
264
	 *
265
	 * You can modify the return url via $args.
266
	 *
267
	 * @param array $args
268
	 * @return string
269
	 */
270
	public static function customizer_link( $args = array() ) {
271
		$args = wp_parse_args( $args, array(
272
			'return_url' => urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
273
		) );
274
275
		return add_query_arg(
276
			array(
277
				array(
278
					'autofocus' => array(
279
						'section' => 'custom_css'
280
					),
281
				),
282
				'return' => $args['return_url'],
283
			),
284
			admin_url( 'customize.php' )
285
		);
286
	}
287
288
	/**
289
	 * Handle the enqueueing and localizing for scripts to be used in the Customizer.
290
	 */
291
	public static function customize_controls_enqueue_scripts() {
292
		wp_enqueue_style( 'jetpack-customizer-css' );
293
		wp_enqueue_script( 'jetpack-customizer-css' );
294
295
		$content_help = __( 'Set a different content width for full size images.', 'jetpack' );
296
		if ( ! empty( $GLOBALS['content_width'] ) ) {
297
			$content_help .= sprintf( __( ' The default content width for the <strong>%s</strong> theme is %d pixels.', 'jetpack' ), wp_get_theme()->Name, intval( $GLOBALS['content_width'] ) );
298
		}
299
300
		wp_localize_script( 'jetpack-customizer-css', '_jp_css_settings', array(
301
			/** This filter is documented in modules/custom-css/custom-css.php */
302
			'useRichEditor' => ! jetpack_is_mobile() && apply_filters( 'safecss_use_ace', true ),
303
			'areThereCssRevisions' => self::are_there_css_revisions(),
304
			'revisionsUrl' => self::get_revisions_url(),
305
			'cssHelpUrl' => '//en.support.wordpress.com/custom-design/editing-css/',
306
			'l10n' => array(
307
				'mode'           => __( 'Start Fresh', 'jetpack' ),
308
				'mobile'         => __( 'On Mobile', 'jetpack' ),
309
				'contentWidth'   => $content_help,
310
				'revisions'      => _x( 'See full history', 'Toolbar button to see full CSS revision history', 'jetpack' ),
311
				'css_help_title' => _x( 'Help', 'Toolbar button to get help with custom CSS', 'jetpack' )
312
			)
313
		));
314
	}
315
316
	/**
317
	 * Check whether there are CSS Revisions for a given theme.
318
	 *
319
	 * Going forward, there should always be, but this was necessitated
320
	 * early on by https://core.trac.wordpress.org/ticket/30854
321
	 *
322
	 * @param string $stylesheet
323
	 * @return bool|null|WP_Post
324
	 */
325
	public static function are_there_css_revisions( $stylesheet = '' ) {
326
		$post = wp_get_custom_css_post( $stylesheet );
327
		if ( empty( $post ) ) {
328
			return $post;
329
		}
330
		return (bool) wp_get_post_revisions( $post );
331
	}
332
333
	/**
334
	 * Core doesn't have a function to get the revisions url for a given post ID.
335
	 *
336
	 * @param string $stylesheet
337
	 * @return null|string|void
338
	 */
339
	public static function get_revisions_url( $stylesheet = '' ) {
340
		$post = wp_get_custom_css_post( $stylesheet );
341
342
		// If we have any currently saved customizations...
343
		if ( $post instanceof WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
344
			$revisions = wp_get_post_revisions( $post->ID, array( 'posts_per_page' => 1 ) );
345
			$revision = reset( $revisions );
346
			return get_edit_post_link( $revision->ID );
347
		}
348
349
		return admin_url( 'themes.php?page=editcss' );
350
	}
351
352
    /**
353
     * Get a map of all theme names and theme stylesheets for mapping stuff.
354
     *
355
     * @return array
356
     */
357
	public static function get_themes() {
358
		$themes = wp_get_themes( array( 'errors' => null ) );
359
		$all = array();
360
		foreach ( $themes as $theme ) {
361
			$all[ $theme->name ] = $theme->stylesheet;
362
		}
363
		return $all;
364
	}
365
366
    /**
367
     * When we need to get all themes that have Custom CSS saved.
368
     *
369
     * @return array
370
     */
371
	public static function get_all_themes_with_custom_css() {
372
		$themes = self::get_themes();
373
		$custom_css = get_posts( array(
374
			'post_type'   => 'custom_css',
375
			'post_status' => get_post_stati(),
376
			'number'      => -1,
377
			'order'       => 'DESC',
378
			'orderby'     => 'modified',
379
		) );
380
		$return = array();
381
382
		foreach ( $custom_css as $post ) {
383
			$stylesheet = $post->post_title;
384
			$label      = array_search( $stylesheet, $themes );
385
386
			if ( ! $label ) {
387
				continue;
388
			}
389
390
			$return[ $stylesheet ] = array(
391
				'label' => $label,
392
				'post'  => $post,
393
			);
394
		}
395
396
		return $return;
397
	}
398
399
	/**
400
	 * Handle the enqueueing of scripts for customize previews.
401
	 */
402
	public static function wp_enqueue_scripts() {
403
		if ( is_customize_preview() ) {
404
			wp_enqueue_script( 'jetpack-customizer-css-preview' );
405
			wp_localize_script( 'jetpack-customizer-css-preview', 'jpCustomizerCssPreview', array(
406
				/** This filter is documented in modules/custom-css/custom-css.php */
407
				'preprocessors' => apply_filters( 'jetpack_custom_css_preprocessors', array() ),
408
			));
409
		}
410
	}
411
412
	/**
413
	 * Sanitize the CSS for users without `unfiltered_html`.
414
	 *
415
	 * @param $css
416
	 * @param array $args
417
	 * @return mixed|string
418
	 */
419
	public static function sanitize_css( $css, $args = array() ) {
420
		$args = wp_parse_args( $args, array(
421
			'force'        => false,
422
			'preprocessor' => null,
423
		) );
424
425
		if ( $args['force'] || ! current_user_can( 'unfiltered_html' ) ) {
426
427
			$warnings = array();
428
429
			safecss_class();
430
			$csstidy = new csstidy();
431
			$csstidy->optimise = new safecss( $csstidy );
0 ignored issues
show
Documentation introduced by
$csstidy is of type object<csstidy>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
432
433
			$csstidy->set_cfg( 'remove_bslash',              false );
434
			$csstidy->set_cfg( 'compress_colors',            false );
435
			$csstidy->set_cfg( 'compress_font-weight',       false );
436
			$csstidy->set_cfg( 'optimise_shorthands',        0 );
437
			$csstidy->set_cfg( 'remove_last_;',              false );
438
			$csstidy->set_cfg( 'case_properties',            false );
439
			$csstidy->set_cfg( 'discard_invalid_properties', true );
440
			$csstidy->set_cfg( 'css_level',                  'CSS3.0' );
441
			$csstidy->set_cfg( 'preserve_css',               true );
442
			$csstidy->set_cfg( 'template',                   dirname( __FILE__ ) . '/csstidy/wordpress-standard.tpl' );
443
444
			// Test for some preg_replace stuff.
445
			{
446
				$prev = $css;
447
				$css = preg_replace( '/\\\\([0-9a-fA-F]{4})/', '\\\\\\\\$1', $css );
448
				// prevent content: '\3434' from turning into '\\3434'
449
				$css = str_replace( array( '\'\\\\', '"\\\\' ), array( '\'\\', '"\\' ), $css );
450
				if ( $css !== $prev ) {
451
					$warnings[] = 'preg_replace found stuff';
452
				}
453
			}
454
455
			// Some people put weird stuff in their CSS, KSES tends to be greedy
456
			$css = str_replace( '<=', '&lt;=', $css );
457
458
			// Test for some kses stuff.
459
			{
460
				$prev = $css;
461
				// Why KSES instead of strip_tags?  Who knows?
462
				$css = wp_kses_split( $css, array(), array() );
463
				$css = str_replace( '&gt;', '>', $css ); // kses replaces lone '>' with &gt;
464
				// Why both KSES and strip_tags?  Because we just added some '>'.
465
				$css = strip_tags( $css );
466
467
				if ( $css != $prev ) {
468
					$warnings[] = 'kses found stuff';
469
				}
470
			}
471
472
			// if we're not using a preprocessor
473 View Code Duplication
			if ( ! $args['preprocessor'] ) {
474
475
				/**
476
				 * Fires before parsing the css with CSSTidy, but only if
477
				 * the preprocessor is not configured for use.
478
				 *
479
				 * @module custom-css
480
				 *
481
				 * @since 1.7.0
482
				 *
483
				 * @param obj $csstidy The csstidy object.
484
				 * @param string $css Custom CSS.
485
				 * @param array $args Array of custom CSS arguments.
486
				 */
487
				do_action( 'safecss_parse_pre', $csstidy, $css, $args );
488
489
				$csstidy->parse( $css );
490
491
				/**
492
				 * Fires after parsing the css with CSSTidy, but only if
493
				 * the preprocessor is not configured for use.
494
				 *
495
				 * @module custom-css
496
				 *
497
				 * @since 1.7.0
498
				 *
499
				 * @param obj $csstidy The csstidy object.
500
				 * @param array $warnings Array of warnings.
501
				 * @param array $args Array of custom CSS arguments.
502
				 */
503
				do_action( 'safecss_parse_post', $csstidy, $warnings, $args );
504
505
				$css = $csstidy->print->plain();
506
			}
507
		}
508
		return $css;
509
	}
510
511
	/**
512
	 * Override $content_width in customizer previews.
513
	 */
514
	public static function preview_content_width() {
515
		global $wp_customize;
516
		if ( ! is_customize_preview() ) {
517
			return;
518
		}
519
520
		$setting = $wp_customize->get_setting( 'jetpack_custom_css[content_width]' );
521
		if ( ! $setting ) {
522
			return;
523
		}
524
525
		$customized_content_width = (int) $setting->post_value();
526
		if ( ! empty( $customized_content_width ) ) {
527
			$GLOBALS['content_width'] = $customized_content_width;
528
		}
529
	}
530
531
	/**
532
	 * Filter the current theme's stylesheet for potentially nullifying it.
533
	 *
534
	 * @param $current
535
	 * @return mixed|void
536
	 */
537
	static function style_filter( $current ) {
538
		if ( is_admin() ) {
539
			return $current;
540
		} elseif ( self::is_freetrial() && ( ! self::is_preview() || ! current_user_can( 'switch_themes' ) ) ) {
541
			return $current;
542
		} elseif ( self::skip_stylesheet() ) {
543
			/** This filter is documented in modules/custom-css/custom-css.php */
544
			return apply_filters( 'safecss_style_filter_url', plugins_url( 'custom-css/css/blank.css', __FILE__ ) );
545
		}
546
547
		return $current;
548
	}
549
550
	/**
551
	 * Determine whether or not we should have the theme skip its main stylesheet.
552
	 *
553
	 * @return mixed The truthiness of this value determines whether the stylesheet should be skipped.
554
	 */
555
	static function skip_stylesheet() {
556
		/** This filter is documented in modules/custom-css/custom-css.php */
557
		$skip_stylesheet = apply_filters( 'safecss_skip_stylesheet', null );
558
		if ( ! is_null( $skip_stylesheet ) ) {
559
			return $skip_stylesheet;
560
		}
561
562
		$jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
563
		if ( isset( $jetpack_custom_css['replace'] ) ) {
564
			return $jetpack_custom_css['replace'];
565
		}
566
567
		return false;
568
	}
569
570
	/**
571
	 * Override $content_width in customizer previews.
572
	 *
573
	 * Runs on `safecss_skip_stylesheet` filter.
574
	 */
575
	public static function preview_skip_stylesheet( $skip_value ) {
576
		global $wp_customize;
577
		if ( ! is_customize_preview() ) {
578
			return $skip_value;
579
		}
580
581
		$setting = $wp_customize->get_setting( 'jetpack_custom_css[replace]' );
582
		if ( ! $setting ) {
583
			return $skip_value;
584
		}
585
586
		$customized_replace = $setting->post_value();
587
		if ( null !== $customized_replace ) {
588
			return $customized_replace;
589
		}
590
591
		return $skip_value;
592
	}
593
594
	/**
595
	 * Add Custom CSS section and controls.
596
	 */
597
	public static function customize_register( $wp_customize ) {
598
599
		// SETTINGS
600
601
		$wp_customize->add_setting( 'jetpack_custom_css[preprocessor]', array(
602
			'default' => '',
603
			'transport' => 'postMessage',
604
			'sanitize_callback' => array( __CLASS__, 'sanitize_preprocessor' ),
605
		) );
606
607
		$wp_customize->add_setting( 'jetpack_custom_css[replace]', array(
608
			'default' => false,
609
			'transport' => 'refresh',
610
		) );
611
612
		$wp_customize->add_setting( 'jetpack_custom_css[content_width]', array(
613
			'default' => '',
614
			'transport' => 'refresh',
615
			'sanitize_callback' => array( __CLASS__, 'intval_base10' ),
616
		) );
617
618
		// Add custom sanitization to the core css customizer setting.
619
		foreach ( $wp_customize->settings() as $setting ) {
620
			if ( $setting instanceof WP_Customize_Custom_CSS_Setting ) {
0 ignored issues
show
Bug introduced by
The class WP_Customize_Custom_CSS_Setting does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
621
				add_filter( "customize_sanitize_{$setting->id}", array( __CLASS__, 'sanitize_css_callback' ), 10, 2 );
622
			}
623
		}
624
625
		// CONTROLS
626
627
		// Overwrite the Core Control.
628
		$core_custom_css = $wp_customize->get_control( 'custom_css' );
629
		if ( $core_custom_css ) {
630
			$wp_customize->remove_control( 'custom_css' );
631
			$core_custom_css->type = 'jetpackCss';
632
			$wp_customize->add_control( $core_custom_css );
633
		}
634
635
		$wp_customize->selective_refresh->add_partial( 'custom_css', array(
636
			'type'                => 'custom_css',
637
			'selector'            => '#wp-custom-css',
638
			'container_inclusive' => false,
639
			'fallback_refresh'    => false,
640
			'settings'            => array(
641
				'custom_css[' . $wp_customize->get_stylesheet() . ']',
642
				'jetpack_custom_css[preprocessor]',
643
			),
644
			'render_callback' => array( __CLASS__, 'echo_custom_css_partial' ),
645
		) );
646
647
		$wp_customize->add_control( 'wpcom_custom_css_content_width_control', array(
648
			'type'     => 'text',
649
			'label'    => __( 'Media Width', 'jetpack' ),
650
			'section'  => 'custom_css',
651
			'settings' => 'jetpack_custom_css[content_width]',
652
		) );
653
654
		$wp_customize->add_control( 'jetpack_css_mode_control', array(
655
			'type'     => 'checkbox',
656
			'label'    => __( 'Don\'t use the theme\'s original CSS.', 'jetpack' ),
657
			'section'  => 'custom_css',
658
			'settings' => 'jetpack_custom_css[replace]',
659
		) );
660
661
		/**
662
		 * An action to grab on to if another Jetpack Module would like to add its own controls.
663
		 *
664
		 * @module custom-css
665
		 *
666
		 * @since 4.?.?
667
		 *
668
		 * @param $wp_customize The WP_Customize object.
669
		 */
670
		do_action( 'jetpack_custom_css_customizer_controls', $wp_customize );
671
672
		/** This filter is documented in modules/custom-css/custom-css.php */
673
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
674
		if ( ! empty( $preprocessors ) ) {
675
			$preprocessor_choices = array(
676
				'' => __( 'None', 'jetpack' ),
677
			);
678
679
			foreach ( $preprocessors as $preprocessor_key => $processor ) {
680
				$preprocessor_choices[$preprocessor_key] = $processor['name'];
681
			}
682
683
			$wp_customize->add_control( 'jetpack_css_preprocessors_control', array(
684
				'type'     => 'select',
685
				'choices'  => $preprocessor_choices,
686
				'label'    => __( 'Preprocessor', 'jetpack' ),
687
				'section'  => 'custom_css',
688
				'settings' => 'jetpack_custom_css[preprocessor]',
689
			) );
690
		}
691
692
	}
693
694
	/**
695
	 * The callback to handle sanitizing the CSS.  Takes different arguments, hence the proxy function.
696
	 *
697
	 * @param $css
698
	 * @param $setting
699
	 * @return mixed|string
700
	 */
701
	public static function sanitize_css_callback( $css, $setting ) {
0 ignored issues
show
Unused Code introduced by
The parameter $setting is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
702
		global $wp_customize;
703
		return self::sanitize_css( $css, array(
704
			'preprocessor' => $wp_customize->get_setting('jetpack_custom_css[preprocessor]')->value(),
705
		) );
706
	}
707
708
	/**
709
	 * Flesh out for wpcom.
710
	 *
711
	 * @todo
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
712
	 *
713
	 * @return bool
714
	 */
715
	public static function is_freetrial() {
716
		return false;
717
	}
718
719
	/**
720
	 * Flesh out for wpcom.
721
	 *
722
	 * @todo
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
723
	 *
724
	 * @return bool
725
	 */
726
	public static function is_preview() {
727
		return false;
728
	}
729
730
	/**
731
	 * Output the custom css for customize preview.
732
	 *
733
	 * @param $css
734
	 * @return mixed
735
	 */
736
	public static function customize_preview_wp_get_custom_css( $css ) {
737
		global $wp_customize;
738
739
		$preprocessor = $wp_customize->get_setting('jetpack_custom_css[preprocessor]')->value();
740
741
		// If it's empty, just return.
742
		if ( empty( $preprocessor ) ) {
743
			return $css;
744
		}
745
746
		/** This filter is documented in modules/custom-css/custom-css.php */
747
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
748
		if ( isset( $preprocessors[ $preprocessor ] ) ) {
749
			return call_user_func( $preprocessors[ $preprocessor ]['callback'], $css );
750
		}
751
752
		return $css;
753
	}
754
755
	/**
756
	 * @param $css
757
	 * @param $setting
758
	 * @return string
759
	 */
760
	public static function customize_value_custom_css( $css, $setting ) {
761
		// Find the current preprocessor
762
		$jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
763
		if ( isset( $jetpack_custom_css['preprocessor'] ) ) {
764
			$preprocessor = $jetpack_custom_css['preprocessor'];
765
		}
766
767
		// If it's not supported, just return.
768
		/** This filter is documented in modules/custom-css/custom-css.php */
769
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
770
		if ( ! isset( $preprocessors[ $preprocessor ] ) ) {
771
			return $css;
772
		}
773
774
		// Swap it for the `post_content_filtered` instead.
775
		$post = wp_get_custom_css_post( $setting->stylesheet );
776
		if ( $post && ! empty( $post->post_content_filtered ) ) {
777
			$css = $post->post_content_filtered;
778
		}
779
780
		return $css;
781
	}
782
783
	/**
784
	 * @param $args
785
	 * @param $css
786
	 * @param $setting
787
	 * @return mixed
788
	 */
789
	public static function customize_update_custom_css_post_content_args( $args, $css, $setting ) {
0 ignored issues
show
Unused Code introduced by
The parameter $setting is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
790
		// Find the current preprocessor
791
		$jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
792
		if ( empty( $jetpack_custom_css['preprocessor'] ) ) {
793
			return $args;
794
		}
795
796
		$preprocessor = $jetpack_custom_css['preprocessor'];
797
		/** This filter is documented in modules/custom-css/custom-css.php */
798
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
799
800
		// If it's empty, just return.
801
		if ( empty( $preprocessor ) ) {
802
			return $args;
803
		}
804
805 View Code Duplication
		if ( isset( $preprocessors[ $preprocessor ] ) ) {
806
			$args['post_content_filtered'] = $css;
807
			$args['post_content'] = call_user_func( $preprocessors[ $preprocessor ]['callback'], $css );
808
		}
809
810
		return $args;
811
	}
812
813
	/**
814
	 * Filter to handle the processing of preprocessed css on save.
815
	 *
816
	 * @param $args
817
	 * @param $stylesheet
818
	 * @return mixed
819
	 */
820
	public static function update_custom_css_data( $args, $stylesheet ) {
0 ignored issues
show
Unused Code introduced by
The parameter $stylesheet is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
821
		// Find the current preprocessor
822
		$jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
823
		if ( empty( $jetpack_custom_css['preprocessor'] ) ) {
824
			return $args;
825
		}
826
827
		/** This filter is documented in modules/custom-css/custom-css.php */
828
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
829
		$preprocessor = $jetpack_custom_css['preprocessor'];
830
831
		// If we have a preprocessor specified ...
832
		if ( isset( $preprocessors[ $preprocessor ] ) ) {
833
			// And no other preprocessor has run ...
834
			if ( empty( $args['preprocessed'] ) ) {
835
				$args['preprocessed'] = $args['css'];
836
				$args['css'] = call_user_func( $preprocessors[ $preprocessor ]['callback'], $args['css'] );
837
			} else {
838
				trigger_error( 'Jetpack CSS Preprocessor specified, but something else has already modified the argument.', E_USER_WARNING );
839
			}
840
		}
841
842
		return $args;
843
	}
844
845
	/**
846
	 * When on the edit screen, make sure the custom content width
847
	 * setting is applied to the large image size.
848
	 *
849
	 * @param array $dims
850
	 * @param string $size
851
	 * @param null $context
852
	 * @return array
853
	 */
854 View Code Duplication
	static function editor_max_image_size( $dims, $size = 'medium', $context = null ) {
855
		list( $width, $height ) = $dims;
856
857
		if ( 'large' === $size && 'edit' === $context ) {
858
			$width = Jetpack::get_content_width();
859
		}
860
861
		return array( $width, $height );
862
	}
863
864
	/**
865
	 * Override the content_width with a custom value if one is set.
866
	 *
867
	 * @param $content_width
868
	 * @return int
869
	 */
870
	static function jetpack_content_width( $content_width ) {
871
		$custom_content_width = 0;
872
873
		$jetpack_custom_css = get_theme_mod( 'jetpack_custom_css', array() );
874
		if ( isset( $jetpack_custom_css['content_width'] ) ) {
875
			$custom_content_width = $jetpack_custom_css['content_width'];
876
		}
877
878
		if ( $custom_content_width > 0 ) {
879
			return $custom_content_width;
880
		}
881
882
		return $content_width;
883
	}
884
885
	/**
886
	 * Currently this filter function gets called on
887
	 * 'template_redirect' action and
888
	 * 'admin_init' action
889
	 */
890 View Code Duplication
	static function set_content_width(){
891
		// Don't apply this filter on the Edit CSS page
892
		if ( isset( $_GET['page'] ) && 'editcss' === $_GET['page'] && is_admin() ) {
893
			return;
894
		}
895
896
		$GLOBALS['content_width'] = Jetpack::get_content_width();
897
	}
898
899
	/**
900
	 * Make sure the preprocessor we're saving is one we know about.
901
	 *
902
	 * @param $preprocessor The preprocessor to sanitize.
903
	 * @return null|string
904
	 */
905
	public static function sanitize_preprocessor( $preprocessor ) {
906
		/** This filter is documented in modules/custom-css/custom-css.php */
907
		$preprocessors = apply_filters( 'jetpack_custom_css_preprocessors', array() );
908
		if ( empty( $preprocessor ) || array_key_exists( $preprocessor, $preprocessors ) ) {
909
			return $preprocessor;
910
		}
911
		return null;
912
	}
913
914
	/**
915
	 * Get the base10 intval.
916
	 *
917
	 * This is used as a setting's sanitize_callback; we can't use just plain
918
	 * intval because the second argument is not what intval() expects.
919
	 *
920
	 * @access public
921
	 *
922
	 * @param mixed $value Number to convert.
923
	 * @return int Integer.
924
	 */
925
	public static function intval_base10( $value ) {
926
		return intval( $value, 10 );
927
	}
928
929
	/**
930
	 * Add a footer action on revision.php to print some customizations for the theme switcher.
931
	 */
932
	public static function load_revision_php() {
933
		add_action( 'admin_footer', array( __CLASS__, 'revision_admin_footer' ) );
934
	}
935
936
	/**
937
	 * Print the theme switcher on revision.php and move it into place.
938
	 */
939
	public static function revision_admin_footer() {
940
		$post = get_post();
941
		if ( 'custom_css' !== $post->post_type ) {
942
			return;
943
		}
944
		$stylesheet = $post->post_title;
945
		?>
946
<script type="text/html" id="tmpl-other-themes-switcher">
947
	<?php self::revisions_switcher_box( $stylesheet ); ?>
948
</script>
949
<style>
950
.other-themes-wrap {
951
	float: right;
952
	background-color: #fff;
953
	-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.1);
954
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
955
	padding: 5px 10px;
956
	margin-bottom: 10px;
957
}
958
.other-themes-wrap label {
959
	display: block;
960
	margin-bottom: 10px;
961
}
962
.other-themes-wrap select {
963
	float: left;
964
	width: 77%;
965
}
966
.other-themes-wrap button {
967
	float: right;
968
	width: 20%;
969
}
970
.revisions {
971
	clear: both;
972
}
973
/* Hide the back-to-post link */
974
.long-header + a {
975
	display: none;
976
}
977
</style>
978
<script>
979
(function($){
980
	var switcher = $('#tmpl-other-themes-switcher').html(),
981
		qty = $( switcher ).find('select option').length,
982
		$switcher;
983
984
	if ( qty >= 3 ) {
985
		$('h1.long-header').before( switcher );
986
		$switcher = $('.other-themes-wrap');
987
		$switcher.find('button').on('click', function(e){
988
			e.preventDefault();
989
			if ( $switcher.find('select').val() ) {
990
				window.location.href = $switcher.find('select').val();
991
			}
992
		})
993
	}
994
})(jQuery);
995
</script>
996
		<?php
997
	}
998
999
	/**
1000
	 * The HTML for the theme revision switcher box.
1001
	 *
1002
	 * @param string $stylesheet
1003
	 */
1004
	public static function revisions_switcher_box( $stylesheet = '' ) {
1005
		$themes = self::get_all_themes_with_custom_css();
1006
		?>
1007
		<div class="other-themes-wrap">
1008
			<label for="other-themes"><?php esc_html_e( 'Select another theme to view its custom CSS.', 'jetpack' ); ?></label>
1009
			<select id="other-themes">
1010
				<option value=""><?php esc_html_e( 'Select a theme&hellip;', 'jetpack' ); ?></option>
1011
				<?php
1012
				foreach ( $themes as $theme_stylesheet => $data ) {
1013
					$revisions = wp_get_post_revisions( $data['post']->ID, array( 'posts_per_page' => 1 ) );
1014
					if ( ! $revisions ) {
1015
						?>
1016
						<option value="<?php echo esc_url( add_query_arg( 'id', $data['post']->ID, menu_page_url( 'editcss', 0 ) ) ); ?>" <?php disabled( $stylesheet, $theme_stylesheet ); ?>>
1017
							<?php echo esc_html( $data['label'] ); ?>
1018
							<?php printf( esc_html__( '(modified %s ago)', 'jetpack' ), human_time_diff( strtotime( $data['post']->post_modified_gmt ) ) ); ?></option>
1019
						<?php
1020
						continue;
1021
					}
1022
					$revision = array_shift( $revisions );
1023
					?>
1024
					<option value="<?php echo esc_url( get_edit_post_link( $revision->ID ) ); ?>" <?php disabled( $stylesheet, $theme_stylesheet ); ?>>
1025
						<?php echo esc_html( $data['label'] ); ?>
1026
						<?php printf( esc_html__( '(modified %s ago)', 'jetpack' ), human_time_diff( strtotime( $data['post']->post_modified_gmt ) ) ); ?></option>
1027
					<?php
1028
				}
1029
				?>
1030
			</select>
1031
			<button class="button" id="other_theme_custom_css_switcher"><?php esc_html_e( 'Switch', 'jetpack' ); ?></button>
1032
		</div>
1033
		<?php
1034
	}
1035
}
1036
1037
Jetpack_Custom_CSS_Enhancements::add_hooks();
1038
1039 View Code Duplication
if ( ! function_exists( 'safecss_class' ) ) :
1040
/**
1041
 * Load in the class only when needed.  Makes lighter load by having one less class in memory.
1042
 */
1043
function safecss_class() {
1044
	// Wrapped so we don't need the parent class just to load the plugin
1045
	if ( class_exists('safecss') ) {
1046
		return;
1047
	}
1048
1049
	require_once( dirname( __FILE__ ) . '/csstidy/class.csstidy.php' );
1050
1051
	/**
1052
	 * Class safecss
1053
	 */
1054
	class safecss extends csstidy_optimise {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
1055
1056
		function postparse() {
1057
1058
			/**
1059
			 * Fires after parsing the css.
1060
			 *
1061
			 * @module custom-css
1062
			 *
1063
			 * @since 1.8.0
1064
			 *
1065
			 * @param obj $this CSSTidy object.
1066
			 */
1067
			do_action( 'csstidy_optimize_postparse', $this );
1068
1069
			return parent::postparse();
1070
		}
1071
1072
		function subvalue() {
1073
1074
			/**
1075
			 * Fires before optimizing the Custom CSS subvalue.
1076
			 *
1077
			 * @module custom-css
1078
			 *
1079
			 * @since 1.8.0
1080
			 *
1081
			 * @param obj $this CSSTidy object.
1082
			 **/
1083
			do_action( 'csstidy_optimize_subvalue', $this );
1084
1085
			return parent::subvalue();
1086
		}
1087
	}
1088
}
1089
endif;
1090