]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
* i18n/L10n update
[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('.well-known/host-meta',
54                     array('action' => 'hostmeta'));
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         $act = new Activity();
561
562         $act->verb = ActivityVerb::FOLLOW;
563
564         $act->id   = TagURI::mint('follow:%d:%d:%s',
565                                   $subscriber->id,
566                                   $other->id,
567                                   common_date_iso8601(time()));
568
569         $act->time    = time();
570         $act->title   = _m("Follow");
571         // TRANS: Success message for subscribe to user attempt through OStatus.
572         // TRANS: %1$s is the subscriber name, %2$s is the subscribed user's name.
573         $act->content = sprintf(_m('%1$s is now following %2$s.'),
574                                $subscriber->getBestName(),
575                                $other->getBestName());
576
577         $act->actor   = ActivityObject::fromProfile($subscriber);
578         $act->object  = ActivityObject::fromProfile($other);
579
580         $oprofile->notifyActivity($act, $subscriber);
581
582         return true;
583     }
584
585     /**
586      * Notify remote server and garbage collect unused feeds on unsubscribe.
587      * @fixme send these operations to background queues
588      *
589      * @param User $user
590      * @param Profile $other
591      * @return hook return value
592      */
593     function onEndUnsubscribe($profile, $other)
594     {
595         $user = User::staticGet('id', $profile->id);
596
597         if (empty($user)) {
598             return true;
599         }
600
601         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
602
603         if (empty($oprofile)) {
604             return true;
605         }
606
607         // Drop the PuSH subscription if there are no other subscribers.
608         $oprofile->garbageCollect();
609
610         $act = new Activity();
611
612         $act->verb = ActivityVerb::UNFOLLOW;
613
614         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
615                                   $profile->id,
616                                   $other->id,
617                                   common_date_iso8601(time()));
618
619         $act->time    = time();
620         $act->title   = _m('Unfollow');
621         // TRANS: Success message for unsubscribe from user attempt through OStatus.
622         // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
623         $act->content = sprintf(_m('%1$s stopped following %2$s.'),
624                                $profile->getBestName(),
625                                $other->getBestName());
626
627         $act->actor   = ActivityObject::fromProfile($profile);
628         $act->object  = ActivityObject::fromProfile($other);
629
630         $oprofile->notifyActivity($act, $profile);
631
632         return true;
633     }
634
635     /**
636      * When one of our local users tries to join a remote group,
637      * notify the remote server. If the notification is rejected,
638      * deny the join.
639      *
640      * @param User_group $group
641      * @param User $user
642      *
643      * @return mixed hook return value
644      */
645
646     function onStartJoinGroup($group, $user)
647     {
648         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
649         if ($oprofile) {
650             if (!$oprofile->subscribe()) {
651                 throw new Exception(_m('Could not set up remote group membership.'));
652             }
653
654             $member = Profile::staticGet($user->id);
655
656             $act = new Activity();
657             $act->id = TagURI::mint('join:%d:%d:%s',
658                                     $member->id,
659                                     $group->id,
660                                     common_date_iso8601(time()));
661
662             $act->actor = ActivityObject::fromProfile($member);
663             $act->verb = ActivityVerb::JOIN;
664             $act->object = $oprofile->asActivityObject();
665
666             $act->time = time();
667             $act->title = _m("Join");
668             // TRANS: Success message for subscribe to group attempt through OStatus.
669             // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
670             $act->content = sprintf(_m("%1$s has joined group %2$s."),
671                                     $member->getBestName(),
672                                     $oprofile->getBestName());
673
674             if ($oprofile->notifyActivity($act, $member)) {
675                 return true;
676             } else {
677                 $oprofile->garbageCollect();
678                 // TRANS: Exception.
679                 throw new Exception(_m("Failed joining remote group."));
680             }
681         }
682     }
683
684     /**
685      * When one of our local users leaves a remote group, notify the remote
686      * server.
687      *
688      * @fixme Might be good to schedule a resend of the leave notification
689      * if it failed due to a transitory error. We've canceled the local
690      * membership already anyway, but if the remote server comes back up
691      * it'll be left with a stray membership record.
692      *
693      * @param User_group $group
694      * @param User $user
695      *
696      * @return mixed hook return value
697      */
698
699     function onEndLeaveGroup($group, $user)
700     {
701         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
702         if ($oprofile) {
703             // Drop the PuSH subscription if there are no other subscribers.
704             $oprofile->garbageCollect();
705
706             $member = Profile::staticGet($user->id);
707
708             $act = new Activity();
709             $act->id = TagURI::mint('leave:%d:%d:%s',
710                                     $member->id,
711                                     $group->id,
712                                     common_date_iso8601(time()));
713
714             $act->actor = ActivityObject::fromProfile($member);
715             $act->verb = ActivityVerb::LEAVE;
716             $act->object = $oprofile->asActivityObject();
717
718             $act->time = time();
719             $act->title = _m("Leave");
720             // TRANS: Success message for unsubscribe from group attempt through OStatus.
721             // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
722             $act->content = sprintf(_m("%1$s has left group %2$s."),
723                                     $member->getBestName(),
724                                     $oprofile->getBestName());
725
726             $oprofile->notifyActivity($act, $member);
727         }
728     }
729
730     /**
731      * Notify remote users when their notices get favorited.
732      *
733      * @param Profile or User $profile of local user doing the faving
734      * @param Notice $notice being favored
735      * @return hook return value
736      */
737     function onEndFavorNotice(Profile $profile, Notice $notice)
738     {
739         $user = User::staticGet('id', $profile->id);
740
741         if (empty($user)) {
742             return true;
743         }
744
745         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
746
747         if (empty($oprofile)) {
748             return true;
749         }
750
751         $act = new Activity();
752
753         $act->verb = ActivityVerb::FAVORITE;
754         $act->id   = TagURI::mint('favor:%d:%d:%s',
755                                   $profile->id,
756                                   $notice->id,
757                                   common_date_iso8601(time()));
758
759         $act->time    = time();
760         $act->title   = _m('Favor');
761         // TRANS: Success message for adding a favorite notice through OStatus.
762         // TRANS: %1$s is the favoring user's name, %2$s is URI to the favored notice.
763         $act->content = sprintf(_m('%1$s marked notice %2$s as a favorite.'),
764                                $profile->getBestName(),
765                                $notice->uri);
766
767         $act->actor   = ActivityObject::fromProfile($profile);
768         $act->object  = ActivityObject::fromNotice($notice);
769
770         $oprofile->notifyActivity($act, $profile);
771
772         return true;
773     }
774
775     /**
776      * Notify remote users when their notices get de-favorited.
777      *
778      * @param Profile $profile Profile person doing the de-faving
779      * @param Notice  $notice  Notice being favored
780      *
781      * @return hook return value
782      */
783
784     function onEndDisfavorNotice(Profile $profile, Notice $notice)
785     {
786         $user = User::staticGet('id', $profile->id);
787
788         if (empty($user)) {
789             return true;
790         }
791
792         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
793
794         if (empty($oprofile)) {
795             return true;
796         }
797
798         $act = new Activity();
799
800         $act->verb = ActivityVerb::UNFAVORITE;
801         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
802                                   $profile->id,
803                                   $notice->id,
804                                   common_date_iso8601(time()));
805         $act->time    = time();
806         $act->title   = _m('Disfavor');
807         // TRANS: Success message for remove a favorite notice through OStatus.
808         // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
809         $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
810                                $profile->getBestName(),
811                                $notice->uri);
812
813         $act->actor   = ActivityObject::fromProfile($profile);
814         $act->object  = ActivityObject::fromNotice($notice);
815
816         $oprofile->notifyActivity($act, $profile);
817
818         return true;
819     }
820
821     function onStartGetProfileUri($profile, &$uri)
822     {
823         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
824         if (!empty($oprofile)) {
825             $uri = $oprofile->uri;
826             return false;
827         }
828         return true;
829     }
830
831     function onStartUserGroupHomeUrl($group, &$url)
832     {
833         return $this->onStartUserGroupPermalink($group, $url);
834     }
835
836     function onStartUserGroupPermalink($group, &$url)
837     {
838         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
839         if ($oprofile) {
840             // @fixme this should probably be in the user_group table
841             // @fixme this uri not guaranteed to be a profile page
842             $url = $oprofile->uri;
843             return false;
844         }
845     }
846
847     function onStartShowSubscriptionsContent($action)
848     {
849         $this->showEntityRemoteSubscribe($action);
850
851         return true;
852     }
853
854     function onStartShowUserGroupsContent($action)
855     {
856         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
857
858         return true;
859     }
860
861     function onEndShowSubscriptionsMiniList($action)
862     {
863         $this->showEntityRemoteSubscribe($action);
864
865         return true;
866     }
867
868     function onEndShowGroupsMiniList($action)
869     {
870         $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
871
872         return true;
873     }
874
875     function showEntityRemoteSubscribe($action, $target='ostatussub')
876     {
877         $user = common_current_user();
878         if ($user && ($user->id == $action->profile->id)) {
879             $action->elementStart('div', 'entity_actions');
880             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
881                                              'class' => 'entity_subscribe'));
882             $action->element('a', array('href' => common_local_url($target),
883                                         'class' => 'entity_remote_subscribe'),
884                                 // TRANS: Link text for link to remote subscribe.
885                                 _m('Remote'));
886             $action->elementEnd('p');
887             $action->elementEnd('div');
888         }
889     }
890
891     /**
892      * Ping remote profiles with updates to this profile.
893      * Salmon pings are queued for background processing.
894      */
895     function onEndBroadcastProfile(Profile $profile)
896     {
897         $user = User::staticGet('id', $profile->id);
898
899         // Find foreign accounts I'm subscribed to that support Salmon pings.
900         //
901         // @fixme we could run updates through the PuSH feed too,
902         // in which case we can skip Salmon pings to folks who
903         // are also subscribed to me.
904         $sql = "SELECT * FROM ostatus_profile " .
905                "WHERE profile_id IN " .
906                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
907                "OR group_id IN " .
908                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
909         $oprofile = new Ostatus_profile();
910         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
911
912         if ($oprofile->N == 0) {
913             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
914             return true;
915         }
916
917         $act = new Activity();
918
919         $act->verb = ActivityVerb::UPDATE_PROFILE;
920         $act->id   = TagURI::mint('update-profile:%d:%s',
921                                   $profile->id,
922                                   common_date_iso8601(time()));
923         $act->time    = time();
924         // TRANS: Title for activity.
925         $act->title   = _m("Profile update");
926         // TRANS: Ping text for remote profile update through OStatus.
927         // TRANS: %s is user that updated their profile.
928         $act->content = sprintf(_m("%s has updated their profile page."),
929                                $profile->getBestName());
930
931         $act->actor   = ActivityObject::fromProfile($profile);
932         $act->object  = $act->actor;
933
934         while ($oprofile->fetch()) {
935             $oprofile->notifyDeferred($act, $profile);
936         }
937
938         return true;
939     }
940
941     function onStartProfileListItemActionElements($item)
942     {
943         if (!common_logged_in()) {
944
945             $profileUser = User::staticGet('id', $item->profile->id);
946
947             if (!empty($profileUser)) {
948
949                 $output = $item->out;
950
951                 // Add an OStatus subscribe
952                 $output->elementStart('li', 'entity_subscribe');
953                 $url = common_local_url('ostatusinit',
954                                         array('nickname' => $profileUser->nickname));
955                 $output->element('a', array('href' => $url,
956                                             'class' => 'entity_remote_subscribe'),
957                                   // TRANS: Link text for a user to subscribe to an OStatus user.
958                                  _m('Subscribe'));
959                 $output->elementEnd('li');
960             }
961         }
962
963         return true;
964     }
965
966     function onPluginVersion(&$versions)
967     {
968         $versions[] = array('name' => 'OStatus',
969                             'version' => STATUSNET_VERSION,
970                             'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
971                             'homepage' => 'http://status.net/wiki/Plugin:OStatus',
972                             // TRANS: Plugin description.
973                             'rawdescription' => _m('Follow people across social networks that implement '.
974                                '<a href="http://ostatus.org/">OStatus</a>.'));
975
976         return true;
977     }
978
979     /**
980      * Utility function to check if the given URL is a canonical group profile
981      * page, and if so return the ID number.
982      *
983      * @param string $url
984      * @return mixed int or false
985      */
986     public static function localGroupFromUrl($url)
987     {
988         $template = common_local_url('groupbyid', array('id' => '31337'));
989         $template = preg_quote($template, '/');
990         $template = str_replace('31337', '(\d+)', $template);
991         if (preg_match("/$template/", $url, $matches)) {
992             return intval($matches[1]);
993         }
994         return false;
995     }
996
997     public function onStartProfileGetAtomFeed($profile, &$feed)
998     {
999         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1000
1001         if (empty($oprofile)) {
1002             return true;
1003         }
1004
1005         $feed = $oprofile->feeduri;
1006         return false;
1007     }
1008
1009     function onStartGetProfileFromURI($uri, &$profile) {
1010
1011         // XXX: do discovery here instead (OStatus_profile::ensureProfileURI($uri))
1012
1013         $oprofile = Ostatus_profile::staticGet('uri', $uri);
1014
1015         if (!empty($oprofile) && !$oprofile->isGroup()) {
1016             $profile = $oprofile->localProfile();
1017             return false;
1018         }
1019
1020         return true;
1021     }
1022 }