]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Notices for faves are already sent as they are notices now.
[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, &$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(Profile $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_log(LOG_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 user it has got a new people tag
872      *   - tag verb is queued
873      *   - the subscription is done immediately if not present
874      *
875      * @param Profile_tag $ptag the people tag that was created
876      * @return hook return value
877      * @throws Exception of various kinds, some from $oprofile->subscribe();
878      */
879     function onEndTagProfile($ptag)
880     {
881         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
882         if (!$oprofile instanceof Ostatus_profile) {
883             return true;
884         }
885
886         $plist = $ptag->getMeta();
887         if ($plist->private) {
888             return true;
889         }
890
891         $act = new Activity();
892
893         $tagger = $plist->getTagger();
894         $tagged = Profile::getKV('id', $ptag->tagged);
895
896         $act->verb = ActivityVerb::TAG;
897         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
898                                   $plist->tagger, $plist->id,
899                                   common_date_iso8601(time()));
900         $act->time = time();
901         // TRANS: Title for listing a remote profile.
902         $act->title = _m('TITLE','List');
903         // TRANS: Success message for remote list addition through OStatus.
904         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
905         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
906                                 $tagger->getBestName(),
907                                 $tagged->getBestName(),
908                                 $plist->getBestName());
909
910         $act->actor  = $tagger->asActivityObject();
911         $act->objects = array($tagged->asActivityObject());
912         $act->target = ActivityObject::fromPeopletag($plist);
913
914         $oprofile->notifyDeferred($act, $tagger);
915
916         // initiate a PuSH subscription for the person being tagged
917         $oprofile->subscribe();
918         return true;
919     }
920
921     /**
922      * Notify remote user that a people tag has been removed
923      *   - untag verb is queued
924      *   - the subscription is undone immediately if not required
925      *     i.e garbageCollect()'d
926      *
927      * @param Profile_tag $ptag the people tag that was deleted
928      * @return hook return value
929      */
930     function onEndUntagProfile($ptag)
931     {
932         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
933         if (!$oprofile instanceof Ostatus_profile) {
934             return true;
935         }
936
937         $plist = $ptag->getMeta();
938         if ($plist->private) {
939             return true;
940         }
941
942         $act = new Activity();
943
944         $tagger = $plist->getTagger();
945         $tagged = Profile::getKV('id', $ptag->tagged);
946
947         $act->verb = ActivityVerb::UNTAG;
948         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
949                                   $plist->tagger, $plist->id,
950                                   common_date_iso8601(time()));
951         $act->time = time();
952         // TRANS: Title for unlisting a remote profile.
953         $act->title = _m('TITLE','Unlist');
954         // TRANS: Success message for remote list removal through OStatus.
955         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
956         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
957                                 $tagger->getBestName(),
958                                 $tagged->getBestName(),
959                                 $plist->getBestName());
960
961         $act->actor  = $tagger->asActivityObject();
962         $act->objects = array($tagged->asActivityObject());
963         $act->target = ActivityObject::fromPeopletag($plist);
964
965         $oprofile->notifyDeferred($act, $tagger);
966
967         // unsubscribe to PuSH feed if no more required
968         $oprofile->garbageCollect();
969
970         return true;
971     }
972
973     /**
974      * Notify remote users when their notices get de-favorited.
975      *
976      * @param Profile $profile Profile person doing the de-faving
977      * @param Notice  $notice  Notice being favored
978      *
979      * @return hook return value
980      */
981     function onEndDisfavorNotice(Profile $profile, Notice $notice)
982     {
983         // Only distribute local users' disfavor actions, remote users
984         // will have already distributed theirs.
985         if (!$profile->isLocal()) {
986             return true;
987         }
988
989         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
990         if (!$oprofile instanceof Ostatus_profile) {
991             return true;
992         }
993
994         $act = new Activity();
995
996         $act->verb = ActivityVerb::UNFAVORITE;
997         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
998                                   $profile->id,
999                                   $notice->id,
1000                                   common_date_iso8601(time()));
1001         $act->time    = time();
1002         // TRANS: Title for unliking a remote notice.
1003         $act->title   = _m('Unlike');
1004         // TRANS: Success message for remove a favorite notice through OStatus.
1005         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1006         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1007                                $profile->getBestName(),
1008                                $notice->getUrl());
1009
1010         $act->actor   = $profile->asActivityObject();
1011         $act->object  = $notice->asActivityObject();
1012
1013         $oprofile->notifyActivity($act, $profile);
1014
1015         return true;
1016     }
1017
1018     function onStartGetProfileUri($profile, &$uri)
1019     {
1020         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1021         if ($oprofile instanceof Ostatus_profile) {
1022             $uri = $oprofile->uri;
1023             return false;
1024         }
1025         return true;
1026     }
1027
1028     function onStartUserGroupHomeUrl($group, &$url)
1029     {
1030         return $this->onStartUserGroupPermalink($group, $url);
1031     }
1032
1033     function onStartUserGroupPermalink($group, &$url)
1034     {
1035         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1036         if ($oprofile instanceof Ostatus_profile) {
1037             // @fixme this should probably be in the user_group table
1038             // @fixme this uri not guaranteed to be a profile page
1039             $url = $oprofile->uri;
1040             return false;
1041         }
1042     }
1043
1044     function onStartShowSubscriptionsContent($action)
1045     {
1046         $this->showEntityRemoteSubscribe($action);
1047
1048         return true;
1049     }
1050
1051     function onStartShowUserGroupsContent($action)
1052     {
1053         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1054
1055         return true;
1056     }
1057
1058     function onEndShowSubscriptionsMiniList($action)
1059     {
1060         $this->showEntityRemoteSubscribe($action);
1061
1062         return true;
1063     }
1064
1065     function onEndShowGroupsMiniList($action)
1066     {
1067         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1068
1069         return true;
1070     }
1071
1072     function showEntityRemoteSubscribe($action, $target='ostatussub')
1073     {
1074         $user = common_current_user();
1075         if ($user && ($user->id == $action->profile->id)) {
1076             $action->elementStart('div', 'entity_actions');
1077             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1078                                              'class' => 'entity_subscribe'));
1079             $action->element('a', array('href' => common_local_url($target),
1080                                         'class' => 'entity_remote_subscribe'),
1081                                 // TRANS: Link text for link to remote subscribe.
1082                                 _m('Remote'));
1083             $action->elementEnd('p');
1084             $action->elementEnd('div');
1085         }
1086     }
1087
1088     /**
1089      * Ping remote profiles with updates to this profile.
1090      * Salmon pings are queued for background processing.
1091      */
1092     function onEndBroadcastProfile(Profile $profile)
1093     {
1094         $user = User::getKV('id', $profile->id);
1095
1096         // Find foreign accounts I'm subscribed to that support Salmon pings.
1097         //
1098         // @fixme we could run updates through the PuSH feed too,
1099         // in which case we can skip Salmon pings to folks who
1100         // are also subscribed to me.
1101         $sql = "SELECT * FROM ostatus_profile " .
1102                "WHERE profile_id IN " .
1103                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1104                "OR group_id IN " .
1105                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1106         $oprofile = new Ostatus_profile();
1107         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1108
1109         if ($oprofile->N == 0) {
1110             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1111             return true;
1112         }
1113
1114         $act = new Activity();
1115
1116         $act->verb = ActivityVerb::UPDATE_PROFILE;
1117         $act->id   = TagURI::mint('update-profile:%d:%s',
1118                                   $profile->id,
1119                                   common_date_iso8601(time()));
1120         $act->time    = time();
1121         // TRANS: Title for activity.
1122         $act->title   = _m('Profile update');
1123         // TRANS: Ping text for remote profile update through OStatus.
1124         // TRANS: %s is user that updated their profile.
1125         $act->content = sprintf(_m('%s has updated their profile page.'),
1126                                $profile->getBestName());
1127
1128         $act->actor   = $profile->asActivityObject();
1129         $act->object  = $act->actor;
1130
1131         while ($oprofile->fetch()) {
1132             $oprofile->notifyDeferred($act, $profile);
1133         }
1134
1135         return true;
1136     }
1137
1138     function onStartProfileListItemActionElements($item, $profile=null)
1139     {
1140         if (!common_logged_in()) {
1141
1142             $profileUser = User::getKV('id', $item->profile->id);
1143
1144             if (!empty($profileUser)) {
1145
1146                 if ($item instanceof Action) {
1147                     $output = $item;
1148                     $profile = $item->profile;
1149                 } else {
1150                     $output = $item->out;
1151                 }
1152
1153                 // Add an OStatus subscribe
1154                 $output->elementStart('li', 'entity_subscribe');
1155                 $url = common_local_url('ostatusinit',
1156                                         array('nickname' => $profileUser->nickname));
1157                 $output->element('a', array('href' => $url,
1158                                             'class' => 'entity_remote_subscribe'),
1159                                   // TRANS: Link text for a user to subscribe to an OStatus user.
1160                                  _m('Subscribe'));
1161                 $output->elementEnd('li');
1162
1163                 $output->elementStart('li', 'entity_tag');
1164                 $url = common_local_url('ostatustag',
1165                                         array('nickname' => $profileUser->nickname));
1166                 $output->element('a', array('href' => $url,
1167                                             'class' => 'entity_remote_tag'),
1168                                   // TRANS: Link text for a user to list an OStatus user.
1169                                  _m('List'));
1170                 $output->elementEnd('li');
1171             }
1172         }
1173
1174         return true;
1175     }
1176
1177     function onPluginVersion(&$versions)
1178     {
1179         $versions[] = array('name' => 'OStatus',
1180                             'version' => GNUSOCIAL_VERSION,
1181                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1182                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1183                             // TRANS: Plugin description.
1184                             'rawdescription' => _m('Follow people across social networks that implement '.
1185                                '<a href="http://ostatus.org/">OStatus</a>.'));
1186
1187         return true;
1188     }
1189
1190     /**
1191      * Utility function to check if the given URI is a canonical group profile
1192      * page, and if so return the ID number.
1193      *
1194      * @param string $url
1195      * @return mixed int or false
1196      */
1197     public static function localGroupFromUrl($url)
1198     {
1199         $group = User_group::getKV('uri', $url);
1200         if ($group instanceof User_group) {
1201             if ($group->isLocal()) {
1202                 return $group->id;
1203             }
1204         } else {
1205             // To find local groups which haven't had their uri fields filled out...
1206             // If the domain has changed since a subscriber got the URI, it'll
1207             // be broken.
1208             $template = common_local_url('groupbyid', array('id' => '31337'));
1209             $template = preg_quote($template, '/');
1210             $template = str_replace('31337', '(\d+)', $template);
1211             if (preg_match("/$template/", $url, $matches)) {
1212                 return intval($matches[1]);
1213             }
1214         }
1215         return false;
1216     }
1217
1218     public function onStartProfileGetAtomFeed($profile, &$feed)
1219     {
1220         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1221
1222         if (!$oprofile instanceof Ostatus_profile) {
1223             return true;
1224         }
1225
1226         $feed = $oprofile->feeduri;
1227         return false;
1228     }
1229
1230     function onStartGetProfileFromURI($uri, &$profile)
1231     {
1232         // Don't want to do Web-based discovery on our own server,
1233         // so we check locally first.
1234
1235         $user = User::getKV('uri', $uri);
1236
1237         if (!empty($user)) {
1238             $profile = $user->getProfile();
1239             return false;
1240         }
1241
1242         // Now, check remotely
1243
1244         try {
1245             $oprofile = Ostatus_profile::ensureProfileURI($uri);
1246             $profile = $oprofile->localProfile();
1247             return !($profile instanceof Profile);  // localProfile won't throw exception but can return null
1248         } catch (Exception $e) {
1249             return true; // It's not an OStatus profile as far as we know, continue event handling
1250         }
1251     }
1252
1253     function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1254     {
1255         $author = $target->getProfile();
1256         $profiletype = $this->profileTypeString($author);
1257         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1258         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1259         return true;
1260     }
1261
1262     function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1263     {
1264         if ($target->getObjectType() === ActivityObject::PERSON) {
1265             $this->addWebFingerPersonLinks($xrd, $target);
1266         }
1267
1268         // Salmon
1269         $profiletype = $this->profileTypeString($target);
1270         $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1271
1272         $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1273
1274         // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1275         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1276         $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1277
1278         // TODO - finalize where the redirect should go on the publisher
1279         $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1280                               common_local_url('ostatussub') . '?profile={uri}',
1281                               null, // type not set
1282                               true); // isTemplate
1283
1284         return true;
1285     }
1286
1287     protected function profileTypeString(Profile $target)
1288     {
1289         // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1290         switch ($target->getObjectType()) {
1291         case ActivityObject::PERSON:
1292             return 'user';
1293         case ActivityObject::GROUP:
1294             return 'group';
1295         default:
1296             throw new ServerException('Unknown profile type for WebFinger profile links');
1297         }
1298     }
1299
1300     protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1301     {
1302         $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1303                             common_local_url('ApiTimelineUser',
1304                                 array('id' => $target->id, 'format' => 'atom')),
1305                             'application/atom+xml');
1306
1307         // Get this profile's keypair
1308         $magicsig = Magicsig::getKV('user_id', $target->id);
1309         if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1310             $magicsig = Magicsig::generate($target->getUser());
1311         }
1312
1313         if ($magicsig instanceof Magicsig) {
1314             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1315                                 'data:application/magic-public-key,'. $magicsig->toString());
1316             $xrd->links[] = new XML_XRD_Element_Link(Magicsig::DIASPORA_PUBLICKEYREL,
1317                                 base64_encode($magicsig->exportPublicKey()));
1318         }
1319     }
1320
1321     public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1322     {
1323         list($mentions, $groups) = Ostatus_profile::filterAttention($actor, $attention_uris);
1324     }
1325
1326     // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1327     static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1328     {
1329         try {
1330             $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1331             $profile = $oprofile->checkAuthorship($activity);
1332         } catch (Exception $e) {
1333             common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1334             $profile = null;
1335             return false;
1336         }
1337         return true;
1338     }
1339
1340     public function onProfileDeleteRelated($profile, &$related)
1341     {
1342         // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1343         $related[] = 'Ostatus_profile';
1344
1345         // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1346         $magicsig = Magicsig::getKV('user_id', $profile->id);
1347         if ($magicsig instanceof Magicsig) {
1348             $magicsig->delete();
1349         }
1350         return true;
1351     }
1352 }