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