-
Notifications
You must be signed in to change notification settings - Fork 98
/
shorty.php
395 lines (339 loc) · 9.36 KB
/
shorty.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php
/**
* Shorty: A simple URL shortener.
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://www.opensource.org/licenses/mit-license.php
*/
class Shorty {
/**
* Default characters to use for shortening.
*
* @var string
*/
private $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
/**
* Salt for id encoding.
*
* @var string
*/
private $salt = '';
/**
* Length of number padding.
*/
private $padding = 1;
/**
* Hostname
*/
private $hostname = '';
/**
* PDO database connection.
*
* @var object
*/
private $connection = null;
/**
* Whitelist of IPs allowed to save URLs.
* If the list is empty, then any IP is allowed.
*
* @var array
*/
private $whitelist = array();
/**
* Constructor
*
* @param string $hostname Hostname
* @param object $connection Database connection
*/
public function __construct($hostname, $connection) {
$this->hostname = $hostname;
$this->connection = $connection;
}
/**
* Gets the character set for encoding.
*
* @return string Set of characters
*/
public function get_chars() {
return $this->chars;
}
/**
* Sets the character set for encoding.
*
* @param string $chars Set of characters
*/
public function set_chars($chars) {
if (!is_string($chars) || empty($chars)) {
throw new Exception('Invalid input.');
}
$this->chars = $chars;
}
/**
* Gets the salt string for encoding.
*
* @return string Salt
*/
public function get_salt() {
return $this->salt;
}
/**
* Sets the salt string for encoding.
*
* @param string $salt Salt string
*/
public function set_salt($salt) {
$this->salt = $salt;
}
/**
* Gets the padding length.
*
* @return int Padding length
*/
public function get_padding() {
return $this->padding;
}
/**
* Sets the padding length.
*
* @param int $padding Padding length
*/
public function set_padding($padding) {
$this->padding = $padding;
}
/**
* Converts an id to an encoded string.
*
* @param int $n Number to encode
* @return string Encoded string
*/
public function encode($n) {
$k = 0;
if ($this->padding > 0 && !empty($this->salt)) {
$k = self::get_seed($n, $this->salt, $this->padding);
$n = (int)($k.$n);
}
return self::num_to_alpha($n, $this->chars);
}
/**
* Converts an encoded string into a number.
*
* @param string $s String to decode
* @return int Decoded number
*/
public function decode($s) {
$n = self::alpha_to_num($s, $this->chars);
return (!empty($this->salt)) ? substr($n, $this->padding) : $n;
}
/**
* Gets a number for padding based on a salt.
*
* @param int $n Number to pad
* @param string $salt Salt string
* @param int $padding Padding length
* @return int Number for padding
*/
public static function get_seed($n, $salt, $padding) {
$hash = md5($n.$salt);
$dec = hexdec(substr($hash, 0, $padding));
$num = $dec % pow(10, $padding);
if ($num == 0) $num = 1;
$num = str_pad($num, $padding, '0');
return $num;
}
/**
* Converts a number to an alpha-numeric string.
*
* @param int $num Number to convert
* @param string $s String of characters for conversion
* @return string Alpha-numeric string
*/
public static function num_to_alpha($n, $s) {
$b = strlen($s);
$m = $n % $b;
if ($n - $m == 0) return substr($s, $n, 1);
$a = '';
while ($m > 0 || $n > 0) {
$a = substr($s, $m, 1).$a;
$n = ($n - $m) / $b;
$m = $n % $b;
}
return $a;
}
/**
* Converts an alpha numeric string to a number.
*
* @param string $a Alpha-numeric string to convert
* @param string $s String of characters for conversion
* @return int Converted number
*/
public static function alpha_to_num($a, $s) {
$b = strlen($s);
$l = strlen($a);
for ($n = 0, $i = 0; $i < $l; $i++) {
$n += strpos($s, substr($a, $i, 1)) * pow($b, $l - $i - 1);
}
return $n;
}
/**
* Looks up a URL in the database by id.
*
* @param string $id URL id
* @return array URL record
*/
public function fetch($id) {
$statement = $this->connection->prepare(
'SELECT * FROM urls WHERE id = ?'
);
$statement->execute(array($id));
return $statement->fetch(PDO::FETCH_ASSOC);
}
/**
* Attempts to locate a URL in the database.
*
* @param string $url URL
* @return array URL record
*/
public function find($url) {
$statement = $this->connection->prepare(
'SELECT * FROM urls WHERE url = ?'
);
$statement->execute(array($url));
return $statement->fetch(PDO::FETCH_ASSOC);
}
/**
* Stores a URL in the database.
*
* @param string $url URL to store
* @return int Insert id
*/
public function store($url) {
$datetime = date('Y-m-d H:i:s');
$statement = $this->connection->prepare(
'INSERT INTO urls (url, created) VALUES (?,?)'
);
$statement->execute(array($url, $datetime));
return $this->connection->lastInsertId();
}
/**
* Updates statistics for a URL.
*
* @param int $id URL id
*/
public function update($id) {
$datetime = date('Y-m-d H:i:s');
$statement = $this->connection->prepare(
'UPDATE urls SET hits = hits + 1, accessed = ? WHERE id = ?'
);
$statement->execute(array($datetime, $id));
}
/**
* Sends a redirect to a URL.
*
* @param string $url URL
*/
public function redirect($url) {
header("Location: $url", true, 301);
exit();
}
/**
* Sends a 404 response.
*/
public function not_found() {
header('Status: 404 Not Found');
exit(
'<h1>404 Not Found</h1>'.
str_repeat(' ', 512)
);
}
/**
* Sends an error message.
*
* @param string $message Error message
*/
public function error($message) {
exit("<h1>$message</h1>");
}
/**
* Adds an IP to allow saving URLs.
*
* @param string|array $ip IP address or array of IP addresses
*/
public function allow($ip) {
if (is_array($ip)) {
$this->whitelist = array_merge($this->whitelist, $ip);
}
else {
array_push($this->whitelist, $ip);
}
}
/**
* Starts the program.
*/
public function run() {
$q = str_replace('/', '', $_GET['q']);
$url = '';
if (isset($_GET['url'])) {
$url = urldecode($_GET['url']);
}
$format = '';
if (isset($_GET['format'])) {
$format = strtolower($_GET['format']);
}
// If adding a new URL
if (!empty($url)) {
if (!empty($this->whitelist) && !in_array($_SERVER['REMOTE_ADDR'], $this->whitelist)) {
$this->error('Not allowed.');
}
if (preg_match('/^http[s]?\:\/\/[\w]+/', $url)) {
$result = $this->find($url);
// Not found, so save it
if (empty($result)) {
$id = $this->store($url);
$url = $this->hostname.'/'.$this->encode($id);
}
else {
$url = $this->hostname.'/'.$this->encode($result['id']);
}
// Display the shortened url
switch ($format) {
case 'text':
exit($url);
case 'json':
header('Content-Type: application/json');
exit(json_encode(array('url' => $url)));
case 'xml':
header('Content-Type: application/xml');
exit(implode("\n", array(
'<?xml version="1.0"?'.'>',
'<response>',
' <url>'.htmlentities($url).'</url>',
'</response>'
)));
default:
exit('<a href="'.$url.'">'.$url.'</a>');
}
}
else {
$this->error('Bad input.');
}
}
// Lookup by id
else {
if (empty($q)) {
$this->not_found();
return;
}
if (preg_match('/^([a-zA-Z0-9]+)$/', $q, $matches)) {
$id = self::decode($matches[1]);
$result = $this->fetch($id);
if (!empty($result)) {
$this->update($id);
$this->redirect($result['url']);
}
else {
$this->not_found();
}
}
}
}
}