Completed
Pull Request — trunk (#598)
by
unknown
19:10
created

CMB2_Sanitize::_save_utc_value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/**
3
 * CMB2 field sanitization
4
 *
5
 * @since  0.0.4
6
 *
7
 * @category  WordPress_Plugin
8
 * @package   CMB2
9
 * @author    WebDevStudios
10
 * @license   GPL-2.0+
11
 * @link      http://webdevstudios.com
12
 *
13
 * @method string _id()
14
 */
15
class CMB2_Sanitize {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
16
17
	/**
18
	 * A CMB field object
19
	 * @var CMB2_Field object
20
	 */
21
	public $field;
22
23
	/**
24
	 * Field's value
25
	 * @var mixed
26
	 */
27
	public $value;
28
29
	/**
30
	 * Setup our class vars
31
	 * @since 1.1.0
32
	 * @param CMB2_Field $field A CMB2 field object
33
	 * @param mixed      $value Field value
34
	 */
35
	public function __construct( CMB2_Field $field, $value ) {
36
		$this->field = $field;
37
		$this->value = stripslashes_deep( $value ); // get rid of those evil magic quotes
38
	}
39
40
	/**
41
	 * Catchall method if field's 'sanitization_cb' is NOT defined, or field type does not have a corresponding validation method
42
	 * @since  1.0.0
43
	 * @param  string $name      Non-existent method name
44
	 * @param  array  $arguments All arguments passed to the method
45
	 */
46
	public function __call( $name, $arguments ) {
47
		return $this->default_sanitization();
48
	}
49
50
	/**
51
	 * Default fallback sanitization method. Applies filters.
52
	 * @since  1.0.2
53
	 */
54
	public function default_sanitization() {
55
56
		/**
57
		 * This exists for back-compatibility, but validation
58
		 * is not what happens here.
59
		 * @deprecated See documentation for "cmb2_sanitize_{$this->type()}".
60
		 */
61
		$override_value = apply_filters( "cmb2_validate_{$this->field->type()}", null, $this->value, $this->field->object_id, $this->field->args(), $this );
62
63
		if ( null !== $override_value ) {
64
			return $override_value;
65
		}
66
67
		$sanitized_value = '';
68
		switch ( $this->field->type() ) {
69
			case 'wysiwyg':
70
			case 'textarea_small':
71
				$sanitized_value = $this->textarea();
72
				break;
73
			case 'taxonomy_select':
74
			case 'taxonomy_radio':
75
			case 'taxonomy_radio_inline':
76
			case 'taxonomy_multicheck':
77
			case 'taxonomy_multicheck_inline':
78
				if ( $this->field->args( 'taxonomy' ) ) {
79
					wp_set_object_terms( $this->field->object_id, $this->value, $this->field->args( 'taxonomy' ) );
80
				} else {
81
					cmb2_utils()->log_if_debug( __METHOD__, __LINE__, "{$this->field->type()} {$this->field->_id()} is missing the 'taxonomy' parameter." );
82
				}
83
				break;
84
			case 'multicheck':
85
			case 'multicheck_inline':
86
			case 'file_list':
87
			case 'oembed':
88
			case 'group':
89
				// no filtering
90
				$sanitized_value = $this->value;
91
				break;
92
			default:
93
				// Handle repeatable fields array
94
				// We'll fallback to 'sanitize_text_field'
95
				$sanitized_value = is_array( $this->value ) ? array_map( 'sanitize_text_field', $this->value ) : call_user_func( 'sanitize_text_field', $this->value );
96
				break;
97
		}
98
99
		return $this->_is_empty_array( $sanitized_value ) ? '' : $sanitized_value;
100
	}
101
102
	/**
103
	 * Simple checkbox validation
104
	 * @since  1.0.1
105
	 * @return string|false 'on' or false
106
	 */
107
	public function checkbox() {
108
		return $this->value === 'on' ? 'on' : false;
109
	}
110
111
	/**
112
	 * Validate url in a meta value
113
	 * @since  1.0.1
114
	 * @return string        Empty string or escaped url
115
	 */
116
	public function text_url() {
117
		$protocols = $this->field->args( 'protocols' );
118
		// for repeatable
119
		if ( is_array( $this->value ) ) {
120
			foreach ( $this->value as $key => $val ) {
121
				$this->value[ $key ] = $val ? esc_url_raw( $val, $protocols ) : $this->field->args( 'default' );
122
			}
123
		} else {
124
			$this->value = $this->value ? esc_url_raw( $this->value, $protocols ) : $this->field->args( 'default' );
125
		}
126
127
		return $this->value;
128
	}
129
130
	public function colorpicker() {
131
		// for repeatable
132
		if ( is_array( $this->value ) ) {
133
			$check = $this->value;
134
			$this->value = array();
135
			foreach ( $check as $key => $val ) {
136
				if ( $val && '#' != $val ) {
137
					$this->value[ $key ] = esc_attr( $val );
138
				}
139
			}
140
		} else {
141
			$this->value = ! $this->value || '#' == $this->value ? '' : esc_attr( $this->value );
142
		}
143
		return $this->value;
144
	}
145
146
	/**
147
	 * Validate email in a meta value
148
	 * @since  1.0.1
149
	 * @return string       Empty string or sanitized email
150
	 */
151
	public function text_email() {
152
		// for repeatable
153
		if ( is_array( $this->value ) ) {
154
			foreach ( $this->value as $key => $val ) {
155
				$val = trim( $val );
156
				$this->value[ $key ] = is_email( $val ) ? $val : '';
157
			}
158
		} else {
159
			$this->value = trim( $this->value );
160
			$this->value = is_email( $this->value ) ? $this->value : '';
161
		}
162
163
		return $this->value;
164
	}
165
166
	/**
167
	 * Validate money in a meta value
168
	 * @since  1.0.1
169
	 * @return string       Empty string or sanitized money value
170
	 */
171
	public function text_money() {
172
173
		global $wp_locale;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
174
175
		$search = array( $wp_locale->number_format['thousands_sep'], $wp_locale->number_format['decimal_point'] );
176
		$replace = array( '', '.' );
177
178
		// for repeatable
179
		if ( is_array( $this->value ) ) {
180
			foreach ( $this->value as $key => $val ) {
181
				$this->value[ $key ] = number_format_i18n( (float) str_ireplace( $search, $replace, $val ), 2 );
182
			}
183
		} else {
184
			$this->value = number_format_i18n( (float) str_ireplace( $search, $replace, $this->value ), 2 );
185
		}
186
187
		return $this->value;
188
	}
189
190
	/**
191
	 * Converts text date to timestamp
192
	 * @since  1.0.2
193
	 * @return string Timestring
194
	 */
195
	public function text_date_timestamp() {
196
		if (is_array($this->value)) {
197
			$returnValue = [];
198
			foreach ($this->value as $value) {
199
				$date_object   = DateTime::createFromFormat($this->field->args['date_format'], $value);
0 ignored issues
show
Bug introduced by
The method createFromFormat() does not exist on DateTime. Did you maybe mean format()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
200
				$returnValue[] = $date_object ? $date_object->setTime(0, 0, 0)->getTimeStamp() : '';
201
			}
202
		} else {
203
			$date_object = DateTime::createFromFormat($this->field->args['date_format'], $this->value);
0 ignored issues
show
Bug introduced by
The method createFromFormat() does not exist on DateTime. Did you maybe mean format()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
204
			$returnValue = $date_object ? $date_object->setTime(0, 0, 0)->getTimeStamp() : '';
205
		}
206
207
 		return $returnValue;
208
	}
209
210
	/**
211
	 * Datetime to timestamp
212
	 * @since  1.0.1
213
	 * @return string Timestring
214
	 */
215
	public function text_datetime_timestamp( $repeat = false ) {
216
217
		$test = is_array( $this->value ) ? array_filter( $this->value ) : '';
218
		if ( empty( $test ) ) {
219
			return '';
220
		}
221
222
		$repeat_value = $this->_check_repeat( __FUNCTION__, $repeat );
223
		if ( false !== $repeat_value ) {
224
			return $repeat_value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $repeat_value; (array) is incompatible with the return type documented by CMB2_Sanitize::text_datetime_timestamp of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
225
		}
226
227
		if ( isset( $this->value['date'], $this->value['time'] ) ) {
228
			$this->value = $this->field->get_timestamp_from_value( $this->value['date'] . ' ' . $this->value['time'] );
229
		}
230
231
		if ( $tz_offset = $this->field->field_timezone_offset() ) {
232
			$this->value += (int) $tz_offset;
233
		}
234
235
		return $this->value;
236
	}
237
238
	/**
239
	 * Datetime to timestamp with timezone
240
	 * @since  1.0.1
241
	 * @return string       Timestring
242
	 */
243
	public function text_datetime_timestamp_timezone( $repeat = false ) {
244
		static $utc_values = array();
245
246
		$test = is_array( $this->value ) ? array_filter( $this->value ) : '';
247
		if ( empty( $test ) ) {
248
			return '';
249
		}
250
251
		$utc_key = $this->field->_id() . '_utc';
252
253
		$repeat_value = $this->_check_repeat( __FUNCTION__, $repeat );
254
		if ( false !== $repeat_value ) {
255
			if ( ! empty( $utc_values[ $utc_key ] ) ) {
256
				$this->_save_utc_value( $utc_key, $utc_values[ $utc_key ] );
257
				unset( $utc_values[ $utc_key ] );
258
			}
259
260
			return $repeat_value;
261
		}
262
263
		$tzstring = null;
264
265
		if ( is_array( $this->value ) && array_key_exists( 'timezone', $this->value ) ) {
266
			$tzstring = $this->value['timezone'];
267
		}
268
269
		if ( empty( $tzstring ) ) {
270
			$tzstring = cmb2_utils()->timezone_string();
271
		}
272
273
		$offset = cmb2_utils()->timezone_offset( $tzstring );
274
275
		if ( 'UTC' === substr( $tzstring, 0, 3 ) ) {
276
			$tzstring = timezone_name_from_abbr( '', $offset, 0 );
277
			/*
278
			 * timezone_name_from_abbr() returns false if not found based on offset.
279
			 * Since there are currently some invalid timezones in wp_timezone_dropdown(),
280
			 * fallback to an offset of 0 (UTC+0)
281
			 * https://core.trac.wordpress.org/ticket/29205
282
			 */
283
			$tzstring = false !== $tzstring ? $tzstring : timezone_name_from_abbr( '', 0, 0 );
284
		}
285
286
		$full_format = $this->field->args['date_format'] . ' ' . $this->field->args['time_format'];
287
		$full_date   = $this->value['date'] . ' ' . $this->value['time'];
288
289
		try {
290
291
			$datetime = date_create_from_format( $full_format, $full_date );
292
293
			if ( ! is_object( $datetime ) ) {
294
				$this->value = $utc_stamp = '';
295
			} else {
296
				$timestamp   = $datetime->setTimezone( new DateTimeZone( $tzstring ) )->getTimestamp();
297
				$utc_stamp   = $timestamp - $offset;
298
				$this->value = serialize( $datetime );
299
			}
300
301
			if ( $this->field->group ) {
302
				$this->value = array(
303
					'supporting_field_value' => $utc_stamp,
304
					'supporting_field_id'    => $utc_key,
305
					'value'                  => $this->value,
306
				);
307
			} else {
308
				// Save the utc timestamp supporting field
309
				if ( $repeat ) {
310
					$utc_values[ $utc_key ][] = $utc_stamp;
311
				} else {
312
					$this->_save_utc_value( $utc_key, $utc_stamp );
313
				}
314
			}
315
316
		} catch ( Exception $e ) {
317
			$this->value = '';
318
			cmb2_utils()->log_if_debug( __METHOD__, __LINE__, $e->getMessage() );
319
		}
320
321
		return $this->value;
322
	}
323
324
	/**
325
	 * Sanitize textareas and wysiwyg fields
326
	 * @since  1.0.1
327
	 * @return string       Sanitized data
328
	 */
329
	public function textarea() {
330
		return is_array( $this->value ) ? array_map( 'wp_kses_post', $this->value ) : wp_kses_post( $this->value );
331
	}
332
333
	/**
334
	 * Sanitize code textareas
335
	 * @since  1.0.2
336
	 * @return string       Sanitized data
337
	 */
338
	public function textarea_code( $repeat = false ) {
339
		$repeat_value = $this->_check_repeat( __FUNCTION__, $repeat );
340
		if ( false !== $repeat_value ) {
341
			return $repeat_value;
342
		}
343
344
		return htmlspecialchars_decode( stripslashes( $this->value ) );
345
	}
346
347
	/**
348
	 * Handles saving of attachment post ID and sanitizing file url
349
	 * @since  1.1.0
350
	 * @return string        Sanitized url
351
	 */
352
	public function file() {
353
		$file_id_key = $this->field->_id() . '_id';
354
355
		if ( $this->field->group ) {
356
			// Return an array with url/id if saving a group field
357
			$this->value = $this->_get_group_file_value_array( $file_id_key );
358
		} else {
359
			$this->_save_file_id_value( $file_id_key );
360
			$this->text_url();
361
		}
362
363
		return $this->value;
364
	}
365
366
	/**
367
	 * Gets the values for the `file` field type from the data being saved.
368
	 * @since  2.2.0
369
	 */
370
	public function _get_group_file_value_array( $id_key ) {
371
		$alldata = $this->field->group->data_to_save;
372
		$base_id = $this->field->group->_id();
373
		$i       = $this->field->group->index;
374
375
		// Check group $alldata data
376
		$id_val  = isset( $alldata[ $base_id ][ $i ][ $id_key ] )
377
			? absint( $alldata[ $base_id ][ $i ][ $id_key ] )
378
			: 0;
379
380
		return array(
381
			'value' => $this->text_url(),
382
			'supporting_field_value' => $id_val,
383
			'supporting_field_id'    => $id_key,
384
		);
385
	}
386
387
	/**
388
	 * Peforms saving of `file` attachement's ID
389
	 * @since  1.1.0
390
	 */
391
	public function _save_file_id_value( $file_id_key ) {
392
		$id_field = $this->_new_supporting_field( $file_id_key );
393
394
		// Check standard data_to_save data
395
		$id_val = isset( $this->field->data_to_save[ $file_id_key ] )
396
			? $this->field->data_to_save[ $file_id_key ]
397
			: null;
398
399
		// If there is no ID saved yet, try to get it from the url
400
		if ( $this->value && ! $id_val ) {
401
			$id_val = cmb2_utils()->image_id_from_url( $this->value );
402
		}
403
404
		return $id_field->save_field( $id_val );
405
	}
406
407
	/**
408
	 * Peforms saving of `text_datetime_timestamp_timezone` utc timestamp
409
	 * @since  2.2.0
410
	 */
411
	public function _save_utc_value( $utc_key, $utc_stamp ) {
412
		return $this->_new_supporting_field( $utc_key )->save_field( $utc_stamp );
413
	}
414
415
	/**
416
	 * Returns a new, supporting, CMB2_Field object based on a new field id.
417
	 * @since  2.2.0
418
	 */
419
	public function _new_supporting_field( $new_field_id ) {
420
		$args = $this->field->args();
421
		unset( $args['_id'], $args['_name'] );
422
423
		$args['id'] = $new_field_id;
424
		$args['sanitization_cb'] = false;
425
426
		// And get new field object
427
		return new CMB2_Field( array(
428
			'field_args'  => $args,
429
			'group_field' => $this->field->group,
430
			'object_id'   => $this->field->object_id,
431
			'object_type' => $this->field->object_type,
432
		) );
433
	}
434
435
	/**
436
	 * If repeating, loop through and re-apply sanitization method
437
	 * @since  1.1.0
438
	 * @param  string $method Class method
439
	 * @param  bool   $repeat Whether repeating or not
440
	 * @return mixed          Sanitized value
441
	 */
442
	public function _check_repeat( $method, $repeat ) {
443
		if ( $repeat || ! $this->field->args( 'repeatable' ) ) {
444
			return false;
445
		}
446
447
		$values_array = $this->value;
448
449
		$new_value = array();
450
		foreach ( $values_array as $iterator => $this->value ) {
451
			if ( $this->value ) {
452
				$val = $this->$method( true );
453
				if ( ! empty( $val ) ) {
454
					$new_value[] = $val;
455
				}
456
			}
457
		}
458
459
		$this->value = $new_value;
460
461
		return empty( $this->value ) ? null : $this->value;
462
	}
463
464
	/**
465
	 * Determine if passed value is an empty array
466
	 * @since  2.0.6
467
	 * @param  mixed  $to_check Value to check
468
	 * @return boolean          Whether value is an array that's empty
469
	 */
470
	public function _is_empty_array( $to_check ) {
471
		if ( is_array( $to_check ) ) {
472
			$cleaned_up = array_filter( $to_check );
473
			return empty( $cleaned_up );
474
		}
475
		return false;
476
	}
477
478
}
479