| 1 |
<?php |
| 2 |
|
| 3 |
namespace Bookit\Helpers; |
| 4 |
|
| 5 |
/** |
| 6 |
* Bookit Serialization Helper |
| 7 |
*/ |
| 8 |
class SerializationHelper { |
| 9 |
|
| 10 |
/** |
| 11 |
* Unserialize a stored value while rejecting anything that isn't a |
| 12 |
* plain array, guarding against PHP object injection and suppressing |
| 13 |
* the native warning on malformed input. |
| 14 |
* |
| 15 |
* @since 2.6.0.3 |
| 16 |
* |
| 17 |
* @param mixed $value |
| 18 |
* @return array|false The unserialized array, or false if $value isn't a |
| 19 |
* string, fails to unserialize, or unserializes to |
| 20 |
* anything containing an object. |
| 21 |
*/ |
| 22 |
public static function safe_unserialize( $value ) { |
| 23 |
if ( ! is_string( $value ) ) { |
| 24 |
return false; |
| 25 |
} |
| 26 |
|
| 27 |
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize |
| 28 |
$data = @unserialize( $value, array( 'allowed_classes' => false ) ); |
| 29 |
|
| 30 |
if ( ! is_array( $data ) || self::contains_object( $data ) ) { |
| 31 |
return false; |
| 32 |
} |
| 33 |
|
| 34 |
return $data; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Recursively check whether a value contains an object, including a |
| 39 |
* `__PHP_Incomplete_Class` produced by unserializing with |
| 40 |
* `allowed_classes => false`. |
| 41 |
* |
| 42 |
* @since 2.6.0.3 |
| 43 |
* |
| 44 |
* @param mixed $value |
| 45 |
* @return bool |
| 46 |
*/ |
| 47 |
private static function contains_object( $value ) { |
| 48 |
if ( is_object( $value ) ) { |
| 49 |
return true; |
| 50 |
} |
| 51 |
|
| 52 |
if ( is_array( $value ) ) { |
| 53 |
foreach ( $value as $item ) { |
| 54 |
if ( self::contains_object( $item ) ) { |
| 55 |
return true; |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
return false; |
| 61 |
} |
| 62 |
} |
| 63 |
|