]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge remote branch 'gitorious/0.9.x' into 1.0.x
[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/ostatus?nickname=:nickname',
60                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
61         $m->connect('main/ostatus?group=:group',
62                   array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
63         $m->connect('main/ostatussub',
64                     array('action' => 'ostatussub'));
65         $m->connect('main/ostatusgroup',
66                     array('action' => 'ostatusgroup'));
67
68         // PuSH actions
69         $m->connect('main/push/hub', array('action' => 'pushhub'));
70
71         $m->connect('main/push/callback/:feed',
72                     array('action' => 'pushcallback'),
73                     array('feed' => '[0-9]+'));
74
75         // Salmon endpoint
76         $m->connect('main/salmon/user/:id',
77                     array('action' => 'usersalmon'),
78                     array('id' => '[0-9]+'));
79         $m->connect('main/salmon/group/:id',
80                     array('action' => 'groupsalmon'),
81                     array('id' => '[0-9]+'));
82         return true;
83     }
84
85     /**
86      * Set up queue handlers for outgoing hub pushes
87      * @param QueueManager $qm
88      * @return boolean hook return
89      */
90     function onEndInitializeQueueManager(QueueManager $qm)
91     {
92         // Prepare outgoing distributions after notice save.
93         $qm->connect('ostatus', 'OStatusQueueHandler');
94
95         // Outgoing from our internal PuSH hub
96         $qm->connect('hubconf', 'HubConfQueueHandler');
97         $qm->connect('hubprep', 'HubPrepQueueHandler');
98
99         $qm->connect('hubout', 'HubOutQueueHandler');
100
101         // Outgoing Salmon replies (when we don't need a return value)
102         $qm->connect('salmon', 'SalmonQueueHandler');
103
104         // Incoming from a foreign PuSH hub
105         $qm->connect('pushin', 'PushInQueueHandler');
106         return true;
107     }
108
109     /**
110      * Put saved notices into the queue for pubsub distribution.
111      */
112     function onStartEnqueueNotice($notice, &$transports)
113     {
114         if ($notice->isLocal()) {
115             // put our transport first, in case there's any conflict (like OMB)
116             array_unshift($transports, 'ostatus');
117         }
118         return true;
119     }
120
121     /**
122      * Add a link header for LRDD Discovery
123      */
124     function onStartShowHTML($action)
125     {
126         if ($action instanceof ShowstreamAction) {
127             $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
128             $url = common_local_url('userxrd');
129             $url.= '?uri='. $acct;
130
131             header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
132         }
133     }
134
135     /**
136      * Set up a PuSH hub link to our internal link for canonical timeline
137      * Atom feeds for users and groups.
138      */
139     function onStartApiAtom($feed)
140     {
141         $id = null;
142
143         if ($feed instanceof AtomUserNoticeFeed) {
144             $salmonAction = 'usersalmon';
145             $user = $feed->getUser();
146             $id   = $user->id;
147             $profile = $user->getProfile();
148         } else if ($feed instanceof AtomGroupNoticeFeed) {
149             $salmonAction = 'groupsalmon';
150             $group = $feed->getGroup();
151             $id = $group->id;
152         } else {
153             return true;
154         }
155
156         if (!empty($id)) {
157             $hub = common_config('ostatus', 'hub');
158             if (empty($hub)) {
159                 // Updates will be handled through our internal PuSH hub.
160                 $hub = common_local_url('pushhub');
161             }
162             $feed->addLink($hub, array('rel' => 'hub'));
163
164             // Also, we'll add in the salmon link
165             $salmon = common_local_url($salmonAction, array('id' => $id));
166             $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
167
168             // XXX: these are deprecated
169             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
170             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
171         }
172
173         return true;
174     }
175
176     /**
177      * Automatically load the actions and libraries used by the plugin
178      *
179      * @param Class $cls the class
180      *
181      * @return boolean hook return
182      *
183      */
184     function onAutoload($cls)
185     {
186         $base = dirname(__FILE__);
187         $lower = strtolower($cls);
188         $map = array('activityverb' => 'activity',
189                      'activityobject' => 'activity',
190                      'activityutils' => 'activity');
191         if (isset($map[$lower])) {
192             $lower = $map[$lower];
193         }
194         $files = array("$base/classes/$cls.php",
195                        "$base/lib/$lower.php");
196         if (substr($lower, -6) == 'action') {
197             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
198         }
199         foreach ($files as $file) {
200             if (file_exists($file)) {
201                 include_once $file;
202                 return false;
203             }
204         }
205         return true;
206     }
207
208     /**
209      * Add in an OStatus subscribe button
210      */
211     function onStartProfileRemoteSubscribe($output, $profile)
212     {
213         $cur = common_current_user();
214
215         if (empty($cur)) {
216             // Add an OStatus subscribe
217             $output->elementStart('li', 'entity_subscribe');
218             $url = common_local_url('ostatusinit',
219                                     array('nickname' => $profile->nickname));
220             $output->element('a', array('href' => $url,
221                                         'class' => 'entity_remote_subscribe'),
222                                 // TRANS: Link description for link to subscribe to a remote user.
223                                 _m('Subscribe'));
224
225             $output->elementEnd('li');
226         }
227
228         return false;
229     }
230
231     function onStartGroupSubscribe($output, $group)
232     {
233         $cur = common_current_user();
234
235         if (empty($cur)) {
236             // Add an OStatus subscribe
237             $url = common_local_url('ostatusinit',
238                                     array('group' => $group->nickname));
239             $output->element('a', array('href' => $url,
240                                         'class' => 'entity_remote_subscribe'),
241                                 // TRANS: Link description for link to join a remote group.
242                                 _m('Join'));
243         }
244
245         return true;
246     }
247
248     /**
249      * Find any explicit remote mentions. Accepted forms:
250      *   Webfinger: @user@example.com
251      *   Profile link: @example.com/mublog/user
252      * @param Profile $sender (os user?)
253      * @param string $text input markup text
254      * @param array &$mention in/out param: set of found mentions
255      * @return boolean hook return value
256      */
257
258     function onEndFindMentions($sender, $text, &$mentions)
259     {
260         $matches = array();
261
262         // Webfinger matches: @user@example.com
263         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
264                        $text,
265                        $wmatches,
266                        PREG_OFFSET_CAPTURE)) {
267             foreach ($wmatches[1] as $wmatch) {
268                 list($target, $pos) = $wmatch;
269                 $this->log(LOG_INFO, "Checking webfinger '$target'");
270                 try {
271                     $oprofile = Ostatus_profile::ensureWebfinger($target);
272                     if ($oprofile && !$oprofile->isGroup()) {
273                         $profile = $oprofile->localProfile();
274                         $matches[$pos] = array('mentioned' => array($profile),
275                                                'text' => $target,
276                                                'position' => $pos,
277                                                'url' => $profile->profileurl);
278                     }
279                 } catch (Exception $e) {
280                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
281                 }
282             }
283         }
284
285         // Profile matches: @example.com/mublog/user
286         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
287                        $text,
288                        $wmatches,
289                        PREG_OFFSET_CAPTURE)) {
290             foreach ($wmatches[1] as $wmatch) {
291                 list($target, $pos) = $wmatch;
292                 $schemes = array('http', 'https');
293                 foreach ($schemes as $scheme) {
294                     $url = "$scheme://$target";
295                     $this->log(LOG_INFO, "Checking profile address '$url'");
296                     try {
297                         $oprofile = Ostatus_profile::ensureProfileURL($url);
298                         if ($oprofile && !$oprofile->isGroup()) {
299                             $profile = $oprofile->localProfile();
300                             $matches[$pos] = array('mentioned' => array($profile),
301                                                    'text' => $target,
302                                                    'position' => $pos,
303                                                    'url' => $profile->profileurl);
304                             break;
305                         }
306                     } catch (Exception $e) {
307                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
308                     }
309                 }
310             }
311         }
312
313         foreach ($mentions as $i => $other) {
314             // If we share a common prefix with a local user, override it!
315             $pos = $other['position'];
316             if (isset($matches[$pos])) {
317                 $mentions[$i] = $matches[$pos];
318                 unset($matches[$pos]);
319             }
320         }
321         foreach ($matches as $mention) {
322             $mentions[] = $mention;
323         }
324
325         return true;
326     }
327
328     /**
329      * Allow remote profile references to be used in commands:
330      *   sub update@status.net
331      *   whois evan@identi.ca
332      *   reply http://identi.ca/evan hey what's up
333      *
334      * @param Command $command
335      * @param string $arg
336      * @param Profile &$profile
337      * @return hook return code
338      */
339     function onStartCommandGetProfile($command, $arg, &$profile)
340     {
341         $oprofile = $this->pullRemoteProfile($arg);
342         if ($oprofile && !$oprofile->isGroup()) {
343             $profile = $oprofile->localProfile();
344             return false;
345         } else {
346             return true;
347         }
348     }
349
350     /**
351      * Allow remote group references to be used in commands:
352      *   join group+statusnet@identi.ca
353      *   join http://identi.ca/group/statusnet
354      *   drop identi.ca/group/statusnet
355      *
356      * @param Command $command
357      * @param string $arg
358      * @param User_group &$group
359      * @return hook return code
360      */
361     function onStartCommandGetGroup($command, $arg, &$group)
362     {
363         $oprofile = $this->pullRemoteProfile($arg);
364         if ($oprofile && $oprofile->isGroup()) {
365             $group = $oprofile->localGroup();
366             return false;
367         } else {
368             return true;
369         }
370     }
371
372     protected function pullRemoteProfile($arg)
373     {
374         $oprofile = null;
375         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
376             // webfinger lookup
377             try {
378                 return Ostatus_profile::ensureWebfinger($arg);
379             } catch (Exception $e) {
380                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
381                                     $arg . ': ' . $e->getMessage());
382             }
383         }
384
385         // Look for profile URLs, with or without scheme:
386         $urls = array();
387         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
388             $urls[] = $arg;
389         }
390         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
391             $schemes = array('http', 'https');
392             foreach ($schemes as $scheme) {
393                 $urls[] = "$scheme://$arg";
394             }
395         }
396
397         foreach ($urls as $url) {
398             try {
399                 return Ostatus_profile::ensureProfileURL($url);
400             } catch (Exception $e) {
401                 common_log(LOG_ERR, 'Profile lookup failed for ' .
402                                     $arg . ': ' . $e->getMessage());
403             }
404         }
405         return null;
406     }
407
408     /**
409      * Make sure necessary tables are filled out.
410      */
411     function onCheckSchema() {
412         $schema = Schema::get();
413         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
414         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
415         $schema->ensureTable('feedsub', FeedSub::schemaDef());
416         $schema->ensureTable('hubsub', HubSub::schemaDef());
417         $schema->ensureTable('magicsig', Magicsig::schemaDef());
418         return true;
419     }
420
421     function onEndShowStatusNetStyles($action) {
422         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
423         return true;
424     }
425
426     function onEndShowStatusNetScripts($action) {
427         $action->script('plugins/OStatus/js/ostatus.js');
428         return true;
429     }
430
431     /**
432      * Override the "from ostatus" bit in notice lists to link to the
433      * original post and show the domain it came from.
434      *
435      * @param Notice in $notice
436      * @param string out &$name
437      * @param string out &$url
438      * @param string out &$title
439      * @return mixed hook return code
440      */
441     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
442     {
443         if ($notice->source == 'ostatus') {
444             if ($notice->url) {
445                 $bits = parse_url($notice->url);
446                 $domain = $bits['host'];
447                 if (substr($domain, 0, 4) == 'www.') {
448                     $name = substr($domain, 4);
449                 } else {
450                     $name = $domain;
451                 }
452
453                 $url = $notice->url;
454                 // TRANSLATE: %s is a domain.
455                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
456                 return false;
457             }
458         }
459         return true;
460     }
461
462     /**
463      * Send incoming PuSH feeds for OStatus endpoints in for processing.
464      *
465      * @param FeedSub $feedsub
466      * @param DOMDocument $feed
467      * @return mixed hook return code
468      */
469     function onStartFeedSubReceive($feedsub, $feed)
470     {
471         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
472         if ($oprofile) {
473             $oprofile->processFeed($feed, 'push');
474         } else {
475             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
476         }
477     }
478
479     /**
480      * Tell the FeedSub infrastructure whether we have any active OStatus
481      * usage for the feed; if not it'll be able to garbage-collect the
482      * feed subscription.
483      *
484      * @param FeedSub $feedsub
485      * @param integer $count in/out
486      * @return mixed hook return code
487      */
488     function onFeedSubSubscriberCount($feedsub, &$count)
489     {
490         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
491         if ($oprofile) {
492             $count += $oprofile->subscriberCount();
493         }
494         return true;
495     }
496
497     /**
498      * When about to subscribe to a remote user, start a server-to-server
499      * PuSH subscription if needed. If we can't establish that, abort.
500      *
501      * @fixme If something else aborts later, we could end up with a stray
502      *        PuSH subscription. This is relatively harmless, though.
503      *
504      * @param Profile $subscriber
505      * @param Profile $other
506      *
507      * @return hook return code
508      *
509      * @throws Exception
510      */
511     function onStartSubscribe($subscriber, $other)
512     {
513         $user = User::staticGet('id', $subscriber->id);
514
515         if (empty($user)) {
516             return true;
517         }
518
519         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
520
521         if (empty($oprofile)) {
522             return true;
523         }
524
525         if (!$oprofile->subscribe()) {
526             // TRANS: Exception.
527             throw new Exception(_m('Could not set up remote subscription.'));
528         }
529     }
530
531     /**
532      * Having established a remote subscription, send a notification to the
533      * remote OStatus profile's endpoint.
534      *
535      * @param Profile $subscriber
536      * @param Profile $other
537      *
538      * @return hook return code
539      *
540      * @throws Exception
541      */
542     function onEndSubscribe($subscriber, $other)
543     {
544         $user = User::staticGet('id', $subscriber->id);
545
546         if (empty($user)) {
547             return true;
548         }
549
550         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
551
552         if (empty($oprofile)) {
553             return true;
554         }
555
556         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
557                                            'subscribed' => $other->id));
558
559         $act = $sub->asActivity();
560
561         $oprofile->notifyActivity($act, $subscriber);
562
563         return true;
564     }
565
566     /**
567      * Notify remote server and garbage collect unused feeds on unsubscribe.
568      * @fixme send these operations to background queues
569      *
570      * @param User $user
571      * @param Profile $other
572      * @return hook return value
573      */
574     function onEndUnsubscribe($profile, $other)
575     {
576         $user = User::staticGet('id', $profile->id);
577
578         if (empty($user)) {
579             return true;
580         }
581
582         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
583
584         if (empty($oprofile)) {
585             return true;
586         }
587
588         // Drop the PuSH subscription if there are no other subscribers.
589         $oprofile->garbageCollect();
590
591         $act = new Activity();
592
593         $act->verb = ActivityVerb::UNFOLLOW;
594
595         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
596                                   $profile->id,
597                                   $other->id,
598                                   common_date_iso8601(time()));
599
600         $act->time    = time();
601         $act->title   = _m('Unfollow');
602         // TRANS: Success message for unsubscribe from user attempt through OStatus.
603         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
604         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
605                                $profile->getBestName(),
606                                $other->getBestName());
607
608         $act->actor   = ActivityObject::fromProfile($profile);
609         $act->object  = ActivityObject::fromProfile($other);
610
611         $oprofile->notifyActivity($act, $profile);
612
613         return true;
614     }
615
616     /**
617      * When one of our local users tries to join a remote group,
618      * notify the remote server. If the notification is rejected,
619      * deny the join.
620      *
621      * @param User_group $group
622      * @param User $user
623      *
624      * @return mixed hook return value
625      */
626
627     function onStartJoinGroup($group, $user)
628     {
629         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
630         if ($oprofile) {
631             if (!$oprofile->subscribe()) {
632                 throw new Exception(_m('Could not set up remote group membership.'));
633             }
634
635             // NOTE: we don't use Group_member::asActivity() since that record
636             // has not yet been created.
637
638             $member = Profile::staticGet($user->id);
639
640             $act = new Activity();
641             $act->id = TagURI::mint('join:%d:%d:%s',
642                                     $member->id,
643                                     $group->id,
644                                     common_date_iso8601(time()));
645
646             $act->actor = ActivityObject::fromProfile($member);
647             $act->verb = ActivityVerb::JOIN;
648             $act->object = $oprofile->asActivityObject();
649
650             $act->time = time();
651             $act->title = _m("Join");
652             // TRANS: Success message for subscribe to group attempt through OStatus.
653             // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
654             $act->content = sprintf(_m('%1$s has joined group %2$s.'),
655                                     $member->getBestName(),
656                                     $oprofile->getBestName());
657
658             if ($oprofile->notifyActivity($act, $member)) {
659                 return true;
660             } else {
661                 $oprofile->garbageCollect();
662                 // TRANS: Exception.
663                 throw new Exception(_m("Failed joining remote group."));
664             }
665         }
666     }
667
668     /**
669      * When one of our local users leaves a remote group, notify the remote
670      * server.
671      *
672      * @fixme Might be good to schedule a resend of the leave notification
673      * if it failed due to a transitory error. We've canceled the local
674      * membership already anyway, but if the remote server comes back up
675      * it'll be left with a stray membership record.
676      *
677      * @param User_group $group
678      * @param User $user
679      *
680      * @return mixed hook return value
681      */
682
683     function onEndLeaveGroup($group, $user)
684     {
685         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
686         if ($oprofile) {
687             // Drop the PuSH subscription if there are no other subscribers.
688             $oprofile->garbageCollect();
689
690             $member = Profile::staticGet($user->id);
691
692             $act = new Activity();
693             $act->id = TagURI::mint('leave:%d:%d:%s',
694                                     $member->id,
695                                     $group->id,
696                                     common_date_iso8601(time()));
697
698             $act->actor = ActivityObject::fromProfile($member);
699             $act->verb = ActivityVerb::LEAVE;
700             $act->object = $oprofile->asActivityObject();
701
702             $act->time = time();
703             $act->title = _m("Leave");
704             // TRANS: Success message for unsubscribe from group attempt through OStatus.
705             // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
706             $act->content = sprintf(_m('%1$s has left group %2$s.'),
707                                     $member->getBestName(),
708                                     $oprofile->getBestName());
709
710             $oprofile->notifyActivity($act, $member);
711         }
712     }
713
714     /**
715      * Notify remote users when their notices get favorited.
716      *
717      * @param Profile or User $profile of local user doing the faving
718      * @param Notice $notice being favored
719      * @return hook return value
720      */
721     function onEndFavorNotice(Profile $profile, Notice $notice)
722     {
723         $user = User::staticGet('id', $profile->id);
724
725         if (empty($user)) {
726             return true;
727         }
728
729         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
730
731         if (empty($oprofile)) {
732             return true;
733         }
734
735         $fav = Fave::pkeyGet(array('user_id' => $user->id,
736                                    'notice_id' => $notice->id));
737
738         if (empty($fav)) {
739             // That's weird.
740             return true;
741         }
742
743         $act = $fav->asActivity();
744
745         $oprofile->notifyActivity($act, $profile);
746
747         return true;
748     }
749
750     /**
751      * Notify remote users when their notices get de-favorited.
752      *
753      * @param Profile $profile Profile person doing the de-faving
754      * @param Notice  $notice  Notice being favored
755      *
756      * @return hook return value
757      */
758
759     function onEndDisfavorNotice(Profile $profile, Notice $notice)
760     {
761         $user = User::staticGet('id', $profile->id);
762
763         if (empty($user)) {
764             return true;
765         }
766
767         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
768
769         if (empty($oprofile)) {
770             return true;
771         }
772
773         $act = new Activity();
774
775         $act->verb = ActivityVerb::UNFAVORITE;
776         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
777                                   $profile->id,
778                                   $notice->id,
779                                   common_date_iso8601(time()));
780         $act->time    = time();
781         $act->title   = _m('Disfavor');
782         // TRANS: Success message for remove a favorite notice through OStatus.
783         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
784         $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
785                                $profile->getBestName(),
786                                $notice->uri);
787
788         $act->actor   = ActivityObject::fromProfile($profile);
789         $act->object  = ActivityObject::fromNotice($notice);
790
791         $oprofile->notifyActivity($act, $profile);
792
793         return true;
794     }
795
796     function onStartGetProfileUri($profile, &$uri)
797     {
798         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
799         if (!empty($oprofile)) {
800             $uri = $oprofile->uri;
801             return false;
802         }
803         return true;
804     }
805
806     function onStartUserGroupHomeUrl($group, &$url)
807     {
808         return $this->onStartUserGroupPermalink($group, $url);
809     }
810
811     function onStartUserGroupPermalink($group, &$url)
812     {
813         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
814         if ($oprofile) {
815             // @fixme this should probably be in the user_group table
816             // @fixme this uri not guaranteed to be a profile page
817             $url = $oprofile->uri;
818             return false;
819         }
820     }
821
822     function onStartShowSubscriptionsContent($action)
823     {
824         $this->showEntityRemoteSubscribe($action);
825
826         return true;
827     }
828
829     function onStartShowUserGroupsContent($action)
830     {
831         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
832
833         return true;
834     }
835
836     function onEndShowSubscriptionsMiniList($action)
837     {
838         $this->showEntityRemoteSubscribe($action);
839
840         return true;
841     }
842
843     function onEndShowGroupsMiniList($action)
844     {
845         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
846
847         return true;
848     }
849
850     function showEntityRemoteSubscribe($action, $target='ostatussub')
851     {
852         $user = common_current_user();
853         if ($user && ($user->id == $action->profile->id)) {
854             $action->elementStart('div', 'entity_actions');
855             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
856                                              'class' => 'entity_subscribe'));
857             $action->element('a', array('href' => common_local_url($target),
858                                         'class' => 'entity_remote_subscribe'),
859                                 // TRANS: Link text for link to remote subscribe.
860                                 _m('Remote'));
861             $action->elementEnd('p');
862             $action->elementEnd('div');
863         }
864     }
865
866     /**
867      * Ping remote profiles with updates to this profile.
868      * Salmon pings are queued for background processing.
869      */
870     function onEndBroadcastProfile(Profile $profile)
871     {
872         $user = User::staticGet('id', $profile->id);
873
874         // Find foreign accounts I'm subscribed to that support Salmon pings.
875         //
876         // @fixme we could run updates through the PuSH feed too,
877         // in which case we can skip Salmon pings to folks who
878         // are also subscribed to me.
879         $sql = "SELECT * FROM ostatus_profile " .
880                "WHERE profile_id IN " .
881                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
882                "OR group_id IN " .
883                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
884         $oprofile = new Ostatus_profile();
885         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
886
887         if ($oprofile->N == 0) {
888             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
889             return true;
890         }
891
892         $act = new Activity();
893
894         $act->verb = ActivityVerb::UPDATE_PROFILE;
895         $act->id   = TagURI::mint('update-profile:%d:%s',
896                                   $profile->id,
897                                   common_date_iso8601(time()));
898         $act->time    = time();
899         // TRANS: Title for activity.
900         $act->title   = _m("Profile update");
901         // TRANS: Ping text for remote profile update through OStatus.
902         // TRANS: %s is user that updated their profile.
903         $act->content = sprintf(_m("%s has updated their profile page."),
904                                $profile->getBestName());
905
906         $act->actor   = ActivityObject::fromProfile($profile);
907         $act->object  = $act->actor;
908
909         while ($oprofile->fetch()) {
910             $oprofile->notifyDeferred($act, $profile);
911         }
912
913         return true;
914     }
915
916     function onStartProfileListItemActionElements($item)
917     {
918         if (!common_logged_in()) {
919
920             $profileUser = User::staticGet('id', $item->profile->id);
921
922             if (!empty($profileUser)) {
923
924                 $output = $item->out;
925
926                 // Add an OStatus subscribe
927                 $output->elementStart('li', 'entity_subscribe');
928                 $url = common_local_url('ostatusinit',
929                                         array('nickname' => $profileUser->nickname));
930                 $output->element('a', array('href' => $url,
931                                             'class' => 'entity_remote_subscribe'),
932                                   // TRANS: Link text for a user to subscribe to an OStatus user.
933                                  _m('Subscribe'));
934                 $output->elementEnd('li');
935             }
936         }
937
938         return true;
939     }
940
941     function onPluginVersion(&$versions)
942     {
943         $versions[] = array('name' => 'OStatus',
944                             'version' => STATUSNET_VERSION,
945                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
946                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
947                             // TRANS: Plugin description.
948                             'rawdescription' => _m('Follow people across social networks that implement '.
949                                '<a href="http://ostatus.org/">OStatus</a>.'));
950
951         return true;
952     }
953
954     /**
955      * Utility function to check if the given URI is a canonical group profile
956      * page, and if so return the ID number.
957      *
958      * @param string $url
959      * @return mixed int or false
960      */
961     public static function localGroupFromUrl($url)
962     {
963         $group = User_group::staticGet('uri', $url);
964         if ($group) {
965             $local = Local_group::staticGet('group_id', $group->id);
966             if ($local) {
967                 return $group->id;
968             }
969         } else {
970             // To find local groups which haven't had their uri fields filled out...
971             // If the domain has changed since a subscriber got the URI, it'll
972             // be broken.
973             $template = common_local_url('groupbyid', array('id' => '31337'));
974             $template = preg_quote($template, '/');
975             $template = str_replace('31337', '(\d+)', $template);
976             if (preg_match("/$template/", $url, $matches)) {
977                 return intval($matches[1]);
978             }
979         }
980         return false;
981     }
982
983     public function onStartProfileGetAtomFeed($profile, &$feed)
984     {
985         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
986
987         if (empty($oprofile)) {
988             return true;
989         }
990
991         $feed = $oprofile->feeduri;
992         return false;
993     }
994
995     function onStartGetProfileFromURI($uri, &$profile) {
996
997         // XXX: do discovery here instead (OStatus_profile::ensureProfileURI($uri))
998
999         $oprofile = Ostatus_profile::staticGet('uri', $uri);
1000
1001         if (!empty($oprofile) && !$oprofile->isGroup()) {
1002             $profile = $oprofile->localProfile();
1003             return false;
1004         }
1005
1006         return true;
1007     }
1008
1009     function onEndXrdActionLinks(&$xrd, $user)
1010     {
1011         $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1012                               'href' => common_local_url('ApiTimelineUser',
1013                                                          array('id' => $user->id,
1014                                                                'format' => 'atom')),
1015                               'type' => 'application/atom+xml');
1016         
1017                     // Salmon
1018         $salmon_url = common_local_url('usersalmon',
1019                                        array('id' => $user->id));
1020
1021         $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1022                               'href' => $salmon_url);
1023         // XXX : Deprecated - to be removed.
1024         $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1025                               'href' => $salmon_url);
1026
1027         $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1028                               'href' => $salmon_url);
1029
1030         // Get this user's keypair
1031         $magickey = Magicsig::staticGet('user_id', $user->id);
1032         if (!$magickey) {
1033             // No keypair yet, let's generate one.
1034             $magickey = new Magicsig();
1035             $magickey->generate($user->id);
1036         }
1037
1038         $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1039                               'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1040
1041         // TODO - finalize where the redirect should go on the publisher
1042         $url = common_local_url('ostatussub') . '?profile={uri}';
1043         $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1044                               'template' => $url );
1045         
1046         return true;
1047     }
1048 }