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