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