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