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