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