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