]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RSSCloud/RSSCloudRequestNotify.php
Some phpcs cleanup
[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         } else if (strtolower($this->protocol) != 'http-post') {
110             $msg = 'Only http-post notifications are supported at this time.';
111             $this->showResult(false, $msg);
112             return;
113         }
114
115         if (!isset($this->procedure)) {
116             $missing[] = 'notifyProcedure';
117         }
118
119         if (!empty($missing)) {
120             $msg = 'The following parameters were missing from the request body: ' .
121                 implode(', ', $missing) . '.';
122             $this->showResult(false, $msg);
123             return;
124         }
125
126         if (empty($this->feeds)) {
127             $msg = 'You must provide at least one valid profile feed url ' .
128               '(url1, url2, url3 ... urlN).';
129             $this->showResult(false, $msg);
130             return;
131         }
132
133         // We have to validate everything before saving anything.
134         // We only return one success or failure no matter how
135         // many feeds the subscriber is trying to subscribe to
136
137         foreach ($this->feeds as $feed) {
138
139             if (!$this->validateFeed($feed)) {
140                 $msg = 'Feed subscription failed - Not a valid feed.';
141                 $this->showResult(false, $msg);
142                 return;
143             }
144
145             if (!$this->testNotificationHandler($feed)) {
146                 $msg = 'Feed subscription failed - ' .
147                 'notification handler doesn\'t respond correctly.';
148                 $this->showResult(false, $msg);
149                 return;
150             }
151
152         }
153
154         foreach ($this->feeds as $feed) {
155             $this->saveSubscription($feed);
156         }
157
158         // XXX: What to do about deleting stale subscriptions?
159         // 25 hours seems harsh. WordPress doesn't ever remove
160         // subscriptions.
161
162         $msg = 'Thanks for the subscription. ' .
163           'When the feed(s) update(s) we\'ll notify you.';
164
165         $this->showResult(true, $msg);
166     }
167
168     /**
169      * Validate that the requested feed is one we serve
170      * up via RSSCloud.
171      *
172      * @param string $feed the feed in question
173      *
174      * @return void
175      */
176
177     function validateFeed($feed)
178     {
179         $user = $this->userFromFeed($feed);
180
181         if (empty($user)) {
182             return false;
183         }
184
185         return true;
186     }
187
188     /**
189      * Pull all of the urls (url1, url2, url3...urlN) that
190      * the subscriber wants to subscribe to.
191      *
192      * @return array $feeds the list of feeds
193      */
194
195     function getFeeds()
196     {
197         $feeds = array();
198
199         while (list($key, $feed) = each($this->args)) {
200             if (preg_match('/^url\d*$/', $key)) {
201                 $feeds[] = $feed;
202             }
203         }
204
205         return $feeds;
206     }
207
208     /**
209      * Test that a notification handler is there and is reponding
210      * correctly.  This is called before adding a subscription.
211      *
212      * @param string $feed the feed to verify
213      *
214      * @return boolean success result
215      */
216
217     function testNotificationHandler($feed)
218     {
219         common_debug("RSSCloudPlugin - testNotificationHandler()");
220
221         $notifyUrl = $this->getNotifyUrl();
222
223         $notifier = new RSSCloudNotifier();
224
225         if (isset($this->domain)) {
226
227             // 'domain' param set, so we have to use GET and send a challenge
228
229             common_log(LOG_INFO, 'Testing notification handler with challenge: ' .
230                        $notifyUrl);
231             return $notifier->challenge($notifyUrl, $feed);
232
233         } else {
234             common_log(LOG_INFO, 'Testing notification handler: ' .
235                        $notifyUrl);
236
237             return $notifier->postUpdate($notifyUrl, $feed);
238         }
239     }
240
241     /**
242      * Build the URL for the notification handler based on the
243      * parameters passed in with the subscription request.
244      *
245      * @return string notification handler url
246      */
247
248     function getNotifyUrl()
249     {
250         if (isset($this->domain)) {
251             return 'http://' . $this->domain . ':' . $this->port . $this->path;
252         } else {
253             return 'http://' . $this->ip . ':' . $this->port . $this->path;
254         }
255     }
256
257     /**
258      * Uses the nickname part of the subscribed feed URL to figure out
259      * whethere there's really a user with such a feed.  Used to
260      * validate feeds before adding a subscription.
261      *
262      * @param string $feed the feed in question
263      *
264      * @return boolean success
265      */
266
267     function userFromFeed($feed)
268     {
269         // We only do profile feeds
270
271         $path  = common_path('api/statuses/user_timeline/');
272         $valid = '%^' . $path . '(?<nickname>.*)\.rss$%';
273
274         if (preg_match($valid, $feed, $matches)) {
275             $user = User::staticGet('nickname', $matches['nickname']);
276             if (!empty($user)) {
277                 return $user;
278             }
279         }
280
281         return false;
282     }
283
284     /**
285      * Save an RSSCloud subscription
286      *
287      * @param string $feed a valid profile feed
288      *
289      * @return boolean success result
290      */
291
292     function saveSubscription($feed)
293     {
294         $user = $this->userFromFeed($feed);
295
296         $notifyUrl = $this->getNotifyUrl();
297
298         $sub = RSSCloudSubscription::getSubscription($user->id, $notifyUrl);
299
300         if ($sub) {
301             common_debug("Already subscribed to that!");
302         } else {
303
304             $sub = new RSSCloudSubscription();
305
306             $sub->subscribed = $user->id;
307             $sub->url        = $notifyUrl;
308             $sub->created    = common_sql_now();
309
310             if (!$sub->insert()) {
311                 common_log_db_error($sub, 'INSERT', __FILE__);
312                 return false;
313             }
314
315         }
316
317         return true;
318     }
319
320     /**
321      * Show an XML message indicating the subscription
322      * was successful or failed.
323      *
324      * @param boolean $success whether it was good or bad
325      * @param string  $msg     the message to output
326      *
327      * @return boolean success result
328      */
329
330     function showResult($success, $msg)
331     {
332         $this->startXML();
333         $this->elementStart('notifyResult',
334                             array('success' => ($success) ? 'true' : 'false',
335                                   'msg'     => $msg));
336         $this->endXML();
337     }
338
339 }
340