Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
   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      /**
  27       * New random ID.
  28       */
  29      public function __construct()
  30      {
  31          $this->_id = $this->generate();
  32      }
  33  
  34      /**
  35       * Generate a random ID.
  36       */
  37      public function generate()
  38      {
  39          $elts = array(
  40              uniqid(),
  41              mt_rand(),
  42              getmypid(),
  43              spl_object_hash($this)
  44          );
  45          if (function_exists('zend_thread_id')) {
  46              $elts[] = zend_thread_id();
  47          }
  48          if (function_exists('sys_getloadavg') &&
  49              ($loadavg = sys_getloadavg())) {
  50              $elts = array_merge($elts, $loadavg);
  51          }
  52          if (function_exists('memory_get_usage')) {
  53              $elts[] = memory_get_usage();
  54              $elts[] = memory_get_peak_usage();
  55          }
  56  
  57          shuffle($elts);
  58  
  59          /* Base64 can have /, +, and = characters. Restrict to URL-safe
  60           * characters. */
  61          return substr(str_replace(
  62              array('/', '+', '='),
  63              array('-', '_', ''),
  64              base64_encode(hash('sha1', serialize($elts), true))
  65          ), 0, 23);
  66      }
  67  
  68      /**
  69       * Cooerce to string.
  70       *
  71       * @return string  The random ID.
  72       */
  73      public function __toString()
  74      {
  75          return $this->_id;
  76      }
  77  }