Hashids.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /*
  3. * This file is part of Hashids.
  4. *
  5. * (c) Ivan Akimov <ivan@barreleye.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Hashids;
  11. use Hashids\Math\Bc;
  12. use Hashids\Math\Gmp;
  13. use RuntimeException;
  14. /**
  15. * This is the hashids class.
  16. *
  17. * @author Ivan Akimov <ivan@barreleye.com>
  18. * @author Vincent Klaiber <hello@vinkla.com>
  19. * @author Johnson Page <jwpage@gmail.com>
  20. */
  21. class Hashids implements HashidsInterface
  22. {
  23. /**
  24. * The seps divider.
  25. *
  26. * @var float
  27. */
  28. const SEP_DIV = 3.5;
  29. /**
  30. * The guard divider.
  31. *
  32. * @var float
  33. */
  34. const GUARD_DIV = 12;
  35. /**
  36. * The alphabet string.
  37. *
  38. * @var string
  39. */
  40. protected $alphabet;
  41. /**
  42. * Shuffled alphabets, referenced by alphabet and salt.
  43. *
  44. * @var array
  45. */
  46. protected $shuffledAlphabets;
  47. /**
  48. * The seps string.
  49. *
  50. * @var string
  51. */
  52. protected $seps = 'cfhistuCFHISTU';
  53. /**
  54. * The guards string.
  55. *
  56. * @var string
  57. */
  58. protected $guards;
  59. /**
  60. * The minimum hash length.
  61. *
  62. * @var int
  63. */
  64. protected $minHashLength;
  65. /**
  66. * The salt string.
  67. *
  68. * @var string
  69. */
  70. protected $salt;
  71. /**
  72. * The math class.
  73. *
  74. * @var \Hashids\Math\MathInterface
  75. */
  76. protected $math;
  77. /**
  78. * Create a new hashids instance.
  79. *
  80. * @param string $salt
  81. * @param int $minHashLength
  82. * @param string $alphabet
  83. *
  84. * @throws \Hashids\HashidsException
  85. *
  86. * @return void
  87. */
  88. public function __construct($salt = '', $minHashLength = 0, $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')
  89. {
  90. $this->salt = $salt;
  91. $this->minHashLength = $minHashLength;
  92. $this->alphabet = implode('', array_unique(str_split($alphabet)));
  93. $this->math = $this->getMathExtension();
  94. if (strlen($this->alphabet) < 16) {
  95. throw new HashidsException('Alphabet must contain at least 16 unique characters.');
  96. }
  97. if (strpos($this->alphabet, ' ') !== false) {
  98. throw new HashidsException('Alphabet can\'t contain spaces.');
  99. }
  100. $alphabetArray = str_split($this->alphabet);
  101. $sepsArray = str_split($this->seps);
  102. $this->seps = implode('', array_intersect($sepsArray, $alphabetArray));
  103. $this->alphabet = implode('', array_diff($alphabetArray, $sepsArray));
  104. $this->seps = $this->shuffle($this->seps, $this->salt);
  105. if (!$this->seps || (strlen($this->alphabet) / strlen($this->seps)) > self::SEP_DIV) {
  106. $sepsLength = (int) ceil(strlen($this->alphabet) / self::SEP_DIV);
  107. if ($sepsLength > strlen($this->seps)) {
  108. $diff = $sepsLength - strlen($this->seps);
  109. $this->seps .= substr($this->alphabet, 0, $diff);
  110. $this->alphabet = substr($this->alphabet, $diff);
  111. }
  112. }
  113. $this->alphabet = $this->shuffle($this->alphabet, $this->salt);
  114. $guardCount = (int) ceil(strlen($this->alphabet) / self::GUARD_DIV);
  115. if (strlen($this->alphabet) < 3) {
  116. $this->guards = substr($this->seps, 0, $guardCount);
  117. $this->seps = substr($this->seps, $guardCount);
  118. } else {
  119. $this->guards = substr($this->alphabet, 0, $guardCount);
  120. $this->alphabet = substr($this->alphabet, $guardCount);
  121. }
  122. }
  123. /**
  124. * Encode parameters to generate a hash.
  125. *
  126. * @param mixed $numbers
  127. *
  128. * @return string
  129. */
  130. public function encode(...$numbers)
  131. {
  132. $ret = '';
  133. if (1 === count($numbers) && is_array($numbers[0])) {
  134. $numbers = $numbers[0];
  135. }
  136. if (!$numbers) {
  137. return $ret;
  138. }
  139. foreach ($numbers as $number) {
  140. $isNumber = ctype_digit((string) $number);
  141. if (!$isNumber) {
  142. return $ret;
  143. }
  144. }
  145. $alphabet = $this->alphabet;
  146. $numbersSize = count($numbers);
  147. $numbersHashInt = 0;
  148. foreach ($numbers as $i => $number) {
  149. $numbersHashInt += $this->math->intval($this->math->mod($number, ($i + 100)));
  150. }
  151. $lottery = $ret = $alphabet[$numbersHashInt % strlen($alphabet)];
  152. foreach ($numbers as $i => $number) {
  153. $alphabet = $this->shuffle($alphabet, substr($lottery.$this->salt.$alphabet, 0, strlen($alphabet)));
  154. $ret .= $last = $this->hash($number, $alphabet);
  155. if ($i + 1 < $numbersSize) {
  156. $number %= (ord($last) + $i);
  157. $sepsIndex = $this->math->intval($this->math->mod($number, strlen($this->seps)));
  158. $ret .= $this->seps[$sepsIndex];
  159. }
  160. }
  161. if (strlen($ret) < $this->minHashLength) {
  162. $guardIndex = ($numbersHashInt + ord($ret[0])) % strlen($this->guards);
  163. $guard = $this->guards[$guardIndex];
  164. $ret = $guard.$ret;
  165. if (strlen($ret) < $this->minHashLength) {
  166. $guardIndex = ($numbersHashInt + ord($ret[2])) % strlen($this->guards);
  167. $guard = $this->guards[$guardIndex];
  168. $ret .= $guard;
  169. }
  170. }
  171. $halfLength = (int) (strlen($alphabet) / 2);
  172. while (strlen($ret) < $this->minHashLength) {
  173. $alphabet = $this->shuffle($alphabet, $alphabet);
  174. $ret = substr($alphabet, $halfLength).$ret.substr($alphabet, 0, $halfLength);
  175. $excess = strlen($ret) - $this->minHashLength;
  176. if ($excess > 0) {
  177. $ret = substr($ret, $excess / 2, $this->minHashLength);
  178. }
  179. }
  180. return $ret;
  181. }
  182. /**
  183. * Decode a hash to the original parameter values.
  184. *
  185. * @param string $hash
  186. *
  187. * @return array
  188. */
  189. public function decode($hash)
  190. {
  191. $ret = [];
  192. if (!is_string($hash) || !($hash = trim($hash))) {
  193. return $ret;
  194. }
  195. $alphabet = $this->alphabet;
  196. $ret = [];
  197. $hashBreakdown = str_replace(str_split($this->guards), ' ', $hash);
  198. $hashArray = explode(' ', $hashBreakdown);
  199. $i = count($hashArray) == 3 || count($hashArray) == 2 ? 1 : 0;
  200. $hashBreakdown = $hashArray[$i];
  201. if (isset($hashBreakdown[0])) {
  202. $lottery = $hashBreakdown[0];
  203. $hashBreakdown = substr($hashBreakdown, 1);
  204. $hashBreakdown = str_replace(str_split($this->seps), ' ', $hashBreakdown);
  205. $hashArray = explode(' ', $hashBreakdown);
  206. foreach ($hashArray as $subHash) {
  207. $alphabet = $this->shuffle($alphabet, substr($lottery.$this->salt.$alphabet, 0, strlen($alphabet)));
  208. $result = $this->unhash($subHash, $alphabet);
  209. if ($this->math->greaterThan($result, PHP_INT_MAX)) {
  210. $ret[] = $this->math->strval($result);
  211. } else {
  212. $ret[] = $this->math->intval($result);
  213. }
  214. }
  215. if ($this->encode($ret) != $hash) {
  216. $ret = [];
  217. }
  218. }
  219. return $ret;
  220. }
  221. /**
  222. * Encode hexadecimal values and generate a hash string.
  223. *
  224. * @param string $str
  225. *
  226. * @return string
  227. */
  228. public function encodeHex($str)
  229. {
  230. if (!ctype_xdigit((string) $str)) {
  231. return '';
  232. }
  233. $numbers = trim(chunk_split($str, 12, ' '));
  234. $numbers = explode(' ', $numbers);
  235. foreach ($numbers as $i => $number) {
  236. $numbers[$i] = hexdec('1'.$number);
  237. }
  238. return call_user_func_array([$this, 'encode'], $numbers);
  239. }
  240. /**
  241. * Decode a hexadecimal hash.
  242. *
  243. * @param string $hash
  244. *
  245. * @return string
  246. */
  247. public function decodeHex($hash)
  248. {
  249. $ret = '';
  250. $numbers = $this->decode($hash);
  251. foreach ($numbers as $i => $number) {
  252. $ret .= substr(dechex($number), 1);
  253. }
  254. return $ret;
  255. }
  256. /**
  257. * Shuffle alphabet by given salt.
  258. *
  259. * @param string $alphabet
  260. * @param string $salt
  261. *
  262. * @return string
  263. */
  264. protected function shuffle($alphabet, $salt)
  265. {
  266. $key = $alphabet.' '.$salt;
  267. if (isset($this->shuffledAlphabets[$key])) {
  268. return $this->shuffledAlphabets[$key];
  269. }
  270. $saltLength = strlen($salt);
  271. if (!$saltLength) {
  272. return $alphabet;
  273. }
  274. for ($i = strlen($alphabet) - 1, $v = 0, $p = 0; $i > 0; $i--, $v++) {
  275. $v %= $saltLength;
  276. $p += $int = ord($salt[$v]);
  277. $j = ($int + $v + $p) % $i;
  278. $temp = $alphabet[$j];
  279. $alphabet[$j] = $alphabet[$i];
  280. $alphabet[$i] = $temp;
  281. }
  282. $this->shuffledAlphabets[$key] = $alphabet;
  283. return $alphabet;
  284. }
  285. /**
  286. * Hash given input value.
  287. *
  288. * @param string $input
  289. * @param string $alphabet
  290. *
  291. * @return string
  292. */
  293. protected function hash($input, $alphabet)
  294. {
  295. $hash = '';
  296. $alphabetLength = strlen($alphabet);
  297. do {
  298. $hash = $alphabet[$this->math->intval($this->math->mod($input, $alphabetLength))].$hash;
  299. $input = $this->math->divide($input, $alphabetLength);
  300. } while ($this->math->greaterThan($input, 0));
  301. return $hash;
  302. }
  303. /**
  304. * Unhash given input value.
  305. *
  306. * @param string $input
  307. * @param string $alphabet
  308. *
  309. * @return int
  310. */
  311. protected function unhash($input, $alphabet)
  312. {
  313. $number = 0;
  314. $inputLength = strlen($input);
  315. if ($inputLength && $alphabet) {
  316. $alphabetLength = strlen($alphabet);
  317. $inputChars = str_split($input);
  318. foreach ($inputChars as $char) {
  319. $position = strpos($alphabet, $char);
  320. $number = $this->math->multiply($number, $alphabetLength);
  321. $number = $this->math->add($number, $position);
  322. }
  323. }
  324. return $number;
  325. }
  326. /**
  327. * Get BC Math or GMP extension.
  328. *
  329. * @codeCoverageIgnore
  330. *
  331. * @throws \RuntimeException
  332. *
  333. * @return \Hashids\Math\Bc|\Hashids\Math\Gmp
  334. */
  335. protected function getMathExtension()
  336. {
  337. if (extension_loaded('gmp')) {
  338. return new Gmp();
  339. }
  340. if (extension_loaded('bcmath')) {
  341. return new Bc();
  342. }
  343. throw new RuntimeException('Missing BC Math or GMP extension.');
  344. }
  345. }