]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/pushhub.php
68035ab5cc20aaad6e6a760e0aeb6154e18e8a2c
[quix0rs-gnu-social.git] / plugins / OStatus / actions / pushhub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * Integrated PuSH hub; lets us only ping them what need it.
22  * @package Hub
23  * @maintainer Brion Vibber <brion@status.net>
24  */
25
26 /**
27
28
29 Things to consider...
30 * should we purge incomplete subscriptions that never get a verification pingback?
31 * when can we send subscription renewal checks?
32     - at next send time probably ok
33 * when can we handle trimming of subscriptions?
34     - at next send time probably ok
35 * should we keep a fail count?
36
37 */
38
39 class PushHubAction extends Action
40 {
41     function arg($arg, $def=null)
42     {
43         // PHP converts '.'s in incoming var names to '_'s.
44         // It also merges multiple values, which'll break hub.verify and hub.topic for publishing
45         // @fixme handle multiple args
46         $arg = str_replace('hub.', 'hub_', $arg);
47         return parent::arg($arg, $def);
48     }
49
50     function prepare($args)
51     {
52         StatusNet::setApi(true); // reduce exception reports to aid in debugging
53         return parent::prepare($args);
54     }
55
56     function handle()
57     {
58         $mode = $this->trimmed('hub.mode');
59         switch ($mode) {
60         case "subscribe":
61         case "unsubscribe":
62             $this->subunsub($mode);
63             break;
64         case "publish":
65             // TRANS: Client exception.
66             throw new ClientException(_m('Publishing outside feeds not supported.'), 400);
67         default:
68             // TRANS: Client exception. %s is a mode.
69             throw new ClientException(sprintf(_m('Unrecognized mode "%s".'),$mode), 400);
70         }
71     }
72
73     /**
74      * Process a request for a new or modified PuSH feed subscription.
75      * If asynchronous verification is requested, updates won't be saved immediately.
76      *
77      * HTTP return codes:
78      *   202 Accepted - request saved and awaiting verification
79      *   204 No Content - already subscribed
80      *   400 Bad Request - rejecting this (not specifically spec'd)
81      */
82     function subunsub($mode)
83     {
84         $callback = $this->argUrl('hub.callback');
85
86         $topic = $this->argUrl('hub.topic');
87         if (!$this->recognizedFeed($topic)) {
88             // TRANS: Client exception. %s is a topic.
89             throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
90         }
91
92         $verify = $this->arg('hub.verify'); // @fixme may be multiple
93         if ($verify != 'sync' && $verify != 'async') {
94             // TRANS: Client exception.
95             throw new ClientException(sprintf(_m('Invalid hub.verify "%s". It must be sync or async.'),$verify));
96         }
97
98         $lease = $this->arg('hub.lease_seconds', null);
99         if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
100             // TRANS: Client exception.
101             throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
102         }
103
104         $token = $this->arg('hub.verify_token', null);
105
106         $secret = $this->arg('hub.secret', null);
107         if ($secret != '' && strlen($secret) >= 200) {
108             // TRANS: Client exception.
109             throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
110         }
111
112         $sub = HubSub::staticGet($topic, $callback);
113         if (!$sub) {
114             // Creating a new one!
115             $sub = new HubSub();
116             $sub->topic = $topic;
117             $sub->callback = $callback;
118         }
119         if ($mode == 'subscribe') {
120             if ($secret) {
121                 $sub->secret = $secret;
122             }
123             if ($lease) {
124                 $sub->setLease(intval($lease));
125             }
126         }
127
128         if (!common_config('queue', 'enabled')) {
129             // Won't be able to background it.
130             $verify = 'sync';
131         }
132         if ($verify == 'async') {
133             $sub->scheduleVerify($mode, $token);
134             header('HTTP/1.1 202 Accepted');
135         } else {
136             $sub->verify($mode, $token);
137             header('HTTP/1.1 204 No Content');
138         }
139     }
140
141     /**
142      * Check whether the given URL represents one of our canonical
143      * user or group Atom feeds.
144      *
145      * @param string $feed URL
146      * @return boolean true if it matches
147      */
148     function recognizedFeed($feed)
149     {
150         $matches = array();
151         if (preg_match('!/(\d+)\.atom$!', $feed, $matches)) {
152             $id = $matches[1];
153             $params = array('id' => $id, 'format' => 'atom');
154             $userFeed = common_local_url('ApiTimelineUser', $params);
155             $groupFeed = common_local_url('ApiTimelineGroup', $params);
156
157             if ($feed == $userFeed) {
158                 $user = User::staticGet('id', $id);
159                 if (!$user) {
160                     // TRANS: Client exception.
161                     throw new ClientException(sprintt(_m('Invalid hub.topic "%s". User doesn\'t exist.'),$feed));
162                 } else {
163                     return true;
164                 }
165             }
166             if ($feed == $groupFeed) {
167                 $user = User_group::staticGet('id', $id);
168                 if (!$user) {
169                     // TRANS: Client exception.
170                     throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Group doesn\'t exist.'),$feed));
171                 } else {
172                     return true;
173                 }
174             }
175             common_log(LOG_DEBUG, "Not a user or group feed? $feed $userFeed $groupFeed");
176         }
177         common_log(LOG_DEBUG, "LOST $feed");
178         return false;
179     }
180
181     /**
182      * Grab and validate a URL from POST parameters.
183      * @throws ClientException for malformed or non-http/https URLs
184      */
185     protected function argUrl($arg)
186     {
187         $url = $this->arg($arg);
188         $params = array('domain_check' => false, // otherwise breaks my local tests :P
189                         'allowed_schemes' => array('http', 'https'));
190         if (Validate::uri($url, $params)) {
191             return $url;
192         } else {
193             // TRANS: Client exception.
194             // TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
195             throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
196         }
197     }
198
199     /**
200      * Get HubSub subscription record for a given feed & subscriber.
201      *
202      * @param string $feed
203      * @param string $callback
204      * @return mixed HubSub or false
205      */
206     protected function getSub($feed, $callback)
207     {
208         return HubSub::staticGet($feed, $callback);
209     }
210 }