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