]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RSSCloud/RSSCloudRequestNotify.php
Added a bunch of function commment blocks
[quix0rs-gnu-social.git] / plugins / RSSCloud / RSSCloudRequestNotify.php
1 <?php
2 /**
3  * Action to let RSSCloud aggregators request update notification when
4  * user profile feeds change.
5  *
6  * PHP version 5
7  *
8  * @category Plugin
9  * @package  StatusNet
10  * @author   Zach Copley <zach@status.net>
11  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
12  * @link     http://status.net/
13  *
14  * StatusNet - the distributed open-source microblogging tool
15  * Copyright (C) 2009, StatusNet, Inc.
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU Affero General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU Affero General Public License for more details.
26  *
27  * You should have received a copy of the GNU Affero General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Action class to handle RSSCloud notification (subscription) requests
37  *
38  * @category Plugin
39  * @package  StatusNet
40  * @author   Zach Copley <zach@status.net>
41  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
42  * @link     http://status.net/
43  **/
44
45 class RSSCloudRequestNotifyAction extends Action
46 {
47     /**
48      * Initialization.
49      *
50      * @param array $args Web and URL arguments
51      *
52      * @return boolean false if user doesn't exist
53      */
54
55     function prepare($args)
56     {
57         parent::prepare($args);
58
59         $this->ip        = $_SERVER['REMOTE_ADDR'];
60         $this->port      = $this->arg('port');
61         $this->path      = $this->arg('path');
62
63         if ($this->path[0] != '/') {
64             $this->path = '/' . $this->path;
65         }
66
67         $this->protocol  = $this->arg('protocol');
68         $this->procedure = $this->arg('notifyProcedure');
69         $this->domain    = $this->arg('domain');
70
71         $this->feeds     = $this->getFeeds();
72
73         return true;
74     }
75
76     /**
77      * Handle the request
78      *
79      * Checks for all the required parameters for a subscription,
80      * validates that the feed being subscribed to is real, and then
81      * saves the subsctiption.
82      *
83      * @param array $args $_REQUEST data (unused)
84      *
85      * @return void
86      */
87
88     function handle($args)
89     {
90         parent::handle($args);
91
92         if ($_SERVER['REQUEST_METHOD'] != 'POST') {
93             $this->showResult(false, 'Request must be POST.');
94             return;
95         }
96
97         $missing = array();
98
99         if (empty($this->port)) {
100             $missing[] = 'port';
101         }
102
103         if (empty($this->path)) {
104             $missing[] = 'path';
105         }
106
107         if (empty($this->protocol)) {
108             $missing[] = 'protocol';
109         }
110
111         if (!isset($this->procedure)) {
112             $missing[] = 'notifyProcedure';
113         }
114
115         if (!empty($missing)) {
116             $msg = 'The following parameters were missing from the request body: ' .
117                 implode(', ', $missing) . '.';
118             $this->showResult(false, $msg);
119             return;
120         }
121
122         if (empty($this->feeds)) {
123             $this->showResult(false,
124                               'You must provide at least one valid profile feed url (url1, url2, url3 ... urlN).');
125             return;
126         }
127
128         // We have to validate everything before saving anything.
129         // We only return one success or failure no matter how
130         // many feeds the subscriber is trying to subscribe to
131
132         foreach ($this->feeds as $feed) {
133
134             if (!$this->validateFeed($feed)) {
135                 $msg = 'Feed subscription failed - Not a valid feed.';
136                 $this->showResult(false, $msg);
137                 return;
138             }
139
140             if (!$this->testNotificationHandler($feed)) {
141                 $msg = 'Feed subscription failed - ' .
142                 'notification handler doesn\'t respond correctly.';
143                 $this->showResult(false, $msg);
144                 return;
145             }
146
147         }
148
149         foreach ($this->feeds as $feed) {
150             $this->saveSubscription($feed);
151         }
152
153         // XXX: What to do about deleting stale subscriptions?
154         // 25 hours seems harsh. WordPress doesn't ever remove
155         // subscriptions.
156
157         $msg = 'Thanks for the subscription. ' .
158           'When the feed(s) update(s) we\'ll notify you.';
159
160         $this->showResult(true, $msg);
161     }
162
163     /**
164      * Validate that the requested feed is one we serve
165      * up via RSSCloud.
166      *
167      * @param string $feed the feed in question
168      *
169      * @return void
170      */
171
172     function validateFeed($feed)
173     {
174         $user = $this->userFromFeed($feed);
175
176         if (empty($user)) {
177             return false;
178         }
179
180         return true;
181     }
182
183     /**
184      * Pull all of the urls (url1, url2, url3...urlN) that
185      * the subscriber wants to subscribe to.
186      *
187      * @return array $feeds the list of feeds
188      */
189
190     function getFeeds()
191     {
192         $feeds = array();
193
194         while (list($key, $feed) = each ($this->args)) {
195             if (preg_match('/^url\d*$/', $key)) {
196                 $feeds[] = $feed;
197             }
198         }
199
200         return $feeds;
201     }
202
203     /**
204      * Test that a notification handler is there and is reponding
205      * correctly.  This is called before adding a subscription.
206      *
207      * @param string $feed the feed to verify
208      *
209      * @return boolean success result
210      */
211
212     function testNotificationHandler($feed)
213     {
214         common_debug("RSSCloudPlugin - testNotificationHandler()");
215
216         $notifyUrl = $this->getNotifyUrl();
217
218         $notifier = new RSSCloudNotifier();
219
220         if (isset($this->domain)) {
221
222             // 'domain' param set, so we have to use GET and send a challenge
223
224             common_log(LOG_INFO, 'Testing notification handler with challenge: ' .
225                        $notifyUrl);
226             return $notifier->challenge($notifyUrl, $feed);
227
228         } else {
229             common_log(LOG_INFO, 'Testing notification handler: ' .
230                        $notifyUrl);
231
232             return $notifier->postUpdate($notifyUrl, $feed);
233         }
234     }
235
236     /**
237      * Build the URL for the notification handler based on the
238      * parameters passed in with the subscription request.
239      *
240      * @return string notification handler url
241      */
242
243     function getNotifyUrl()
244     {
245         if (isset($this->domain)) {
246             return 'http://' . $this->domain . ':' . $this->port . $this->path;
247         } else {
248             return 'http://' . $this->ip . ':' . $this->port . $this->path;
249         }
250      }
251
252     /**
253      * Uses the nickname part of the subscribed feed URL to figure out
254      * whethere there's really a user with such a feed.  Used to
255      * validate feeds before adding a subscription.
256      *
257      * @param string $feed the feed in question
258      *
259      * @return boolean success
260      */
261
262     function userFromFeed($feed)
263     {
264         // We only do profile feeds
265
266         $path = common_path('api/statuses/user_timeline/');
267         $valid = '%^' . $path . '(?<nickname>.*)\.rss$%';
268
269         if (preg_match($valid, $feed, $matches)) {
270             $user = User::staticGet('nickname', $matches['nickname']);
271             if (!empty($user)) {
272                 return $user;
273             }
274         }
275
276         return false;
277     }
278
279     /**
280      * Save an RSSCloud subscription
281      *
282      * @param $feed a valid profile feed
283      *
284      * @return boolean success result
285      */
286
287     function saveSubscription($feed)
288     {
289         $user = $this->userFromFeed($feed);
290
291         $notifyUrl = $this->getNotifyUrl();
292
293         $sub = RSSCloudSubscription::getSubscription($user->id, $notifyUrl);
294
295         if ($sub) {
296             common_debug("Already subscribed to that!");
297         } else {
298
299             $sub = new RSSCloudSubscription();
300
301             $sub->subscribed = $user->id;
302             $sub->url        = $notifyUrl;
303             $sub->created    = common_sql_now();
304
305             if (!$sub->insert()) {
306                 common_log_db_error($sub, 'INSERT', __FILE__);
307                 return false;
308             }
309
310         }
311
312         return true;
313     }
314
315     /**
316      * Show an XML message indicating the subscription
317      * was successful or failed.
318      *
319      * @param boolean $success whether it was good or bad
320      * @param string  $msg     the message to output
321      *
322      * @return boolean success result
323      */
324
325     function showResult($success, $msg)
326     {
327         $this->startXML();
328         $this->elementStart('notifyResult', array('success' => ($success) ? 'true' : 'false',
329                                                   'msg'     => $msg));
330         $this->endXML();
331     }
332
333 }
334