]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
543944454952cf6e64b07fe6ff6487bb5c870bdc
[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'));
153         }
154
155         return true;
156     }
157
158     /**
159      * Automatically load the actions and libraries used by the plugin
160      *
161      * @param Class $cls the class
162      *
163      * @return boolean hook return
164      *
165      */
166     function onAutoload($cls)
167     {
168         $base = dirname(__FILE__);
169         $lower = strtolower($cls);
170         $map = array('activityverb' => 'activity',
171                      'activityobject' => 'activity',
172                      'activityutils' => 'activity');
173         if (isset($map[$lower])) {
174             $lower = $map[$lower];
175         }
176         $files = array("$base/classes/$cls.php",
177                        "$base/lib/$lower.php");
178         if (substr($lower, -6) == 'action') {
179             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
180         }
181         foreach ($files as $file) {
182             if (file_exists($file)) {
183                 include_once $file;
184                 return false;
185             }
186         }
187         return true;
188     }
189
190     /**
191      * Add in an OStatus subscribe button
192      */
193     function onStartProfileRemoteSubscribe($output, $profile)
194     {
195         $cur = common_current_user();
196
197         if (empty($cur)) {
198             // Add an OStatus subscribe
199             $output->elementStart('li', 'entity_subscribe');
200             $url = common_local_url('ostatusinit',
201                                     array('nickname' => $profile->nickname));
202             $output->element('a', array('href' => $url,
203                                         'class' => 'entity_remote_subscribe'),
204                                 _m('Subscribe'));
205
206             $output->elementEnd('li');
207         }
208
209         return false;
210     }
211
212     /**
213      * Check if we've got remote replies to send via Salmon.
214      *
215      * @fixme push webfinger lookup & sending to a background queue
216      * @fixme also detect short-form name for remote subscribees where not ambiguous
217      */
218
219     function onEndNoticeSave($notice)
220     {
221     }
222
223     /**
224      *
225      */
226
227     function onEndFindMentions($sender, $text, &$mentions)
228     {
229         preg_match_all('/(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)/',
230                        $text,
231                        $wmatches,
232                        PREG_OFFSET_CAPTURE);
233
234         foreach ($wmatches[1] as $wmatch) {
235
236             $webfinger = $wmatch[0];
237
238             $this->log(LOG_INFO, "Checking Webfinger for address '$webfinger'");
239
240             $oprofile = Ostatus_profile::ensureWebfinger($webfinger);
241
242             if (empty($oprofile)) {
243
244                 $this->log(LOG_INFO, "No Ostatus_profile found for address '$webfinger'");
245
246             } else {
247
248                 $this->log(LOG_INFO, "Ostatus_profile found for address '$webfinger'");
249
250                 if ($oprofile->isGroup()) {
251                     continue;
252                 }
253                 $profile = $oprofile->localProfile();
254
255                 $pos = $wmatch[1];
256                 foreach ($mentions as $i => $other) {
257                     // If we share a common prefix with a local user, override it!
258                     if ($other['position'] == $pos) {
259                         unset($mentions[$i]);
260                     }
261                 }
262                 $mentions[] = array('mentioned' => array($profile),
263                                     'text' => $wmatch[0],
264                                     'position' => $pos,
265                                     'url' => $profile->profileurl);
266             }
267         }
268
269         return true;
270     }
271
272     /**
273      * Make sure necessary tables are filled out.
274      */
275     function onCheckSchema() {
276         $schema = Schema::get();
277         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
278         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
279         $schema->ensureTable('feedsub', FeedSub::schemaDef());
280         $schema->ensureTable('hubsub', HubSub::schemaDef());
281         $schema->ensureTable('magicsig', Magicsig::schemaDef());
282         return true;
283     }
284
285     function onEndShowStatusNetStyles($action) {
286         $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
287         return true;
288     }
289
290     function onEndShowStatusNetScripts($action) {
291         $action->script('plugins/OStatus/js/ostatus.js');
292         return true;
293     }
294
295     /**
296      * Override the "from ostatus" bit in notice lists to link to the
297      * original post and show the domain it came from.
298      *
299      * @param Notice in $notice
300      * @param string out &$name
301      * @param string out &$url
302      * @param string out &$title
303      * @return mixed hook return code
304      */
305     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
306     {
307         if ($notice->source == 'ostatus') {
308             if ($notice->url) {
309                 $bits = parse_url($notice->url);
310                 $domain = $bits['host'];
311                 if (substr($domain, 0, 4) == 'www.') {
312                     $name = substr($domain, 4);
313                 } else {
314                     $name = $domain;
315                 }
316
317                 $url = $notice->url;
318                 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
319                 return false;
320             }
321         }
322     }
323
324     /**
325      * Send incoming PuSH feeds for OStatus endpoints in for processing.
326      *
327      * @param FeedSub $feedsub
328      * @param DOMDocument $feed
329      * @return mixed hook return code
330      */
331     function onStartFeedSubReceive($feedsub, $feed)
332     {
333         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
334         if ($oprofile) {
335             $oprofile->processFeed($feed, 'push');
336         } else {
337             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
338         }
339     }
340
341     /**
342      * When about to subscribe to a remote user, start a server-to-server
343      * PuSH subscription if needed. If we can't establish that, abort.
344      *
345      * @fixme If something else aborts later, we could end up with a stray
346      *        PuSH subscription. This is relatively harmless, though.
347      *
348      * @param Profile $subscriber
349      * @param Profile $other
350      *
351      * @return hook return code
352      *
353      * @throws Exception
354      */
355     function onStartSubscribe($subscriber, $other)
356     {
357         $user = User::staticGet('id', $subscriber->id);
358
359         if (empty($user)) {
360             return true;
361         }
362
363         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
364
365         if (empty($oprofile)) {
366             return true;
367         }
368
369         if (!$oprofile->subscribe()) {
370             throw new Exception(_m('Could not set up remote subscription.'));
371         }
372     }
373
374     /**
375      * Having established a remote subscription, send a notification to the
376      * remote OStatus profile's endpoint.
377      *
378      * @param Profile $subscriber
379      * @param Profile $other
380      *
381      * @return hook return code
382      *
383      * @throws Exception
384      */
385     function onEndSubscribe($subscriber, $other)
386     {
387         $user = User::staticGet('id', $subscriber->id);
388
389         if (empty($user)) {
390             return true;
391         }
392
393         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
394
395         if (empty($oprofile)) {
396             return true;
397         }
398
399         $act = new Activity();
400
401         $act->verb = ActivityVerb::FOLLOW;
402
403         $act->id   = TagURI::mint('follow:%d:%d:%s',
404                                   $subscriber->id,
405                                   $other->id,
406                                   common_date_iso8601(time()));
407
408         $act->time    = time();
409         $act->title   = _("Follow");
410         $act->content = sprintf(_("%s is now following %s."),
411                                $subscriber->getBestName(),
412                                $other->getBestName());
413
414         $act->actor   = ActivityObject::fromProfile($subscriber);
415         $act->object  = ActivityObject::fromProfile($other);
416
417         $oprofile->notifyActivity($act);
418
419         return true;
420     }
421
422     /**
423      * Notify remote server and garbage collect unused feeds on unsubscribe.
424      * @fixme send these operations to background queues
425      *
426      * @param User $user
427      * @param Profile $other
428      * @return hook return value
429      */
430     function onEndUnsubscribe($profile, $other)
431     {
432         $user = User::staticGet('id', $profile->id);
433
434         if (empty($user)) {
435             return true;
436         }
437
438         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
439
440         if (empty($oprofile)) {
441             return true;
442         }
443
444         // Drop the PuSH subscription if there are no other subscribers.
445         $oprofile->garbageCollect();
446
447         $act = new Activity();
448
449         $act->verb = ActivityVerb::UNFOLLOW;
450
451         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
452                                   $profile->id,
453                                   $other->id,
454                                   common_date_iso8601(time()));
455
456         $act->time    = time();
457         $act->title   = _("Unfollow");
458         $act->content = sprintf(_("%s stopped following %s."),
459                                $profile->getBestName(),
460                                $other->getBestName());
461
462         $act->actor   = ActivityObject::fromProfile($profile);
463         $act->object  = ActivityObject::fromProfile($other);
464
465         $oprofile->notifyActivity($act);
466
467         return true;
468     }
469
470     /**
471      * When one of our local users tries to join a remote group,
472      * notify the remote server. If the notification is rejected,
473      * deny the join.
474      *
475      * @param User_group $group
476      * @param User $user
477      *
478      * @return mixed hook return value
479      */
480
481     function onStartJoinGroup($group, $user)
482     {
483         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
484         if ($oprofile) {
485             if (!$oprofile->subscribe()) {
486                 throw new Exception(_m('Could not set up remote group membership.'));
487             }
488
489             $member = Profile::staticGet($user->id);
490
491             $act = new Activity();
492             $act->id = TagURI::mint('join:%d:%d:%s',
493                                     $member->id,
494                                     $group->id,
495                                     common_date_iso8601(time()));
496
497             $act->actor = ActivityObject::fromProfile($member);
498             $act->verb = ActivityVerb::JOIN;
499             $act->object = $oprofile->asActivityObject();
500
501             $act->time = time();
502             $act->title = _m("Join");
503             $act->content = sprintf(_m("%s has joined group %s."),
504                                     $member->getBestName(),
505                                     $oprofile->getBestName());
506
507             if ($oprofile->notifyActivity($act)) {
508                 return true;
509             } else {
510                 $oprofile->garbageCollect();
511                 throw new Exception(_m("Failed joining remote group."));
512             }
513         }
514     }
515
516     /**
517      * When one of our local users leaves a remote group, notify the remote
518      * server.
519      *
520      * @fixme Might be good to schedule a resend of the leave notification
521      * if it failed due to a transitory error. We've canceled the local
522      * membership already anyway, but if the remote server comes back up
523      * it'll be left with a stray membership record.
524      *
525      * @param User_group $group
526      * @param User $user
527      *
528      * @return mixed hook return value
529      */
530
531     function onEndLeaveGroup($group, $user)
532     {
533         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
534         if ($oprofile) {
535             // Drop the PuSH subscription if there are no other subscribers.
536             $oprofile->garbageCollect();
537
538
539             $member = Profile::staticGet($user->id);
540
541             $act = new Activity();
542             $act->id = TagURI::mint('leave:%d:%d:%s',
543                                     $member->id,
544                                     $group->id,
545                                     common_date_iso8601(time()));
546
547             $act->actor = ActivityObject::fromProfile($member);
548             $act->verb = ActivityVerb::LEAVE;
549             $act->object = $oprofile->asActivityObject();
550
551             $act->time = time();
552             $act->title = _m("Leave");
553             $act->content = sprintf(_m("%s has left group %s."),
554                                     $member->getBestName(),
555                                     $oprofile->getBestName());
556
557             $oprofile->notifyActivity($act);
558         }
559     }
560
561     /**
562      * Notify remote users when their notices get favorited.
563      *
564      * @param Profile or User $profile of local user doing the faving
565      * @param Notice $notice being favored
566      * @return hook return value
567      */
568
569     function onEndFavorNotice(Profile $profile, Notice $notice)
570     {
571         $user = User::staticGet('id', $profile->id);
572
573         if (empty($user)) {
574             return true;
575         }
576
577         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
578
579         if (empty($oprofile)) {
580             return true;
581         }
582
583         $act = new Activity();
584
585         $act->verb = ActivityVerb::FAVORITE;
586         $act->id   = TagURI::mint('favor:%d:%d:%s',
587                                   $profile->id,
588                                   $notice->id,
589                                   common_date_iso8601(time()));
590
591         $act->time    = time();
592         $act->title   = _("Favor");
593         $act->content = sprintf(_("%s marked notice %s as a favorite."),
594                                $profile->getBestName(),
595                                $notice->uri);
596
597         $act->actor   = ActivityObject::fromProfile($profile);
598         $act->object  = ActivityObject::fromNotice($notice);
599
600         $oprofile->notifyActivity($act);
601
602         return true;
603     }
604
605     /**
606      * Notify remote users when their notices get de-favorited.
607      *
608      * @param Profile $profile Profile person doing the de-faving
609      * @param Notice  $notice  Notice being favored
610      *
611      * @return hook return value
612      */
613
614     function onEndDisfavorNotice(Profile $profile, Notice $notice)
615     {
616         $user = User::staticGet('id', $profile->id);
617
618         if (empty($user)) {
619             return true;
620         }
621
622         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
623
624         if (empty($oprofile)) {
625             return true;
626         }
627
628         $act = new Activity();
629
630         $act->verb = ActivityVerb::UNFAVORITE;
631         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
632                                   $profile->id,
633                                   $notice->id,
634                                   common_date_iso8601(time()));
635         $act->time    = time();
636         $act->title   = _("Disfavor");
637         $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
638                                $profile->getBestName(),
639                                $notice->uri);
640
641         $act->actor   = ActivityObject::fromProfile($profile);
642         $act->object  = ActivityObject::fromNotice($notice);
643
644         $oprofile->notifyActivity($act);
645
646         return true;
647     }
648
649     function onStartGetProfileUri($profile, &$uri)
650     {
651         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
652         if (!empty($oprofile)) {
653             $uri = $oprofile->uri;
654             return false;
655         }
656         return true;
657     }
658
659     function onStartUserGroupHomeUrl($group, &$url)
660     {
661         return $this->onStartUserGroupPermalink($group, $url);
662     }
663
664     function onStartUserGroupPermalink($group, &$url)
665     {
666         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
667         if ($oprofile) {
668             // @fixme this should probably be in the user_group table
669             // @fixme this uri not guaranteed to be a profile page
670             $url = $oprofile->uri;
671             return false;
672         }
673     }
674
675     function onStartShowSubscriptionsContent($action)
676     {
677         $user = common_current_user();
678         if ($user && ($user->id == $action->profile->id)) {
679             $action->elementStart('div', 'entity_actions');
680             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
681                                              'class' => 'entity_subscribe'));
682             $action->element('a', array('href' => common_local_url('ostatussub'),
683                                         'class' => 'entity_remote_subscribe')
684                                 , _m('Subscribe to remote user'));
685             $action->elementEnd('p');
686             $action->elementEnd('div');
687         }
688
689         return true;
690     }
691
692     /**
693      * Ping remote profiles with updates to this profile.
694      * Salmon pings are queued for background processing.
695      */
696     function onEndBroadcastProfile(Profile $profile)
697     {
698         $user = User::staticGet('id', $profile->id);
699
700         // Find foreign accounts I'm subscribed to that support Salmon pings.
701         //
702         // @fixme we could run updates through the PuSH feed too,
703         // in which case we can skip Salmon pings to folks who
704         // are also subscribed to me.
705         $sql = "SELECT * FROM ostatus_profile " .
706                "WHERE profile_id IN " .
707                "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
708                "OR group_id IN " .
709                "(SELECT group_id FROM group_member WHERE profile_id=%d)";
710         $oprofile = new Ostatus_profile();
711         $oprofile->query(sprintf($sql, $profile->id, $profile->id));
712
713         if ($oprofile->N == 0) {
714             common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
715             return true;
716         }
717
718         $act = new Activity();
719
720         $act->verb = ActivityVerb::UPDATE_PROFILE;
721         $act->id   = TagURI::mint('update-profile:%d:%s',
722                                   $profile->id,
723                                   common_date_iso8601(time()));
724         $act->time    = time();
725         $act->title   = _m("Profile update");
726         $act->content = sprintf(_m("%s has updated their profile page."),
727                                $profile->getBestName());
728
729         $act->actor   = ActivityObject::fromProfile($profile);
730         $act->object  = $act->actor;
731
732         while ($oprofile->fetch()) {
733             $oprofile->notifyDeferred($act);
734         }
735
736         return true;
737     }
738 }