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