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