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