]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/pushhub.php
Debugging log fix.
[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 if (!defined('STATUSNET')) {
27     exit(1);
28 }
29
30 /**
31  * Things to consider...
32  * should we purge incomplete subscriptions that never get a verification pingback?
33  * when can we send subscription renewal checks?
34  *    - at next send time probably ok
35  * when can we handle trimming of subscriptions?
36  *    - at next send time probably ok
37  * should we keep a fail count?
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     protected function prepare(array $args=array())
51     {
52         GNUsocial::setApi(true); // reduce exception reports to aid in debugging
53         return parent::prepare($args);
54     }
55
56     protected 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         common_debug('New PuSH hub request ('._ve($mode).') for callback '._ve($callback));
87         $topic = $this->argUrl('hub.topic');
88         if (!$this->recognizedFeed($topic)) {
89             common_debug('PuSH hub request had unrecognized feed topic=='._ve($topic));
90             // TRANS: Client exception. %s is a topic.
91             throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
92         }
93
94         $lease = $this->arg('hub.lease_seconds', null);
95         if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
96             common_debug('PuSH hub request had invalid lease_seconds=='._ve($lease));
97             // TRANS: Client exception. %s is the invalid lease value.
98             throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
99         }
100
101         $secret = $this->arg('hub.secret', null);
102         if ($secret != '' && strlen($secret) >= 200) {
103             common_debug('PuSH hub request had invalid secret=='._ve($secret));
104             // TRANS: Client exception. %s is the invalid hub secret.
105             throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
106         }
107
108         $sub = HubSub::getByHashkey($topic, $callback);
109         if (!$sub instanceof HubSub) {
110             // Creating a new one!
111             common_debug('PuSH creating new HubSub entry for topic=='._ve($topic).' to remote callback '._ve($callback));
112             $sub = new HubSub();
113             $sub->topic = $topic;
114             $sub->callback = $callback;
115         }
116         if ($mode == 'subscribe') {
117             if ($secret) {
118                 $sub->secret = $secret;
119             }
120             if ($lease) {
121                 $sub->setLease(intval($lease));
122             }
123         }
124         common_debug('PuSH hub request is now:'._ve($sub));
125
126         $verify = $this->arg('hub.verify'); // TODO: deprecated
127         $token = $this->arg('hub.verify_token', null);  // TODO: deprecated
128         if ($verify == 'sync') {    // pre-0.4 PuSH
129             $sub->verify($mode, $token);
130             header('HTTP/1.1 204 No Content');
131         } else {    // If $verify is not "sync", we might be using PuSH 0.4
132             $sub->scheduleVerify($mode, $token);    // If we were certain it's PuSH 0.4, token could be removed
133             header('HTTP/1.1 202 Accepted');
134         }
135     }
136
137     /**
138      * Check whether the given URL represents one of our canonical
139      * user or group Atom feeds.
140      *
141      * @param string $feed URL
142      * @return boolean true if it matches, false if not a recognized local feed
143      * @throws exception if local entity does not exist
144      */
145     protected function recognizedFeed($feed)
146     {
147         $matches = array();
148         // Simple mapping to local ID for user or group
149         if (preg_match('!/(\d+)\.atom$!', $feed, $matches)) {
150             $id = $matches[1];
151             $params = array('id' => $id, 'format' => 'atom');
152
153             // Double-check against locally generated URLs
154             switch ($feed) {
155             case common_local_url('ApiTimelineUser', $params):
156                 $user = User::getKV('id', $id);
157                 if (!$user instanceof User) {
158                     // TRANS: Client exception. %s is a feed URL.
159                     throw new ClientException(sprintf(_m('Invalid hub.topic "%s". User does not exist.'),$feed));
160                 }
161                 return true;
162
163             case common_local_url('ApiTimelineGroup', $params):
164                 $group = Local_group::getKV('group_id', $id);
165                 if (!$group instanceof Local_group) {
166                     // TRANS: Client exception. %s is a feed URL.
167                     throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Local_group does not exist.'),$feed));
168                 }
169                 return true;
170             }
171             common_debug("Feed was not recognized by any local User or Group Atom feed URLs: {$feed}");
172             return false;
173         }
174
175         // Profile lists are unique per user, so we need both IDs
176         if (preg_match('!/(\d+)/lists/(\d+)/statuses\.atom$!', $feed, $matches)) {
177             $user = $matches[1];
178             $id = $matches[2];
179             $params = array('user' => $user, 'id' => $id, 'format' => 'atom');
180
181             // Double-check against locally generated URLs
182             switch ($feed) {
183             case common_local_url('ApiTimelineList', $params):
184                 $list = Profile_list::getKV('id', $id);
185                 $user = User::getKV('id', $user);
186                 if (!$list instanceof Profile_list || !$user instanceof User || $list->tagger != $user->id) {
187                     // TRANS: Client exception. %s is a feed URL.
188                     throw new ClientException(sprintf(_m('Invalid hub.topic %s; list does not exist.'),$feed));
189                 }
190                 return true;
191             }
192             common_debug("Feed was not recognized by any local Profile_list Atom feed URL: {$feed}");
193             return false;
194         }
195
196         common_debug("Unknown feed URL structure, can't match against local user, group or profile_list: {$feed}");
197         return false;
198     }
199
200     /**
201      * Grab and validate a URL from POST parameters.
202      * @throws ClientException for malformed or non-http/https or blacklisted URLs
203      */
204     protected function argUrl($arg)
205     {
206         $url = $this->arg($arg);
207         $params = array('domain_check' => false, // otherwise breaks my local tests :P
208                         'allowed_schemes' => array('http', 'https'));
209         $validate = new Validate();
210         if (!$validate->uri($url, $params)) {
211             // TRANS: Client exception.
212             // TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
213             throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
214         }
215
216         Event::handle('UrlBlacklistTest', array($url));
217         return $url;
218     }
219
220     /**
221      * Get HubSub subscription record for a given feed & subscriber.
222      *
223      * @param string $feed
224      * @param string $callback
225      * @return mixed HubSub or false
226      */
227     protected function getSub($feed, $callback)
228     {
229         return HubSub::getByHashkey($feed, $callback);
230     }
231 }