add JSON api to fetch links for a given URL
[stapibas.git] / www / api / links.php
1 <?php
2 namespace stapibas;
3 /**
4  * Fetch the list of links in the given URL as well as their ping status.
5  * Tells you if it was pinged, and what result it had.
6  */
7
8 require_once '../www-header.php';
9
10 if (!isset($_GET['url'])) {
11     header('HTTP/1.0 400 Bad Request');
12     echo "url missing\n";
13     exit(1);
14 }
15
16 $url = $_GET['url'];
17 $res = $db->query(
18     'SELECT * FROM feedentries WHERE fe_url = ' . $db->quote($url)
19 );
20 $urlRow = $res->fetch(PDO::FETCH_OBJ);
21 if ($urlRow === false) {
22     header('HTTP/1.0 404 Not Found');
23     echo "Url not found\n";
24     exit(1);
25 }
26 $json = (object) array(
27     'url'         => $urlRow->fe_url,
28     'updated'     => $urlRow->fe_updated,
29     'needsUpdate' => (bool) $urlRow->fe_needs_update,
30     'links'       => array()
31 );
32
33 $res = $db->query(
34     'SELECT * FROM feedentryurls'
35     . ' WHERE feu_fe_id = ' . $db->quote($urlRow->fe_id)
36 );
37 while ($linkRow = $res->fetch(\PDO::FETCH_OBJ)) {
38     $status = null;
39     if (!$linkRow->feu_pinged) {
40         $status = 'queued';
41     } else if ($linkRow->feu_retry && $linkRow->feu_tries < 5) {
42         $status = 'pinging';
43     } else if ($linkRow->feu_error) {
44         $status = 'error';
45     } else {
46         $status = 'ok';
47     }
48     $json->links[] = (object) array(
49         'url'     => $linkRow->feu_url,
50         'pinged'  => (bool) $linkRow->feu_pinged,
51         'updated' => $linkRow->feu_updated,
52         'status'  => $status,
53         'error'   => (object) array(
54             'code'    => $linkRow->feu_error_code,
55             'message' => $linkRow->feu_error_message
56         ),
57         'tries'   => $linkRow->feu_tries
58     );
59 }
60
61 header('Content-type: application/json');
62 echo json_encode($json) . "\n";
63 ?>