]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
For good measure, don't return autocomplete results when not logged in.
[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/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                                 // TRANS: Link description for link to subscribe to a remote user.
225                                 _m('Subscribe'));
226
227             $output->elementEnd('li');
228         }
229
230         return false;
231     }
232
233     function onStartGroupSubscribe($output, $group)
234     {
235         $cur = common_current_user();
236
237         if (empty($cur)) {
238             // Add an OStatus subscribe
239             $url = common_local_url('ostatusinit',
240                                     array('group' => $group->nickname));
241             $output->element('a', array('href' => $url,
242                                         'class' => 'entity_remote_subscribe'),
243                                 // TRANS: Link description for link to join a remote group.
244                                 _m('Join'));
245         }
246
247         return true;
248     }
249
250     /**
251      * Find any explicit remote mentions. Accepted forms:
252      *   Webfinger: @user@example.com
253      *   Profile link: @example.com/mublog/user
254      * @param Profile $sender (os user?)
255      * @param string $text input markup text
256      * @param array &$mention in/out param: set of found mentions
257      * @return boolean hook return value
258      */
259
260     function onEndFindMentions($sender, $text, &$mentions)
261     {
262         $matches = array();
263
264         // Webfinger matches: @user@example.com
265         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
266                        $text,
267                        $wmatches,
268                        PREG_OFFSET_CAPTURE)) {
269             foreach ($wmatches[1] as $wmatch) {
270                 list($target, $pos) = $wmatch;
271                 $this->log(LOG_INFO, "Checking webfinger '$target'");
272                 try {
273                     $oprofile = Ostatus_profile::ensureWebfinger($target);
274                     if ($oprofile && !$oprofile->isGroup()) {
275                         $profile = $oprofile->localProfile();
276                         $matches[$pos] = array('mentioned' => array($profile),
277                                                'text' => $target,
278                                                'position' => $pos,
279                                                'url' => $profile->profileurl);
280                     }
281                 } catch (Exception $e) {
282                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
283                 }
284             }
285         }
286
287         // Profile matches: @example.com/mublog/user
288         if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
289                        $text,
290                        $wmatches,
291                        PREG_OFFSET_CAPTURE)) {
292             foreach ($wmatches[1] as $wmatch) {
293                 list($target, $pos) = $wmatch;
294                 $schemes = array('http', 'https');
295                 foreach ($schemes as $scheme) {
296                     $url = "$scheme://$target";
297                     $this->log(LOG_INFO, "Checking profile address '$url'");
298                     try {
299                         $oprofile = Ostatus_profile::ensureProfileURL($url);
300                         if ($oprofile && !$oprofile->isGroup()) {
301                             $profile = $oprofile->localProfile();
302                             $matches[$pos] = array('mentioned' => array($profile),
303                                                    'text' => $target,
304                                                    'position' => $pos,
305                                                    'url' => $profile->profileurl);
306                             break;
307                         }
308                     } catch (Exception $e) {
309                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
310                     }
311                 }
312             }
313         }
314
315         foreach ($mentions as $i => $other) {
316             // If we share a common prefix with a local user, override it!
317             $pos = $other['position'];
318             if (isset($matches[$pos])) {
319                 $mentions[$i] = $matches[$pos];
320                 unset($matches[$pos]);
321             }
322         }
323         foreach ($matches as $mention) {
324             $mentions[] = $mention;
325         }
326
327         return true;
328     }
329
330     /**
331      * Allow remote profile references to be used in commands:
332      *   sub update@status.net
333      *   whois evan@identi.ca
334      *   reply http://identi.ca/evan hey what's up
335      *
336      * @param Command $command
337      * @param string $arg
338      * @param Profile &$profile
339      * @return hook return code
340      */
341     function onStartCommandGetProfile($command, $arg, &$profile)
342     {
343         $oprofile = $this->pullRemoteProfile($arg);
344         if ($oprofile && !$oprofile->isGroup()) {
345             $profile = $oprofile->localProfile();
346             return false;
347         } else {
348             return true;
349         }
350     }
351
352     /**
353      * Allow remote group references to be used in commands:
354      *   join group+statusnet@identi.ca
355      *   join http://identi.ca/group/statusnet
356      *   drop identi.ca/group/statusnet
357      *
358      * @param Command $command
359      * @param string $arg
360      * @param User_group &$group
361      * @return hook return code
362      */
363     function onStartCommandGetGroup($command, $arg, &$group)
364     {
365         $oprofile = $this->pullRemoteProfile($arg);
366         if ($oprofile && $oprofile->isGroup()) {
367             $group = $oprofile->localGroup();
368             return false;
369         } else {
370             return true;
371         }
372     }
373
374     protected function pullRemoteProfile($arg)
375     {
376         $oprofile = null;
377         if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
378             // webfinger lookup
379             try {
380                 return Ostatus_profile::ensureWebfinger($arg);
381             } catch (Exception $e) {
382                 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
383                                     $arg . ': ' . $e->getMessage());
384             }
385         }
386
387         // Look for profile URLs, with or without scheme:
388         $urls = array();
389         if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
390             $urls[] = $arg;
391         }
392         if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
393             $schemes = array('http', 'https');
394             foreach ($schemes as $scheme) {
395                 $urls[] = "$scheme://$arg";
396             }
397         }
398
399         foreach ($urls as $url) {
400             try {
401                 return Ostatus_profile::ensureProfileURL($url);
402             } catch (Exception $e) {
403                 common_log(LOG_ERR, 'Profile lookup failed for ' .
404                                     $arg . ': ' . $e->getMessage());
405             }
406         }
407         return null;
408     }
409
410     /**
411      * Make sure necessary tables are filled out.
412      */
413     function onCheckSchema() {
414         $schema = Schema::get();
415         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
416         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
417         $schema->ensureTable('feedsub', FeedSub::schemaDef());
418         $schema->ensureTable('hubsub', HubSub::schemaDef());
419         $schema->ensureTable('magicsig', Magicsig::schemaDef());
420         return true;
421     }
422
423     function onEndShowStatusNetStyles($action) {
424         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
425         return true;
426     }
427
428     function onEndShowStatusNetScripts($action) {
429         $action->script('plugins/OStatus/js/ostatus.js');
430         return true;
431     }
432
433     /**
434      * Override the "from ostatus" bit in notice lists to link to the
435      * original post and show the domain it came from.
436      *
437      * @param Notice in $notice
438      * @param string out &$name
439      * @param string out &$url
440      * @param string out &$title
441      * @return mixed hook return code
442      */
443     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
444     {
445         if ($notice->source == 'ostatus') {
446             if ($notice->url) {
447                 $bits = parse_url($notice->url);
448                 $domain = $bits['host'];
449                 if (substr($domain, 0, 4) == 'www.') {
450                     $name = substr($domain, 4);
451                 } else {
452                     $name = $domain;
453                 }
454
455                 $url = $notice->url;
456                 // TRANSLATE: %s is a domain.
457                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
458                 return false;
459             }
460         }
461         return true;
462     }
463
464     /**
465      * Send incoming PuSH feeds for OStatus endpoints in for processing.
466      *
467      * @param FeedSub $feedsub
468      * @param DOMDocument $feed
469      * @return mixed hook return code
470      */
471     function onStartFeedSubReceive($feedsub, $feed)
472     {
473         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
474         if ($oprofile) {
475             $oprofile->processFeed($feed, 'push');
476         } else {
477             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
478         }
479     }
480
481     /**
482      * Tell the FeedSub infrastructure whether we have any active OStatus
483      * usage for the feed; if not it'll be able to garbage-collect the
484      * feed subscription.
485      *
486      * @param FeedSub $feedsub
487      * @param integer $count in/out
488      * @return mixed hook return code
489      */
490     function onFeedSubSubscriberCount($feedsub, &$count)
491     {
492         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
493         if ($oprofile) {
494             $count += $oprofile->subscriberCount();
495         }
496         return true;
497     }
498
499     /**
500      * When about to subscribe to a remote user, start a server-to-server
501      * PuSH subscription if needed. If we can't establish that, abort.
502      *
503      * @fixme If something else aborts later, we could end up with a stray
504      *        PuSH subscription. This is relatively harmless, though.
505      *
506      * @param Profile $subscriber
507      * @param Profile $other
508      *
509      * @return hook return code
510      *
511      * @throws Exception
512      */
513     function onStartSubscribe($subscriber, $other)
514     {
515         $user = User::staticGet('id', $subscriber->id);
516
517         if (empty($user)) {
518             return true;
519         }
520
521         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
522
523         if (empty($oprofile)) {
524             return true;
525         }
526
527         if (!$oprofile->subscribe()) {
528             // TRANS: Exception.
529             throw new Exception(_m('Could not set up remote subscription.'));
530         }
531     }
532
533     /**
534      * Having established a remote subscription, send a notification to the
535      * remote OStatus profile's endpoint.
536      *
537      * @param Profile $subscriber
538      * @param Profile $other
539      *
540      * @return hook return code
541      *
542      * @throws Exception
543      */
544     function onEndSubscribe($subscriber, $other)
545     {
546         $user = User::staticGet('id', $subscriber->id);
547
548         if (empty($user)) {
549             return true;
550         }
551
552         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
553
554         if (empty($oprofile)) {
555             return true;
556         }
557
558         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
559                                            'subscribed' => $other->id));
560
561         $act = $sub->asActivity();
562
563         $oprofile->notifyActivity($act, $subscriber);
564
565         return true;
566     }
567
568     /**
569      * Notify remote server and garbage collect unused feeds on unsubscribe.
570      * @fixme send these operations to background queues
571      *
572      * @param User $user
573      * @param Profile $other
574      * @return hook return value
575      */
576     function onEndUnsubscribe($profile, $other)
577     {
578         $user = User::staticGet('id', $profile->id);
579
580         if (empty($user)) {
581             return true;
582         }
583
584         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
585
586         if (empty($oprofile)) {
587             return true;
588         }
589
590         // Drop the PuSH subscription if there are no other subscribers.
591         $oprofile->garbageCollect();
592
593         $act = new Activity();
594
595         $act->verb = ActivityVerb::UNFOLLOW;
596
597         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
598                                   $profile->id,
599                                   $other->id,
600                                   common_date_iso8601(time()));
601
602         $act->time    = time();
603         $act->title   = _m('Unfollow');
604         // TRANS: Success message for unsubscribe from user attempt through OStatus.
605         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
606         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
607                                $profile->getBestName(),
608                                $other->getBestName());
609
610         $act->actor   = ActivityObject::fromProfile($profile);
611         $act->object  = ActivityObject::fromProfile($other);
612
613         $oprofile->notifyActivity($act, $profile);
614
615         return true;
616     }
617
618     /**
619      * When one of our local users tries to join a remote group,
620      * notify the remote server. If the notification is rejected,
621      * deny the join.
622      *
623      * @param User_group $group
624      * @param User $user
625      *
626      * @return mixed hook return value
627      */
628
629     function onStartJoinGroup($group, $user)
630     {
631         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
632         if ($oprofile) {
633             if (!$oprofile->subscribe()) {
634                 throw new Exception(_m('Could not set up remote group membership.'));
635             }
636
637             // NOTE: we don't use Group_member::asActivity() since that record
638             // has not yet been created.
639
640             $member = Profile::staticGet($user->id);
641
642             $act = new Activity();
643             $act->id = TagURI::mint('join:%d:%d:%s',
644                                     $member->id,
645                                     $group->id,
646                                     common_date_iso8601(time()));
647
648             $act->actor = ActivityObject::fromProfile($member);
649             $act->verb = ActivityVerb::JOIN;
650             $act->object = $oprofile->asActivityObject();
651
652             $act->time = time();
653             $act->title = _m("Join");
654             // TRANS: Success message for subscribe to group attempt through OStatus.
655             // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
656             $act->content = sprintf(_m('%1$s has joined group %2$s.'),
657                                     $member->getBestName(),
658                                     $oprofile->getBestName());
659
660             if ($oprofile->notifyActivity($act, $member)) {
661                 return true;
662             } else {
663                 $oprofile->garbageCollect();
664                 // TRANS: Exception.
665                 throw new Exception(_m("Failed joining remote group."));
666             }
667         }
668     }
669
670     /**
671      * When one of our local users leaves a remote group, notify the remote
672      * server.
673      *
674      * @fixme Might be good to schedule a resend of the leave notification
675      * if it failed due to a transitory error. We've canceled the local
676      * membership already anyway, but if the remote server comes back up
677      * it'll be left with a stray membership record.
678      *
679      * @param User_group $group
680      * @param User $user
681      *
682      * @return mixed hook return value
683      */
684
685     function onEndLeaveGroup($group, $user)
686     {
687         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
688         if ($oprofile) {
689             // Drop the PuSH subscription if there are no other subscribers.
690             $oprofile->garbageCollect();
691
692             $member = Profile::staticGet($user->id);
693
694             $act = new Activity();
695             $act->id = TagURI::mint('leave:%d:%d:%s',
696                                     $member->id,
697                                     $group->id,
698                                     common_date_iso8601(time()));
699
700             $act->actor = ActivityObject::fromProfile($member);
701             $act->verb = ActivityVerb::LEAVE;
702             $act->object = $oprofile->asActivityObject();
703
704             $act->time = time();
705             $act->title = _m("Leave");
706             // TRANS: Success message for unsubscribe from group attempt through OStatus.
707             // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
708             $act->content = sprintf(_m('%1$s has left group %2$s.'),
709                                     $member->getBestName(),
710                                     $oprofile->getBestName());
711
712             $oprofile->notifyActivity($act, $member);
713         }
714     }
715
716     /**
717      * Notify remote users when their notices get favorited.
718      *
719      * @param Profile or User $profile of local user doing the faving
720      * @param Notice $notice being favored
721      * @return hook return value
722      */
723     function onEndFavorNotice(Profile $profile, Notice $notice)
724     {
725         $user = User::staticGet('id', $profile->id);
726
727         if (empty($user)) {
728             return true;
729         }
730
731         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
732
733         if (empty($oprofile)) {
734             return true;
735         }
736
737         $fav = Fave::pkeyGet(array('user_id' => $user->id,
738                                    'notice_id' => $notice->id));
739
740         if (empty($fav)) {
741             // That's weird.
742             return true;
743         }
744
745         $act = $fav->asActivity();
746
747         $oprofile->notifyActivity($act, $profile);
748
749         return true;
750     }
751
752     /**
753      * Notify remote users when their notices get de-favorited.
754      *
755      * @param Profile $profile Profile person doing the de-faving
756      * @param Notice  $notice  Notice being favored
757      *
758      * @return hook return value
759      */
760
761     function onEndDisfavorNotice(Profile $profile, Notice $notice)
762     {
763         $user = User::staticGet('id', $profile->id);
764
765         if (empty($user)) {
766             return true;
767         }
768
769         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
770
771         if (empty($oprofile)) {
772             return true;
773         }
774
775         $act = new Activity();
776
777         $act->verb = ActivityVerb::UNFAVORITE;
778         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
779                                   $profile->id,
780                                   $notice->id,
781                                   common_date_iso8601(time()));
782         $act->time    = time();
783         $act->title   = _m('Disfavor');
784         // TRANS: Success message for remove a favorite notice through OStatus.
785         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
786         $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
787                                $profile->getBestName(),
788                                $notice->uri);
789
790         $act->actor   = ActivityObject::fromProfile($profile);
791         $act->object  = ActivityObject::fromNotice($notice);
792
793         $oprofile->notifyActivity($act, $profile);
794
795         return true;
796     }
797
798     function onStartGetProfileUri($profile, &$uri)
799     {
800         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
801         if (!empty($oprofile)) {
802             $uri = $oprofile->uri;
803             return false;
804         }
805         return true;
806     }
807
808     function onStartUserGroupHomeUrl($group, &$url)
809     {
810         return $this->onStartUserGroupPermalink($group, $url);
811     }
812
813     function onStartUserGroupPermalink($group, &$url)
814     {
815         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
816         if ($oprofile) {
817             // @fixme this should probably be in the user_group table
818             // @fixme this uri not guaranteed to be a profile page
819             $url = $oprofile->uri;
820             return false;
821         }
822     }
823
824     function onStartShowSubscriptionsContent($action)
825     {
826         $this->showEntityRemoteSubscribe($action);
827
828         return true;
829     }
830
831     function onStartShowUserGroupsContent($action)
832     {
833         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
834
835         return true;
836     }
837
838     function onEndShowSubscriptionsMiniList($action)
839     {
840         $this->showEntityRemoteSubscribe($action);
841
842         return true;
843     }
844
845     function onEndShowGroupsMiniList($action)
846     {
847         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
848
849         return true;
850     }
851
852     function showEntityRemoteSubscribe($action, $target='ostatussub')
853     {
854         $user = common_current_user();
855         if ($user && ($user->id == $action->profile->id)) {
856             $action->elementStart('div', 'entity_actions');
857             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
858                                              'class' => 'entity_subscribe'));
859             $action->element('a', array('href' => common_local_url($target),
860                                         'class' => 'entity_remote_subscribe'),
861                                 // TRANS: Link text for link to remote subscribe.
862                                 _m('Remote'));
863             $action->elementEnd('p');
864             $action->elementEnd('div');
865         }
866     }
867
868     /**
869      * Ping remote profiles with updates to this profile.
870      * Salmon pings are queued for background processing.
871      */
872     function onEndBroadcastProfile(Profile $profile)
873     {
874         $user = User::staticGet('id', $profile->id);
875
876         // Find foreign accounts I'm subscribed to that support Salmon pings.
877         //
878         // @fixme we could run updates through the PuSH feed too,
879         // in which case we can skip Salmon pings to folks who
880         // are also subscribed to me.
881         $sql = "SELECT * FROM ostatus_profile " .
882                "WHERE profile_id IN " .
883                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
884                "OR group_id IN " .
885                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
886         $oprofile = new Ostatus_profile();
887         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
888
889         if ($oprofile->N == 0) {
890             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
891             return true;
892         }
893
894         $act = new Activity();
895
896         $act->verb = ActivityVerb::UPDATE_PROFILE;
897         $act->id   = TagURI::mint('update-profile:%d:%s',
898                                   $profile->id,
899                                   common_date_iso8601(time()));
900         $act->time    = time();
901         // TRANS: Title for activity.
902         $act->title   = _m("Profile update");
903         // TRANS: Ping text for remote profile update through OStatus.
904         // TRANS: %s is user that updated their profile.
905         $act->content = sprintf(_m("%s has updated their profile page."),
906                                $profile->getBestName());
907
908         $act->actor   = ActivityObject::fromProfile($profile);
909         $act->object  = $act->actor;
910
911         while ($oprofile->fetch()) {
912             $oprofile->notifyDeferred($act, $profile);
913         }
914
915         return true;
916     }
917
918     function onStartProfileListItemActionElements($item)
919     {
920         if (!common_logged_in()) {
921
922             $profileUser = User::staticGet('id', $item->profile->id);
923
924             if (!empty($profileUser)) {
925
926                 $output = $item->out;
927
928                 // Add an OStatus subscribe
929                 $output->elementStart('li', 'entity_subscribe');
930                 $url = common_local_url('ostatusinit',
931                                         array('nickname' => $profileUser->nickname));
932                 $output->element('a', array('href' => $url,
933                                             'class' => 'entity_remote_subscribe'),
934                                   // TRANS: Link text for a user to subscribe to an OStatus user.
935                                  _m('Subscribe'));
936                 $output->elementEnd('li');
937             }
938         }
939
940         return true;
941     }
942
943     function onPluginVersion(&$versions)
944     {
945         $versions[] = array('name' => 'OStatus',
946                             'version' => STATUSNET_VERSION,
947                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
948                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
949                             // TRANS: Plugin description.
950                             'rawdescription' => _m('Follow people across social networks that implement '.
951                                '<a href="http://ostatus.org/">OStatus</a>.'));
952
953         return true;
954     }
955
956     /**
957      * Utility function to check if the given URI is a canonical group profile
958      * page, and if so return the ID number.
959      *
960      * @param string $url
961      * @return mixed int or false
962      */
963     public static function localGroupFromUrl($url)
964     {
965         $group = User_group::staticGet('uri', $url);
966         if ($group) {
967             $local = Local_group::staticGet('group_id', $group->id);
968             if ($local) {
969                 return $group->id;
970             }
971         } else {
972             // To find local groups which haven't had their uri fields filled out...
973             // If the domain has changed since a subscriber got the URI, it'll
974             // be broken.
975             $template = common_local_url('groupbyid', array('id' => '31337'));
976             $template = preg_quote($template, '/');
977             $template = str_replace('31337', '(\d+)', $template);
978             if (preg_match("/$template/", $url, $matches)) {
979                 return intval($matches[1]);
980             }
981         }
982         return false;
983     }
984
985     public function onStartProfileGetAtomFeed($profile, &$feed)
986     {
987         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
988
989         if (empty($oprofile)) {
990             return true;
991         }
992
993         $feed = $oprofile->feeduri;
994         return false;
995     }
996
997     function onStartGetProfileFromURI($uri, &$profile) {
998
999         // XXX: do discovery here instead (OStatus_profile::ensureProfileURI($uri))
1000
1001         $oprofile = Ostatus_profile::staticGet('uri', $uri);
1002
1003         if (!empty($oprofile) && !$oprofile->isGroup()) {
1004             $profile = $oprofile->localProfile();
1005             return false;
1006         }
1007
1008         return true;
1009     }
1010
1011     function onEndXrdActionLinks(&$xrd, $user)
1012     {
1013         $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1014                               'href' => common_local_url('ApiTimelineUser',
1015                                                          array('id' => $user->id,
1016                                                                'format' => 'atom')),
1017                               'type' => 'application/atom+xml');
1018         
1019                     // Salmon
1020         $salmon_url = common_local_url('usersalmon',
1021                                        array('id' => $user->id));
1022
1023         $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1024                               'href' => $salmon_url);
1025         // XXX : Deprecated - to be removed.
1026         $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1027                               'href' => $salmon_url);
1028
1029         $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1030                               'href' => $salmon_url);
1031
1032         // Get this user's keypair
1033         $magickey = Magicsig::staticGet('user_id', $user->id);
1034         if (!$magickey) {
1035             // No keypair yet, let's generate one.
1036             $magickey = new Magicsig();
1037             $magickey->generate($user->id);
1038         }
1039
1040         $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1041                               'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1042
1043         // TODO - finalize where the redirect should go on the publisher
1044         $url = common_local_url('ostatussub') . '?profile={uri}';
1045         $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1046                               'template' => $url );
1047         
1048         return true;
1049     }
1050 }