Add cli tool to unsubscribe from a topic
[phinde.git] / bin / unsubscribe.php
1 #!/usr/bin/env php
2 <?php
3 namespace phinde;
4 /**
5  * Unsubscribe from a WebSub subscription
6  */
7 require_once __DIR__ . '/../src/init.php';
8
9 $cc = new \Console_CommandLine();
10 $cc->description = 'Unsubscribe from a WebSub subscription';
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 $topic = $urlObj->getNormalizedURL();
31
32
33 $sub = $subDb->get($topic);
34 if ($sub === false) {
35     Log::error("No existing subscription for URL");
36     exit(2);
37 }
38 if ($sub->sub_status === 'unsubscribed') {
39     Log::info('Already unsubscribed');
40     exit(0);
41 }
42
43 $subDb->unsubscribing($sub->sub_id);
44
45 $callbackUrl = $GLOBALS['phinde']['baseurl'] . 'push-subscription.php'
46     . '?hub.topic=' . urlencode($topic)
47     . '&capkey=' . urlencode($sub->sub_capkey);
48 $req = new HttpRequest($sub->sub_hub, 'POST');
49 $req->addPostParameter('hub.callback', $callbackUrl);
50 $req->addPostParameter('hub.mode', 'unsubscribe');
51 $req->addPostParameter('hub.topic', $topic);
52 $req->addPostParameter('hub.lease_seconds', $sub->sub_lease_seconds);
53 $req->addPostParameter('hub.secret', $sub->sub_secret);
54 $res = $req->send();
55
56 if (intval($res->getStatus()) == 202) {
57     Log::info('Unsubscription initiated');
58     exit(0);
59 }
60
61 Log::error(
62     'Error: Unsubscription response status code was not 202 but '
63     . $res->getStatus()
64 );
65 Log::error($res->getBody());
66 ?>