PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/class.uuid.php

https://github.com/ianjvr/class.uuid.php
PHP | 340 lines | 209 code | 42 blank | 89 comment | 14 complexity | 730a32ab2eb508886caef537d01c2cf2 MD5 | raw file
  1. <?php
  2. /*-
  3. * Copyright (c) 2011 Fredrik Lindberg - http://www.shapeshifter.se
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. *
  26. * Alternative this software might be licensed under the following license
  27. *
  28. * Copyright 2011 Fredrik Lindberg
  29. *
  30. * Licensed under the Apache License, Version 2.0 (the "License");
  31. * you may not use this file except in compliance with the License.
  32. * You may obtain a copy of the License at
  33. *
  34. * http://www.apache.org/licenses/LICENSE-2.0
  35. *
  36. * Unless required by applicable law or agreed to in writing, software
  37. * distributed under the License is distributed on an "AS IS" BASIS,
  38. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39. * See the License for the specific language governing permissions and
  40. * limitations under the License.
  41. *
  42. */
  43. /*
  44. * UUID (RFC4122) Generator
  45. * http://tools.ietf.org/html/rfc4122
  46. *
  47. * Implements version 1, 3, 4 and 5
  48. */
  49. class UUID {
  50. /* UUID versions */
  51. const UUID_TIME = 1; /* Time based UUID */
  52. const UUID_NAME_MD5 = 3; /* Name based (MD5) UUID */
  53. const UUID_RANDOM = 4; /* Random UUID */
  54. const UUID_NAME_SHA1 = 5; /* Name based (SHA1) UUID */
  55. /* UUID formats */
  56. const FMT_FIELD = 100;
  57. const FMT_STRING = 101;
  58. const FMT_BINARY = 102;
  59. const FMT_QWORD = 1; /* Quad-word, 128-bit (not impl.) */
  60. const FMT_DWORD = 2; /* Double-word, 64-bit (not impl.) */
  61. const FMT_WORD = 4; /* Word, 32-bit (not impl.) */
  62. const FMT_SHORT = 8; /* Short (not impl.) */
  63. const FMT_BYTE = 16; /* Byte */
  64. const FMT_DEFAULT = 16;
  65. /* Field UUID representation */
  66. static private $m_uuid_field = array(
  67. 'time_low' => 0, /* 32-bit */
  68. 'time_mid' => 0, /* 16-bit */
  69. 'time_hi' => 0, /* 16-bit */
  70. 'clock_seq_hi' => 0, /* 8-bit */
  71. 'clock_seq_low' => 0, /* 8-bit */
  72. 'node' => array() /* 48-bit */
  73. );
  74. static private $m_generate = array(
  75. self::UUID_TIME => "generateTime",
  76. self::UUID_RANDOM => "generateRandom",
  77. self::UUID_NAME_MD5 => "generateNameMD5",
  78. self::UUID_NAME_SHA1 => "generateNameSHA1"
  79. );
  80. static private $m_convert = array(
  81. self::FMT_FIELD => array(
  82. self::FMT_BYTE => "conv_field2byte",
  83. self::FMT_STRING => "conv_field2string",
  84. self::FMT_BINARY => "conv_field2binary"
  85. ),
  86. self::FMT_BYTE => array(
  87. self::FMT_FIELD => "conv_byte2field",
  88. self::FMT_STRING => "conv_byte2string",
  89. self::FMT_BINARY => "conv_byte2binary"
  90. ),
  91. self::FMT_STRING => array(
  92. self::FMT_BYTE => "conv_string2byte",
  93. self::FMT_FIELD => "conv_string2field",
  94. self::FMT_BINARY => "conv_string2binary"
  95. ),
  96. );
  97. /* Swap byte order of a 32-bit number */
  98. static private function swap32($x) {
  99. return (($x & 0x000000ff) << 24) | (($x & 0x0000ff00) << 8) |
  100. (($x & 0x00ff0000) >> 8) | (($x & 0xff000000) >> 24);
  101. }
  102. /* Swap byte order of a 16-bit number */
  103. static private function swap16($x) {
  104. return (($x & 0x00ff) << 8) | (($x & 0xff00) >> 8);
  105. }
  106. /* Auto-detect UUID format */
  107. static private function detectFormat($src) {
  108. if (is_string($src))
  109. return self::FMT_STRING;
  110. else if (is_array($src)) {
  111. $len = count($src);
  112. if ($len == 1 || ($len % 2) == 0)
  113. return $len;
  114. else
  115. return (-1);
  116. }
  117. else
  118. return self::FMT_BINARY;
  119. }
  120. /*
  121. * Public API, generate a UUID of 'type' in format 'fmt' for
  122. * the given namespace 'ns' and node 'node'
  123. */
  124. static public function generate($type, $fmt = self::FMT_BYTE,
  125. $node = "", $ns = "") {
  126. $func = self::$m_generate[$type];
  127. if (!isset($func))
  128. return null;
  129. $conv = self::$m_convert[self::FMT_FIELD][$fmt];
  130. $uuid = self::$func($ns, $node);
  131. return self::$conv($uuid);
  132. }
  133. /*
  134. * Public API, convert a UUID from one format to another
  135. */
  136. static public function convert($uuid, $from, $to) {
  137. $conv = self::$m_convert[$from][$to];
  138. if (!isset($conv))
  139. return ($uuid);
  140. return (self::$conv($uuid));
  141. }
  142. /*
  143. * Generate an UUID version 4 (pseudo random)
  144. */
  145. static private function generateRandom($ns, $node) {
  146. $uuid = self::$m_uuid_field;
  147. $uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
  148. $uuid['clock_seq_hi'] = (1 << 7) | mt_rand(0, 128);
  149. $uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
  150. $uuid['time_mid'] = mt_rand(0, 0xffff);
  151. $uuid['clock_seq_low'] = mt_rand(0, 255);
  152. for ($i = 0; $i < 6; $i++)
  153. $uuid['node'][$i] = mt_rand(0, 255);
  154. return ($uuid);
  155. }
  156. /*
  157. * Generate UUID version 3 and 5 (name based)
  158. */
  159. static private function generateName($ns, $node, $hash, $version) {
  160. $ns_fmt = self::detectFormat($ns);
  161. $field = self::convert($ns, $ns_fmt, self::FMT_FIELD);
  162. /* Swap byte order to keep it in big endian on all platforms */
  163. $field['time_low'] = self::swap32($field['time_low']);
  164. $field['time_mid'] = self::swap16($field['time_mid']);
  165. $field['time_hi'] = self::swap16($field['time_hi']);
  166. /* Convert the namespace to binary and concatenate node */
  167. $raw = self::convert($field, self::FMT_FIELD, self::FMT_BINARY);
  168. $raw .= $node;
  169. /* Hash the namespace and node and convert to a byte array */
  170. $val = $hash($raw, true);
  171. $tmp = unpack('C16', $val);
  172. foreach (array_keys($tmp) as $key)
  173. $byte[$key - 1] = $tmp[$key];
  174. /* Convert byte array to a field array */
  175. $field = self::conv_byte2field($byte);
  176. $field['time_low'] = self::swap32($field['time_low']);
  177. $field['time_mid'] = self::swap16($field['time_mid']);
  178. $field['time_hi'] = self::swap16($field['time_hi']);
  179. /* Apply version and constants */
  180. $field['clock_seq_hi'] &= 0x3f;
  181. $field['clock_seq_hi'] |= (1 << 7);
  182. $field['time_hi'] &= 0x0fff;
  183. $field['time_hi'] |= ($version << 12);
  184. return ($field);
  185. }
  186. static private function generateNameMD5($ns, $node) {
  187. return self::generateName($ns, $node, "md5",
  188. self::UUID_NAME_MD5);
  189. }
  190. static private function generateNameSHA1($ns, $node) {
  191. return self::generateName($ns, $node, "sha1",
  192. self::UUID_NAME_SHA1);
  193. }
  194. /*
  195. * Generate UUID version 1 (time based)
  196. */
  197. static private function generateTime($ns, $node) {
  198. $uuid = self::$m_uuid_field;
  199. /*
  200. * Get current time in 100 ns intervals. The magic value
  201. * is the offset between UNIX epoch and the UUID UTC
  202. * time base October 15, 1582.
  203. */
  204. $tp = gettimeofday();
  205. $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) +
  206. 0x01B21DD213814000;
  207. $uuid['time_low'] = $time & 0xffffffff;
  208. /* Work around PHP 32-bit bit-operation limits */
  209. $high = intval($time / 0xffffffff);
  210. $uuid['time_mid'] = $high & 0xffff;
  211. $uuid['time_hi'] = (($high >> 16) & 0xfff) | (self::UUID_TIME << 12);
  212. /*
  213. * We don't support saved state information and generate
  214. * a random clock sequence each time.
  215. */
  216. $uuid['clock_seq_hi'] = 0x80 | mt_rand(0, 64);
  217. $uuid['clock_seq_low'] = mt_rand(0, 255);
  218. /*
  219. * Node should be set to the 48-bit IEEE node identifier, but
  220. * we leave it for the user to supply the node.
  221. */
  222. for ($i = 0; $i < 6; $i++)
  223. $uuid['node'][$i] = ord(substr($node, $i, 1));
  224. return ($uuid);
  225. }
  226. /* Assumes correct byte order */
  227. static private function conv_field2byte($src) {
  228. $uuid[0] = ($src['time_low'] & 0xff000000) >> 24;
  229. $uuid[1] = ($src['time_low'] & 0x00ff0000) >> 16;
  230. $uuid[2] = ($src['time_low'] & 0x0000ff00) >> 8;
  231. $uuid[3] = ($src['time_low'] & 0x000000ff);
  232. $uuid[4] = ($src['time_mid'] & 0xff00) >> 8;
  233. $uuid[5] = ($src['time_mid'] & 0x00ff);
  234. $uuid[6] = ($src['time_hi'] & 0xff00) >> 8;
  235. $uuid[7] = ($src['time_hi'] & 0x00ff);
  236. $uuid[8] = $src['clock_seq_hi'];
  237. $uuid[9] = $src['clock_seq_low'];
  238. for ($i = 0; $i < 6; $i++)
  239. $uuid[10+$i] = $src['node'][$i];
  240. return ($uuid);
  241. }
  242. static private function conv_field2string($src) {
  243. $str = sprintf(
  244. '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
  245. ($src['time_low']), ($src['time_mid']), ($src['time_hi']),
  246. $src['clock_seq_hi'], $src['clock_seq_low'],
  247. $src['node'][0], $src['node'][1], $src['node'][2],
  248. $src['node'][3], $src['node'][4], $src['node'][5]);
  249. return ($str);
  250. }
  251. static private function conv_field2binary($src) {
  252. $byte = self::conv_field2byte($src);
  253. return self::conv_byte2binary($byte);
  254. }
  255. static private function conv_byte2field($uuid) {
  256. $field = self::$m_uuid_field;
  257. $field['time_low'] = ($uuid[0] << 24) | ($uuid[1] << 16) |
  258. ($uuid[2] << 8) | $uuid[3];
  259. $field['time_mid'] = ($uuid[4] << 8) | $uuid[5];
  260. $field['time_hi'] = ($uuid[6] << 8) | $uuid[7];
  261. $field['clock_seq_hi'] = $uuid[8];
  262. $field['clock_seq_low'] = $uuid[9];
  263. for ($i = 0; $i < 6; $i++)
  264. $field['node'][$i] = $uuid[10+$i];
  265. return ($field);
  266. }
  267. static public function conv_byte2string($src) {
  268. $field = self::conv_byte2field($src);
  269. return self::conv_field2string($field);
  270. }
  271. static private function conv_byte2binary($src) {
  272. $raw = pack('C16', $src[0], $src[1], $src[2], $src[3],
  273. $src[4], $src[5], $src[6], $src[7], $src[8], $src[9],
  274. $src[10], $src[11], $src[12], $src[13], $src[14], $src[15]);
  275. return ($raw);
  276. }
  277. static private function conv_string2field($src) {
  278. $parts = sscanf($src, '%x-%x-%x-%x-%02x%02x%02x%02x%02x%02x');
  279. $field = self::$m_uuid_field;
  280. $field['time_low'] = ($parts[0]);
  281. $field['time_mid'] = ($parts[1]);
  282. $field['time_hi'] = ($parts[2]);
  283. $field['clock_seq_hi'] = ($parts[3] & 0xff00) >> 8;
  284. $field['clock_seq_low'] = $parts[3] & 0x00ff;
  285. for ($i = 0; $i < 6; $i++)
  286. $field['node'][$i] = $parts[4+$i];
  287. return ($field);
  288. }
  289. static private function conv_string2byte($src) {
  290. $field = self::conv_string2field($src);
  291. return self::conv_field2byte($field);
  292. }
  293. static private function conv_string2binary($src) {
  294. $byte = self::conv_string2byte($src);
  295. return self::conv_byte2binary($byte);
  296. }
  297. }
  298. ?>