]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[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 = 'usersalmon';
106             $user = $feed->getUser();
107             $id   = $user->id;
108             $profile = $user->getProfile();
109             $feed->setActivitySubject($profile->asActivityNoun('subject'));
110         } else if ($feed instanceof AtomGroupNoticeFeed) {
111             $salmonAction = 'groupsalmon';
112             $group = $feed->getGroup();
113             $id = $group->id;
114             $feed->setActivitySubject($group->asActivitySubject());
115         } else {
116             return true;
117         }
118
119         if (!empty($id)) {
120             $hub = common_config('ostatus', 'hub');
121             if (empty($hub)) {
122                 // Updates will be handled through our internal PuSH hub.
123                 $hub = common_local_url('pushhub');
124             }
125             $feed->addLink($hub, array('rel' => 'hub'));
126
127             // Also, we'll add in the salmon link
128             $salmon = common_local_url($salmonAction, array('id' => $id));
129             $feed->addLink($salmon, array('rel' => 'salmon'));
130         }
131
132         return true;
133     }
134
135     /**
136      * Add the feed settings page to the Connect Settings menu
137      *
138      * @param Action &$action The calling page
139      *
140      * @return boolean hook return
141      */
142     function onEndConnectSettingsNav(&$action)
143     {
144         $action_name = $action->trimmed('action');
145
146         $action->menuItem(common_local_url('feedsubsettings'),
147                           _m('Feeds'),
148                           _m('Feed subscription options'),
149                           $action_name === 'feedsubsettings');
150
151         return true;
152     }
153
154     /**
155      * Automatically load the actions and libraries used by the plugin
156      *
157      * @param Class $cls the class
158      *
159      * @return boolean hook return
160      *
161      */
162     function onAutoload($cls)
163     {
164         $base = dirname(__FILE__);
165         $lower = strtolower($cls);
166         $map = array('activityverb' => 'activity',
167                      'activityobject' => 'activity',
168                      'activityutils' => 'activity');
169         if (isset($map[$lower])) {
170             $lower = $map[$lower];
171         }
172         $files = array("$base/classes/$cls.php",
173                        "$base/lib/$lower.php");
174         if (substr($lower, -6) == 'action') {
175             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
176         }
177         foreach ($files as $file) {
178             if (file_exists($file)) {
179                 include_once $file;
180                 return false;
181             }
182         }
183         return true;
184     }
185
186     /**
187      * Add in an OStatus subscribe button
188      */
189     function onStartProfileRemoteSubscribe($output, $profile)
190     {
191         $cur = common_current_user();
192
193         if (empty($cur)) {
194             // Add an OStatus subscribe
195             $output->elementStart('li', 'entity_subscribe');
196             $url = common_local_url('ostatusinit',
197                                     array('nickname' => $profile->nickname));
198             $output->element('a', array('href' => $url,
199                                         'class' => 'entity_remote_subscribe'),
200                                 _m('Subscribe'));
201
202             $output->elementEnd('li');
203         }
204
205         return false;
206     }
207
208     /**
209      * Check if we've got remote replies to send via Salmon.
210      *
211      * @fixme push webfinger lookup & sending to a background queue
212      * @fixme also detect short-form name for remote subscribees where not ambiguous
213      */
214     function onEndNoticeSave($notice)
215     {
216         $count = preg_match_all('/(\w+\.)*\w+@(\w+\.)*\w+(\w+\-\w+)*\.\w+/', $notice->content, $matches);
217         if ($count) {
218             foreach ($matches[0] as $webfinger) {
219
220                 // FIXME: look up locally first
221
222                 // Check to see if we've got an actual webfinger
223                 $w = new Webfinger;
224
225                 $endpoint_uri = '';
226
227                 $result = $w->lookup($webfinger);
228                 if (empty($result)) {
229                     continue;
230                 }
231
232                 foreach ($result->links as $link) {
233                     if ($link['rel'] == 'salmon') {
234                         $endpoint_uri = $link['href'];
235                     }
236                 }
237
238                 if (empty($endpoint_uri)) {
239                     continue;
240                 }
241
242                 // FIXME: this needs to go out in a queue handler
243
244                 $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
245                 $xml .= $notice->asAtomEntry();
246
247                 $salmon = new Salmon();
248                 $salmon->post($endpoint_uri, $xml);
249             }
250         }
251     }
252
253     /**
254      * Notify remote server and garbage collect unused feeds on unsubscribe.
255      * @fixme send these operations to background queues
256      *
257      * @param User $user
258      * @param Profile $other
259      * @return hook return value
260      */
261     function onEndUnsubscribe($profile, $other)
262     {
263         $user = User::staticGet('id', $profile->id);
264
265         if (empty($user)) {
266             return true;
267         }
268
269         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
270
271         if (empty($oprofile)) {
272             return true;
273         }
274
275         // Drop the PuSH subscription if there are no other subscribers.
276
277         if ($other->subscriberCount() == 0) {
278             common_log(LOG_INFO, "Unsubscribing from now-unused feed $oprofile->feeduri");
279             $oprofile->unsubscribe();
280         }
281
282         $act = new Activity();
283
284         $act->verb = ActivityVerb::UNFOLLOW;
285
286         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
287                                   $profile->id,
288                                   $other->id,
289                                   common_date_iso8601(time()));
290
291         $act->time    = time();
292         $act->title   = _("Unfollow");
293         $act->content = sprintf(_("%s stopped following %s."),
294                                $profile->getBestName(),
295                                $other->getBestName());
296
297         $act->actor   = ActivityObject::fromProfile($profile);
298         $act->object  = ActivityObject::fromProfile($other);
299
300         $oprofile->notifyActivity($act);
301
302         return true;
303     }
304
305     /**
306      * Make sure necessary tables are filled out.
307      */
308     function onCheckSchema() {
309         $schema = Schema::get();
310         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
311         $schema->ensureTable('feedsub', FeedSub::schemaDef());
312         $schema->ensureTable('hubsub', HubSub::schemaDef());
313         return true;
314     }
315
316     function onEndShowStatusNetStyles($action) {
317         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
318         return true;
319     }
320
321     function onEndShowStatusNetScripts($action) {
322         $action->script('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
349     /**
350      * Send incoming PuSH feeds for OStatus endpoints in for processing.
351      *
352      * @param FeedSub $feedsub
353      * @param DOMDocument $feed
354      * @return mixed hook return code
355      */
356     function onStartFeedSubReceive($feedsub, $feed)
357     {
358         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
359         if ($oprofile) {
360             $oprofile->processFeed($feed);
361         } else {
362             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
363         }
364     }
365
366     function onEndSubscribe($subscriber, $other)
367     {
368         $user = User::staticGet('id', $subscriber->id);
369
370         if (empty($user)) {
371             return true;
372         }
373
374         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
375
376         if (empty($oprofile)) {
377             return true;
378         }
379
380         $act = new Activity();
381
382         $act->verb = ActivityVerb::FOLLOW;
383
384         $act->id   = TagURI::mint('follow:%d:%d:%s',
385                                   $subscriber->id,
386                                   $other->id,
387                                   common_date_iso8601(time()));
388
389         $act->time    = time();
390         $act->title   = _("Follow");
391         $act->content = sprintf(_("%s is now following %s."),
392                                $subscriber->getBestName(),
393                                $other->getBestName());
394
395         $act->actor   = ActivityObject::fromProfile($subscriber);
396         $act->object  = ActivityObject::fromProfile($other);
397
398         $oprofile->notifyActivity($act);
399
400         return true;
401     }
402
403     /**
404      * Notify remote users when their notices get favorited.
405      *
406      * @param Profile or User $profile of local user doing the faving
407      * @param Notice $notice being favored
408      * @return hook return value
409      */
410
411     function onEndFavorNotice(Profile $profile, Notice $notice)
412     {
413         $user = User::staticGet('id', $profile->id);
414
415         if (empty($user)) {
416             return true;
417         }
418
419         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
420
421         if (empty($oprofile)) {
422             return true;
423         }
424
425         $act = new Activity();
426
427         $act->verb = ActivityVerb::FAVORITE;
428         $act->id   = TagURI::mint('favor:%d:%d:%s',
429                                   $profile->id,
430                                   $notice->id,
431                                   common_date_iso8601(time()));
432
433         $act->time    = time();
434         $act->title   = _("Favor");
435         $act->content = sprintf(_("%s marked notice %s as a favorite."),
436                                $profile->getBestName(),
437                                $notice->uri);
438
439         $act->actor   = ActivityObject::fromProfile($profile);
440         $act->object  = ActivityObject::fromNotice($notice);
441
442         $oprofile->notifyActivity($act);
443
444         return true;
445     }
446
447     /**
448      * Notify remote users when their notices get de-favorited.
449      *
450      * @param Profile $profile Profile person doing the de-faving
451      * @param Notice  $notice  Notice being favored
452      *
453      * @return hook return value
454      */
455
456     function onEndDisfavorNotice(Profile $profile, Notice $notice)
457     {
458         $user = User::staticGet('id', $profile->id);
459
460         if (empty($user)) {
461             return true;
462         }
463
464         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
465
466         if (empty($oprofile)) {
467             return true;
468         }
469
470         $act = new Activity();
471
472         $act->verb = ActivityVerb::UNFAVORITE;
473         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
474                                   $profile->id,
475                                   $notice->id,
476                                   common_date_iso8601(time()));
477         $act->time    = time();
478         $act->title   = _("Disfavor");
479         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
480                                $profile->getBestName(),
481                                $notice->uri);
482
483         $act->actor   = ActivityObject::fromProfile($profile);
484         $act->object  = ActivityObject::fromNotice($notice);
485
486         $oprofile->notifyActivity($act);
487
488         return true;
489     }
490 }