]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline 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+)!',
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     }
456
457     /**
458      * Send incoming PuSH feeds for OStatus endpoints in for processing.
459      *
460      * @param FeedSub $feedsub
461      * @param DOMDocument $feed
462      * @return mixed hook return code
463      */
464     function onStartFeedSubReceive($feedsub, $feed)
465     {
466         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
467         if ($oprofile) {
468             $oprofile->processFeed($feed, 'push');
469         } else {
470             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
471         }
472     }
473
474     /**
475      * When about to subscribe to a remote user, start a server-to-server
476      * PuSH subscription if needed. If we can't establish that, abort.
477      *
478      * @fixme If something else aborts later, we could end up with a stray
479      *        PuSH subscription. This is relatively harmless, though.
480      *
481      * @param Profile $subscriber
482      * @param Profile $other
483      *
484      * @return hook return code
485      *
486      * @throws Exception
487      */
488     function onStartSubscribe($subscriber, $other)
489     {
490         $user = User::staticGet('id', $subscriber->id);
491
492         if (empty($user)) {
493             return true;
494         }
495
496         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
497
498         if (empty($oprofile)) {
499             return true;
500         }
501
502         if (!$oprofile->subscribe()) {
503             throw new Exception(_m('Could not set up remote subscription.'));
504         }
505     }
506
507     /**
508      * Having established a remote subscription, send a notification to the
509      * remote OStatus profile's endpoint.
510      *
511      * @param Profile $subscriber
512      * @param Profile $other
513      *
514      * @return hook return code
515      *
516      * @throws Exception
517      */
518     function onEndSubscribe($subscriber, $other)
519     {
520         $user = User::staticGet('id', $subscriber->id);
521
522         if (empty($user)) {
523             return true;
524         }
525
526         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
527
528         if (empty($oprofile)) {
529             return true;
530         }
531
532         $act = new Activity();
533
534         $act->verb = ActivityVerb::FOLLOW;
535
536         $act->id   = TagURI::mint('follow:%d:%d:%s',
537                                   $subscriber->id,
538                                   $other->id,
539                                   common_date_iso8601(time()));
540
541         $act->time    = time();
542         $act->title   = _("Follow");
543         $act->content = sprintf(_("%s is now following %s."),
544                                $subscriber->getBestName(),
545                                $other->getBestName());
546
547         $act->actor   = ActivityObject::fromProfile($subscriber);
548         $act->object  = ActivityObject::fromProfile($other);
549
550         $oprofile->notifyActivity($act, $subscriber);
551
552         return true;
553     }
554
555     /**
556      * Notify remote server and garbage collect unused feeds on unsubscribe.
557      * @fixme send these operations to background queues
558      *
559      * @param User $user
560      * @param Profile $other
561      * @return hook return value
562      */
563     function onEndUnsubscribe($profile, $other)
564     {
565         $user = User::staticGet('id', $profile->id);
566
567         if (empty($user)) {
568             return true;
569         }
570
571         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
572
573         if (empty($oprofile)) {
574             return true;
575         }
576
577         // Drop the PuSH subscription if there are no other subscribers.
578         $oprofile->garbageCollect();
579
580         $act = new Activity();
581
582         $act->verb = ActivityVerb::UNFOLLOW;
583
584         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
585                                   $profile->id,
586                                   $other->id,
587                                   common_date_iso8601(time()));
588
589         $act->time    = time();
590         $act->title   = _("Unfollow");
591         $act->content = sprintf(_("%s stopped following %s."),
592                                $profile->getBestName(),
593                                $other->getBestName());
594
595         $act->actor   = ActivityObject::fromProfile($profile);
596         $act->object  = ActivityObject::fromProfile($other);
597
598         $oprofile->notifyActivity($act, $profile);
599
600         return true;
601     }
602
603     /**
604      * When one of our local users tries to join a remote group,
605      * notify the remote server. If the notification is rejected,
606      * deny the join.
607      *
608      * @param User_group $group
609      * @param User $user
610      *
611      * @return mixed hook return value
612      */
613
614     function onStartJoinGroup($group, $user)
615     {
616         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
617         if ($oprofile) {
618             if (!$oprofile->subscribe()) {
619                 throw new Exception(_m('Could not set up remote group membership.'));
620             }
621
622             $member = Profile::staticGet($user->id);
623
624             $act = new Activity();
625             $act->id = TagURI::mint('join:%d:%d:%s',
626                                     $member->id,
627                                     $group->id,
628                                     common_date_iso8601(time()));
629
630             $act->actor = ActivityObject::fromProfile($member);
631             $act->verb = ActivityVerb::JOIN;
632             $act->object = $oprofile->asActivityObject();
633
634             $act->time = time();
635             $act->title = _m("Join");
636             $act->content = sprintf(_m("%s has joined group %s."),
637                                     $member->getBestName(),
638                                     $oprofile->getBestName());
639
640             if ($oprofile->notifyActivity($act, $member)) {
641                 return true;
642             } else {
643                 $oprofile->garbageCollect();
644                 throw new Exception(_m("Failed joining remote group."));
645             }
646         }
647     }
648
649     /**
650      * When one of our local users leaves a remote group, notify the remote
651      * server.
652      *
653      * @fixme Might be good to schedule a resend of the leave notification
654      * if it failed due to a transitory error. We've canceled the local
655      * membership already anyway, but if the remote server comes back up
656      * it'll be left with a stray membership record.
657      *
658      * @param User_group $group
659      * @param User $user
660      *
661      * @return mixed hook return value
662      */
663
664     function onEndLeaveGroup($group, $user)
665     {
666         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
667         if ($oprofile) {
668             // Drop the PuSH subscription if there are no other subscribers.
669             $oprofile->garbageCollect();
670
671             $member = Profile::staticGet($user->id);
672
673             $act = new Activity();
674             $act->id = TagURI::mint('leave:%d:%d:%s',
675                                     $member->id,
676                                     $group->id,
677                                     common_date_iso8601(time()));
678
679             $act->actor = ActivityObject::fromProfile($member);
680             $act->verb = ActivityVerb::LEAVE;
681             $act->object = $oprofile->asActivityObject();
682
683             $act->time = time();
684             $act->title = _m("Leave");
685             $act->content = sprintf(_m("%s has left group %s."),
686                                     $member->getBestName(),
687                                     $oprofile->getBestName());
688
689             $oprofile->notifyActivity($act, $member);
690         }
691     }
692
693     /**
694      * Notify remote users when their notices get favorited.
695      *
696      * @param Profile or User $profile of local user doing the faving
697      * @param Notice $notice being favored
698      * @return hook return value
699      */
700
701     function onEndFavorNotice(Profile $profile, Notice $notice)
702     {
703         $user = User::staticGet('id', $profile->id);
704
705         if (empty($user)) {
706             return true;
707         }
708
709         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
710
711         if (empty($oprofile)) {
712             return true;
713         }
714
715         $act = new Activity();
716
717         $act->verb = ActivityVerb::FAVORITE;
718         $act->id   = TagURI::mint('favor:%d:%d:%s',
719                                   $profile->id,
720                                   $notice->id,
721                                   common_date_iso8601(time()));
722
723         $act->time    = time();
724         $act->title   = _("Favor");
725         $act->content = sprintf(_("%s marked notice %s as a favorite."),
726                                $profile->getBestName(),
727                                $notice->uri);
728
729         $act->actor   = ActivityObject::fromProfile($profile);
730         $act->object  = ActivityObject::fromNotice($notice);
731
732         $oprofile->notifyActivity($act, $profile);
733
734         return true;
735     }
736
737     /**
738      * Notify remote users when their notices get de-favorited.
739      *
740      * @param Profile $profile Profile person doing the de-faving
741      * @param Notice  $notice  Notice being favored
742      *
743      * @return hook return value
744      */
745
746     function onEndDisfavorNotice(Profile $profile, Notice $notice)
747     {
748         $user = User::staticGet('id', $profile->id);
749
750         if (empty($user)) {
751             return true;
752         }
753
754         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
755
756         if (empty($oprofile)) {
757             return true;
758         }
759
760         $act = new Activity();
761
762         $act->verb = ActivityVerb::UNFAVORITE;
763         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
764                                   $profile->id,
765                                   $notice->id,
766                                   common_date_iso8601(time()));
767         $act->time    = time();
768         $act->title   = _("Disfavor");
769         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
770                                $profile->getBestName(),
771                                $notice->uri);
772
773         $act->actor   = ActivityObject::fromProfile($profile);
774         $act->object  = ActivityObject::fromNotice($notice);
775
776         $oprofile->notifyActivity($act, $profile);
777
778         return true;
779     }
780
781     function onStartGetProfileUri($profile, &$uri)
782     {
783         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
784         if (!empty($oprofile)) {
785             $uri = $oprofile->uri;
786             return false;
787         }
788         return true;
789     }
790
791     function onStartUserGroupHomeUrl($group, &$url)
792     {
793         return $this->onStartUserGroupPermalink($group, $url);
794     }
795
796     function onStartUserGroupPermalink($group, &$url)
797     {
798         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
799         if ($oprofile) {
800             // @fixme this should probably be in the user_group table
801             // @fixme this uri not guaranteed to be a profile page
802             $url = $oprofile->uri;
803             return false;
804         }
805     }
806
807     function onStartShowSubscriptionsContent($action)
808     {
809         $this->showEntityRemoteSubscribe($action);
810
811         return true;
812     }
813
814     function onStartShowUserGroupsContent($action)
815     {
816         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
817
818         return true;
819     }
820
821     function onEndShowSubscriptionsMiniList($action)
822     {
823         $this->showEntityRemoteSubscribe($action);
824
825         return true;
826     }
827
828     function onEndShowGroupsMiniList($action)
829     {
830         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
831
832         return true;
833     }
834
835     function showEntityRemoteSubscribe($action, $target='ostatussub')
836     {
837         $user = common_current_user();
838         if ($user && ($user->id == $action->profile->id)) {
839             $action->elementStart('div', 'entity_actions');
840             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
841                                              'class' => 'entity_subscribe'));
842             $action->element('a', array('href' => common_local_url($target),
843                                         'class' => 'entity_remote_subscribe')
844                                 , _m('Remote'));
845             $action->elementEnd('p');
846             $action->elementEnd('div');
847         }
848     }
849
850     /**
851      * Ping remote profiles with updates to this profile.
852      * Salmon pings are queued for background processing.
853      */
854     function onEndBroadcastProfile(Profile $profile)
855     {
856         $user = User::staticGet('id', $profile->id);
857
858         // Find foreign accounts I'm subscribed to that support Salmon pings.
859         //
860         // @fixme we could run updates through the PuSH feed too,
861         // in which case we can skip Salmon pings to folks who
862         // are also subscribed to me.
863         $sql = "SELECT * FROM ostatus_profile " .
864                "WHERE profile_id IN " .
865                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
866                "OR group_id IN " .
867                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
868         $oprofile = new Ostatus_profile();
869         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
870
871         if ($oprofile->N == 0) {
872             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
873             return true;
874         }
875
876         $act = new Activity();
877
878         $act->verb = ActivityVerb::UPDATE_PROFILE;
879         $act->id   = TagURI::mint('update-profile:%d:%s',
880                                   $profile->id,
881                                   common_date_iso8601(time()));
882         $act->time    = time();
883         $act->title   = _m("Profile update");
884         $act->content = sprintf(_m("%s has updated their profile page."),
885                                $profile->getBestName());
886
887         $act->actor   = ActivityObject::fromProfile($profile);
888         $act->object  = $act->actor;
889
890         while ($oprofile->fetch()) {
891             $oprofile->notifyDeferred($act, $profile);
892         }
893
894         return true;
895     }
896
897     function onStartProfileListItemActionElements($item)
898     {
899         if (!common_logged_in()) {
900
901             $profileUser = User::staticGet('id', $item->profile->id);
902
903             if (!empty($profileUser)) {
904
905                 $output = $item->out;
906
907                 // Add an OStatus subscribe
908                 $output->elementStart('li', 'entity_subscribe');
909                 $url = common_local_url('ostatusinit',
910                                         array('nickname' => $profileUser->nickname));
911                 $output->element('a', array('href' => $url,
912                                             'class' => 'entity_remote_subscribe'),
913                                  _m('Subscribe'));
914                 $output->elementEnd('li');
915             }
916         }
917
918         return true;
919     }
920
921     function onPluginVersion(&$versions)
922     {
923         $versions[] = array('name' => 'OStatus',
924                             'version' => STATUSNET_VERSION,
925                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
926                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
927                             'rawdescription' =>
928                             _m('Follow people across social networks that implement '.
929                                '<a href="http://ostatus.org/">OStatus</a>.'));
930
931         return true;
932     }
933
934     /**
935      * Utility function to check if the given URL is a canonical group profile
936      * page, and if so return the ID number.
937      *
938      * @param string $url
939      * @return mixed int or false
940      */
941     public static function localGroupFromUrl($url)
942     {
943         $template = common_local_url('groupbyid', array('id' => '31337'));
944         $template = preg_quote($template, '/');
945         $template = str_replace('31337', '(\d+)', $template);
946         if (preg_match("/$template/", $url, $matches)) {
947             return intval($matches[1]);
948         }
949         return false;
950     }
951 }