oxuniversallyuniqueidgenerator.php

Go to the documentation of this file.
00001 <?php
00002 
00006 class oxUniversallyUniqueIdGenerator
00007 {
00008 
00012     private $_openSSLChecker;
00013 
00019     public function __construct(oxOpenSSLFunctionalityChecker $openSSLChecker = null)
00020     {
00021         if (is_null($openSSLChecker)) {
00022             $openSSLChecker = oxNew('oxOpenSSLFunctionalityChecker');
00023         }
00024         $this->_openSSLChecker = $openSSLChecker;
00025     }
00026 
00032     public function generate()
00033     {
00034         $sSeed = $this->generateV4();
00035 
00036         return $this->generateV5($sSeed, php_uname('n'));
00037     }
00038 
00044     public function generateV4()
00045     {
00046         if ($this->_getOpenSSLChecker()->isOpenSslRandomBytesGeneratorAvailable()) {
00047             $sUUID = $this->_generateBasedOnOpenSSL();
00048         } else {
00049             $sUUID = $this->_generateBasedOnMtRand();
00050         }
00051 
00052         return $sUUID;
00053     }
00054 
00063     public function generateV5($sSeed, $sSalt)
00064     {
00065         $sSeed = str_replace(array('-', '{', '}'), '', $sSeed);
00066         $sBinarySeed = '';
00067         for ($i = 0; $i < strlen($sSeed); $i += 2) {
00068             $sBinarySeed .= chr(hexdec($sSeed[$i] . $sSeed[$i + 1]));
00069         }
00070         $sHash = sha1($sBinarySeed . $sSalt);
00071         $sUUID = sprintf(
00072             '%08s-%04s-%04x-%04x-%12s',
00073             substr($sHash, 0, 8), substr($sHash, 8, 4),
00074             (hexdec(substr($sHash, 12, 4)) & 0x0fff) | 0x3000,
00075             (hexdec(substr($sHash, 16, 4)) & 0x3fff) | 0x8000,
00076             substr($sHash, 20, 12)
00077         );
00078 
00079         return $sUUID;
00080     }
00081 
00087     protected function _getOpenSSLChecker()
00088     {
00089         return $this->_openSSLChecker;
00090     }
00091 
00097     protected function _generateBasedOnOpenSSL()
00098     {
00099         $sRandomData = openssl_random_pseudo_bytes(16);
00100         $sRandomData[6] = chr(ord($sRandomData[6]) & 0x0f | 0x40); // set version to 0100
00101         $sRandomData[8] = chr(ord($sRandomData[8]) & 0x3f | 0x80); // set bits 6-7 to 10
00102 
00103         return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($sRandomData), 4));
00104     }
00105 
00111     protected function _generateBasedOnMtRand()
00112     {
00113         return sprintf(
00114             '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
00115             mt_rand(0, 0xffff), mt_rand(0, 0xffff),
00116             mt_rand(0, 0xffff),
00117             mt_rand(0, 0x0fff) | 0x4000,
00118             mt_rand(0, 0x3fff) | 0x8000,
00119             mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
00120         );
00121     }
00122 }