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