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