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