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