3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
21 * @package OStatusPlugin
22 * @maintainer Brion Vibber <brion@status.net>
25 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
27 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/');
29 class FeedSubException extends Exception
33 class OStatusPlugin extends Plugin
36 * Hook for RouterInitialized event.
38 * @param Net_URL_Mapper $m path-to-action mapper
39 * @return boolean hook return
41 function onRouterInitialized($m)
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\.\/\:]+'));
58 $m->connect('main/push/hub', array('action' => 'pushhub'));
60 $m->connect('main/push/callback/:feed',
61 array('action' => 'pushcallback'),
62 array('feed' => '[0-9]+'));
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]+'));
75 * Set up queue handlers for outgoing hub pushes
76 * @param QueueManager $qm
77 * @return boolean hook return
79 function onEndInitializeQueueManager(QueueManager $qm)
81 // Outgoing from our internal PuSH hub
82 $qm->connect('hubverify', 'HubVerifyQueueHandler');
83 $qm->connect('hubdistrib', 'HubDistribQueueHandler');
84 $qm->connect('hubout', 'HubOutQueueHandler');
86 // Incoming from a foreign PuSH hub
87 $qm->connect('pushinput', 'PushInputQueueHandler');
92 * Put saved notices into the queue for pubsub distribution.
94 function onStartEnqueueNotice($notice, &$transports)
96 $transports[] = 'hubdistrib';
101 * Set up a PuSH hub link to our internal link for canonical timeline
102 * Atom feeds for users and groups.
104 function onStartApiAtom($feed)
108 if ($feed instanceof AtomUserNoticeFeed) {
109 $salmonAction = 'usersalmon';
110 $user = $feed->getUser();
112 $profile = $user->getProfile();
113 $feed->setActivitySubject($profile->asActivityNoun('subject'));
114 } else if ($feed instanceof AtomGroupNoticeFeed) {
115 $salmonAction = 'groupsalmon';
116 $group = $feed->getGroup();
118 $feed->setActivitySubject($group->asActivitySubject());
124 $hub = common_config('ostatus', 'hub');
126 // Updates will be handled through our internal PuSH hub.
127 $hub = common_local_url('pushhub');
129 $feed->addLink($hub, array('rel' => 'hub'));
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'));
140 * Automatically load the actions and libraries used by the plugin
142 * @param Class $cls the class
144 * @return boolean hook return
147 function onAutoload($cls)
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];
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";
162 foreach ($files as $file) {
163 if (file_exists($file)) {
172 * Add in an OStatus subscribe button
174 function onStartProfileRemoteSubscribe($output, $profile)
176 $cur = common_current_user();
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'),
187 $output->elementEnd('li');
194 * Check if we've got remote replies to send via Salmon.
196 * @fixme push webfinger lookup & sending to a background queue
197 * @fixme also detect short-form name for remote subscribees where not ambiguous
200 function onEndNoticeSave($notice)
202 $mentioned = $notice->getReplies();
204 foreach ($mentioned as $profile_id) {
206 $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
208 if (!empty($oprofile) && !empty($oprofile->salmonuri)) {
210 common_log(LOG_INFO, "Sending notice '{$notice->uri}' to remote profile '{$oprofile->uri}'.");
212 // FIXME: this needs to go out in a queue handler
214 $xml = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
215 $xml .= $notice->asAtomEntry(true, true);
217 $salmon = new Salmon();
218 $salmon->post($oprofile->salmonuri, $xml);
227 function onEndFindMentions($sender, $text, &$mentions)
229 preg_match_all('/(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)/',
232 PREG_OFFSET_CAPTURE);
234 foreach ($wmatches[1] as $wmatch) {
236 $webfinger = $wmatch[0];
238 $oprofile = Ostatus_profile::ensureWebfinger($webfinger);
240 if (!empty($oprofile)) {
242 $profile = $oprofile->localProfile();
244 $mentions[] = array('mentioned' => array($profile),
245 'text' => $wmatch[0],
246 'position' => $wmatch[1],
247 'url' => $profile->profileurl);
255 * Make sure necessary tables are filled out.
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());
267 function onEndShowStatusNetStyles($action) {
268 $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
272 function onEndShowStatusNetScripts($action) {
273 $action->script(common_path('plugins/OStatus/js/ostatus.js'));
278 * Override the "from ostatus" bit in notice lists to link to the
279 * original post and show the domain it came from.
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
287 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
289 if ($notice->source == 'ostatus') {
290 $bits = parse_url($notice->uri);
291 $domain = $bits['host'];
295 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
301 * Send incoming PuSH feeds for OStatus endpoints in for processing.
303 * @param FeedSub $feedsub
304 * @param DOMDocument $feed
305 * @return mixed hook return code
307 function onStartFeedSubReceive($feedsub, $feed)
309 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
311 $oprofile->processFeed($feed);
313 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
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.
321 * @fixme If something else aborts later, we could end up with a stray
322 * PuSH subscription. This is relatively harmless, though.
324 * @param Profile $subscriber
325 * @param Profile $other
327 * @return hook return code
331 function onStartSubscribe($subscriber, $other)
333 $user = User::staticGet('id', $subscriber->id);
339 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
341 if (empty($oprofile)) {
345 if (!$oprofile->subscribe()) {
346 throw new Exception(_m('Could not set up remote subscription.'));
351 * Having established a remote subscription, send a notification to the
352 * remote OStatus profile's endpoint.
354 * @param Profile $subscriber
355 * @param Profile $other
357 * @return hook return code
361 function onEndSubscribe($subscriber, $other)
363 $user = User::staticGet('id', $subscriber->id);
369 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
371 if (empty($oprofile)) {
375 $act = new Activity();
377 $act->verb = ActivityVerb::FOLLOW;
379 $act->id = TagURI::mint('follow:%d:%d:%s',
382 common_date_iso8601(time()));
385 $act->title = _("Follow");
386 $act->content = sprintf(_("%s is now following %s."),
387 $subscriber->getBestName(),
388 $other->getBestName());
390 $act->actor = ActivityObject::fromProfile($subscriber);
391 $act->object = ActivityObject::fromProfile($other);
393 $oprofile->notifyActivity($act);
399 * Notify remote server and garbage collect unused feeds on unsubscribe.
400 * @fixme send these operations to background queues
403 * @param Profile $other
404 * @return hook return value
406 function onEndUnsubscribe($profile, $other)
408 $user = User::staticGet('id', $profile->id);
414 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
416 if (empty($oprofile)) {
420 // Drop the PuSH subscription if there are no other subscribers.
421 $oprofile->garbageCollect();
423 $act = new Activity();
425 $act->verb = ActivityVerb::UNFOLLOW;
427 $act->id = TagURI::mint('unfollow:%d:%d:%s',
430 common_date_iso8601(time()));
433 $act->title = _("Unfollow");
434 $act->content = sprintf(_("%s stopped following %s."),
435 $profile->getBestName(),
436 $other->getBestName());
438 $act->actor = ActivityObject::fromProfile($profile);
439 $act->object = ActivityObject::fromProfile($other);
441 $oprofile->notifyActivity($act);
447 * When one of our local users tries to join a remote group,
448 * notify the remote server. If the notification is rejected,
451 * @param User_group $group
454 * @return mixed hook return value
457 function onStartJoinGroup($group, $user)
459 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
461 if (!$oprofile->subscribe()) {
462 throw new Exception(_m('Could not set up remote group membership.'));
465 $member = Profile::staticGet($user->id);
467 $act = new Activity();
468 $act->id = TagURI::mint('join:%d:%d:%s',
471 common_date_iso8601(time()));
473 $act->actor = ActivityObject::fromProfile($member);
474 $act->verb = ActivityVerb::JOIN;
475 $act->object = $oprofile->asActivityObject();
478 $act->title = _m("Join");
479 $act->content = sprintf(_m("%s has joined group %s."),
480 $member->getBestName(),
481 $oprofile->getBestName());
483 if ($oprofile->notifyActivity($act)) {
486 $oprofile->garbageCollect();
487 throw new Exception(_m("Failed joining remote group."));
493 * When one of our local users leaves a remote group, notify the remote
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.
501 * @param User_group $group
504 * @return mixed hook return value
507 function onEndLeaveGroup($group, $user)
509 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
511 // Drop the PuSH subscription if there are no other subscribers.
512 $oprofile->garbageCollect();
515 $member = Profile::staticGet($user->id);
517 $act = new Activity();
518 $act->id = TagURI::mint('leave:%d:%d:%s',
521 common_date_iso8601(time()));
523 $act->actor = ActivityObject::fromProfile($member);
524 $act->verb = ActivityVerb::LEAVE;
525 $act->object = $oprofile->asActivityObject();
528 $act->title = _m("Leave");
529 $act->content = sprintf(_m("%s has left group %s."),
530 $member->getBestName(),
531 $oprofile->getBestName());
533 $oprofile->notifyActivity($act);
538 * Notify remote users when their notices get favorited.
540 * @param Profile or User $profile of local user doing the faving
541 * @param Notice $notice being favored
542 * @return hook return value
545 function onEndFavorNotice(Profile $profile, Notice $notice)
547 $user = User::staticGet('id', $profile->id);
553 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
555 if (empty($oprofile)) {
559 $act = new Activity();
561 $act->verb = ActivityVerb::FAVORITE;
562 $act->id = TagURI::mint('favor:%d:%d:%s',
565 common_date_iso8601(time()));
568 $act->title = _("Favor");
569 $act->content = sprintf(_("%s marked notice %s as a favorite."),
570 $profile->getBestName(),
573 $act->actor = ActivityObject::fromProfile($profile);
574 $act->object = ActivityObject::fromNotice($notice);
576 $oprofile->notifyActivity($act);
582 * Notify remote users when their notices get de-favorited.
584 * @param Profile $profile Profile person doing the de-faving
585 * @param Notice $notice Notice being favored
587 * @return hook return value
590 function onEndDisfavorNotice(Profile $profile, Notice $notice)
592 $user = User::staticGet('id', $profile->id);
598 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
600 if (empty($oprofile)) {
604 $act = new Activity();
606 $act->verb = ActivityVerb::UNFAVORITE;
607 $act->id = TagURI::mint('disfavor:%d:%d:%s',
610 common_date_iso8601(time()));
612 $act->title = _("Disfavor");
613 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
614 $profile->getBestName(),
617 $act->actor = ActivityObject::fromProfile($profile);
618 $act->object = ActivityObject::fromNotice($notice);
620 $oprofile->notifyActivity($act);
625 function onStartGetProfileUri($profile, &$uri)
627 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
628 if (!empty($oprofile)) {
629 $uri = $oprofile->uri;
635 function onStartUserGroupHomeUrl($group, &$url)
637 return $this->onStartUserGroupPermalink($group, &$url);
640 function onStartUserGroupPermalink($group, &$url)
642 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
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;
651 function onStartShowSubscriptionsContent($action)
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');