411fa8671cb86dfde43ec9c56eb9494e0f7be122
[phinde.git] / bin / subscribe.php
1 #!/usr/bin/env php
2 <?php
3 namespace phinde;
4 /**
5  * Subscribe with PubSubHubbub to an URL
6  */
7 require_once __DIR__ . '/../src/init.php';
8
9 $cc = new \Console_CommandLine();
10 $cc->description = 'Subscribe to URL updates';
11 $cc->version = '0.0.1';
12 $cc->addArgument(
13     'url',
14     array(
15         'description' => 'URL to process',
16         'multiple'    => false
17     )
18 );
19 try {
20     $res = $cc->parse();
21 } catch (\Exception $e) {
22     $cc->displayError($e->getMessage());
23 }
24
25 $url = $res->args['url'];
26 $url = Helper::addSchema($url);
27 $urlObj = new \Net_URL2($url);
28 $url = $urlObj->getNormalizedURL();
29 if (!Helper::isUrlAllowed($url)) {
30     Log::error("Domain is not allowed; not crawling");
31     exit(2);
32 }
33
34 $subDb = new Subscriptions();
35
36 list($topic, $hub) = $subDb->detectHub($url);
37 if ($hub === null) {
38     Log::error('No hub URL found for topic');
39     exit(10);
40 }
41 if ($topic != $url) {
42     Log::info('Topic URL differs from URL: ' . $topic);
43 }
44
45 $sub = $subDb->get($topic);
46 if ($sub === false) {
47     $subDb->create($topic);
48 } else {
49     Log::info(
50         'Topic exists already in subscription table with status '
51         . $sub->sub_status
52     );
53     Log::info('Renewing subscription...');
54     $subDb->renew($sub->sub_id);
55 }
56 $sub = $subDb->get($topic);
57
58 $callbackUrl = $GLOBALS['phinde']['baseurl'] . 'push-subscription.php'
59     . '?hub.topic=' . urlencode($topic)
60     . '&capkey=' . urlencode($sub->sub_capkey);
61 $req = new HttpRequest($hub, 'POST');
62 $req->addPostParameter('hub.callback', $callbackUrl);
63 $req->addPostParameter('hub.mode', 'subscribe');
64 $req->addPostParameter('hub.topic', $topic);
65 $req->addPostParameter('hub.lease_seconds', $sub->sub_lease_seconds);
66 $req->addPostParameter('hub.secret', $sub->sub_secret);
67 $res = $req->send();
68
69 if (intval($res->getStatus()) == 202) {
70     Log::info('Subscription initiated');
71     exit(0);
72 }
73
74 Log::error(
75     'Error: Subscription response status code was not 202 but '
76     . $res->getStatus()
77 );
78 Log::error($res->getBody());
79 ?>