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