]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'master' into social-master
[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  * OStatusPlugin implementation for GNU Social
22  *
23  * Depends on: WebFinger plugin
24  *
25  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28
29 if (!defined('GNUSOCIAL')) { exit(1); }
30
31 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpseclib');
32
33 class FeedSubException extends Exception
34 {
35     function __construct($msg=null)
36     {
37         $type = get_class($this);
38         if ($msg) {
39             parent::__construct("$type: $msg");
40         } else {
41             parent::__construct($type);
42         }
43     }
44 }
45
46 class OStatusPlugin extends Plugin
47 {
48     /**
49      * Hook for RouterInitialized event.
50      *
51      * @param URLMapper $m path-to-action mapper
52      * @return boolean hook return
53      */
54     public function onRouterInitialized(URLMapper $m)
55     {
56         // Discovery actions
57         $m->connect('main/ostatustag',
58                     array('action' => 'ostatustag'));
59         $m->connect('main/ostatustag?nickname=:nickname',
60                     array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
61         $m->connect('main/ostatus/nickname/:nickname',
62                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
63         $m->connect('main/ostatus/group/:group',
64                   array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
65         $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
66                   array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
67                                                           'peopletag' => '[A-Za-z0-9_-]+'));
68         $m->connect('main/ostatus',
69                     array('action' => 'ostatusinit'));
70
71         // Remote subscription actions
72         $m->connect('main/ostatussub',
73                     array('action' => 'ostatussub'));
74         $m->connect('main/ostatusgroup',
75                     array('action' => 'ostatusgroup'));
76         $m->connect('main/ostatuspeopletag',
77                     array('action' => 'ostatuspeopletag'));
78
79         // PuSH actions
80         $m->connect('main/push/hub', array('action' => 'pushhub'));
81
82         $m->connect('main/push/callback/:feed',
83                     array('action' => 'pushcallback'),
84                     array('feed' => '[0-9]+'));
85
86         // Salmon endpoint
87         $m->connect('main/salmon/user/:id',
88                     array('action' => 'usersalmon'),
89                     array('id' => '[0-9]+'));
90         $m->connect('main/salmon/group/:id',
91                     array('action' => 'groupsalmon'),
92                     array('id' => '[0-9]+'));
93         $m->connect('main/salmon/peopletag/:id',
94                     array('action' => 'peopletagsalmon'),
95                     array('id' => '[0-9]+'));
96         return true;
97     }
98
99     /**
100      * Set up queue handlers for outgoing hub pushes
101      * @param QueueManager $qm
102      * @return boolean hook return
103      */
104     function onEndInitializeQueueManager(QueueManager $qm)
105     {
106         // Prepare outgoing distributions after notice save.
107         $qm->connect('ostatus', 'OStatusQueueHandler');
108
109         // Outgoing from our internal PuSH hub
110         $qm->connect('hubconf', 'HubConfQueueHandler');
111         $qm->connect('hubprep', 'HubPrepQueueHandler');
112
113         $qm->connect('hubout', 'HubOutQueueHandler');
114
115         // Outgoing Salmon replies (when we don't need a return value)
116         $qm->connect('salmon', 'SalmonQueueHandler');
117
118         // Incoming from a foreign PuSH hub
119         $qm->connect('pushin', 'PushInQueueHandler');
120         return true;
121     }
122
123     /**
124      * Put saved notices into the queue for pubsub distribution.
125      */
126     function onStartEnqueueNotice(Notice $notice, array &$transports)
127     {
128         if ($notice->inScope(null)) {
129             // put our transport first, in case there's any conflict (like OMB)
130             array_unshift($transports, 'ostatus');
131             $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
132         } else {
133             // FIXME: we don't do privacy-controlled OStatus updates yet.
134             // once that happens, finer grain of control here.
135             $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
136         }
137         return true;
138     }
139
140     /**
141      * Set up a PuSH hub link to our internal link for canonical timeline
142      * Atom feeds for users and groups.
143      */
144     function onStartApiAtom($feed)
145     {
146         $id = null;
147
148         if ($feed instanceof AtomUserNoticeFeed) {
149             $salmonAction = 'usersalmon';
150             $user = $feed->getUser();
151             $id   = $user->id;
152             $profile = $user->getProfile();
153         } else if ($feed instanceof AtomGroupNoticeFeed) {
154             $salmonAction = 'groupsalmon';
155             $group = $feed->getGroup();
156             $id = $group->id;
157         } else if ($feed instanceof AtomListNoticeFeed) {
158             $salmonAction = 'peopletagsalmon';
159             $peopletag = $feed->getList();
160             $id = $peopletag->id;
161         } else {
162             return true;
163         }
164
165         if (!empty($id)) {
166             $hub = common_config('ostatus', 'hub');
167             if (empty($hub)) {
168                 // Updates will be handled through our internal PuSH hub.
169                 $hub = common_local_url('pushhub');
170             }
171             $feed->addLink($hub, array('rel' => 'hub'));
172
173             // Also, we'll add in the salmon link
174             $salmon = common_local_url($salmonAction, array('id' => $id));
175             $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
176
177             // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
178             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
179             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
180         }
181
182         return true;
183     }
184
185     /**
186      * Add in an OStatus subscribe button
187      */
188     function onStartProfileRemoteSubscribe($output, $profile)
189     {
190         $this->onStartProfileListItemActionElements($output, $profile);
191         return false;
192     }
193
194     function onStartGroupSubscribe($widget, $group)
195     {
196         $cur = common_current_user();
197
198         if (empty($cur)) {
199             $widget->out->elementStart('li', 'entity_subscribe');
200
201             $url = common_local_url('ostatusinit',
202                                     array('group' => $group->nickname));
203             $widget->out->element('a', array('href' => $url,
204                                              'class' => 'entity_remote_subscribe'),
205                                 // TRANS: Link to subscribe to a remote entity.
206                                 _m('Subscribe'));
207
208             $widget->out->elementEnd('li');
209             return false;
210         }
211
212         return true;
213     }
214
215     function onStartSubscribePeopletagForm($output, $peopletag)
216     {
217         $cur = common_current_user();
218
219         if (empty($cur)) {
220             $output->elementStart('li', 'entity_subscribe');
221             $profile = $peopletag->getTagger();
222             $url = common_local_url('ostatusinit',
223                                     array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
224             $output->element('a', array('href' => $url,
225                                         'class' => 'entity_remote_subscribe'),
226                                 // TRANS: Link to subscribe to a remote entity.
227                                 _m('Subscribe'));
228
229             $output->elementEnd('li');
230             return false;
231         }
232
233         return true;
234     }
235
236     function onStartTagProfileAction($action, $profile)
237     {
238         $err = null;
239         $uri = $action->trimmed('uri');
240
241         if (!$profile && $uri) {
242             try {
243                 if (Validate::email($uri)) {
244                     $oprofile = Ostatus_profile::ensureWebfinger($uri);
245                 } else if (Validate::uri($uri)) {
246                     $oprofile = Ostatus_profile::ensureProfileURL($uri);
247                 } else {
248                     // TRANS: Exception in OStatus when invalid URI was entered.
249                     throw new Exception(_m('Invalid URI.'));
250                 }
251
252                 // redirect to the new profile.
253                 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
254
255             } catch (Exception $e) {
256                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
257                 // TRANS: and example.net, as these are official standard domain names for use in examples.
258                 $err = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
259             }
260
261             $action->showForm($err);
262             return false;
263         }
264         return true;
265     }
266
267     /*
268      * If the field being looked for is URI look for the profile
269      */
270     function onStartProfileCompletionSearch($action, $profile, $search_engine) {
271         if ($action->field == 'uri') {
272             $profile->joinAdd(array('id', 'user:id'));
273             $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
274             $profile->query();
275
276             if ($profile->N == 0) {
277                 try {
278                     if (Validate::email($q)) {
279                         $oprofile = Ostatus_profile::ensureWebfinger($q);
280                     } else if (Validate::uri($q)) {
281                         $oprofile = Ostatus_profile::ensureProfileURL($q);
282                     } else {
283                         // TRANS: Exception in OStatus when invalid URI was entered.
284                         throw new Exception(_m('Invalid URI.'));
285                     }
286                     return $this->filter(array($oprofile->localProfile()));
287
288                 } catch (Exception $e) {
289                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
290                 // TRANS: and example.net, as these are official standard domain names for use in examples.
291                     $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
292                     return array();
293                 }
294             }
295             return false;
296         }
297         return true;
298     }
299
300     /**
301      * Find any explicit remote mentions. Accepted forms:
302      *   Webfinger: @user@example.com
303      *   Profile link: @example.com/mublog/user
304      * @param Profile $sender
305      * @param string $text input markup text
306      * @param array &$mention in/out param: set of found mentions
307      * @return boolean hook return value
308      */
309     function onEndFindMentions($sender, $text, &$mentions)
310     {
311         $matches = array();
312
313         // Webfinger matches: @user@example.com
314         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
315                        $text,
316                        $wmatches,
317                        PREG_OFFSET_CAPTURE)) {
318             foreach ($wmatches[1] as $wmatch) {
319                 list($target, $pos) = $wmatch;
320                 $this->log(LOG_INFO, "Checking webfinger '$target'");
321                 try {
322                     $oprofile = Ostatus_profile::ensureWebfinger($target);
323                     if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
324                         $profile = $oprofile->localProfile();
325                         $matches[$pos] = array('mentioned' => array($profile),
326                                                'type' => 'mention',
327                                                'text' => $target,
328                                                'position' => $pos,
329                                                'url' => $profile->getUrl());
330                     }
331                 } catch (Exception $e) {
332                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
333                 }
334             }
335         }
336
337         // Profile matches: @example.com/mublog/user
338         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
339                        $text,
340                        $wmatches,
341                        PREG_OFFSET_CAPTURE)) {
342             foreach ($wmatches[1] as $wmatch) {
343                 list($target, $pos) = $wmatch;
344                 $schemes = array('http', 'https');
345                 foreach ($schemes as $scheme) {
346                     $url = "$scheme://$target";
347                     $this->log(LOG_INFO, "Checking profile address '$url'");
348                     try {
349                         $oprofile = Ostatus_profile::ensureProfileURL($url);
350                         if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
351                             $profile = $oprofile->localProfile();
352                             $matches[$pos] = array('mentioned' => array($profile),
353                                                    'type' => 'mention',
354                                                    'text' => $target,
355                                                    'position' => $pos,
356                                                    'url' => $profile->getUrl());
357                             break;
358                         }
359                     } catch (Exception $e) {
360                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
361                     }
362                 }
363             }
364         }
365
366         foreach ($mentions as $i => $other) {
367             // If we share a common prefix with a local user, override it!
368             $pos = $other['position'];
369             if (isset($matches[$pos])) {
370                 $mentions[$i] = $matches[$pos];
371                 unset($matches[$pos]);
372             }
373         }
374         foreach ($matches as $mention) {
375             $mentions[] = $mention;
376         }
377
378         return true;
379     }
380
381     /**
382      * Allow remote profile references to be used in commands:
383      *   sub update@status.net
384      *   whois evan@identi.ca
385      *   reply http://identi.ca/evan hey what's up
386      *
387      * @param Command $command
388      * @param string $arg
389      * @param Profile &$profile
390      * @return hook return code
391      */
392     function onStartCommandGetProfile($command, $arg, &$profile)
393     {
394         $oprofile = $this->pullRemoteProfile($arg);
395         if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
396             try {
397                 $profile = $oprofile->localProfile();
398             } catch (NoProfileException $e) {
399                 // No locally stored profile found for remote profile
400                 return true;
401             }
402             return false;
403         } else {
404             return true;
405         }
406     }
407
408     /**
409      * Allow remote group references to be used in commands:
410      *   join group+statusnet@identi.ca
411      *   join http://identi.ca/group/statusnet
412      *   drop identi.ca/group/statusnet
413      *
414      * @param Command $command
415      * @param string $arg
416      * @param User_group &$group
417      * @return hook return code
418      */
419     function onStartCommandGetGroup($command, $arg, &$group)
420     {
421         $oprofile = $this->pullRemoteProfile($arg);
422         if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
423             $group = $oprofile->localGroup();
424             return false;
425         } else {
426             return true;
427         }
428     }
429
430     protected function pullRemoteProfile($arg)
431     {
432         $oprofile = null;
433         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
434             // webfinger lookup
435             try {
436                 return Ostatus_profile::ensureWebfinger($arg);
437             } catch (Exception $e) {
438                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
439                                     $arg . ': ' . $e->getMessage());
440             }
441         }
442
443         // Look for profile URLs, with or without scheme:
444         $urls = array();
445         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
446             $urls[] = $arg;
447         }
448         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
449             $schemes = array('http', 'https');
450             foreach ($schemes as $scheme) {
451                 $urls[] = "$scheme://$arg";
452             }
453         }
454
455         foreach ($urls as $url) {
456             try {
457                 return Ostatus_profile::ensureProfileURL($url);
458             } catch (Exception $e) {
459                 common_log(LOG_ERR, 'Profile lookup failed for ' .
460                                     $arg . ': ' . $e->getMessage());
461             }
462         }
463         return null;
464     }
465
466     /**
467      * Make sure necessary tables are filled out.
468      */
469     function onCheckSchema() {
470         $schema = Schema::get();
471         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
472         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
473         $schema->ensureTable('feedsub', FeedSub::schemaDef());
474         $schema->ensureTable('hubsub', HubSub::schemaDef());
475         $schema->ensureTable('magicsig', Magicsig::schemaDef());
476         return true;
477     }
478
479     public function onEndShowStylesheets(Action $action) {
480         $action->cssLink($this->path('theme/base/css/ostatus.css'));
481         return true;
482     }
483
484     function onEndShowStatusNetScripts($action) {
485         $action->script($this->path('js/ostatus.js'));
486         return true;
487     }
488
489     /**
490      * Override the "from ostatus" bit in notice lists to link to the
491      * original post and show the domain it came from.
492      *
493      * @param Notice in $notice
494      * @param string out &$name
495      * @param string out &$url
496      * @param string out &$title
497      * @return mixed hook return code
498      */
499     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
500     {
501         // If we don't handle this, keep the event handler going
502         if ($notice->source != 'ostatus') {
503             return true;
504         }
505
506         try {
507             $url = $notice->getUrl();
508             // If getUrl() throws exception, $url is never set
509             
510             $bits = parse_url($url);
511             $domain = $bits['host'];
512             if (substr($domain, 0, 4) == 'www.') {
513                 $name = substr($domain, 4);
514             } else {
515                 $name = $domain;
516             }
517
518             // TRANS: Title. %s is a domain name.
519             $title = sprintf(_m('Sent from %s via OStatus'), $domain);
520
521             // Abort event handler, we have a name and URL!
522             return false;
523         } catch (InvalidUrlException $e) {
524             // This just means we don't have the notice source data
525             return true;
526         }
527     }
528
529     /**
530      * Send incoming PuSH feeds for OStatus endpoints in for processing.
531      *
532      * @param FeedSub $feedsub
533      * @param DOMDocument $feed
534      * @return mixed hook return code
535      */
536     function onStartFeedSubReceive($feedsub, $feed)
537     {
538         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
539         if ($oprofile instanceof Ostatus_profile) {
540             $oprofile->processFeed($feed, 'push');
541         } else {
542             common_debug("No ostatus profile for incoming feed $feedsub->uri");
543         }
544     }
545
546     /**
547      * Tell the FeedSub infrastructure whether we have any active OStatus
548      * usage for the feed; if not it'll be able to garbage-collect the
549      * feed subscription.
550      *
551      * @param FeedSub $feedsub
552      * @param integer $count in/out
553      * @return mixed hook return code
554      */
555     function onFeedSubSubscriberCount($feedsub, &$count)
556     {
557         $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
558         if ($oprofile instanceof Ostatus_profile) {
559             $count += $oprofile->subscriberCount();
560         }
561         return true;
562     }
563
564     /**
565      * When about to subscribe to a remote user, start a server-to-server
566      * PuSH subscription if needed. If we can't establish that, abort.
567      *
568      * @fixme If something else aborts later, we could end up with a stray
569      *        PuSH subscription. This is relatively harmless, though.
570      *
571      * @param Profile $profile  subscriber
572      * @param Profile $other    subscribee
573      *
574      * @return hook return code
575      *
576      * @throws Exception
577      */
578     function onStartSubscribe(Profile $profile, Profile $other)
579     {
580         if (!$profile->isLocal()) {
581             return true;
582         }
583
584         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
585         if (!$oprofile instanceof Ostatus_profile) {
586             return true;
587         }
588
589         $oprofile->subscribe();
590     }
591
592     /**
593      * Having established a remote subscription, send a notification to the
594      * remote OStatus profile's endpoint.
595      *
596      * @param Profile $profile  subscriber
597      * @param Profile $other    subscribee
598      *
599      * @return hook return code
600      *
601      * @throws Exception
602      */
603     function onEndSubscribe(Profile $profile, Profile $other)
604     {
605         if (!$profile->isLocal()) {
606             return true;
607         }
608
609         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
610         if (!$oprofile instanceof Ostatus_profile) {
611             return true;
612         }
613
614         $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
615                                            'subscribed' => $other->id));
616
617         $act = $sub->asActivity();
618
619         $oprofile->notifyActivity($act, $profile);
620
621         return true;
622     }
623
624     /**
625      * Notify remote server and garbage collect unused feeds on unsubscribe.
626      * @todo FIXME: Send these operations to background queues
627      *
628      * @param User $user
629      * @param Profile $other
630      * @return hook return value
631      */
632     function onEndUnsubscribe(Profile $profile, Profile $other)
633     {
634         if (!$profile->isLocal()) {
635             return true;
636         }
637
638         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
639         if (!$oprofile instanceof Ostatus_profile) {
640             return true;
641         }
642
643         // Drop the PuSH subscription if there are no other subscribers.
644         $oprofile->garbageCollect();
645
646         $act = new Activity();
647
648         $act->verb = ActivityVerb::UNFOLLOW;
649
650         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
651                                   $profile->id,
652                                   $other->id,
653                                   common_date_iso8601(time()));
654
655         $act->time    = time();
656         // TRANS: Title for unfollowing a remote profile.
657         $act->title   = _m('TITLE','Unfollow');
658         // TRANS: Success message for unsubscribe from user attempt through OStatus.
659         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
660         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
661                                $profile->getBestName(),
662                                $other->getBestName());
663
664         $act->actor   = $profile->asActivityObject();
665         $act->object  = $other->asActivityObject();
666
667         $oprofile->notifyActivity($act, $profile);
668
669         return true;
670     }
671
672     /**
673      * When one of our local users tries to join a remote group,
674      * notify the remote server. If the notification is rejected,
675      * deny the join.
676      *
677      * @param User_group $group
678      * @param Profile    $profile
679      *
680      * @return mixed hook return value
681      * @throws Exception of various kinds, some from $oprofile->subscribe();
682      */
683     function onStartJoinGroup($group, $profile)
684     {
685         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
686         if (!$oprofile instanceof Ostatus_profile) {
687             return true;
688         }
689
690         $oprofile->subscribe();
691
692         // NOTE: we don't use Group_member::asActivity() since that record
693         // has not yet been created.
694
695         $act = new Activity();
696         $act->id = TagURI::mint('join:%d:%d:%s',
697                                 $profile->id,
698                                 $group->id,
699                                 common_date_iso8601(time()));
700
701         $act->actor = $profile->asActivityObject();
702         $act->verb = ActivityVerb::JOIN;
703         $act->object = $oprofile->asActivityObject();
704
705         $act->time = time();
706         // TRANS: Title for joining a remote groep.
707         $act->title = _m('TITLE','Join');
708         // TRANS: Success message for subscribe to group attempt through OStatus.
709         // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
710         $act->content = sprintf(_m('%1$s has joined group %2$s.'),
711                                 $profile->getBestName(),
712                                 $oprofile->getBestName());
713
714         if ($oprofile->notifyActivity($act, $profile)) {
715             return true;
716         } else {
717             $oprofile->garbageCollect();
718             // TRANS: Exception thrown when joining a remote group fails.
719             throw new Exception(_m('Failed joining remote group.'));
720         }
721     }
722
723     /**
724      * When one of our local users leaves a remote group, notify the remote
725      * server.
726      *
727      * @fixme Might be good to schedule a resend of the leave notification
728      * if it failed due to a transitory error. We've canceled the local
729      * membership already anyway, but if the remote server comes back up
730      * it'll be left with a stray membership record.
731      *
732      * @param User_group $group
733      * @param Profile $profile
734      *
735      * @return mixed hook return value
736      */
737     function onEndLeaveGroup($group, $profile)
738     {
739         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
740         if (!$oprofile instanceof Ostatus_profile) {
741             return true;
742         }
743
744         // Drop the PuSH subscription if there are no other subscribers.
745         $oprofile->garbageCollect();
746
747         $member = $profile;
748
749         $act = new Activity();
750         $act->id = TagURI::mint('leave:%d:%d:%s',
751                                 $member->id,
752                                 $group->id,
753                                 common_date_iso8601(time()));
754
755         $act->actor = $member->asActivityObject();
756         $act->verb = ActivityVerb::LEAVE;
757         $act->object = $oprofile->asActivityObject();
758
759         $act->time = time();
760         // TRANS: Title for leaving a remote group.
761         $act->title = _m('TITLE','Leave');
762         // TRANS: Success message for unsubscribe from group attempt through OStatus.
763         // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
764         $act->content = sprintf(_m('%1$s has left group %2$s.'),
765                                 $member->getBestName(),
766                                 $oprofile->getBestName());
767
768         $oprofile->notifyActivity($act, $member);
769     }
770
771     /**
772      * When one of our local users tries to subscribe to a remote peopletag,
773      * notify the remote server. If the notification is rejected,
774      * deny the subscription.
775      *
776      * @param Profile_list $peopletag
777      * @param User         $user
778      *
779      * @return mixed hook return value
780      * @throws Exception of various kinds, some from $oprofile->subscribe();
781      */
782
783     function onStartSubscribePeopletag($peopletag, $user)
784     {
785         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
786         if (!$oprofile instanceof Ostatus_profile) {
787             return true;
788         }
789
790         $oprofile->subscribe();
791
792         $sub = $user->getProfile();
793         $tagger = Profile::getKV($peopletag->tagger);
794
795         $act = new Activity();
796         $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
797                                 $sub->id,
798                                 $peopletag->id,
799                                 common_date_iso8601(time()));
800
801         $act->actor = $sub->asActivityObject();
802         $act->verb = ActivityVerb::FOLLOW;
803         $act->object = $oprofile->asActivityObject();
804
805         $act->time = time();
806         // TRANS: Title for following a remote list.
807         $act->title = _m('TITLE','Follow list');
808         // TRANS: Success message for remote list follow through OStatus.
809         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
810         $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
811                                 $sub->getBestName(),
812                                 $oprofile->getBestName(),
813                                 $tagger->getBestName());
814
815         if ($oprofile->notifyActivity($act, $sub)) {
816             return true;
817         } else {
818             $oprofile->garbageCollect();
819             // TRANS: Exception thrown when subscription to remote list fails.
820             throw new Exception(_m('Failed subscribing to remote list.'));
821         }
822     }
823
824     /**
825      * When one of our local users unsubscribes to a remote peopletag, notify the remote
826      * server.
827      *
828      * @param Profile_list $peopletag
829      * @param User         $user
830      *
831      * @return mixed hook return value
832      */
833
834     function onEndUnsubscribePeopletag($peopletag, $user)
835     {
836         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
837         if (!$oprofile instanceof Ostatus_profile) {
838             return true;
839         }
840
841         // Drop the PuSH subscription if there are no other subscribers.
842         $oprofile->garbageCollect();
843
844         $sub = Profile::getKV($user->id);
845         $tagger = Profile::getKV($peopletag->tagger);
846
847         $act = new Activity();
848         $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
849                                 $sub->id,
850                                 $peopletag->id,
851                                 common_date_iso8601(time()));
852
853         $act->actor = $member->asActivityObject();
854         $act->verb = ActivityVerb::UNFOLLOW;
855         $act->object = $oprofile->asActivityObject();
856
857         $act->time = time();
858         // TRANS: Title for unfollowing a remote list.
859         $act->title = _m('Unfollow list');
860         // TRANS: Success message for remote list unfollow through OStatus.
861         // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
862         $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
863                                 $sub->getBestName(),
864                                 $oprofile->getBestName(),
865                                 $tagger->getBestName());
866
867         $oprofile->notifyActivity($act, $user);
868     }
869
870     /**
871      * Notify remote users when their notices get favorited.
872      *
873      * @param Profile or User $profile of local user doing the faving
874      * @param Notice $notice being favored
875      * @return hook return value
876      */
877     function onEndFavorNotice(Profile $profile, Notice $notice)
878     {
879         // Only distribute local users' favor actions, remote users
880         // will have already distributed theirs.
881         if (!$profile->isLocal()) {
882             return true;
883         }
884
885         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
886         if (!$oprofile instanceof Ostatus_profile) {
887             return true;
888         }
889
890         $fav = Fave::pkeyGet(array('user_id' => $profile->id,
891                                    'notice_id' => $notice->id));
892
893         if (!$fav instanceof Fave) {
894             // That's weird.
895             // TODO: Make pkeyGet throw exception, since this is a critical failure.
896             return true;
897         }
898
899         $act = $fav->asActivity();
900
901         $oprofile->notifyActivity($act, $profile);
902
903         return true;
904     }
905
906     /**
907      * Notify remote user it has got a new people tag
908      *   - tag verb is queued
909      *   - the subscription is done immediately if not present
910      *
911      * @param Profile_tag $ptag the people tag that was created
912      * @return hook return value
913      * @throws Exception of various kinds, some from $oprofile->subscribe();
914      */
915     function onEndTagProfile($ptag)
916     {
917         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
918         if (!$oprofile instanceof Ostatus_profile) {
919             return true;
920         }
921
922         $plist = $ptag->getMeta();
923         if ($plist->private) {
924             return true;
925         }
926
927         $act = new Activity();
928
929         $tagger = $plist->getTagger();
930         $tagged = Profile::getKV('id', $ptag->tagged);
931
932         $act->verb = ActivityVerb::TAG;
933         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
934                                   $plist->tagger, $plist->id,
935                                   common_date_iso8601(time()));
936         $act->time = time();
937         // TRANS: Title for listing a remote profile.
938         $act->title = _m('TITLE','List');
939         // TRANS: Success message for remote list addition through OStatus.
940         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
941         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
942                                 $tagger->getBestName(),
943                                 $tagged->getBestName(),
944                                 $plist->getBestName());
945
946         $act->actor  = $tagger->asActivityObject();
947         $act->objects = array($tagged->asActivityObject());
948         $act->target = ActivityObject::fromPeopletag($plist);
949
950         $oprofile->notifyDeferred($act, $tagger);
951
952         // initiate a PuSH subscription for the person being tagged
953         $oprofile->subscribe();
954         return true;
955     }
956
957     /**
958      * Notify remote user that a people tag has been removed
959      *   - untag verb is queued
960      *   - the subscription is undone immediately if not required
961      *     i.e garbageCollect()'d
962      *
963      * @param Profile_tag $ptag the people tag that was deleted
964      * @return hook return value
965      */
966     function onEndUntagProfile($ptag)
967     {
968         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
969         if (!$oprofile instanceof Ostatus_profile) {
970             return true;
971         }
972
973         $plist = $ptag->getMeta();
974         if ($plist->private) {
975             return true;
976         }
977
978         $act = new Activity();
979
980         $tagger = $plist->getTagger();
981         $tagged = Profile::getKV('id', $ptag->tagged);
982
983         $act->verb = ActivityVerb::UNTAG;
984         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
985                                   $plist->tagger, $plist->id,
986                                   common_date_iso8601(time()));
987         $act->time = time();
988         // TRANS: Title for unlisting a remote profile.
989         $act->title = _m('TITLE','Unlist');
990         // TRANS: Success message for remote list removal through OStatus.
991         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
992         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
993                                 $tagger->getBestName(),
994                                 $tagged->getBestName(),
995                                 $plist->getBestName());
996
997         $act->actor  = $tagger->asActivityObject();
998         $act->objects = array($tagged->asActivityObject());
999         $act->target = ActivityObject::fromPeopletag($plist);
1000
1001         $oprofile->notifyDeferred($act, $tagger);
1002
1003         // unsubscribe to PuSH feed if no more required
1004         $oprofile->garbageCollect();
1005
1006         return true;
1007     }
1008
1009     /**
1010      * Notify remote users when their notices get de-favorited.
1011      *
1012      * @param Profile $profile Profile person doing the de-faving
1013      * @param Notice  $notice  Notice being favored
1014      *
1015      * @return hook return value
1016      */
1017     function onEndDisfavorNotice(Profile $profile, Notice $notice)
1018     {
1019         // Only distribute local users' disfavor actions, remote users
1020         // will have already distributed theirs.
1021         if (!$profile->isLocal()) {
1022             return true;
1023         }
1024
1025         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1026         if (!$oprofile instanceof Ostatus_profile) {
1027             return true;
1028         }
1029
1030         $act = new Activity();
1031
1032         $act->verb = ActivityVerb::UNFAVORITE;
1033         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
1034                                   $profile->id,
1035                                   $notice->id,
1036                                   common_date_iso8601(time()));
1037         $act->time    = time();
1038         // TRANS: Title for unliking a remote notice.
1039         $act->title   = _m('Unlike');
1040         // TRANS: Success message for remove a favorite notice through OStatus.
1041         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1042         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1043                                $profile->getBestName(),
1044                                $notice->getUrl());
1045
1046         $act->actor   = $profile->asActivityObject();
1047         $act->object  = $notice->asActivityObject();
1048
1049         $oprofile->notifyActivity($act, $profile);
1050
1051         return true;
1052     }
1053
1054     function onStartGetProfileUri($profile, &$uri)
1055     {
1056         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1057         if ($oprofile instanceof Ostatus_profile) {
1058             $uri = $oprofile->uri;
1059             return false;
1060         }
1061         return true;
1062     }
1063
1064     function onStartUserGroupHomeUrl($group, &$url)
1065     {
1066         return $this->onStartUserGroupPermalink($group, $url);
1067     }
1068
1069     function onStartUserGroupPermalink($group, &$url)
1070     {
1071         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1072         if ($oprofile instanceof Ostatus_profile) {
1073             // @fixme this should probably be in the user_group table
1074             // @fixme this uri not guaranteed to be a profile page
1075             $url = $oprofile->uri;
1076             return false;
1077         }
1078     }
1079
1080     function onStartShowSubscriptionsContent($action)
1081     {
1082         $this->showEntityRemoteSubscribe($action);
1083
1084         return true;
1085     }
1086
1087     function onStartShowUserGroupsContent($action)
1088     {
1089         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1090
1091         return true;
1092     }
1093
1094     function onEndShowSubscriptionsMiniList($action)
1095     {
1096         $this->showEntityRemoteSubscribe($action);
1097
1098         return true;
1099     }
1100
1101     function onEndShowGroupsMiniList($action)
1102     {
1103         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1104
1105         return true;
1106     }
1107
1108     function showEntityRemoteSubscribe($action, $target='ostatussub')
1109     {
1110         $user = common_current_user();
1111         if ($user && ($user->id == $action->profile->id)) {
1112             $action->elementStart('div', 'entity_actions');
1113             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1114                                              'class' => 'entity_subscribe'));
1115             $action->element('a', array('href' => common_local_url($target),
1116                                         'class' => 'entity_remote_subscribe'),
1117                                 // TRANS: Link text for link to remote subscribe.
1118                                 _m('Remote'));
1119             $action->elementEnd('p');
1120             $action->elementEnd('div');
1121         }
1122     }
1123
1124     /**
1125      * Ping remote profiles with updates to this profile.
1126      * Salmon pings are queued for background processing.
1127      */
1128     function onEndBroadcastProfile(Profile $profile)
1129     {
1130         $user = User::getKV('id', $profile->id);
1131
1132         // Find foreign accounts I'm subscribed to that support Salmon pings.
1133         //
1134         // @fixme we could run updates through the PuSH feed too,
1135         // in which case we can skip Salmon pings to folks who
1136         // are also subscribed to me.
1137         $sql = "SELECT * FROM ostatus_profile " .
1138                "WHERE profile_id IN " .
1139                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1140                "OR group_id IN " .
1141                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1142         $oprofile = new Ostatus_profile();
1143         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1144
1145         if ($oprofile->N == 0) {
1146             common_debug("No OStatus remote subscribees for $profile->nickname");
1147             return true;
1148         }
1149
1150         $act = new Activity();
1151
1152         $act->verb = ActivityVerb::UPDATE_PROFILE;
1153         $act->id   = TagURI::mint('update-profile:%d:%s',
1154                                   $profile->id,
1155                                   common_date_iso8601(time()));
1156         $act->time    = time();
1157         // TRANS: Title for activity.
1158         $act->title   = _m('Profile update');
1159         // TRANS: Ping text for remote profile update through OStatus.
1160         // TRANS: %s is user that updated their profile.
1161         $act->content = sprintf(_m('%s has updated their profile page.'),
1162                                $profile->getBestName());
1163
1164         $act->actor   = $profile->asActivityObject();
1165         $act->object  = $act->actor;
1166
1167         while ($oprofile->fetch()) {
1168             $oprofile->notifyDeferred($act, $profile);
1169         }
1170
1171         return true;
1172     }
1173
1174     function onStartProfileListItemActionElements($item, $profile=null)
1175     {
1176         if (!common_logged_in()) {
1177
1178             $profileUser = User::getKV('id', $item->profile->id);
1179
1180             if (!empty($profileUser)) {
1181
1182                 if ($item instanceof Action) {
1183                     $output = $item;
1184                     $profile = $item->profile;
1185                 } else {
1186                     $output = $item->out;
1187                 }
1188
1189                 // Add an OStatus subscribe
1190                 $output->elementStart('li', 'entity_subscribe');
1191                 $url = common_local_url('ostatusinit',
1192                                         array('nickname' => $profileUser->nickname));
1193                 $output->element('a', array('href' => $url,
1194                                             'class' => 'entity_remote_subscribe'),
1195                                   // TRANS: Link text for a user to subscribe to an OStatus user.
1196                                  _m('Subscribe'));
1197                 $output->elementEnd('li');
1198
1199                 $output->elementStart('li', 'entity_tag');
1200                 $url = common_local_url('ostatustag',
1201                                         array('nickname' => $profileUser->nickname));
1202                 $output->element('a', array('href' => $url,
1203                                             'class' => 'entity_remote_tag'),
1204                                   // TRANS: Link text for a user to list an OStatus user.
1205                                  _m('List'));
1206                 $output->elementEnd('li');
1207             }
1208         }
1209
1210         return true;
1211     }
1212
1213     function onPluginVersion(array &$versions)
1214     {
1215         $versions[] = array('name' => 'OStatus',
1216                             'version' => GNUSOCIAL_VERSION,
1217                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1218                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1219                             // TRANS: Plugin description.
1220                             'rawdescription' => _m('Follow people across social networks that implement '.
1221                                '<a href="http://ostatus.org/">OStatus</a>.'));
1222
1223         return true;
1224     }
1225
1226     /**
1227      * Utility function to check if the given URI is a canonical group profile
1228      * page, and if so return the ID number.
1229      *
1230      * @param string $url
1231      * @return mixed int or false
1232      */
1233     public static function localGroupFromUrl($url)
1234     {
1235         $group = User_group::getKV('uri', $url);
1236         if ($group instanceof User_group) {
1237             if ($group->isLocal()) {
1238                 return $group->id;
1239             }
1240         } else {
1241             // To find local groups which haven't had their uri fields filled out...
1242             // If the domain has changed since a subscriber got the URI, it'll
1243             // be broken.
1244             $template = common_local_url('groupbyid', array('id' => '31337'));
1245             $template = preg_quote($template, '/');
1246             $template = str_replace('31337', '(\d+)', $template);
1247             if (preg_match("/$template/", $url, $matches)) {
1248                 return intval($matches[1]);
1249             }
1250         }
1251         return false;
1252     }
1253
1254     public function onStartProfileGetAtomFeed($profile, &$feed)
1255     {
1256         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1257
1258         if (!$oprofile instanceof Ostatus_profile) {
1259             return true;
1260         }
1261
1262         $feed = $oprofile->feeduri;
1263         return false;
1264     }
1265
1266     function onStartGetProfileFromURI($uri, &$profile)
1267     {
1268         // Don't want to do Web-based discovery on our own server,
1269         // so we check locally first.
1270
1271         $user = User::getKV('uri', $uri);
1272
1273         if (!empty($user)) {
1274             $profile = $user->getProfile();
1275             return false;
1276         }
1277
1278         // Now, check remotely
1279
1280         try {
1281             $oprofile = Ostatus_profile::ensureProfileURI($uri);
1282             $profile = $oprofile->localProfile();
1283             return !($profile instanceof Profile);  // localProfile won't throw exception but can return null
1284         } catch (Exception $e) {
1285             return true; // It's not an OStatus profile as far as we know, continue event handling
1286         }
1287     }
1288
1289     function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1290     {
1291         $author = $target->getProfile();
1292         $profiletype = $this->profileTypeString($author);
1293         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1294         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1295         return true;
1296     }
1297
1298     function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1299     {
1300         if ($target->getObjectType() === ActivityObject::PERSON) {
1301             $this->addWebFingerPersonLinks($xrd, $target);
1302         }
1303
1304         // Salmon
1305         $profiletype = $this->profileTypeString($target);
1306         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1307
1308         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1309
1310         // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1311         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1312         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1313
1314         // TODO - finalize where the redirect should go on the publisher
1315         $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1316                               common_local_url('ostatussub') . '?profile={uri}',
1317                               null, // type not set
1318                               true); // isTemplate
1319
1320         return true;
1321     }
1322
1323     protected function profileTypeString(Profile $target)
1324     {
1325         // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1326         switch ($target->getObjectType()) {
1327         case ActivityObject::PERSON:
1328             return 'user';
1329         case ActivityObject::GROUP:
1330             return 'group';
1331         default:
1332             throw new ServerException('Unknown profile type for WebFinger profile links');
1333         }
1334     }
1335
1336     protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1337     {
1338         $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1339                             common_local_url('ApiTimelineUser',
1340                                 array('id' => $target->id, 'format' => 'atom')),
1341                             'application/atom+xml');
1342
1343         // Get this profile's keypair
1344         $magicsig = Magicsig::getKV('user_id', $target->id);
1345         if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1346             $magicsig = Magicsig::generate($target->getUser());
1347         }
1348
1349         if ($magicsig instanceof Magicsig) {
1350             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1351                                 'data:application/magic-public-key,'. $magicsig->toString());
1352             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::DIASPORA_PUBLICKEYREL,
1353                                 base64_encode($magicsig->exportPublicKey()));
1354         }
1355     }
1356
1357     public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1358     {
1359         list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1360     }
1361
1362     // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1363     static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1364     {
1365         try {
1366             $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1367             $profile = $oprofile->checkAuthorship($activity);
1368         } catch (Exception $e) {
1369             common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1370             $profile = null;
1371             return false;
1372         }
1373         return true;
1374     }
1375
1376     public function onProfileDeleteRelated(Profile $profile, array &$related)
1377     {
1378         // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1379         $related[] = 'Ostatus_profile';
1380
1381         // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1382         $magicsig = Magicsig::getKV('user_id', $profile->id);
1383         if ($magicsig instanceof Magicsig) {
1384             $magicsig->delete();
1385         }
1386         return true;
1387     }
1388 }