PageRenderTime 43ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/horde/framework/Horde/Support/Randomid.php

https://gitlab.com/unofficial-mirrors/moodle
PHP | 77 lines | 39 code | 5 blank | 33 comment | 3 complexity | 7c2207cbd99c1e8d0ee0549da9ba7d88 MD5 | raw file
  1. <?php
  2. /**
  3. * Class for generating a 23-character random ID string. This string uses all
  4. * characters in the class [-_0-9a-zA-Z].
  5. *
  6. * <code>
  7. * $id = (string)new Horde_Support_Randomid();
  8. * </code>
  9. *
  10. * Copyright 2010-2017 Horde LLC (http://www.horde.org/)
  11. *
  12. * @author Michael Slusarz <slusarz@horde.org>
  13. * @category Horde
  14. * @license http://www.horde.org/licenses/bsd BSD
  15. * @package Support
  16. */
  17. class Horde_Support_Randomid
  18. {
  19. /**
  20. * Generated ID.
  21. *
  22. * @var string
  23. */
  24. private $_id;
  25. /**
  26. * New random ID.
  27. */
  28. public function __construct()
  29. {
  30. $this->_id = $this->generate();
  31. }
  32. /**
  33. * Generate a random ID.
  34. */
  35. public function generate()
  36. {
  37. $elts = array(
  38. uniqid(),
  39. mt_rand(),
  40. getmypid(),
  41. spl_object_hash($this)
  42. );
  43. if (function_exists('zend_thread_id')) {
  44. $elts[] = zend_thread_id();
  45. }
  46. if (function_exists('sys_getloadavg') &&
  47. ($loadavg = sys_getloadavg())) {
  48. $elts = array_merge($elts, $loadavg);
  49. }
  50. if (function_exists('memory_get_usage')) {
  51. $elts[] = memory_get_usage();
  52. $elts[] = memory_get_peak_usage();
  53. }
  54. shuffle($elts);
  55. /* Base64 can have /, +, and = characters. Restrict to URL-safe
  56. * characters. */
  57. return substr(str_replace(
  58. array('/', '+', '='),
  59. array('-', '_', ''),
  60. base64_encode(hash('sha1', serialize($elts), true))
  61. ), 0, 23);
  62. }
  63. /**
  64. * Cooerce to string.
  65. *
  66. * @return string The random ID.
  67. */
  68. public function __toString()
  69. {
  70. return $this->_id;
  71. }
  72. }