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