Passed
Push — develop ( 2f30f7...6d2e79 )
by Aristeides
03:38
created

postmessage/class-kirki-modules-postmessage.php (1 issue)

Severity
1
<?php
2
/**
3
 * Automatic postMessage scripts calculation for Kirki controls.
4
 *
5
 * @package     Kirki
6
 * @category    Modules
7
 * @author      Aristeides Stathopoulos
8
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
9
 * @license    https://opensource.org/licenses/MIT
10
 * @since       3.0.0
11
 */
12
13
// Exit if accessed directly.
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Adds styles to the customizer.
20
 */
21
class Kirki_Modules_PostMessage {
22
23
	/**
24
	 * The object instance.
25
	 *
26
	 * @static
27
	 * @access private
28
	 * @since 3.0.0
29
	 * @var object
30
	 */
31
	private static $instance;
32
33
	/**
34
	 * The script.
35
	 *
36
	 * @access protected
37
	 * @since 3.0.0
38
	 * @var string
39
	 */
40
	protected $script = '';
41
42
	/**
43
	 * Constructor.
44
	 *
45
	 * @access protected
46
	 * @since 3.0.0
47
	 */
48
	protected function __construct() {
49
		add_action( 'customize_preview_init', array( $this, 'postmessage' ) );
50
	}
51
52
	/**
53
	 * Gets an instance of this object.
54
	 * Prevents duplicate instances which avoid artefacts and improves performance.
55
	 *
56
	 * @static
57
	 * @access public
58
	 * @since 3.0.0
59
	 * @return object
60
	 */
61
	public static function get_instance() {
62
		if ( ! self::$instance ) {
63
			self::$instance = new self();
64
		}
65
		return self::$instance;
66
	}
67
68
	/**
69
	 * Enqueues the postMessage script
70
	 * and adds variables to it using the wp_localize_script function.
71
	 * The rest is handled via JS.
72
	 */
73
	public function postmessage() {
74
		wp_enqueue_script( 'kirki_auto_postmessage', trailingslashit( Kirki::$url ) . 'modules/postmessage/postmessage.js', array( 'jquery', 'customize-preview' ), KIRKI_VERSION, true );
75
		$fields = Kirki::$fields;
76
		foreach ( $fields as $field ) {
77
			if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
78
				$this->script .= $this->script( $field );
79
			}
80
		}
81
		$this->script = apply_filters( 'kirki_postmessage_script', $this->script );
82
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
83
	}
84
85
	/**
86
	 * Generates script for a single field.
87
	 *
88
	 * @access protected
89
	 * @since 3.0.0
90
	 * @param array $args The arguments.
91
	 */
92
	protected function script( $args ) {
93
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
94
95
		$add_css = false;
96
		foreach ( $args['js_vars'] as $js_var ) {
97
			if ( ! isset( $js_var['function'] ) || 'html' !== $js_var['function'] ) {
98
				$add_css = true;
99
			}
100
			if ( isset( $js_var['context'] ) && ! in_array( 'front', $js_var['context'] ) ) {
0 ignored issues
show
Not using strict comparison for in_array; supply true for third argument.
Loading history...
101
				$add_css = false;
102
			}
103
		}
104
105
		if ( $add_css ) {
106
107
			// append unique style tag if not exist
108
			// The style ID.
109
			$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
110
			$script  .= 'if(null===document.getElementById(\'' . $style_id . '\')||\'undefined\'===typeof document.getElementById(\'' . $style_id . '\')){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
111
		}
112
113
		// Add anything we need before the main script.
114
		$script .= $this->before_script( $args );
115
116
		$field = array(
117
			'scripts' => array(),
118
		);
119
120
		// Loop through the js_vars and generate the script.
121
		foreach ( $args['js_vars'] as $key => $js_var ) {
122
123
			// Skip styles if "exclude" is defined and value is excluded.
124
			if ( isset( $js_var['exclude'] ) ) {
125
				$js_var['exclude'] = (array) $js_var['exclude'];
126
				$script           .= 'exclude=false;';
127
				foreach ( $js_var['exclude'] as $exclussion ) {
128
					$script .= "if(newval=='{$exclussion}'||(''==='{$exclussion}'&&_.isObject(newval)&&_.isEmpty(newval))){exclude=true;}";
129
				}
130
			}
131
			if ( isset( $js_var['element'] ) ) {
132
133
				// Array to string.
134
				if ( is_array( $js_var['element'] ) ) {
135
					$js_var['element'] = implode( ',', $js_var['element'] );
136
				}
137
138
				// Replace single quotes with double quotes to avoid issues with the compiled JS.
139
				$js_var['element'] = str_replace( '\'', '"', $js_var['element'] );
140
			}
141
			if ( isset( $js_var['function'] ) && 'html' === $js_var['function'] ) {
142
				$script .= $this->script_html_var( $js_var );
143
				continue;
144
			}
145
			$js_var['index_key'] = $key;
146
			$callback            = $this->get_callback( $args );
147
			if ( is_callable( $callback ) ) {
148
				$field['scripts'][ $key ] = call_user_func_array( $callback, array( $js_var, $args ) );
149
				continue;
150
			}
151
			$field['scripts'][ $key ] = $this->script_var( $js_var );
152
		}
153
		$combo_extra_script = '';
154
		$combo_css_script   = '';
155
		foreach ( $field['scripts'] as $script_array ) {
156
			$combo_extra_script .= $script_array['script'];
157
			$combo_css_script   .= ( 'css' !== $combo_css_script ) ? $script_array['css'] : '';
158
		}
159
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
160
161
		$script .= $combo_extra_script . "var cssContent={$text};";
162
		if ( isset( $js_var['exclude'] ) ) {
163
			$script .= 'if(true===exclude){cssContent="";}';
164
		}
165
		if ( $add_css ) {
166
			$script .= "jQuery('#{$style_id}').text(cssContent);jQuery('#{$style_id}').appendTo('head');";
167
		}
168
		$script .= '});});';
169
		return $script;
170
	}
171
172
	/**
173
	 * Generates script for a single js_var when using "html" as function.
174
	 *
175
	 * @access protected
176
	 * @since 3.0.0
177
	 * @param array $args  The arguments for this js_var.
178
	 */
179
	protected function script_html_var( $args ) {
180
		$script = ( isset( $args['choice'] ) ) ? "newval=newval['{$args['choice']}'];" : '';
181
182
		// Apply the value_pattern.
183
		if ( isset( $args['value_pattern'] ) && '' !== $args['value_pattern'] ) {
184
			$script .= $this->value_pattern_replacements( 'newval', $args );
185
		}
186
187
		if ( isset( $args['attr'] ) ) {
188
			$script .= "jQuery('{$args['element']}').attr('{$args['attr']}',newval);";
189
			return $script;
190
		}
191
		$script .= "jQuery('{$args['element']}').html(newval);";
192
		return $script;
193
	}
194
195
	/**
196
	 * Generates script for a single js_var.
197
	 *
198
	 * @access protected
199
	 * @since 3.0.0
200
	 * @param array $args  The arguments for this js_var.
201
	 */
202
	protected function script_var( $args ) {
203
		$script          = '';
204
		$property_script = '';
205
206
		$value_key        = 'newval' . $args['index_key'];
207
		$property_script .= $value_key . '=newval;';
208
209
		$args = $this->get_args( $args );
210
211
		// Apply callback to the value if a callback is defined.
212
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
213
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
214
		}
215
216
		// Apply the value_pattern.
217
		if ( '' !== $args['value_pattern'] ) {
218
			$script .= $this->value_pattern_replacements( $value_key, $args );
219
		}
220
221
		// Tweak to add url() for background-images.
222
		if ( 'background-image' === $args['property'] && ( ! isset( $args['value_pattern'] ) || false === strpos( $args['value_pattern'], 'gradient' ) ) ) {
223
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'")\';}';
224
		}
225
226
		// Apply prefix.
227
		$value = $value_key;
228
		if ( '' !== $args['prefix'] ) {
229
			$value = "'" . $args['prefix'] . "'+" . $value_key;
230
		}
231
		$css = $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}';
232
		if ( isset( $args['media_query'] ) ) {
233
			$css = $args['media_query'] . '{' . $css . '}';
234
		}
235
		return array(
236
			'script' => $property_script . $script,
237
			'css'    => $css,
238
		);
239
	}
240
241
	/**
242
	 * Processes script generation for fields that save an array.
243
	 *
244
	 * @access protected
245
	 * @since 3.0.0
246
	 * @param array $args  The arguments for this js_var.
247
	 */
248
	protected function script_var_array( $args ) {
249
		$script          = ( 0 === $args['index_key'] ) ? 'css=\'\';' : '';
250
		$property_script = '';
251
252
		// Define choice.
253
		$choice = ( isset( $args['choice'] ) && '' !== $args['choice'] ) ? $args['choice'] : '';
254
255
		$value_key        = 'newval' . $args['index_key'];
256
		$property_script .= $value_key . '=newval;';
257
258
		$args = $this->get_args( $args );
259
260
		// Apply callback to the value if a callback is defined.
261
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
262
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
263
		}
264
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
265
266
		// Apply the value_pattern.
267
		if ( '' !== $args['value_pattern'] ) {
268
			$script .= $this->value_pattern_replacements( 'subValue', $args );
269
		}
270
271
		// Tweak to add url() for background-images.
272
		if ( '' === $choice || 'background-image' === $choice ) {
273
			$script .= 'if(\'background-image\'===\'' . $args['property'] . '\'||\'background-image\'===subKey){if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'")\';}}';
274
		}
275
276
		// Apply prefix.
277
		$value = $value_key;
278
		if ( '' !== $args['prefix'] ) {
279
			$value = '\'' . $args['prefix'] . '\'+subValue';
280
		}
281
282
		// Mostly used for padding, margin & position properties.
283
		$direction_script  = 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
284
		$direction_script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
285
286
		// Allows us to apply this just for a specific choice in the array of the values.
287
		if ( '' !== $choice ) {
288
			$choice_is_direction = ( false !== strpos( $choice, 'top' ) || false !== strpos( $choice, 'bottom' ) || false !== strpos( $choice, 'left' ) || false !== strpos( $choice, 'right' ) );
289
290
			// The script.
291
			$script .= 'if(\'' . $choice . '\'===subKey){';
292
			$script .= ( $choice_is_direction ) ? $direction_script . 'else{' : '';
293
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
294
			$script .= ( $choice_is_direction ) ? '}' : '';
295
			$script .= '}';
296
		} else {
297
298
			// This is where most object-based fields will go.
299
			$script .= $direction_script . 'else{css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
300
		}
301
		$script .= '});';
302
303
		if ( isset( $args['media_query'] ) ) {
304
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
305
		}
306
307
		return array(
308
			'script' => $property_script . $script,
309
			'css'    => 'css',
310
		);
311
	}
312
313
	/**
314
	 * Processes script generation for typography fields.
315
	 *
316
	 * @access protected
317
	 * @since 3.0.0
318
	 * @param array $args  The arguments for this js_var.
319
	 * @param array $field The field arguments.
320
	 */
321
	protected function script_var_typography( $args, $field ) {
322
		$args = $this->get_args( $args );
323
324
		$script = '';
325
		$css    = '';
326
327
		// Load the font using WenFontloader.
328
		// This is a bit ugly because wp_add_inline_script doesn't allow adding <script> directly.
329
		$webfont_loader = 'sc=\'a\';jQuery(\'head\').append(sc.replace(\'a\',\'<\')+\'script>if(!_.isUndefined(WebFont)&&fontFamily){WebFont.load({google:{families:["\'+fontFamily.replace( /\"/g, \'&quot;\' )+\':\'+variant+\'cyrillic,cyrillic-ext,devanagari,greek,greek-ext,khmer,latin,latin-ext,vietnamese,hebrew,arabic,bengali,gujarati,tamil,telugu,thai"]}});}\'+sc.replace(\'a\',\'<\')+\'/script>\');';
330
331
		// Add the css.
332
		$css_build_array  = array(
333
			'font-family'     => 'fontFamily',
334
			'font-size'       => 'fontSize',
335
			'line-height'     => 'lineHeight',
336
			'letter-spacing'  => 'letterSpacing',
337
			'word-spacing'    => 'wordSpacing',
338
			'text-align'      => 'textAlign',
339
			'text-transform'  => 'textTransform',
340
			'text-decoration' => 'textDecoration',
341
			'color'           => 'color',
342
			'font-weight'     => 'fontWeight',
343
			'font-style'      => 'fontStyle',
344
		);
345
		$choice_condition = ( isset( $args['choice'] ) && '' !== $args['choice'] && isset( $css_build_array[ $args['choice'] ] ) );
346
		$script          .= ( ! $choice_condition ) ? $webfont_loader : '';
347
		foreach ( $css_build_array as $property => $var ) {
348
			if ( $choice_condition && $property !== $args['choice'] ) {
349
				continue;
350
			}
351
			// Fixes https://github.com/aristath/kirki/issues/1436.
352
			if ( ! isset( $field['default'] ) || (
353
				( 'font-family' === $property && ! isset( $field['default']['font-family'] ) ) ||
354
				( 'font-size' === $property && ! isset( $field['default']['font-size'] ) ) ||
355
				( 'line-height' === $property && ! isset( $field['default']['line-height'] ) ) ||
356
				( 'letter-spacing' === $property && ! isset( $field['default']['letter-spacing'] ) ) ||
357
				( 'word-spacing' === $property && ! isset( $field['default']['word-spacing'] ) ) ||
358
				( 'text-align' === $property && ! isset( $field['default']['text-align'] ) ) ||
359
				( 'text-transform' === $property && ! isset( $field['default']['text-transform'] ) ) ||
360
				( 'text-decoration' === $property && ! isset( $field['default']['text-decoration'] ) ) ||
361
				( 'color' === $property && ! isset( $field['default']['color'] ) ) ||
362
				( 'font-weight' === $property && ! isset( $field['default']['variant'] ) && ! isset( $field['default']['font-weight'] ) ) ||
363
				( 'font-style' === $property && ! isset( $field['default']['variant'] ) && ! isset( $field['default']['font-style'] ) )
364
				) ) {
365
				continue;
366
			}
367
			$script .= ( $choice_condition && 'font-family' === $args['choice'] ) ? $webfont_loader : '';
368
369
			if ( 'font-family' === $property || ( isset( $args['choice'] ) && 'font-family' === $args['choice'] ) ) {
370
				$css .= 'fontFamilyCSS=fontFamily;if(0<fontFamily.indexOf(\' \')&&-1===fontFamily.indexOf(\'"\')){fontFamilyCSS=\'"\'+fontFamily+\'"\';}';
371
				$var  = 'fontFamilyCSS';
372
			}
373
			$var  = ( ( empty( $args['prefix'] ) ) ? '' : '\'' . $args['prefix'] . '\'+' ) . $var . ( ( empty( $args['units'] ) ) ? '' : '+\'' . $args['units'] . '\'' ) . ( ( empty( $args['suffix'] ) ) ? '' : '+\'' . $args['suffix'] . '\'' );
374
			$css .= 'css+=(\'\'!==' . $var . ')?\'' . $args['element'] . '\'+\'{' . $property . ':\'+' . $var . '+\';}\':\'\';';
375
		}
376
377
		$script .= $css;
378
		if ( isset( $args['media_query'] ) ) {
379
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
380
		}
381
		return array(
382
			'script' => $script,
383
			'css'    => 'css',
384
		);
385
	}
386
387
	/**
388
	 * Processes script generation for typography fields.
389
	 *
390
	 * @access protected
391
	 * @since 3.0.0
392
	 * @param array $args  The arguments for this js_var.
393
	 */
394
	protected function script_var_image( $args ) {
395
		$return = $this->script_var( $args );
396
		return array(
397
			'script' => 'newval=(!_.isUndefined(newval.url))?newval.url:newval;' . $return['script'],
398
			'css'    => $return['css'],
399
		);
400
	}
401
402
	/**
403
	 * Adds anything we need before the main script.
404
	 *
405
	 * @access private
406
	 * @since 3.0.0
407
	 * @param array $args The field args.
408
	 * @return string
409
	 */
410
	private function before_script( $args ) {
411
		$script = '';
412
		if ( isset( $args['type'] ) ) {
413
			switch ( $args['type'] ) {
414
				case 'kirki-typography':
415
					$script .= 'fontFamily=(_.isUndefined(newval[\'font-family\']))?\'\':newval[\'font-family\'];variant=(_.isUndefined(newval.variant))?\'400\':newval.variant;fontSize=(_.isUndefined(newval[\'font-size\']))?\'\':newval[\'font-size\'];lineHeight=(_.isUndefined(newval[\'line-height\']))?\'\':newval[\'line-height\'];letterSpacing=(_.isUndefined(newval[\'letter-spacing\']))?\'\':newval[\'letter-spacing\'];wordSpacing=(_.isUndefined(newval[\'word-spacing\']))?\'\':newval[\'word-spacing\'];textAlign=(_.isUndefined(newval[\'text-align\']))?\'\':newval[\'text-align\'];textTransform=(_.isUndefined(newval[\'text-transform\']))?\'\':newval[\'text-transform\'];textDecoration=(_.isUndefined(newval[\'text-decoration\']))?\'\':newval[\'text-decoration\'];color=(_.isUndefined(newval.color))?\'\':newval.color;fw=(!_.isString(newval.variant))?\'400\':newval.variant.match(/\d/g);fontWeight=(!_.isObject(fw))?400:fw.join(\'\');fontStyle=(variant&&-1!==variant.indexOf(\'italic\'))?\'italic\':\'normal\';css=\'\';';
416
					break;
417
			}
418
		}
419
		return $script;
420
	}
421
422
	/**
423
	 * Sanitizes the arguments and makes sure they are all there.
424
	 *
425
	 * @access private
426
	 * @since 3.0.0
427
	 * @param array $args The arguments.
428
	 * @return array
429
	 */
430
	private function get_args( $args ) {
431
432
		// Make sure everything is defined to avoid "undefined index" errors.
433
		$args = wp_parse_args(
434
			$args, array(
435
				'element'       => '',
436
				'property'      => '',
437
				'prefix'        => '',
438
				'suffix'        => '',
439
				'units'         => '',
440
				'js_callback'   => array( '', '' ),
441
				'value_pattern' => '',
442
			)
443
		);
444
445
		// Element should be a string.
446
		if ( is_array( $args['element'] ) ) {
447
			$args['element'] = implode( ',', $args['element'] );
448
		}
449
450
		// Make sure arguments that are passed-on to callbacks are strings.
451
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
452
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
453
		}
454
455
		if ( ! isset( $args['js_callback'][1] ) ) {
456
			$args['js_callback'][1] = '';
457
		}
458
		return $args;
459
	}
460
461
	/**
462
	 * Returns script for value_pattern & replacements.
463
	 *
464
	 * @access private
465
	 * @since 3.0.0
466
	 * @param string $value   The value placeholder.
467
	 * @param array  $js_vars The js_vars argument.
468
	 * @return string         The script.
469
	 */
470
	private function value_pattern_replacements( $value, $js_vars ) {
471
		$script = '';
472
		$alias  = $value;
473
		if ( ! isset( $js_vars['value_pattern'] ) ) {
474
			return $value;
475
		}
476
		$value = $js_vars['value_pattern'];
477
		if ( isset( $js_vars['pattern_replace'] ) ) {
478
			$script .= 'settings=window.wp.customize.get();';
479
			foreach ( $js_vars['pattern_replace'] as $search => $replace ) {
480
				$replace = '\'+settings["' . $replace . '"]+\'';
481
				$value   = str_replace( $search, $replace, $js_vars['value_pattern'] );
482
				$value   = trim( $value, '+' );
483
			}
484
		}
485
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
486
		$value_compiled = trim( $value_compiled, '+' );
487
488
		return $script . $alias . '=\'' . $value_compiled . '\';';
489
	}
490
491
	/**
492
	 * Get the callback function/method we're going to use for this field.
493
	 *
494
	 * @access private
495
	 * @since 3.0.0
496
	 * @param array $args The field args.
497
	 * @return string|array A callable function or method.
498
	 */
499
	protected function get_callback( $args ) {
500
		switch ( $args['type'] ) {
501
			case 'kirki-background':
502
			case 'kirki-dimensions':
503
			case 'kirki-multicolor':
504
			case 'kirki-sortable':
505
				$callback = array( $this, 'script_var_array' );
506
				break;
507
			case 'kirki-typography':
508
				$callback = array( $this, 'script_var_typography' );
509
				break;
510
			case 'kirki-image':
511
				$callback = array( $this, 'script_var_image' );
512
				break;
513
			default:
514
				$callback = array( $this, 'script_var' );
515
		}
516
		return $callback;
517
	}
518
}
519