]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/OStatusPlugin.php
some logging for OStatusPlugin::onStartFindMentions()
[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/webfinger',
47                     array('action' => 'webfinger'));
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         // Outgoing from our internal PuSH hub
82         $qm->connect('hubverify', 'HubVerifyQueueHandler');
83         $qm->connect('hubdistrib', 'HubDistribQueueHandler');
84         $qm->connect('hubout', 'HubOutQueueHandler');
85
86         // Incoming from a foreign PuSH hub
87         $qm->connect('pushinput', 'PushInputQueueHandler');
88         return true;
89     }
90
91     /**
92      * Put saved notices into the queue for pubsub distribution.
93      */
94     function onStartEnqueueNotice($notice, &$transports)
95     {
96         $transports[] = 'hubdistrib';
97         return true;
98     }
99
100     /**
101      * Set up a PuSH hub link to our internal link for canonical timeline
102      * Atom feeds for users and groups.
103      */
104     function onStartApiAtom($feed)
105     {
106         $id = null;
107
108         if ($feed instanceof AtomUserNoticeFeed) {
109             $salmonAction = 'usersalmon';
110             $user = $feed->getUser();
111             $id   = $user->id;
112             $profile = $user->getProfile();
113             $feed->setActivitySubject($profile->asActivityNoun('subject'));
114         } else if ($feed instanceof AtomGroupNoticeFeed) {
115             $salmonAction = 'groupsalmon';
116             $group = $feed->getGroup();
117             $id = $group->id;
118             $feed->setActivitySubject($group->asActivitySubject());
119         } else {
120             return true;
121         }
122
123         if (!empty($id)) {
124             $hub = common_config('ostatus', 'hub');
125             if (empty($hub)) {
126                 // Updates will be handled through our internal PuSH hub.
127                 $hub = common_local_url('pushhub');
128             }
129             $feed->addLink($hub, array('rel' => 'hub'));
130
131             // Also, we'll add in the salmon link
132             $salmon = common_local_url($salmonAction, array('id' => $id));
133             $feed->addLink($salmon, array('rel' => 'salmon'));
134         }
135
136         return true;
137     }
138
139     /**
140      * Automatically load the actions and libraries used by the plugin
141      *
142      * @param Class $cls the class
143      *
144      * @return boolean hook return
145      *
146      */
147     function onAutoload($cls)
148     {
149         $base = dirname(__FILE__);
150         $lower = strtolower($cls);
151         $map = array('activityverb' => 'activity',
152                      'activityobject' => 'activity',
153                      'activityutils' => 'activity');
154         if (isset($map[$lower])) {
155             $lower = $map[$lower];
156         }
157         $files = array("$base/classes/$cls.php",
158                        "$base/lib/$lower.php");
159         if (substr($lower, -6) == 'action') {
160             $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
161         }
162         foreach ($files as $file) {
163             if (file_exists($file)) {
164                 include_once $file;
165                 return false;
166             }
167         }
168         return true;
169     }
170
171     /**
172      * Add in an OStatus subscribe button
173      */
174     function onStartProfileRemoteSubscribe($output, $profile)
175     {
176         $cur = common_current_user();
177
178         if (empty($cur)) {
179             // Add an OStatus subscribe
180             $output->elementStart('li', 'entity_subscribe');
181             $url = common_local_url('ostatusinit',
182                                     array('nickname' => $profile->nickname));
183             $output->element('a', array('href' => $url,
184                                         'class' => 'entity_remote_subscribe'),
185                                 _m('Subscribe'));
186
187             $output->elementEnd('li');
188         }
189
190         return false;
191     }
192
193     /**
194      * Check if we've got remote replies to send via Salmon.
195      *
196      * @fixme push webfinger lookup & sending to a background queue
197      * @fixme also detect short-form name for remote subscribees where not ambiguous
198      */
199
200     function onEndNoticeSave($notice)
201     {
202         $mentioned = $notice->getReplies();
203
204         foreach ($mentioned as $profile_id) {
205
206             $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
207
208             if (!empty($oprofile) && !empty($oprofile->salmonuri)) {
209
210                 common_log(LOG_INFO, "Sending notice '{$notice->uri}' to remote profile '{$oprofile->uri}'.");
211
212                 // FIXME: this needs to go out in a queue handler
213
214                 $xml = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
215                 $xml .= $notice->asAtomEntry(true, true);
216
217                 $salmon = new Salmon();
218                 $salmon->post($oprofile->salmonuri, $xml);
219             }
220         }
221     }
222
223     /**
224      *
225      */
226
227     function onStartFindMentions($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                 $profile = $oprofile->localProfile();
251
252                 $mentions[] = array('mentioned' => array($profile),
253                                     'text' => $wmatch[0],
254                                     'position' => $wmatch[1],
255                                     'url' => $profile->profileurl);
256             }
257         }
258
259         return true;
260     }
261
262     /**
263      * Make sure necessary tables are filled out.
264      */
265     function onCheckSchema() {
266         $schema = Schema::get();
267         $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
268         $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
269         $schema->ensureTable('feedsub', FeedSub::schemaDef());
270         $schema->ensureTable('hubsub', HubSub::schemaDef());
271         $schema->ensureTable('magicsig', Magicsig::schemaDef());
272         return true;
273     }
274
275     function onEndShowStatusNetStyles($action) {
276         $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
277         return true;
278     }
279
280     function onEndShowStatusNetScripts($action) {
281         $action->script(common_path('plugins/OStatus/js/ostatus.js'));
282         return true;
283     }
284
285     /**
286      * Override the "from ostatus" bit in notice lists to link to the
287      * original post and show the domain it came from.
288      *
289      * @param Notice in $notice
290      * @param string out &$name
291      * @param string out &$url
292      * @param string out &$title
293      * @return mixed hook return code
294      */
295     function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
296     {
297         if ($notice->source == 'ostatus') {
298             $bits = parse_url($notice->uri);
299             $domain = $bits['host'];
300
301             $name = $domain;
302             $url = $notice->uri;
303             $title = sprintf(_m("Sent from %s via OStatus"), $domain);
304             return false;
305         }
306     }
307
308     /**
309      * Send incoming PuSH feeds for OStatus endpoints in for processing.
310      *
311      * @param FeedSub $feedsub
312      * @param DOMDocument $feed
313      * @return mixed hook return code
314      */
315     function onStartFeedSubReceive($feedsub, $feed)
316     {
317         $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
318         if ($oprofile) {
319             $oprofile->processFeed($feed);
320         } else {
321             common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
322         }
323     }
324
325     /**
326      * When about to subscribe to a remote user, start a server-to-server
327      * PuSH subscription if needed. If we can't establish that, abort.
328      *
329      * @fixme If something else aborts later, we could end up with a stray
330      *        PuSH subscription. This is relatively harmless, though.
331      *
332      * @param Profile $subscriber
333      * @param Profile $other
334      *
335      * @return hook return code
336      *
337      * @throws Exception
338      */
339     function onStartSubscribe($subscriber, $other)
340     {
341         $user = User::staticGet('id', $subscriber->id);
342
343         if (empty($user)) {
344             return true;
345         }
346
347         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
348
349         if (empty($oprofile)) {
350             return true;
351         }
352
353         if (!$oprofile->subscribe()) {
354             throw new Exception(_m('Could not set up remote subscription.'));
355         }
356     }
357
358     /**
359      * Having established a remote subscription, send a notification to the
360      * remote OStatus profile's endpoint.
361      *
362      * @param Profile $subscriber
363      * @param Profile $other
364      *
365      * @return hook return code
366      *
367      * @throws Exception
368      */
369     function onEndSubscribe($subscriber, $other)
370     {
371         $user = User::staticGet('id', $subscriber->id);
372
373         if (empty($user)) {
374             return true;
375         }
376
377         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
378
379         if (empty($oprofile)) {
380             return true;
381         }
382
383         $act = new Activity();
384
385         $act->verb = ActivityVerb::FOLLOW;
386
387         $act->id   = TagURI::mint('follow:%d:%d:%s',
388                                   $subscriber->id,
389                                   $other->id,
390                                   common_date_iso8601(time()));
391
392         $act->time    = time();
393         $act->title   = _("Follow");
394         $act->content = sprintf(_("%s is now following %s."),
395                                $subscriber->getBestName(),
396                                $other->getBestName());
397
398         $act->actor   = ActivityObject::fromProfile($subscriber);
399         $act->object  = ActivityObject::fromProfile($other);
400
401         $oprofile->notifyActivity($act);
402
403         return true;
404     }
405
406     /**
407      * Notify remote server and garbage collect unused feeds on unsubscribe.
408      * @fixme send these operations to background queues
409      *
410      * @param User $user
411      * @param Profile $other
412      * @return hook return value
413      */
414     function onEndUnsubscribe($profile, $other)
415     {
416         $user = User::staticGet('id', $profile->id);
417
418         if (empty($user)) {
419             return true;
420         }
421
422         $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
423
424         if (empty($oprofile)) {
425             return true;
426         }
427
428         // Drop the PuSH subscription if there are no other subscribers.
429         $oprofile->garbageCollect();
430
431         $act = new Activity();
432
433         $act->verb = ActivityVerb::UNFOLLOW;
434
435         $act->id   = TagURI::mint('unfollow:%d:%d:%s',
436                                   $profile->id,
437                                   $other->id,
438                                   common_date_iso8601(time()));
439
440         $act->time    = time();
441         $act->title   = _("Unfollow");
442         $act->content = sprintf(_("%s stopped following %s."),
443                                $profile->getBestName(),
444                                $other->getBestName());
445
446         $act->actor   = ActivityObject::fromProfile($profile);
447         $act->object  = ActivityObject::fromProfile($other);
448
449         $oprofile->notifyActivity($act);
450
451         return true;
452     }
453
454     /**
455      * When one of our local users tries to join a remote group,
456      * notify the remote server. If the notification is rejected,
457      * deny the join.
458      *
459      * @param User_group $group
460      * @param User $user
461      *
462      * @return mixed hook return value
463      */
464
465     function onStartJoinGroup($group, $user)
466     {
467         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
468         if ($oprofile) {
469             if (!$oprofile->subscribe()) {
470                 throw new Exception(_m('Could not set up remote group membership.'));
471             }
472
473             $member = Profile::staticGet($user->id);
474
475             $act = new Activity();
476             $act->id = TagURI::mint('join:%d:%d:%s',
477                                     $member->id,
478                                     $group->id,
479                                     common_date_iso8601(time()));
480
481             $act->actor = ActivityObject::fromProfile($member);
482             $act->verb = ActivityVerb::JOIN;
483             $act->object = $oprofile->asActivityObject();
484
485             $act->time = time();
486             $act->title = _m("Join");
487             $act->content = sprintf(_m("%s has joined group %s."),
488                                     $member->getBestName(),
489                                     $oprofile->getBestName());
490
491             if ($oprofile->notifyActivity($act)) {
492                 return true;
493             } else {
494                 $oprofile->garbageCollect();
495                 throw new Exception(_m("Failed joining remote group."));
496             }
497         }
498     }
499
500     /**
501      * When one of our local users leaves a remote group, notify the remote
502      * server.
503      *
504      * @fixme Might be good to schedule a resend of the leave notification
505      * if it failed due to a transitory error. We've canceled the local
506      * membership already anyway, but if the remote server comes back up
507      * it'll be left with a stray membership record.
508      *
509      * @param User_group $group
510      * @param User $user
511      *
512      * @return mixed hook return value
513      */
514
515     function onEndLeaveGroup($group, $user)
516     {
517         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
518         if ($oprofile) {
519             // Drop the PuSH subscription if there are no other subscribers.
520
521             $members = $group->getMembers(0, 1);
522             if ($members->N == 0) {
523                 common_log(LOG_INFO, "Unsubscribing from now-unused group feed $oprofile->feeduri");
524                 $oprofile->unsubscribe();
525             }
526
527             $member = Profile::staticGet($user->id);
528
529             $act = new Activity();
530             $act->id = TagURI::mint('leave:%d:%d:%s',
531                                     $member->id,
532                                     $group->id,
533                                     common_date_iso8601(time()));
534
535             $act->actor = ActivityObject::fromProfile($member);
536             $act->verb = ActivityVerb::LEAVE;
537             $act->object = $oprofile->asActivityObject();
538
539             $act->time = time();
540             $act->title = _m("Leave");
541             $act->content = sprintf(_m("%s has left group %s."),
542                                     $member->getBestName(),
543                                     $oprofile->getBestName());
544
545             $oprofile->notifyActivity($act);
546         }
547     }
548
549     /**
550      * Notify remote users when their notices get favorited.
551      *
552      * @param Profile or User $profile of local user doing the faving
553      * @param Notice $notice being favored
554      * @return hook return value
555      */
556
557     function onEndFavorNotice(Profile $profile, Notice $notice)
558     {
559         $user = User::staticGet('id', $profile->id);
560
561         if (empty($user)) {
562             return true;
563         }
564
565         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
566
567         if (empty($oprofile)) {
568             return true;
569         }
570
571         $act = new Activity();
572
573         $act->verb = ActivityVerb::FAVORITE;
574         $act->id   = TagURI::mint('favor:%d:%d:%s',
575                                   $profile->id,
576                                   $notice->id,
577                                   common_date_iso8601(time()));
578
579         $act->time    = time();
580         $act->title   = _("Favor");
581         $act->content = sprintf(_("%s marked notice %s as a favorite."),
582                                $profile->getBestName(),
583                                $notice->uri);
584
585         $act->actor   = ActivityObject::fromProfile($profile);
586         $act->object  = ActivityObject::fromNotice($notice);
587
588         $oprofile->notifyActivity($act);
589
590         return true;
591     }
592
593     /**
594      * Notify remote users when their notices get de-favorited.
595      *
596      * @param Profile $profile Profile person doing the de-faving
597      * @param Notice  $notice  Notice being favored
598      *
599      * @return hook return value
600      */
601
602     function onEndDisfavorNotice(Profile $profile, Notice $notice)
603     {
604         $user = User::staticGet('id', $profile->id);
605
606         if (empty($user)) {
607             return true;
608         }
609
610         $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
611
612         if (empty($oprofile)) {
613             return true;
614         }
615
616         $act = new Activity();
617
618         $act->verb = ActivityVerb::UNFAVORITE;
619         $act->id   = TagURI::mint('disfavor:%d:%d:%s',
620                                   $profile->id,
621                                   $notice->id,
622                                   common_date_iso8601(time()));
623         $act->time    = time();
624         $act->title   = _("Disfavor");
625         $act->content = sprintf(_("%s marked notice %s as no longer 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);
633
634         return true;
635     }
636
637     function onStartGetProfileUri($profile, &$uri)
638     {
639         $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
640         if (!empty($oprofile)) {
641             $uri = $oprofile->uri;
642             return false;
643         }
644         return true;
645     }
646
647     function onStartUserGroupHomeUrl($group, &$url)
648     {
649         return $this->onStartUserGroupPermalink($group, &$url);
650     }
651
652     function onStartUserGroupPermalink($group, &$url)
653     {
654         $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
655         if ($oprofile) {
656             // @fixme this should probably be in the user_group table
657             // @fixme this uri not guaranteed to be a profile page
658             $url = $oprofile->uri;
659             return false;
660         }
661     }
662
663     function onStartShowSubscriptionsContent($action)
664     {
665         $user = common_current_user();
666         if ($user && ($user->id == $action->profile->id)) {
667             $action->elementStart('div', 'entity_actions');
668             $action->elementStart('p', array('id' => 'entity_remote_subscribe',
669                                              'class' => 'entity_subscribe'));
670             $action->element('a', array('href' => common_local_url('ostatussub'),
671                                         'class' => 'entity_remote_subscribe')
672                                 , _m('Subscribe to remote user'));
673             $action->elementEnd('p');
674             $action->elementEnd('div');
675         }
676
677         return true;
678     }
679 }