-
Notifications
You must be signed in to change notification settings - Fork 0
/
toreadapi.php
395 lines (343 loc) · 11.8 KB
/
toreadapi.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
$config = parse_ini_file('toread.ini');
// Retrieves the categories.
function getCategories() {
global $dbh;
$categories = array();
$sql = "SELECT * FROM link_categories ORDER BY id ASC";
$cat_stmt = $dbh->query($sql);
$i = 0;
foreach ($cat_stmt as $cat)
{
$color = getColor($i++);
$categories[] = array(
'id' => $cat['id'],
'name' => $cat['name'],
'color' => $color,
'contrastColor' => getContrastColor($color)
);
}
return $categories;
}
// From http://24ways.org/2010/calculating-color-contrast
function getContrastColor($hexcolor)
{
$hexcolor = ltrim($hexcolor, '#');
$r = hexdec(substr($hexcolor,0,2));
$g = hexdec(substr($hexcolor,2,2));
$b = hexdec(substr($hexcolor,4,2));
$yiq = (($r*299)+($g*587)+($b*114))/1000;
return ($yiq >= 128) ? 'black' : 'white';
}
function getColor($index)
{
// Colors found on http://www.colorjack.com
$palette = array(
"45C7BA", "AC0339", "A9533A", "2B20A1", "F79E09", "B7078C",
"23780A", "F2DEC4", "D6FFFC", "333333", "452223", "974ABA",
"00374A", "FF00DD", "DCFE00", "8193AF", "4C010E", "8AABAF",
);
return '#' . $palette[$index];
}
// Retrieves the stats.
function getStats() {
global $dbh;
$sql = "SELECT COUNT(*) FROM links WHERE keywords IS NULL AND DATE(created)='" . date("Y-m-d") . "'";
$res = $dbh->query($sql);
$todayAdded = $res->fetchColumn();
$sql = "SELECT COUNT(*) FROM links WHERE keywords IS NULL AND DATE(deleted)='" . date("Y-m-d") . "'";
$res = $dbh->query($sql);
$todayDeleted = $res->fetchColumn();
$sql = "SELECT COUNT(*) FROM links WHERE keywords IS NULL AND created > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$res = $dbh->query($sql);
$weekAdded = $res->fetchColumn();
$sql = "SELECT COUNT(*) FROM links WHERE keywords IS NULL AND deleted > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$res = $dbh->query($sql);
$weekDeleted = $res->fetchColumn();
return array(
'addedToday' => intval($todayAdded),
'deletedToday' => intval($todayDeleted),
'addedThisWeek' => intval($weekAdded),
'deletedThisWeek' => intval($weekDeleted)
);
}
// Builds SQL clauses for the "q" parameter.
function getSearchQuery($searchString) {
global $dbh;
$searchString = (string)$searchString;
if ($searchString == '') { return ' AND keywords IS NULL'; }
$clauses = array();
// $clauses = array("keywords IS NOT NULL");
$words = preg_split('#\s+#', $searchString);
foreach ($words as $word) {
$escaped = $dbh->quote($word);
$escaped = substr($escaped, 1, strlen($escaped) - 2); // remove surrounding quotes
$clauses[] = "(title LIKE '%" . $escaped . "%' OR keywords LIKE '%" . $escaped . "%')";
}
return ' AND ' . implode(' AND ', $clauses);
}
// Builds SQL clauses for the "tag" parameter.
function getTagQuery($tagId) {
global $dbh;
if (!isset($tagId)) { return ''; }
$clauses = array(
'link_categories.id=' . intval($tagId),
'links_to_categories.category_id=link_categories.id',
'links_to_categories.link_id=links.id',
);
return ' AND ' . join(' AND ', $clauses);
}
function getTables() {
$tables = array('links');
if (isset($_GET['tag'])) {
array_push($tables, 'links_to_categories', 'link_categories');
}
return join(',', $tables);
}
// Retrieves the number of links.
function getTotal() {
global $dbh;
$sql = "SELECT COUNT(*)"
. " FROM (" . getTables() . ")"
. " WHERE deleted IS NULL"
. getSearchQuery(@$_GET['q'])
. getTagQuery(@$_GET['tag']);
$res = $dbh->query($sql);
$numLinks = $res->fetchColumn();
return intval($numLinks);
}
// Retrieves the links.
function getEntry() {
global $config, $dbh;
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
$count = isset($_GET['count']) ? intval($_GET['count']) : 20;
// Query the links.
$selection = "links.*"
. " , UNIX_TIMESTAMP(created) AS time"
. " , UNIX_TIMESTAMP(created) AS created"
. " , UNIX_TIMESTAMP(deleted) AS deleted"
. " , url AS link";
if (isset($_GET['check'])) {
$sql = "SELECT $selection FROM links"
. " WHERE url=" . $dbh->quote(@$_GET['url']);
} else if (isset($_GET['finddups'])) {
$sql = "SELECT $selection, COUNT(*) c FROM links"
. " WHERE deleted IS NULL"
. " AND keywords IS NULL"
. " GROUP BY url HAVING c > 1"
. " ORDER BY created DESC";
} else {
$sql = "SELECT $selection"
. " FROM (" . getTables() . ")"
. " WHERE 1=1"
. getSearchQuery(@$_GET['q'])
. getTagQuery(@$_GET['tag'])
. (@$_GET['include_deleted'] ? "" : " AND deleted IS NULL")
. (
isset($_GET['since'])
? " AND (UNIX_TIMESTAMP(created) >= " . intval($_GET['since'])
. " OR UNIX_TIMESTAMP(deleted) >= " . intval($_GET['since']) . ")"
: ""
)
. " ORDER BY " . (isset($_GET['random']) ? "RAND()" : "created DESC")
. " LIMIT $offset, $count";
}
$feed = $dbh->query($sql);
// Add the links to an array.
$links = array();
foreach ($feed as $item) {
// Query the tags (categories).
$tagSql = "SELECT *"
. " FROM link_categories, links_to_categories"
. " WHERE link_categories.id = category_id"
. " AND link_id = " . $item['id']
. " ORDER BY name ASC";
$tags = array();
$tagData = $dbh->query($tagSql);
foreach ($tagData as $tagInfo) {
$tags[] = $tagInfo['name'];
}
$decodedTitle = html_entity_decode($item['title']);
$decodedTitle = preg_replace_callback("/&#(x?)[0-9]+;/", function($m) {
return mb_convert_encoding($m[0], 'UTF-8', 'HTML-ENTITIES');
}, $decodedTitle);
// Add the link info to the array.
$links[] = array(
'id' => intval($item['id']),
'title' => $decodedTitle,
'link' => $item['link'],
'description' => $item['keywords'],
'hasSnapshot' => !is_null($item['snapshot']),
'time' => date('c', $item['time']),
'created' => $item['created'],
'deleted' => isset($_GET['since']) ? $item['deleted'] : !is_null($item['deleted']),
'tags' => $tags
);
}
$response = array(
'links' => $links,
'total' => getTotal(),
'tags' => getCategories(),
'stats' => getStats(),
);
if (isset($config['debug']) and
$config['debug'] == 'on') {
$response['query'] = $sql;
}
return $response;
}
function postEntry() {
global $dbh;
$maxTitleLength = 191;
$postdata = file_get_contents("php://input");
$POST = json_decode($postdata);
$url = isset($POST->url) ? $POST->url : '';
$keywords = isset($POST->keywords) ? trim($POST->keywords) : '';
$response = array();
// Retrieve the page title.
$html = NULL; // default
$title = htmlentities($url); // default
if (function_exists("curl_init"))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept-Encoding: identity" // turn off compression
));
$result = curl_exec($ch);
if ($result !== false)
{
// Look for a charset definition in the page.
// Convert to UTF-8 if necessary.
if (preg_match("#<meta[^<]*charset=([a-z0-9_-]+)#is", $result, $matches)) {
if (strtolower($matches[1]) !== 'utf-8') {
$result = mb_convert_encoding($result, 'UTF-8', $matches[1]);
}
}
// Save the <title>.
$cleanedHtml = preg_replace('#<script.*</script>#isU', '', $result);
$cleanedHtml = preg_replace('#<style.*</style>#isU', '', $cleanedHtml);
$cleanedHtml = preg_replace('#<svg.*</svg>#isU', '', $cleanedHtml);
if (preg_match("#<title[^>]*>(.*)</title>#isU", $cleanedHtml, $matches)
and $matches[1] != "")
{
$title = mb_substr($matches[1], 0, $maxTitleLength, 'UTF-8');
}
// Save the page, if it's HTML.
if (stripos($result, '<html') !== false) {
$html = $result;
}
}
}
// Add the link.
$sql = "INSERT INTO links"
. " SET created = NOW()"
. " , url = " . $dbh->quote($url)
. " , title = " . $dbh->quote($title)
. " , snapshot = " . (is_null($html) ? "NULL" : $dbh->quote($html))
. " , keywords = " . ($keywords == '' ? "NULL" : $dbh->quote($keywords));
$success = $dbh->exec($sql);
$response['success'] = (bool)$success;
if (!$success) {
$errInfo = $dbh->errorInfo();
$errMessage = $errInfo[2];
if ($errInfo[0]) {
$errMessage .= " ({$errInfo[0]})";
}
$response['error'] = $errMessage;
}
// Parse the tags.
$raw_tags = isset($POST->tags) ? $POST->tags : '';
$tags = preg_split("#,#", $raw_tags, -1, PREG_SPLIT_NO_EMPTY);
$tags = array_map("trim", $tags);
// Add the tags.
if ($success)
{
$link_id = $dbh->lastInsertId();
$response['id'] = $link_id;
foreach ($tags as $tag)
{
// Check if the category exists already.
$category_id = null;
$categories = getCategories();
foreach ($categories as $cat)
{
if (strtolower($cat['name']) == strtolower($tag))
{
$category_id = $cat['id'];
break;
}
}
// Add the category if it doesn't exist.
if (is_null($category_id))
{
$sql = "INSERT INTO link_categories"
. " SET name = " . $dbh->quote($tag);
$success = $dbh->exec($sql);
if ($success)
{
$category_id = $dbh->lastInsertId();
}
else
{
continue; // go to next tag
}
}
// Add the link/category association.
$sql = "INSERT INTO links_to_categories"
. " SET link_id = " . $link_id
. " , category_id = " . $category_id;
$dbh->exec($sql);
}
}
return $response;
}
function deleteEntry() {
global $dbh;
$ids = isset($_GET['id']) ? (array)$_GET['id'] : array();
$success = true;
if (!empty($ids))
{
$ids = array_map('intval', $ids);
// Delete the links.
$sql = "UPDATE links SET deleted=NOW() WHERE id IN (" . implode(",", $ids) . ")";
$success = $dbh->exec($sql);
}
return array('success' => $success, 'deleted' => $ids);
}
try {
$dbh = new PDO(
"mysql:dbname=" . $config['db_name'] . ";host=" . $config['db_host']. ";charset=utf8mb4",
$config['db_user'], $config['db_pass']);
} catch (Exception $e) {
header("HTTP/1.0 500 Internal Server Error");
echo "Could not connect to database: " . $e->getMessage();
exit;
}
// Perform the request.
$method = strtolower($_SERVER['REQUEST_METHOD']);
$func = $method . 'Entry';
$data = $func();
header('Content-Type: application/json; charset=UTF-8');
$encoded = json_encode($data);
if (!$encoded) {
$data['links'] = array(array(
'id' => json_last_error(),
'title' => 'API ERROR: ' . json_last_error_msg(),
'link' => 'http://php.net/manual/en/function.json-last-error.php',
'description' => null,
'time' => date('c'),
'created' => time(),
'deleted' => false,
'tags' => array()
));
$data['total'] = 1;
$encoded = json_encode($data);
}
echo $encoded;
?>