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