Hashids.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. /*
  3. Hashids
  4. http://hashids.org/php
  5. (c) 2013 Ivan Akimov
  6. https://github.com/ivanakimov/hashids.php
  7. hashids may be freely distributed under the MIT license.
  8. */
  9. namespace Hashids;
  10. class Hashids implements HashGenerator {
  11. const VERSION = '1.0.5';
  12. /* internal settings */
  13. const MIN_ALPHABET_LENGTH = 16;
  14. const SEP_DIV = 3.5;
  15. const GUARD_DIV = 12;
  16. /* error messages */
  17. const E_ALPHABET_LENGTH = 'alphabet must contain at least %d unique characters';
  18. const E_ALPHABET_SPACE = 'alphabet cannot contain spaces';
  19. /* set at constructor */
  20. private $_alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  21. private $_seps = 'cfhistuCFHISTU';
  22. private $_min_hash_length = 0;
  23. private $_math_functions = array();
  24. private $_max_int_value = 1000000000;
  25. private static $instance; //单例
  26. /**
  27. * 初始化
  28. * @param array $options
  29. * @return static
  30. */
  31. public static function instance($length = null, $salt = null, $alphabet = null)
  32. {
  33. if (is_null(self::$instance)) {
  34. if ($length === null) $length = config("hashids.length");
  35. if ($salt === null) $salt = config("hashids.salt");
  36. if ($alphabet === null) $alphabet = config("hashids.alphabet");
  37. self::$instance = new static($salt, $length, $alphabet);
  38. }
  39. return self::$instance;
  40. }
  41. public function __construct($salt = '', $min_hash_length = 8, $alphabet = '') {
  42. /* if either math precision library is present, raise $this->_max_int_value */
  43. if (function_exists('gmp_add')) {
  44. $this->_math_functions['add'] = 'gmp_add';
  45. $this->_math_functions['div'] = 'gmp_div';
  46. $this->_math_functions['str'] = 'gmp_strval';
  47. } else if (function_exists('bcadd')) {
  48. $this->_math_functions['add'] = 'bcadd';
  49. $this->_math_functions['div'] = 'bcdiv';
  50. $this->_math_functions['str'] = 'strval';
  51. }
  52. $this->_lower_max_int_value = $this->_max_int_value;
  53. if ($this->_math_functions) {
  54. $this->_max_int_value = PHP_INT_MAX;
  55. }
  56. /* handle parameters */
  57. $this->_salt = $salt;
  58. if ((int)$min_hash_length > 0) {
  59. $this->_min_hash_length = (int)$min_hash_length;
  60. }
  61. if ($alphabet) {
  62. $this->_alphabet = implode('', array_unique(str_split($alphabet)));
  63. }
  64. if (strlen($this->_alphabet) < self::MIN_ALPHABET_LENGTH) {
  65. throw new \Exception(sprintf(self::E_ALPHABET_LENGTH, self::MIN_ALPHABET_LENGTH));
  66. }
  67. if (is_int(strpos($this->_alphabet, ' '))) {
  68. throw new \Exception(self::E_ALPHABET_SPACE);
  69. }
  70. $alphabet_array = str_split($this->_alphabet);
  71. $seps_array = str_split($this->_seps);
  72. $this->_seps = implode('', array_intersect($alphabet_array, $seps_array));
  73. $this->_alphabet = implode('', array_diff($alphabet_array, $seps_array));
  74. $this->_seps = $this->_consistent_shuffle($this->_seps, $this->_salt);
  75. if (!$this->_seps || (strlen($this->_alphabet) / strlen($this->_seps)) > self::SEP_DIV) {
  76. $seps_length = (int)ceil(strlen($this->_alphabet) / self::SEP_DIV);
  77. if ($seps_length == 1) {
  78. $seps_length++;
  79. }
  80. if ($seps_length > strlen($this->_seps)) {
  81. $diff = $seps_length - strlen($this->_seps);
  82. $this->_seps .= substr($this->_alphabet, 0, $diff);
  83. $this->_alphabet = substr($this->_alphabet, $diff);
  84. } else {
  85. $this->_seps = substr($this->_seps, 0, $seps_length);
  86. }
  87. }
  88. $this->_alphabet = $this->_consistent_shuffle($this->_alphabet, $this->_salt);
  89. $guard_count = (int)ceil(strlen($this->_alphabet) / self::GUARD_DIV);
  90. if (strlen($this->_alphabet) < 3) {
  91. $this->_guards = substr($this->_seps, 0, $guard_count);
  92. $this->_seps = substr($this->_seps, $guard_count);
  93. } else {
  94. $this->_guards = substr($this->_alphabet, 0, $guard_count);
  95. $this->_alphabet = substr($this->_alphabet, $guard_count);
  96. }
  97. }
  98. public function encode() {
  99. $ret = '';
  100. $numbers = func_get_args();
  101. if (func_num_args() == 1 && is_array(func_get_arg(0))) {
  102. $numbers = $numbers[0];
  103. }
  104. if (!$numbers) {
  105. return $ret;
  106. }
  107. foreach ($numbers as $number) {
  108. $is_number = ctype_digit((string)$number);
  109. if (!$is_number || $number < 0 || $number > $this->_max_int_value) {
  110. return $ret;
  111. }
  112. }
  113. return $this->_encode($numbers);
  114. }
  115. public function decode($hash) {
  116. $ret = array();
  117. if (!$hash || !is_string($hash) || !trim($hash)) {
  118. return $ret;
  119. }
  120. return $this->_decode(trim($hash), $this->_alphabet);
  121. }
  122. public function encode_hex($str) {
  123. if (!ctype_xdigit((string)$str)) {
  124. return '';
  125. }
  126. $numbers = trim(chunk_split($str, 12, ' '));
  127. $numbers = explode(' ', $numbers);
  128. foreach ($numbers as $i => $number) {
  129. $numbers[$i] = hexdec('1' . $number);
  130. }
  131. return call_user_func_array(array($this, 'encode'), $numbers);
  132. }
  133. public function decode_hex($hash) {
  134. $ret = "";
  135. $numbers = $this->decode($hash);
  136. foreach ($numbers as $i => $number) {
  137. $ret .= substr(dechex($number), 1);
  138. }
  139. return $ret;
  140. }
  141. public function get_max_int_value() {
  142. return $this->_max_int_value;
  143. }
  144. private function _encode(array $numbers) {
  145. $alphabet = $this->_alphabet;
  146. $numbers_size = sizeof($numbers);
  147. $numbers_hash_int = 0;
  148. foreach ($numbers as $i => $number) {
  149. $numbers_hash_int += ($number % ($i + 100));
  150. }
  151. $lottery = $ret = $alphabet[$numbers_hash_int % strlen($alphabet)];
  152. foreach ($numbers as $i => $number) {
  153. $alphabet = $this->_consistent_shuffle($alphabet, substr($lottery . $this->_salt . $alphabet, 0, strlen($alphabet)));
  154. $ret .= $last = $this->_hash($number, $alphabet);
  155. if ($i + 1 < $numbers_size) {
  156. $number %= (ord($last) + $i);
  157. $seps_index = $number % strlen($this->_seps);
  158. $ret .= $this->_seps[$seps_index];
  159. }
  160. }
  161. if (strlen($ret) < $this->_min_hash_length) {
  162. $guard_index = ($numbers_hash_int + ord($ret[0])) % strlen($this->_guards);
  163. $guard = $this->_guards[$guard_index];
  164. $ret = $guard . $ret;
  165. if (strlen($ret) < $this->_min_hash_length) {
  166. $guard_index = ($numbers_hash_int + ord($ret[2])) % strlen($this->_guards);
  167. $guard = $this->_guards[$guard_index];
  168. $ret .= $guard;
  169. }
  170. }
  171. $half_length = (int)(strlen($alphabet) / 2);
  172. while (strlen($ret) < $this->_min_hash_length) {
  173. $alphabet = $this->_consistent_shuffle($alphabet, $alphabet);
  174. $ret = substr($alphabet, $half_length) . $ret . substr($alphabet, 0, $half_length);
  175. $excess = strlen($ret) - $this->_min_hash_length;
  176. if ($excess > 0) {
  177. $ret = substr($ret, $excess / 2, $this->_min_hash_length);
  178. }
  179. }
  180. return $ret;
  181. }
  182. private function _decode($hash, $alphabet) {
  183. $ret = array();
  184. $hash_breakdown = str_replace(str_split($this->_guards), ' ', $hash);
  185. $hash_array = explode(' ', $hash_breakdown);
  186. $i = 0;
  187. if (sizeof($hash_array) == 3 || sizeof($hash_array) == 2) {
  188. $i = 1;
  189. }
  190. $hash_breakdown = $hash_array[$i];
  191. if (isset($hash_breakdown[0])) {
  192. $lottery = $hash_breakdown[0];
  193. $hash_breakdown = substr($hash_breakdown, 1);
  194. $hash_breakdown = str_replace(str_split($this->_seps), ' ', $hash_breakdown);
  195. $hash_array = explode(' ', $hash_breakdown);
  196. foreach ($hash_array as $sub_hash) {
  197. $alphabet = $this->_consistent_shuffle($alphabet, substr($lottery . $this->_salt . $alphabet, 0, strlen($alphabet)));
  198. $ret[] = (int)$this->_unhash($sub_hash, $alphabet);
  199. }
  200. if ($this->_encode($ret) != $hash) {
  201. $ret = array();
  202. }
  203. }
  204. // return $ret;
  205. //修改为直接返回字符串
  206. return $ret[0];
  207. }
  208. private function _consistent_shuffle($alphabet, $salt) {
  209. if (!strlen($salt)) {
  210. return $alphabet;
  211. }
  212. for ($i = strlen($alphabet) - 1, $v = 0, $p = 0; $i > 0; $i--, $v++) {
  213. $v %= strlen($salt);
  214. $p += $int = ord($salt[$v]);
  215. $j = ($int + $v + $p) % $i;
  216. $temp = $alphabet[$j];
  217. $alphabet[$j] = $alphabet[$i];
  218. $alphabet[$i] = $temp;
  219. }
  220. return $alphabet;
  221. }
  222. private function _hash($input, $alphabet) {
  223. $hash = '';
  224. $alphabet_length = strlen($alphabet);
  225. do {
  226. $hash = $alphabet[$input % $alphabet_length] . $hash;
  227. if ($input > $this->_lower_max_int_value && $this->_math_functions) {
  228. $input = $this->_math_functions['str']($this->_math_functions['div']($input, $alphabet_length));
  229. } else {
  230. $input = (int)($input / $alphabet_length);
  231. }
  232. } while ($input);
  233. return $hash;
  234. }
  235. private function _unhash($input, $alphabet) {
  236. $number = 0;
  237. if (strlen($input) && $alphabet) {
  238. $alphabet_length = strlen($alphabet);
  239. $input_chars = str_split($input);
  240. foreach ($input_chars as $i => $char) {
  241. $pos = strpos($alphabet, $char);
  242. if ($this->_math_functions) {
  243. $number = $this->_math_functions['str']($this->_math_functions['add']($number, $pos * pow($alphabet_length, (strlen($input) - $i - 1))));
  244. } else {
  245. $number += $pos * pow($alphabet_length, (strlen($input) - $i - 1));
  246. }
  247. }
  248. }
  249. return $number;
  250. }
  251. }