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