-
Notifications
You must be signed in to change notification settings - Fork 7
/
database.php
88 lines (71 loc) · 2.15 KB
/
database.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
<?php
class MyDB {
public $pdo;
public function __construct() {
$this->pdo = new PDO('sqlite:/usr/share/nginx/tg.pe/sqlite.db');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/* Return code (string) or false (bool) */
public function findCodeByUrl(string $url) {
/* Find existed one */
$sql = "SELECT * FROM main WHERE url = :url";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
':url' => $url
]);
/* Only return first result */
if ($data = $stmt->fetch())
return $data['code'];
return false;
}
/* Return data or false */
public function findByCode(string $code) {
$sql = "SELECT * FROM main WHERE code = :code";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
':code' => $code
]);
return $stmt->fetch();
}
/* Return data array, or empty array */
public function findByAuthor(string $author) {
$sql = "SELECT * FROM main WHERE author = :author";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
':author' => $author
]);
$result = [];
while ($data = $stmt->fetch())
$result[] = $data;
return $result;
}
/* Find unused code */
public function allocateCode(string $prefix = '', $minLen = 3): string {
if (!preg_match('#^[A-Za-z0-9_-]{0,32}$#', $prefix))
return false; // illegal prefix
$base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
for ($len=$minLen; $len<=32; $len++) // Try length from min to 32
for ($_=0; $_<10; $_++) { // Try 10 times
$code = $prefix;
while (strlen($code) < $len)
$code .= $base58[rand(0, 57)];
if (!$this->findByCode($code))
return $code;
}
}
/* Return error info or ['00000', null, null] on success */
public function insert(string $code, string $url, string $author) {
if (!preg_match('#^[A-Za-z0-9_-]{1,32}$#', $code))
return ['SEAN', 0, 'illegal code'];
if (!filter_var($url, FILTER_VALIDATE_URL))
return ['SEAN', 0, 'illegal url'];
$sql = "INSERT INTO main(code, url, author) VALUES (:code, :url, :author)";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
':code' => $code,
':url' => $url,
':author' => $author
]);
return $stmt->errorInfo();
}
}