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