Unserialize.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Brumann\Polyfill;
  3. final class Unserialize
  4. {
  5. /**
  6. * @see https://secure.php.net/manual/en/function.unserialize.php
  7. *
  8. * @param string $serialized Serialized data
  9. * @param array $options Associative array containing options
  10. *
  11. * @return mixed
  12. */
  13. public static function unserialize($serialized, array $options = array())
  14. {
  15. if (PHP_VERSION_ID >= 70000) {
  16. return \unserialize($serialized, $options);
  17. }
  18. if (!array_key_exists('allowed_classes', $options)) {
  19. $options['allowed_classes'] = true;
  20. }
  21. $allowedClasses = $options['allowed_classes'];
  22. if (true === $allowedClasses) {
  23. return \unserialize($serialized);
  24. }
  25. if (false === $allowedClasses) {
  26. $allowedClasses = array();
  27. }
  28. if (!is_array($allowedClasses)) {
  29. trigger_error(
  30. 'unserialize(): allowed_classes option should be array or boolean',
  31. E_USER_WARNING
  32. );
  33. $allowedClasses = array();
  34. }
  35. $sanitizedSerialized = preg_replace_callback(
  36. '/(^|;)O:\d+:"([^"]*)":(\d+):{/',
  37. function ($match) use ($allowedClasses) {
  38. list($completeMatch, $leftBorder, $className, $objectSize) = $match;
  39. if (in_array($className, $allowedClasses)) {
  40. return $completeMatch;
  41. } else {
  42. return sprintf(
  43. '%sO:22:"__PHP_Incomplete_Class":%d:{s:27:"__PHP_Incomplete_Class_Name";%s',
  44. $leftBorder,
  45. $objectSize + 1, // size of object + 1 for added string
  46. \serialize($className)
  47. );
  48. }
  49. },
  50. $serialized
  51. );
  52. return \unserialize($sanitizedSerialized);
  53. }
  54. }