]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
plugins onAutoload now only overloads if necessary (extlibs etc.)
[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 $subscriber
605      * @param Profile $other
606      *
607      * @return hook return code
608      *
609      * @throws Exception
610      */
611     function onStartSubscribe($subscriber, $other)
612     {
613         $user = User::getKV('id', $subscriber->id);
614
615         if (empty($user)) {
616             return true;
617         }
618
619         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
620
621         if (empty($oprofile)) {
622             return true;
623         }
624
625         if (!$oprofile->subscribe()) {
626             // TRANS: Exception thrown when setup of remote subscription fails.
627             throw new Exception(_m('Could not set up remote subscription.'));
628         }
629     }
630
631     /**
632      * Having established a remote subscription, send a notification to the
633      * remote OStatus profile's endpoint.
634      *
635      * @param Profile $subscriber
636      * @param Profile $other
637      *
638      * @return hook return code
639      *
640      * @throws Exception
641      */
642     function onEndSubscribe($subscriber, $other)
643     {
644         $user = User::getKV('id', $subscriber->id);
645
646         if (empty($user)) {
647             return true;
648         }
649
650         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
651
652         if (empty($oprofile)) {
653             return true;
654         }
655
656         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
657                                            'subscribed' => $other->id));
658
659         $act = $sub->asActivity();
660
661         $oprofile->notifyActivity($act, $subscriber);
662
663         return true;
664     }
665
666     /**
667      * Notify remote server and garbage collect unused feeds on unsubscribe.
668      * @todo FIXME: Send these operations to background queues
669      *
670      * @param User $user
671      * @param Profile $other
672      * @return hook return value
673      */
674     function onEndUnsubscribe($profile, $other)
675     {
676         $user = User::getKV('id', $profile->id);
677
678         if (empty($user)) {
679             return true;
680         }
681
682         $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
683
684         if (empty($oprofile)) {
685             return true;
686         }
687
688         // Drop the PuSH subscription if there are no other subscribers.
689         $oprofile->garbageCollect();
690
691         $act = new Activity();
692
693         $act->verb = ActivityVerb::UNFOLLOW;
694
695         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
696                                   $profile->id,
697                                   $other->id,
698                                   common_date_iso8601(time()));
699
700         $act->time    = time();
701         // TRANS: Title for unfollowing a remote profile.
702         $act->title   = _m('TITLE','Unfollow');
703         // TRANS: Success message for unsubscribe from user attempt through OStatus.
704         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
705         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
706                                $profile->getBestName(),
707                                $other->getBestName());
708
709         $act->actor   = ActivityObject::fromProfile($profile);
710         $act->object  = ActivityObject::fromProfile($other);
711
712         $oprofile->notifyActivity($act, $profile);
713
714         return true;
715     }
716
717     /**
718      * When one of our local users tries to join a remote group,
719      * notify the remote server. If the notification is rejected,
720      * deny the join.
721      *
722      * @param User_group $group
723      * @param Profile    $profile
724      *
725      * @return mixed hook return value
726      */
727     function onStartJoinGroup($group, $profile)
728     {
729         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
730         if ($oprofile) {
731             if (!$oprofile->subscribe()) {
732                 // TRANS: Exception thrown when setup of remote group membership fails.
733                 throw new Exception(_m('Could not set up remote group membership.'));
734             }
735
736             // NOTE: we don't use Group_member::asActivity() since that record
737             // has not yet been created.
738
739             $act = new Activity();
740             $act->id = TagURI::mint('join:%d:%d:%s',
741                                     $profile->id,
742                                     $group->id,
743                                     common_date_iso8601(time()));
744
745             $act->actor = ActivityObject::fromProfile($profile);
746             $act->verb = ActivityVerb::JOIN;
747             $act->object = $oprofile->asActivityObject();
748
749             $act->time = time();
750             // TRANS: Title for joining a remote groep.
751             $act->title = _m('TITLE','Join');
752             // TRANS: Success message for subscribe to group attempt through OStatus.
753             // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
754             $act->content = sprintf(_m('%1$s has joined group %2$s.'),
755                                     $profile->getBestName(),
756                                     $oprofile->getBestName());
757
758             if ($oprofile->notifyActivity($act, $profile)) {
759                 return true;
760             } else {
761                 $oprofile->garbageCollect();
762                 // TRANS: Exception thrown when joining a remote group fails.
763                 throw new Exception(_m('Failed joining remote group.'));
764             }
765         }
766     }
767
768     /**
769      * When one of our local users leaves a remote group, notify the remote
770      * server.
771      *
772      * @fixme Might be good to schedule a resend of the leave notification
773      * if it failed due to a transitory error. We've canceled the local
774      * membership already anyway, but if the remote server comes back up
775      * it'll be left with a stray membership record.
776      *
777      * @param User_group $group
778      * @param Profile $profile
779      *
780      * @return mixed hook return value
781      */
782     function onEndLeaveGroup($group, $profile)
783     {
784         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
785         if ($oprofile) {
786             // Drop the PuSH subscription if there are no other subscribers.
787             $oprofile->garbageCollect();
788
789             $member = $profile;
790
791             $act = new Activity();
792             $act->id = TagURI::mint('leave:%d:%d:%s',
793                                     $member->id,
794                                     $group->id,
795                                     common_date_iso8601(time()));
796
797             $act->actor = ActivityObject::fromProfile($member);
798             $act->verb = ActivityVerb::LEAVE;
799             $act->object = $oprofile->asActivityObject();
800
801             $act->time = time();
802             // TRANS: Title for leaving a remote group.
803             $act->title = _m('TITLE','Leave');
804             // TRANS: Success message for unsubscribe from group attempt through OStatus.
805             // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
806             $act->content = sprintf(_m('%1$s has left group %2$s.'),
807                                     $member->getBestName(),
808                                     $oprofile->getBestName());
809
810             $oprofile->notifyActivity($act, $member);
811         }
812     }
813
814     /**
815      * When one of our local users tries to subscribe to a remote peopletag,
816      * notify the remote server. If the notification is rejected,
817      * deny the subscription.
818      *
819      * @param Profile_list $peopletag
820      * @param User         $user
821      *
822      * @return mixed hook return value
823      */
824
825     function onStartSubscribePeopletag($peopletag, $user)
826     {
827         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
828         if ($oprofile) {
829             if (!$oprofile->subscribe()) {
830                 // TRANS: Exception thrown when setup of remote list subscription fails.
831                 throw new Exception(_m('Could not set up remote list subscription.'));
832             }
833
834             $sub = $user->getProfile();
835             $tagger = Profile::getKV($peopletag->tagger);
836
837             $act = new Activity();
838             $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
839                                     $sub->id,
840                                     $peopletag->id,
841                                     common_date_iso8601(time()));
842
843             $act->actor = ActivityObject::fromProfile($sub);
844             $act->verb = ActivityVerb::FOLLOW;
845             $act->object = $oprofile->asActivityObject();
846
847             $act->time = time();
848             // TRANS: Title for following a remote list.
849             $act->title = _m('TITLE','Follow list');
850             // TRANS: Success message for remote list follow through OStatus.
851             // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
852             $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
853                                     $sub->getBestName(),
854                                     $oprofile->getBestName(),
855                                     $tagger->getBestName());
856
857             if ($oprofile->notifyActivity($act, $sub)) {
858                 return true;
859             } else {
860                 $oprofile->garbageCollect();
861                 // TRANS: Exception thrown when subscription to remote list fails.
862                 throw new Exception(_m('Failed subscribing to remote list.'));
863             }
864         }
865     }
866
867     /**
868      * When one of our local users unsubscribes to a remote peopletag, notify the remote
869      * server.
870      *
871      * @param Profile_list $peopletag
872      * @param User         $user
873      *
874      * @return mixed hook return value
875      */
876
877     function onEndUnsubscribePeopletag($peopletag, $user)
878     {
879         $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
880         if ($oprofile) {
881             // Drop the PuSH subscription if there are no other subscribers.
882             $oprofile->garbageCollect();
883
884             $sub = Profile::getKV($user->id);
885             $tagger = Profile::getKV($peopletag->tagger);
886
887             $act = new Activity();
888             $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
889                                     $sub->id,
890                                     $peopletag->id,
891                                     common_date_iso8601(time()));
892
893             $act->actor = ActivityObject::fromProfile($member);
894             $act->verb = ActivityVerb::UNFOLLOW;
895             $act->object = $oprofile->asActivityObject();
896
897             $act->time = time();
898             // TRANS: Title for unfollowing a remote list.
899             $act->title = _m('Unfollow list');
900             // TRANS: Success message for remote list unfollow through OStatus.
901             // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
902             $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
903                                     $sub->getBestName(),
904                                     $oprofile->getBestName(),
905                                     $tagger->getBestName());
906
907             $oprofile->notifyActivity($act, $user);
908         }
909     }
910
911     /**
912      * Notify remote users when their notices get favorited.
913      *
914      * @param Profile or User $profile of local user doing the faving
915      * @param Notice $notice being favored
916      * @return hook return value
917      */
918     function onEndFavorNotice(Profile $profile, Notice $notice)
919     {
920         $user = User::getKV('id', $profile->id);
921
922         if (empty($user)) {
923             return true;
924         }
925
926         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
927
928         if (empty($oprofile)) {
929             return true;
930         }
931
932         $fav = Fave::pkeyGet(array('user_id' => $user->id,
933                                    'notice_id' => $notice->id));
934
935         if (empty($fav)) {
936             // That's weird.
937             return true;
938         }
939
940         $act = $fav->asActivity();
941
942         $oprofile->notifyActivity($act, $profile);
943
944         return true;
945     }
946
947     /**
948      * Notify remote user it has got a new people tag
949      *   - tag verb is queued
950      *   - the subscription is done immediately if not present
951      *
952      * @param Profile_tag $ptag the people tag that was created
953      * @return hook return value
954      */
955     function onEndTagProfile($ptag)
956     {
957         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
958
959         if (empty($oprofile)) {
960             return true;
961         }
962
963         $plist = $ptag->getMeta();
964         if ($plist->private) {
965             return true;
966         }
967
968         $act = new Activity();
969
970         $tagger = $plist->getTagger();
971         $tagged = Profile::getKV('id', $ptag->tagged);
972
973         $act->verb = ActivityVerb::TAG;
974         $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
975                                   $plist->tagger, $plist->id,
976                                   common_date_iso8601(time()));
977         $act->time = time();
978         // TRANS: Title for listing a remote profile.
979         $act->title = _m('TITLE','List');
980         // TRANS: Success message for remote list addition through OStatus.
981         // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
982         $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
983                                 $tagger->getBestName(),
984                                 $tagged->getBestName(),
985                                 $plist->getBestName());
986
987         $act->actor  = ActivityObject::fromProfile($tagger);
988         $act->objects = array(ActivityObject::fromProfile($tagged));
989         $act->target = ActivityObject::fromPeopletag($plist);
990
991         $oprofile->notifyDeferred($act, $tagger);
992
993         // initiate a PuSH subscription for the person being tagged
994         if (!$oprofile->subscribe()) {
995             // TRANS: Exception thrown when subscribing to a remote list fails.
996             throw new Exception(sprintf(_m('Could not complete subscription to remote '.
997                                           'profile\'s feed. List %s could not be saved.'), $ptag->tag));
998             return false;
999         }
1000         return true;
1001     }
1002
1003     /**
1004      * Notify remote user that a people tag has been removed
1005      *   - untag verb is queued
1006      *   - the subscription is undone immediately if not required
1007      *     i.e garbageCollect()'d
1008      *
1009      * @param Profile_tag $ptag the people tag that was deleted
1010      * @return hook return value
1011      */
1012     function onEndUntagProfile($ptag)
1013     {
1014         $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
1015
1016         if (empty($oprofile)) {
1017             return true;
1018         }
1019
1020         $plist = $ptag->getMeta();
1021         if ($plist->private) {
1022             return true;
1023         }
1024
1025         $act = new Activity();
1026
1027         $tagger = $plist->getTagger();
1028         $tagged = Profile::getKV('id', $ptag->tagged);
1029
1030         $act->verb = ActivityVerb::UNTAG;
1031         $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
1032                                   $plist->tagger, $plist->id,
1033                                   common_date_iso8601(time()));
1034         $act->time = time();
1035         // TRANS: Title for unlisting a remote profile.
1036         $act->title = _m('TITLE','Unlist');
1037         // TRANS: Success message for remote list removal through OStatus.
1038         // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1039         $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1040                                 $tagger->getBestName(),
1041                                 $tagged->getBestName(),
1042                                 $plist->getBestName());
1043
1044         $act->actor  = ActivityObject::fromProfile($tagger);
1045         $act->objects = array(ActivityObject::fromProfile($tagged));
1046         $act->target = ActivityObject::fromPeopletag($plist);
1047
1048         $oprofile->notifyDeferred($act, $tagger);
1049
1050         // unsubscribe to PuSH feed if no more required
1051         $oprofile->garbageCollect();
1052
1053         return true;
1054     }
1055
1056     /**
1057      * Notify remote users when their notices get de-favorited.
1058      *
1059      * @param Profile $profile Profile person doing the de-faving
1060      * @param Notice  $notice  Notice being favored
1061      *
1062      * @return hook return value
1063      */
1064     function onEndDisfavorNotice(Profile $profile, Notice $notice)
1065     {
1066         $user = User::getKV('id', $profile->id);
1067
1068         if (empty($user)) {
1069             return true;
1070         }
1071
1072         $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1073
1074         if (empty($oprofile)) {
1075             return true;
1076         }
1077
1078         $act = new Activity();
1079
1080         $act->verb = ActivityVerb::UNFAVORITE;
1081         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
1082                                   $profile->id,
1083                                   $notice->id,
1084                                   common_date_iso8601(time()));
1085         $act->time    = time();
1086         // TRANS: Title for unliking a remote notice.
1087         $act->title   = _m('Unlike');
1088         // TRANS: Success message for remove a favorite notice through OStatus.
1089         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1090         $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1091                                $profile->getBestName(),
1092                                $notice->uri);
1093
1094         $act->actor   = ActivityObject::fromProfile($profile);
1095         $act->object  = ActivityObject::fromNotice($notice);
1096
1097         $oprofile->notifyActivity($act, $profile);
1098
1099         return true;
1100     }
1101
1102     function onStartGetProfileUri($profile, &$uri)
1103     {
1104         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1105         if (!empty($oprofile)) {
1106             $uri = $oprofile->uri;
1107             return false;
1108         }
1109         return true;
1110     }
1111
1112     function onStartUserGroupHomeUrl($group, &$url)
1113     {
1114         return $this->onStartUserGroupPermalink($group, $url);
1115     }
1116
1117     function onStartUserGroupPermalink($group, &$url)
1118     {
1119         $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1120         if ($oprofile) {
1121             // @fixme this should probably be in the user_group table
1122             // @fixme this uri not guaranteed to be a profile page
1123             $url = $oprofile->uri;
1124             return false;
1125         }
1126     }
1127
1128     function onStartShowSubscriptionsContent($action)
1129     {
1130         $this->showEntityRemoteSubscribe($action);
1131
1132         return true;
1133     }
1134
1135     function onStartShowUserGroupsContent($action)
1136     {
1137         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1138
1139         return true;
1140     }
1141
1142     function onEndShowSubscriptionsMiniList($action)
1143     {
1144         $this->showEntityRemoteSubscribe($action);
1145
1146         return true;
1147     }
1148
1149     function onEndShowGroupsMiniList($action)
1150     {
1151         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1152
1153         return true;
1154     }
1155
1156     function showEntityRemoteSubscribe($action, $target='ostatussub')
1157     {
1158         $user = common_current_user();
1159         if ($user && ($user->id == $action->profile->id)) {
1160             $action->elementStart('div', 'entity_actions');
1161             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1162                                              'class' => 'entity_subscribe'));
1163             $action->element('a', array('href' => common_local_url($target),
1164                                         'class' => 'entity_remote_subscribe'),
1165                                 // TRANS: Link text for link to remote subscribe.
1166                                 _m('Remote'));
1167             $action->elementEnd('p');
1168             $action->elementEnd('div');
1169         }
1170     }
1171
1172     /**
1173      * Ping remote profiles with updates to this profile.
1174      * Salmon pings are queued for background processing.
1175      */
1176     function onEndBroadcastProfile(Profile $profile)
1177     {
1178         $user = User::getKV('id', $profile->id);
1179
1180         // Find foreign accounts I'm subscribed to that support Salmon pings.
1181         //
1182         // @fixme we could run updates through the PuSH feed too,
1183         // in which case we can skip Salmon pings to folks who
1184         // are also subscribed to me.
1185         $sql = "SELECT * FROM ostatus_profile " .
1186                "WHERE profile_id IN " .
1187                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1188                "OR group_id IN " .
1189                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1190         $oprofile = new Ostatus_profile();
1191         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1192
1193         if ($oprofile->N == 0) {
1194             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1195             return true;
1196         }
1197
1198         $act = new Activity();
1199
1200         $act->verb = ActivityVerb::UPDATE_PROFILE;
1201         $act->id   = TagURI::mint('update-profile:%d:%s',
1202                                   $profile->id,
1203                                   common_date_iso8601(time()));
1204         $act->time    = time();
1205         // TRANS: Title for activity.
1206         $act->title   = _m('Profile update');
1207         // TRANS: Ping text for remote profile update through OStatus.
1208         // TRANS: %s is user that updated their profile.
1209         $act->content = sprintf(_m('%s has updated their profile page.'),
1210                                $profile->getBestName());
1211
1212         $act->actor   = ActivityObject::fromProfile($profile);
1213         $act->object  = $act->actor;
1214
1215         while ($oprofile->fetch()) {
1216             $oprofile->notifyDeferred($act, $profile);
1217         }
1218
1219         return true;
1220     }
1221
1222     function onStartProfileListItemActionElements($item, $profile=null)
1223     {
1224         if (!common_logged_in()) {
1225
1226             $profileUser = User::getKV('id', $item->profile->id);
1227
1228             if (!empty($profileUser)) {
1229
1230                 if ($item instanceof Action) {
1231                     $output = $item;
1232                     $profile = $item->profile;
1233                 } else {
1234                     $output = $item->out;
1235                 }
1236
1237                 // Add an OStatus subscribe
1238                 $output->elementStart('li', 'entity_subscribe');
1239                 $url = common_local_url('ostatusinit',
1240                                         array('nickname' => $profileUser->nickname));
1241                 $output->element('a', array('href' => $url,
1242                                             'class' => 'entity_remote_subscribe'),
1243                                   // TRANS: Link text for a user to subscribe to an OStatus user.
1244                                  _m('Subscribe'));
1245                 $output->elementEnd('li');
1246
1247                 $output->elementStart('li', 'entity_tag');
1248                 $url = common_local_url('ostatustag',
1249                                         array('nickname' => $profileUser->nickname));
1250                 $output->element('a', array('href' => $url,
1251                                             'class' => 'entity_remote_tag'),
1252                                   // TRANS: Link text for a user to list an OStatus user.
1253                                  _m('List'));
1254                 $output->elementEnd('li');
1255             }
1256         }
1257
1258         return true;
1259     }
1260
1261     function onPluginVersion(&$versions)
1262     {
1263         $versions[] = array('name' => 'OStatus',
1264                             'version' => STATUSNET_VERSION,
1265                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1266                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1267                             // TRANS: Plugin description.
1268                             'rawdescription' => _m('Follow people across social networks that implement '.
1269                                '<a href="http://ostatus.org/">OStatus</a>.'));
1270
1271         return true;
1272     }
1273
1274     /**
1275      * Utility function to check if the given URI is a canonical group profile
1276      * page, and if so return the ID number.
1277      *
1278      * @param string $url
1279      * @return mixed int or false
1280      */
1281     public static function localGroupFromUrl($url)
1282     {
1283         $group = User_group::getKV('uri', $url);
1284         if ($group) {
1285             $local = Local_group::getKV('group_id', $group->id);
1286             if ($local) {
1287                 return $group->id;
1288             }
1289         } else {
1290             // To find local groups which haven't had their uri fields filled out...
1291             // If the domain has changed since a subscriber got the URI, it'll
1292             // be broken.
1293             $template = common_local_url('groupbyid', array('id' => '31337'));
1294             $template = preg_quote($template, '/');
1295             $template = str_replace('31337', '(\d+)', $template);
1296             if (preg_match("/$template/", $url, $matches)) {
1297                 return intval($matches[1]);
1298             }
1299         }
1300         return false;
1301     }
1302
1303     public function onStartProfileGetAtomFeed($profile, &$feed)
1304     {
1305         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1306
1307         if (empty($oprofile)) {
1308             return true;
1309         }
1310
1311         $feed = $oprofile->feeduri;
1312         return false;
1313     }
1314
1315     function onStartGetProfileFromURI($uri, &$profile)
1316     {
1317         // Don't want to do Web-based discovery on our own server,
1318         // so we check locally first.
1319
1320         $user = User::getKV('uri', $uri);
1321
1322         if (!empty($user)) {
1323             $profile = $user->getProfile();
1324             return false;
1325         }
1326
1327         // Now, check remotely
1328
1329         $oprofile = Ostatus_profile::ensureProfileURI($uri);
1330
1331         if (!empty($oprofile)) {
1332             $profile = $oprofile->localProfile();
1333             return false;
1334         }
1335
1336         // Still not a hit, so give up.
1337
1338         return true;
1339     }
1340
1341     function onEndXrdActionLinks(&$xrd, $user)
1342     {
1343         $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1344                   'href' => common_local_url('ApiTimelineUser',
1345                              array('id' => $user->id,
1346                                    'format' => 'atom')),
1347                   'type' => 'application/atom+xml');
1348
1349                 // Salmon
1350         $salmon_url = common_local_url('usersalmon',
1351                                        array('id' => $user->id));
1352
1353         $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1354                               'href' => $salmon_url);
1355         // XXX : Deprecated - to be removed.
1356         $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1357                               'href' => $salmon_url);
1358
1359         $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1360                               'href' => $salmon_url);
1361
1362         // Get this user's keypair
1363         $magickey = Magicsig::getKV('user_id', $user->id);
1364         if (!$magickey) {
1365             // No keypair yet, let's generate one.
1366             $magickey = new Magicsig();
1367             $magickey->generate($user->id);
1368         }
1369
1370         $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1371                               'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1372
1373         // TODO - finalize where the redirect should go on the publisher
1374         $url = common_local_url('ostatussub') . '?profile={uri}';
1375         $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1376                               'template' => $url );
1377
1378         return true;
1379     }
1380 }