]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.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') && !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 }
32
33 class OStatusPlugin extends Plugin
34 {
35     /**
36      * Hook for RouterInitialized event.
37      *
38      * @param Net_URL_Mapper $m path-to-action mapper
39      * @return boolean hook return
40      */
41     function onRouterInitialized($m)
42     {
43         // Discovery actions
44         $m->connect('.well-known/host-meta',
45                     array('action' => 'hostmeta'));
46         $m->connect('main/xrd',
47                     array('action' => 'xrd'));
48         $m->connect('main/ostatus',
49                     array('action' => 'ostatusinit'));
50         $m->connect('main/ostatus?nickname=:nickname',
51                   array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
52         $m->connect('main/ostatussub',
53                     array('action' => 'ostatussub'));
54         $m->connect('main/ostatussub',
55                     array('action' => 'ostatussub'), array('feed' => '[A-Za-z0-9\.\/\:]+'));
56
57         // PuSH actions
58         $m->connect('main/push/hub', array('action' => 'pushhub'));
59
60         $m->connect('main/push/callback/:feed',
61                     array('action' => 'pushcallback'),
62                     array('feed' => '[0-9]+'));
63
64         // Salmon endpoint
65         $m->connect('main/salmon/user/:id',
66                     array('action' => 'usersalmon'),
67                     array('id' => '[0-9]+'));
68         $m->connect('main/salmon/group/:id',
69                     array('action' => 'groupsalmon'),
70                     array('id' => '[0-9]+'));
71         return true;
72     }
73
74     /**
75      * Set up queue handlers for outgoing hub pushes
76      * @param QueueManager $qm
77      * @return boolean hook return
78      */
79     function onEndInitializeQueueManager(QueueManager $qm)
80     {
81         // Prepare outgoing distributions after notice save.
82         $qm->connect('ostatus', 'OStatusQueueHandler');
83
84         // Outgoing from our internal PuSH hub
85         $qm->connect('hubconf', 'HubConfQueueHandler');
86         $qm->connect('hubout', 'HubOutQueueHandler');
87
88         // Outgoing Salmon replies (when we don't need a return value)
89         $qm->connect('salmon', 'SalmonQueueHandler');
90
91         // Incoming from a foreign PuSH hub
92         $qm->connect('pushin', 'PushInQueueHandler');
93         return true;
94     }
95
96     /**
97      * Put saved notices into the queue for pubsub distribution.
98      */
99     function onStartEnqueueNotice($notice, &$transports)
100     {
101         $transports[] = 'ostatus';
102         return true;
103     }
104
105     /**
106      * Add a link header for LRDD Discovery
107      */
108     function onStartShowHTML($action)
109     {
110         if ($action instanceof ShowstreamAction) {
111             $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
112             $url = common_local_url('xrd');
113             $url.= '?uri='. $acct;
114             
115             header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
116         }
117     }
118     
119     /**
120      * Set up a PuSH hub link to our internal link for canonical timeline
121      * Atom feeds for users and groups.
122      */
123     function onStartApiAtom($feed)
124     {
125         $id = null;
126
127         if ($feed instanceof AtomUserNoticeFeed) {
128             $salmonAction = 'usersalmon';
129             $user = $feed->getUser();
130             $id   = $user->id;
131             $profile = $user->getProfile();
132             $feed->setActivitySubject($profile->asActivityNoun('subject'));
133         } else if ($feed instanceof AtomGroupNoticeFeed) {
134             $salmonAction = 'groupsalmon';
135             $group = $feed->getGroup();
136             $id = $group->id;
137             $feed->setActivitySubject($group->asActivitySubject());
138         } else {
139             return true;
140         }
141
142         if (!empty($id)) {
143             $hub = common_config('ostatus', 'hub');
144             if (empty($hub)) {
145                 // Updates will be handled through our internal PuSH hub.
146                 $hub = common_local_url('pushhub');
147             }
148             $feed->addLink($hub, array('rel' => 'hub'));
149
150             // Also, we'll add in the salmon link
151             $salmon = common_local_url($salmonAction, array('id' => $id));
152             $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
153             $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
154         }
155
156         return true;
157     }
158
159     /**
160      * Automatically load the actions and libraries used by the plugin
161      *
162      * @param Class $cls the class
163      *
164      * @return boolean hook return
165      *
166      */
167     function onAutoload($cls)
168     {
169         $base = dirname(__FILE__);
170         $lower = strtolower($cls);
171         $map = array('activityverb' => 'activity',
172                      'activityobject' => 'activity',
173                      'activityutils' => 'activity');
174         if (isset($map[$lower])) {
175             $lower = $map[$lower];
176         }
177         $files = array("$base/classes/$cls.php",
178                        "$base/lib/$lower.php");
179         if (substr($lower, -6) == 'action') {
180             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
181         }
182         foreach ($files as $file) {
183             if (file_exists($file)) {
184                 include_once $file;
185                 return false;
186             }
187         }
188         return true;
189     }
190
191     /**
192      * Add in an OStatus subscribe button
193      */
194     function onStartProfileRemoteSubscribe($output, $profile)
195     {
196         $cur = common_current_user();
197
198         if (empty($cur)) {
199             // Add an OStatus subscribe
200             $output->elementStart('li', 'entity_subscribe');
201             $url = common_local_url('ostatusinit',
202                                     array('nickname' => $profile->nickname));
203             $output->element('a', array('href' => $url,
204                                         'class' => 'entity_remote_subscribe'),
205                                 _m('Subscribe'));
206
207             $output->elementEnd('li');
208         }
209
210         return false;
211     }
212
213     /**
214      * Check if we've got remote replies to send via Salmon.
215      *
216      * @fixme push webfinger lookup & sending to a background queue
217      * @fixme also detect short-form name for remote subscribees where not ambiguous
218      */
219
220     function onEndNoticeSave($notice)
221     {
222     }
223
224     /**
225      * Find any explicit remote mentions. Accepted forms:
226      *   Webfinger: @user@example.com
227      *   Profile link: @example.com/mublog/user
228      * @param Profile $sender (os user?)
229      * @param string $text input markup text
230      * @param array &$mention in/out param: set of found mentions
231      * @return boolean hook return value
232      */
233
234     function onEndFindMentions($sender, $text, &$mentions)
235     {
236         preg_match_all('!(?:^|\s+)
237                         @(                                # Webfinger:
238                           (?:\w+\.)*\w+                   #   user
239                           @                               #   @
240                           (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ #   domain
241                          |                                # Profile:
242                           (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ #   domain
243                           (?:/\w+)+                       #   /path1(/path2...)
244                          )!x',
245                        $text,
246                        $wmatches,
247                        PREG_OFFSET_CAPTURE);
248
249         foreach ($wmatches[1] as $wmatch) {
250             $target = $wmatch[0];
251             $oprofile = null;
252
253             if (strpos($target, '/') === false) {
254                 $this->log(LOG_INFO, "Checking Webfinger for address '$target'");
255                 try {
256                     $oprofile = Ostatus_profile::ensureWebfinger($target);
257                 } catch (Exception $e) {
258                     $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
259                 }
260             } else {
261                 $schemes = array('https', 'http');
262                 foreach ($schemes as $scheme) {
263                     $url = "$scheme://$target";
264                     $this->log(LOG_INFO, "Checking profile address '$url'");
265                     try {
266                         $oprofile = Ostatus_profile::ensureProfile($url);
267                         if ($oprofile) {
268                             continue;
269                         }
270                     } catch (Exception $e) {
271                         $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
272                     }
273                 }
274             }
275
276             if (empty($oprofile)) {
277                 $this->log(LOG_INFO, "No Ostatus_profile found for address '$target'");
278             } else {
279
280                 $this->log(LOG_INFO, "Ostatus_profile found for address '$target'");
281
282                 if ($oprofile->isGroup()) {
283                     continue;
284                 }
285                 $profile = $oprofile->localProfile();
286
287                 $pos = $wmatch[1];
288                 foreach ($mentions as $i => $other) {
289                     // If we share a common prefix with a local user, override it!
290                     if ($other['position'] == $pos) {
291                         unset($mentions[$i]);
292                     }
293                 }
294                 $mentions[] = array('mentioned' => array($profile),
295                                     'text' => $target,
296                                     'position' => $pos,
297                                     'url' => $profile->profileurl);
298             }
299         }
300
301         return true;
302     }
303
304     /**
305      * Make sure necessary tables are filled out.
306      */
307     function onCheckSchema() {
308         $schema = Schema::get();
309         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
310         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
311         $schema->ensureTable('feedsub', FeedSub::schemaDef());
312         $schema->ensureTable('hubsub', HubSub::schemaDef());
313         $schema->ensureTable('magicsig', Magicsig::schemaDef());
314         return true;
315     }
316
317     function onEndShowStatusNetStyles($action) {
318         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
319         return true;
320     }
321
322     function onEndShowStatusNetScripts($action) {
323         $action->script('plugins/OStatus/js/ostatus.js');
324         return true;
325     }
326
327     /**
328      * Override the "from ostatus" bit in notice lists to link to the
329      * original post and show the domain it came from.
330      *
331      * @param Notice in $notice
332      * @param string out &$name
333      * @param string out &$url
334      * @param string out &$title
335      * @return mixed hook return code
336      */
337     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
338     {
339         if ($notice->source == 'ostatus') {
340             if ($notice->url) {
341                 $bits = parse_url($notice->url);
342                 $domain = $bits['host'];
343                 if (substr($domain, 0, 4) == 'www.') {
344                     $name = substr($domain, 4);
345                 } else {
346                     $name = $domain;
347                 }
348
349                 $url = $notice->url;
350                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
351                 return false;
352             }
353         }
354     }
355
356     /**
357      * Send incoming PuSH feeds for OStatus endpoints in for processing.
358      *
359      * @param FeedSub $feedsub
360      * @param DOMDocument $feed
361      * @return mixed hook return code
362      */
363     function onStartFeedSubReceive($feedsub, $feed)
364     {
365         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
366         if ($oprofile) {
367             $oprofile->processFeed($feed, 'push');
368         } else {
369             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
370         }
371     }
372
373     /**
374      * When about to subscribe to a remote user, start a server-to-server
375      * PuSH subscription if needed. If we can't establish that, abort.
376      *
377      * @fixme If something else aborts later, we could end up with a stray
378      *        PuSH subscription. This is relatively harmless, though.
379      *
380      * @param Profile $subscriber
381      * @param Profile $other
382      *
383      * @return hook return code
384      *
385      * @throws Exception
386      */
387     function onStartSubscribe($subscriber, $other)
388     {
389         $user = User::staticGet('id', $subscriber->id);
390
391         if (empty($user)) {
392             return true;
393         }
394
395         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
396
397         if (empty($oprofile)) {
398             return true;
399         }
400
401         if (!$oprofile->subscribe()) {
402             throw new Exception(_m('Could not set up remote subscription.'));
403         }
404     }
405
406     /**
407      * Having established a remote subscription, send a notification to the
408      * remote OStatus profile's endpoint.
409      *
410      * @param Profile $subscriber
411      * @param Profile $other
412      *
413      * @return hook return code
414      *
415      * @throws Exception
416      */
417     function onEndSubscribe($subscriber, $other)
418     {
419         $user = User::staticGet('id', $subscriber->id);
420
421         if (empty($user)) {
422             return true;
423         }
424
425         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
426
427         if (empty($oprofile)) {
428             return true;
429         }
430
431         $act = new Activity();
432
433         $act->verb = ActivityVerb::FOLLOW;
434
435         $act->id   = TagURI::mint('follow:%d:%d:%s',
436                                   $subscriber->id,
437                                   $other->id,
438                                   common_date_iso8601(time()));
439
440         $act->time    = time();
441         $act->title   = _("Follow");
442         $act->content = sprintf(_("%s is now following %s."),
443                                $subscriber->getBestName(),
444                                $other->getBestName());
445
446         $act->actor   = ActivityObject::fromProfile($subscriber);
447         $act->object  = ActivityObject::fromProfile($other);
448
449         $oprofile->notifyActivity($act, $subscriber);
450
451         return true;
452     }
453
454     /**
455      * Notify remote server and garbage collect unused feeds on unsubscribe.
456      * @fixme send these operations to background queues
457      *
458      * @param User $user
459      * @param Profile $other
460      * @return hook return value
461      */
462     function onEndUnsubscribe($profile, $other)
463     {
464         $user = User::staticGet('id', $profile->id);
465
466         if (empty($user)) {
467             return true;
468         }
469
470         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
471
472         if (empty($oprofile)) {
473             return true;
474         }
475
476         // Drop the PuSH subscription if there are no other subscribers.
477         $oprofile->garbageCollect();
478
479         $act = new Activity();
480
481         $act->verb = ActivityVerb::UNFOLLOW;
482
483         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
484                                   $profile->id,
485                                   $other->id,
486                                   common_date_iso8601(time()));
487
488         $act->time    = time();
489         $act->title   = _("Unfollow");
490         $act->content = sprintf(_("%s stopped following %s."),
491                                $profile->getBestName(),
492                                $other->getBestName());
493
494         $act->actor   = ActivityObject::fromProfile($profile);
495         $act->object  = ActivityObject::fromProfile($other);
496
497         $oprofile->notifyActivity($act, $profile);
498
499         return true;
500     }
501
502     /**
503      * When one of our local users tries to join a remote group,
504      * notify the remote server. If the notification is rejected,
505      * deny the join.
506      *
507      * @param User_group $group
508      * @param User $user
509      *
510      * @return mixed hook return value
511      */
512
513     function onStartJoinGroup($group, $user)
514     {
515         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
516         if ($oprofile) {
517             if (!$oprofile->subscribe()) {
518                 throw new Exception(_m('Could not set up remote group membership.'));
519             }
520
521             $member = Profile::staticGet($user->id);
522
523             $act = new Activity();
524             $act->id = TagURI::mint('join:%d:%d:%s',
525                                     $member->id,
526                                     $group->id,
527                                     common_date_iso8601(time()));
528
529             $act->actor = ActivityObject::fromProfile($member);
530             $act->verb = ActivityVerb::JOIN;
531             $act->object = $oprofile->asActivityObject();
532
533             $act->time = time();
534             $act->title = _m("Join");
535             $act->content = sprintf(_m("%s has joined group %s."),
536                                     $member->getBestName(),
537                                     $oprofile->getBestName());
538
539             if ($oprofile->notifyActivity($act, $member)) {
540                 return true;
541             } else {
542                 $oprofile->garbageCollect();
543                 throw new Exception(_m("Failed joining remote group."));
544             }
545         }
546     }
547
548     /**
549      * When one of our local users leaves a remote group, notify the remote
550      * server.
551      *
552      * @fixme Might be good to schedule a resend of the leave notification
553      * if it failed due to a transitory error. We've canceled the local
554      * membership already anyway, but if the remote server comes back up
555      * it'll be left with a stray membership record.
556      *
557      * @param User_group $group
558      * @param User $user
559      *
560      * @return mixed hook return value
561      */
562
563     function onEndLeaveGroup($group, $user)
564     {
565         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
566         if ($oprofile) {
567             // Drop the PuSH subscription if there are no other subscribers.
568             $oprofile->garbageCollect();
569
570
571             $member = Profile::staticGet($user->id);
572
573             $act = new Activity();
574             $act->id = TagURI::mint('leave:%d:%d:%s',
575                                     $member->id,
576                                     $group->id,
577                                     common_date_iso8601(time()));
578
579             $act->actor = ActivityObject::fromProfile($member);
580             $act->verb = ActivityVerb::LEAVE;
581             $act->object = $oprofile->asActivityObject();
582
583             $act->time = time();
584             $act->title = _m("Leave");
585             $act->content = sprintf(_m("%s has left group %s."),
586                                     $member->getBestName(),
587                                     $oprofile->getBestName());
588
589             $oprofile->notifyActivity($act, $member);
590         }
591     }
592
593     /**
594      * Notify remote users when their notices get favorited.
595      *
596      * @param Profile or User $profile of local user doing the faving
597      * @param Notice $notice being favored
598      * @return hook return value
599      */
600
601     function onEndFavorNotice(Profile $profile, Notice $notice)
602     {
603         $user = User::staticGet('id', $profile->id);
604
605         if (empty($user)) {
606             return true;
607         }
608
609         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
610
611         if (empty($oprofile)) {
612             return true;
613         }
614
615         $act = new Activity();
616
617         $act->verb = ActivityVerb::FAVORITE;
618         $act->id   = TagURI::mint('favor:%d:%d:%s',
619                                   $profile->id,
620                                   $notice->id,
621                                   common_date_iso8601(time()));
622
623         $act->time    = time();
624         $act->title   = _("Favor");
625         $act->content = sprintf(_("%s marked notice %s as a favorite."),
626                                $profile->getBestName(),
627                                $notice->uri);
628
629         $act->actor   = ActivityObject::fromProfile($profile);
630         $act->object  = ActivityObject::fromNotice($notice);
631
632         $oprofile->notifyActivity($act, $profile);
633
634         return true;
635     }
636
637     /**
638      * Notify remote users when their notices get de-favorited.
639      *
640      * @param Profile $profile Profile person doing the de-faving
641      * @param Notice  $notice  Notice being favored
642      *
643      * @return hook return value
644      */
645
646     function onEndDisfavorNotice(Profile $profile, Notice $notice)
647     {
648         $user = User::staticGet('id', $profile->id);
649
650         if (empty($user)) {
651             return true;
652         }
653
654         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
655
656         if (empty($oprofile)) {
657             return true;
658         }
659
660         $act = new Activity();
661
662         $act->verb = ActivityVerb::UNFAVORITE;
663         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
664                                   $profile->id,
665                                   $notice->id,
666                                   common_date_iso8601(time()));
667         $act->time    = time();
668         $act->title   = _("Disfavor");
669         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
670                                $profile->getBestName(),
671                                $notice->uri);
672
673         $act->actor   = ActivityObject::fromProfile($profile);
674         $act->object  = ActivityObject::fromNotice($notice);
675
676         $oprofile->notifyActivity($act, $profile);
677
678         return true;
679     }
680
681     function onStartGetProfileUri($profile, &$uri)
682     {
683         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
684         if (!empty($oprofile)) {
685             $uri = $oprofile->uri;
686             return false;
687         }
688         return true;
689     }
690
691     function onStartUserGroupHomeUrl($group, &$url)
692     {
693         return $this->onStartUserGroupPermalink($group, $url);
694     }
695
696     function onStartUserGroupPermalink($group, &$url)
697     {
698         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
699         if ($oprofile) {
700             // @fixme this should probably be in the user_group table
701             // @fixme this uri not guaranteed to be a profile page
702             $url = $oprofile->uri;
703             return false;
704         }
705     }
706
707     function onStartShowSubscriptionsContent($action)
708     {
709         $this->showEntityRemoteSubscribe($action);
710
711         return true;
712     }
713
714     function onStartShowAllContent($action)
715     {
716         $this->showEntityRemoteSubscribe($action);
717
718         return true;
719     }
720
721     function showEntityRemoteSubscribe($action)
722     {
723         $user = common_current_user();
724         if ($user && ($user->id == $action->profile->id)) {
725             $action->elementStart('div', 'entity_actions');
726             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
727                                              'class' => 'entity_subscribe'));
728             $action->element('a', array('href' => common_local_url('ostatussub'),
729                                         'class' => 'entity_remote_subscribe')
730                                 , _m('Subscribe to remote user'));
731             $action->elementEnd('p');
732             $action->elementEnd('div');
733         }
734     }
735
736     /**
737      * Ping remote profiles with updates to this profile.
738      * Salmon pings are queued for background processing.
739      */
740     function onEndBroadcastProfile(Profile $profile)
741     {
742         $user = User::staticGet('id', $profile->id);
743
744         // Find foreign accounts I'm subscribed to that support Salmon pings.
745         //
746         // @fixme we could run updates through the PuSH feed too,
747         // in which case we can skip Salmon pings to folks who
748         // are also subscribed to me.
749         $sql = "SELECT * FROM ostatus_profile " .
750                "WHERE profile_id IN " .
751                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
752                "OR group_id IN " .
753                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
754         $oprofile = new Ostatus_profile();
755         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
756
757         if ($oprofile->N == 0) {
758             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
759             return true;
760         }
761
762         $act = new Activity();
763
764         $act->verb = ActivityVerb::UPDATE_PROFILE;
765         $act->id   = TagURI::mint('update-profile:%d:%s',
766                                   $profile->id,
767                                   common_date_iso8601(time()));
768         $act->time    = time();
769         $act->title   = _m("Profile update");
770         $act->content = sprintf(_m("%s has updated their profile page."),
771                                $profile->getBestName());
772
773         $act->actor   = ActivityObject::fromProfile($profile);
774         $act->object  = $act->actor;
775
776         while ($oprofile->fetch()) {
777             $oprofile->notifyDeferred($act, $profile);
778         }
779
780         return true;
781     }
782 }