Support multiple hub links for WebSub
[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 $subDb = new Subscriptions();
26
27 $url = $res->args['url'];
28 $url = Helper::addSchema($url);
29 $urlObj = new \Net_URL2($url);
30 $url = $urlObj->getNormalizedURL();
31 if (!Helper::isUrlAllowed($url)) {
32     Log::error("Domain is not allowed; not subscribing");
33     $subDb->remove($url);
34     exit(2);
35 }
36
37 list($topic, $hub) = $subDb->detectHub($url);
38 if ($hub === null) {
39     Log::error('No hub URL found for topic');
40     exit(10);
41 }
42 if ($topic != $url) {
43     Log::info('Topic URL differs from URL: ' . $topic);
44 }
45
46 $sub = $subDb->get($topic);
47 if ($sub === false) {
48     $subDb->create($topic, $hub);
49 } else {
50     Log::info(
51         'Topic exists already in subscription table with status '
52         . $sub->sub_status
53     );
54     Log::info('Renewing subscription...');
55     $subDb->renew($sub->sub_id);
56     $hub = $sub->sub_hub;
57 }
58 $sub = $subDb->get($topic);
59
60 $callbackUrl = $GLOBALS['phinde']['baseurl'] . 'push-subscription.php'
61     . '?hub.topic=' . urlencode($topic)
62     . '&capkey=' . urlencode($sub->sub_capkey);
63 $req = new HttpRequest($hub, 'POST');
64 $req->addPostParameter('hub.callback', $callbackUrl);
65 $req->addPostParameter('hub.mode', 'subscribe');
66 $req->addPostParameter('hub.topic', $topic);
67 $req->addPostParameter('hub.lease_seconds', $sub->sub_lease_seconds);
68 $req->addPostParameter('hub.secret', $sub->sub_secret);
69 $res = $req->send();
70
71 if (intval($res->getStatus()) == 202) {
72     Log::info('Subscription initiated');
73     exit(0);
74 }
75
76 Log::error(
77     'Error: Subscription response status code was not 202 but '
78     . $res->getStatus()
79 );
80 Log::error($res->getBody());
81 ?>