]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
OStatus sub/unsub updates:
[quix0rs-gnu-social.git] / plugins / OStatus / OStatusPlugin.php
1 <?php
2 /*
3 StatusNet Plugin: 0.9
4 Plugin Name: FeedSub
5 Plugin URI: http://status.net/wiki/Feed_subscription
6 Description: FeedSub allows subscribing to real-time updates from external feeds supporting PubHubSubbub protocol.
7 Version: 0.1
8 Author: Brion Vibber <brion@status.net>
9 Author URI: http://status.net/
10 */
11
12 /*
13  * StatusNet - the distributed open-source microblogging tool
14  * Copyright (C) 2009, StatusNet, Inc.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU Affero General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU Affero General Public License for more details.
25  *
26  * You should have received a copy of the GNU Affero General Public License
27  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28  */
29
30 /**
31  * @package FeedSubPlugin
32  * @maintainer Brion Vibber <brion@status.net>
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
36
37 define('FEEDSUB_SERVICE', 100); // fixme -- avoid hardcoding these?
38
39 // We bundle the XML_Parse_Feed library...
40 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib');
41
42 class FeedSubException extends Exception
43 {
44 }
45
46 class OStatusPlugin extends Plugin
47 {
48     /**
49      * Hook for RouterInitialized event.
50      *
51      * @param Net_URL_Mapper $m path-to-action mapper
52      * @return boolean hook return
53      */
54     function onRouterInitialized($m)
55     {
56         // Discovery actions
57         $m->connect('.well-known/host-meta',
58                     array('action' => 'hostmeta'));
59         $m->connect('main/webfinger',
60                     array('action' => 'webfinger'));
61         $m->connect('main/ostatus',
62                     array('action' => 'ostatusinit'));
63         $m->connect('main/ostatus?nickname=:nickname',
64                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
65         $m->connect('main/ostatussub',
66                     array('action' => 'ostatussub'));
67         $m->connect('main/ostatussub',
68                     array('action' => 'ostatussub'), array('feed' => '[A-Za-z0-9\.\/\:]+'));
69
70         // PuSH actions
71         $m->connect('main/push/hub', array('action' => 'pushhub'));
72
73         $m->connect('main/push/callback/:feed',
74                     array('action' => 'pushcallback'),
75                     array('feed' => '[0-9]+'));
76         $m->connect('settings/feedsub',
77                     array('action' => 'feedsubsettings'));
78
79         // Salmon endpoint
80         $m->connect('main/salmon/user/:id',
81                     array('action' => 'salmon'),
82                     array('id' => '[0-9]+'));
83         $m->connect('main/salmon/group/:id',
84                     array('action' => 'salmongroup'),
85                     array('id' => '[0-9]+'));
86         return true;
87     }
88
89     /**
90      * Set up queue handlers for outgoing hub pushes
91      * @param QueueManager $qm
92      * @return boolean hook return
93      */
94     function onEndInitializeQueueManager(QueueManager $qm)
95     {
96         $qm->connect('hubverify', 'HubVerifyQueueHandler');
97         $qm->connect('hubdistrib', 'HubDistribQueueHandler');
98         $qm->connect('hubout', 'HubOutQueueHandler');
99         return true;
100     }
101
102     /**
103      * Put saved notices into the queue for pubsub distribution.
104      */
105     function onStartEnqueueNotice($notice, &$transports)
106     {
107         $transports[] = 'hubdistrib';
108         return true;
109     }
110
111     /**
112      * Set up a PuSH hub link to our internal link for canonical timeline
113      * Atom feeds for users and groups.
114      */
115     function onStartApiAtom($feed)
116     {
117         $id = null;
118
119         if ($feed instanceof AtomUserNoticeFeed) {
120             $salmonAction = 'salmon';
121             $id = $feed->getUser()->id;
122         } else if ($feed instanceof AtomGroupNoticeFeed) {
123             $salmonAction = 'salmongroup';
124             $id = $feed->getGroup()->id;
125         } else {
126             return;
127         }
128
129        if (!empty($id)) {
130             $hub = common_config('ostatus', 'hub');
131             if (empty($hub)) {
132                 // Updates will be handled through our internal PuSH hub.
133                 $hub = common_local_url('pushhub');
134             }
135             $feed->addLink($hub, array('rel' => 'hub'));
136
137             // Also, we'll add in the salmon link
138             $salmon = common_local_url($salmonAction, array('id' => $id));
139             $feed->addLink($salmon, array('rel' => 'salmon'));
140         }
141     }
142
143     /**
144      * Add the feed settings page to the Connect Settings menu
145      *
146      * @param Action &$action The calling page
147      *
148      * @return boolean hook return
149      */
150     function onEndConnectSettingsNav(&$action)
151     {
152         $action_name = $action->trimmed('action');
153
154         $action->menuItem(common_local_url('feedsubsettings'),
155                           _m('Feeds'),
156                           _m('Feed subscription options'),
157                           $action_name === 'feedsubsettings');
158
159         return true;
160     }
161
162     /**
163      * Automatically load the actions and libraries used by the plugin
164      *
165      * @param Class $cls the class
166      *
167      * @return boolean hook return
168      *
169      */
170     function onAutoload($cls)
171     {
172         $base = dirname(__FILE__);
173         $lower = strtolower($cls);
174         $map = array('activityverb' => 'activity',
175                      'activityobject' => 'activity',
176                      'activityutils' => 'activity');
177         if (isset($map[$lower])) {
178             $lower = $map[$lower];
179         }
180         $files = array("$base/classes/$cls.php",
181                        "$base/lib/$lower.php");
182         if (substr($lower, -6) == 'action') {
183             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
184         }
185         foreach ($files as $file) {
186             if (file_exists($file)) {
187                 include_once $file;
188                 return false;
189             }
190         }
191         return true;
192     }
193
194     /**
195      * Add in an OStatus subscribe button
196      */
197     function onStartProfileRemoteSubscribe($output, $profile)
198     {
199         $cur = common_current_user();
200
201         if (empty($cur)) {
202             // Add an OStatus subscribe
203             $output->elementStart('li', 'entity_subscribe');
204             $url = common_local_url('ostatusinit',
205                                     array('nickname' => $profile->nickname));
206             $output->element('a', array('href' => $url,
207                                         'class' => 'entity_remote_subscribe'),
208                                 _m('Subscribe'));
209
210             $output->elementEnd('li');
211         }
212
213         return false;
214     }
215
216     /**
217      * Check if we've got remote replies to send via Salmon.
218      *
219      * @fixme push webfinger lookup & sending to a background queue
220      * @fixme also detect short-form name for remote subscribees where not ambiguous
221      */
222     function onEndNoticeSave($notice)
223     {
224         $count = preg_match_all('/(\w+\.)*\w+@(\w+\.)*\w+(\w+\-\w+)*\.\w+/', $notice->content, $matches);
225         if ($count) {
226             foreach ($matches[0] as $webfinger) {
227
228                 // FIXME: look up locally first
229
230                 // Check to see if we've got an actual webfinger
231                 $w = new Webfinger;
232
233                 $endpoint_uri = '';
234
235                 $result = $w->lookup($webfinger);
236                 if (empty($result)) {
237                     continue;
238                 }
239
240                 foreach ($result->links as $link) {
241                     if ($link['rel'] == 'salmon') {
242                         $endpoint_uri = $link['href'];
243                     }
244                 }
245
246                 if (empty($endpoint_uri)) {
247                     continue;
248                 }
249
250                 // FIXME: this needs to go out in a queue handler
251
252                 $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
253                 $xml .= $notice->asAtomEntry();
254
255                 $salmon = new Salmon();
256                 $salmon->post($endpoint_uri, $xml);
257             }
258         }
259     }
260
261     /**
262      * Notify remote server when one of our users subscribes.
263      * @fixme Check and restart the PuSH subscription if needed
264      *
265      * @param User $user
266      * @param Profile $other
267      * @return hook return value
268      */
269     function onEndSubscribe($user, $other)
270     {
271         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
272         if ($oprofile) {
273             // Notify the remote server of the unsub, if supported.
274             $oprofile->notify($user->getProfile(), ActivityVerb::FOLLOW, $oprofile);
275         }
276         return true;
277     }
278
279     /**
280      * Notify remote server and garbage collect unused feeds on unsubscribe.
281      * @fixme send these operations to background queues
282      *
283      * @param User $user
284      * @param Profile $other
285      * @return hook return value
286      */
287     function onEndUnsubscribe($user, $other)
288     {
289         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
290         if ($oprofile) {
291             // Notify the remote server of the unsub, if supported.
292             $oprofile->notify($user->getProfile(), ActivityVerb::UNFOLLOW, $oprofile);
293
294             // Drop the PuSH subscription if there are no other subscribers.
295             $sub = new Subscription();
296             $sub->subscribed = $other->id;
297             $sub->limit(1);
298             if (!$sub->find(true)) {
299                 common_log(LOG_INFO, "Unsubscribing from now-unused feed $oprofile->feeduri on hub $oprofile->huburi");
300                 $oprofile->unsubscribe();
301             }
302         }
303         return true;
304     }
305
306     /**
307      * Make sure necessary tables are filled out.
308      */
309     function onCheckSchema() {
310         $schema = Schema::get();
311         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
312         $schema->ensureTable('hubsub', HubSub::schemaDef());
313         return true;
314     }
315
316     function onEndShowStatusNetStyles($action) {
317         $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
318         return true;
319     }
320
321     function onEndShowStatusNetScripts($action) {
322         $action->script(common_path('plugins/OStatus/js/ostatus.js'));
323         return true;
324     }
325
326     /**
327      * Override the "from ostatus" bit in notice lists to link to the
328      * original post and show the domain it came from.
329      *
330      * @param Notice in $notice
331      * @param string out &$name
332      * @param string out &$url
333      * @param string out &$title
334      * @return mixed hook return code
335      */
336     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
337     {
338         if ($notice->source == 'ostatus') {
339             $bits = parse_url($notice->uri);
340             $domain = $bits['host'];
341
342             $name = $domain;
343             $url = $notice->uri;
344             $title = sprintf(_m("Sent from %s via OStatus"), $domain);
345             return false;
346         }
347     }
348 }