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