Shorty.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. namespace App\Base\Library;
  3. use App\Base\Exceptions\ApiException;
  4. use App\Basic\Facades\UrlsFacade;
  5. class Shorty {
  6. /**
  7. * Default characters to use for shortening.
  8. *
  9. * @var string
  10. */
  11. private $chars = 'DUuW9Pd0lGE2xZp4aIwOrHYkMA7fCi1Te53VzL6gRKnmtSsFoyNQvcjBqJhX8b';
  12. /**
  13. * Salt for id encoding.
  14. *
  15. * @var string
  16. */
  17. private $salt = '';
  18. /**
  19. * Length of number padding.
  20. */
  21. private $padding = 1;
  22. /**
  23. * Hostname
  24. */
  25. private $hostname = '';
  26. /**
  27. * PDO database connection.
  28. *
  29. * @var object
  30. */
  31. private $connection = null;
  32. /**
  33. * Whitelist of IPs allowed to save URLs.
  34. * If the list is empty, then any IP is allowed.
  35. *
  36. * @var array
  37. */
  38. private $whitelist = array();
  39. /**
  40. * Constructor
  41. *
  42. * @param string $hostname Hostname
  43. * @param object $connection Database connection
  44. */
  45. public function __construct($hostname) {
  46. $this->hostname = $hostname;
  47. }
  48. /**
  49. * Gets the character set for encoding.
  50. *
  51. * @return string Set of characters
  52. */
  53. public function get_chars() {
  54. return $this->chars;
  55. }
  56. /**
  57. * Sets the character set for encoding.
  58. *
  59. * @param string $chars Set of characters
  60. */
  61. public function set_chars($chars) {
  62. if (!is_string($chars) || empty($chars)) {
  63. throw new Exception('Invalid input.');
  64. }
  65. $this->chars = $chars;
  66. }
  67. /**
  68. * Gets the salt string for encoding.
  69. *
  70. * @return string Salt
  71. */
  72. public function get_salt() {
  73. return $this->salt;
  74. }
  75. /**
  76. * Sets the salt string for encoding.
  77. *
  78. * @param string $salt Salt string
  79. */
  80. public function set_salt($salt) {
  81. $this->salt = $salt;
  82. }
  83. /**
  84. * Gets the padding length.
  85. *
  86. * @return int Padding length
  87. */
  88. public function get_padding() {
  89. return $this->padding;
  90. }
  91. /**
  92. * Sets the padding length.
  93. *
  94. * @param int $padding Padding length
  95. */
  96. public function set_padding($padding) {
  97. $this->padding = $padding;
  98. }
  99. /**
  100. * Converts an id to an encoded string.
  101. *
  102. * @param int $n Number to encode
  103. * @return string Encoded string
  104. */
  105. public function encode($n) {
  106. $k = 0;
  107. if ($this->padding > 0 && !empty($this->salt)) {
  108. $k = self::get_seed($n, $this->salt, $this->padding);
  109. $n = (int)($k.$n);
  110. }
  111. return self::num_to_alpha($n, $this->chars);
  112. }
  113. /**
  114. * Converts an encoded string into a number.
  115. *
  116. * @param string $s String to decode
  117. * @return int Decoded number
  118. */
  119. public function decode($s) {
  120. $n = self::alpha_to_num($s, $this->chars);
  121. return (!empty($this->salt)) ? substr($n, $this->padding) : $n;
  122. }
  123. /**
  124. * Gets a number for padding based on a salt.
  125. *
  126. * @param int $n Number to pad
  127. * @param string $salt Salt string
  128. * @param int $padding Padding length
  129. * @return int Number for padding
  130. */
  131. public static function get_seed($n, $salt, $padding) {
  132. $hash = md5($n.$salt);
  133. $dec = hexdec(substr($hash, 0, $padding));
  134. $num = $dec % pow(10, $padding);
  135. if ($num == 0) $num = 1;
  136. $num = str_pad($num, $padding, '0');
  137. return $num;
  138. }
  139. /**
  140. * Converts a number to an alpha-numeric string.
  141. *
  142. * @param int $num Number to convert
  143. * @param string $s String of characters for conversion
  144. * @return string Alpha-numeric string
  145. */
  146. public static function num_to_alpha($n, $s) {
  147. $b = strlen($s);
  148. $m = $n % $b;
  149. if ($n - $m == 0) return substr($s, $n, 1);
  150. $a = '';
  151. while ($m > 0 || $n > 0) {
  152. $a = substr($s, $m, 1).$a;
  153. $n = ($n - $m) / $b;
  154. $m = $n % $b;
  155. }
  156. return $a;
  157. }
  158. /**
  159. * Converts an alpha numeric string to a number.
  160. *
  161. * @param string $a Alpha-numeric string to convert
  162. * @param string $s String of characters for conversion
  163. * @return int Converted number
  164. */
  165. public static function alpha_to_num($a, $s) {
  166. $b = strlen($s);
  167. $l = strlen($a);
  168. for ($n = 0, $i = 0; $i < $l; $i++) {
  169. $n += strpos($s, substr($a, $i, 1)) * pow($b, $l - $i - 1);
  170. }
  171. return $n;
  172. }
  173. /**
  174. * Looks up a URL in the database by id.
  175. *
  176. * @param string $id URL id
  177. * @return array URL record
  178. */
  179. public function fetch($id) {
  180. $statement = $this->connection->prepare(
  181. 'SELECT * FROM urls WHERE id = ?'
  182. );
  183. $statement->execute(array($id));
  184. return $statement->fetch(PDO::FETCH_ASSOC);
  185. }
  186. /**
  187. * Attempts to locate a URL in the database.
  188. *
  189. * @param string $url URL
  190. * @return array URL record
  191. */
  192. public function find($url) {
  193. return UrlsFacade::findOneBy([
  194. "url" => $url,
  195. "status" => 0
  196. ], "id,url");
  197. }
  198. /**
  199. * Stores a URL in the database.
  200. *
  201. * @param string $url URL to store
  202. * @return int Insert id
  203. */
  204. public function store($url) {
  205. $info = UrlsFacade::save([
  206. "url" => $url,
  207. "status" => 0
  208. ]);
  209. return $info->id;
  210. }
  211. /**
  212. * Updates statistics for a URL.
  213. *
  214. * @param int $id URL id
  215. */
  216. public function update($id, $key) {
  217. return UrlsFacade::update($id, [
  218. "key" => $key
  219. ]);
  220. }
  221. /**
  222. * Sends a redirect to a URL.
  223. *
  224. * @param string $url URL
  225. */
  226. public function redirect($url) {
  227. header("Location: $url", true, 301);
  228. exit();
  229. }
  230. /**
  231. * Sends a 404 response.
  232. */
  233. public function not_found() {
  234. header('Status: 404 Not Found');
  235. exit(
  236. '<h1>404 Not Found</h1>'.
  237. str_repeat(' ', 512)
  238. );
  239. }
  240. /**
  241. * Sends an error message.
  242. *
  243. * @param string $message Error message
  244. */
  245. public function error($message) {
  246. exit("<h1>$message</h1>");
  247. }
  248. /**
  249. * Adds an IP to allow saving URLs.
  250. *
  251. * @param string|array $ip IP address or array of IP addresses
  252. */
  253. public function allow($ip) {
  254. if (is_array($ip)) {
  255. $this->whitelist = array_merge($this->whitelist, $ip);
  256. }
  257. else {
  258. array_push($this->whitelist, $ip);
  259. }
  260. }
  261. /**
  262. * Starts the program.
  263. */
  264. public function run($url)
  265. {
  266. $url = urldecode($url);
  267. // If adding a new URL
  268. if (!empty($url)) {
  269. if (!empty($this->whitelist) && !in_array($_SERVER['REMOTE_ADDR'], $this->whitelist)) {
  270. throw new ApiException("", "请求地址不在白名单中");
  271. }
  272. if (preg_match('/^http[s]?\:\/\/[\w]+/', $url)) {
  273. $result = $this->find($url); //查询是否存在
  274. // Not found, so save it
  275. if (empty($result)) {
  276. $id = $this->store($url); // 新增
  277. $code = $this->encode($id);
  278. $url = $this->hostname . '/' . $code;
  279. $this->update($id, $code);
  280. } else {
  281. $url = $this->hostname . '/' . $this->encode($result['id']);
  282. }
  283. return $url;
  284. } else {
  285. throw new ApiException("", "地址错误");
  286. }
  287. } else {
  288. throw new ApiException("", "地址错误");
  289. }
  290. }
  291. }