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