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