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/xrd',
47 array('action' => 'xrd'));
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 // Prepare outgoing distributions after notice save.
82 $qm->connect('ostatus', 'OStatusQueueHandler');
84 // Outgoing from our internal PuSH hub
85 $qm->connect('hubconf', 'HubConfQueueHandler');
86 $qm->connect('hubout', 'HubOutQueueHandler');
88 // Outgoing Salmon replies (when we don't need a return value)
89 $qm->connect('salmon', 'SalmonQueueHandler');
91 // Incoming from a foreign PuSH hub
92 $qm->connect('pushin', 'PushInQueueHandler');
97 * Put saved notices into the queue for pubsub distribution.
99 function onStartEnqueueNotice($notice, &$transports)
101 $transports[] = 'ostatus';
106 * Add a link header for LRDD Discovery
108 function onStartShowHTML($action)
110 if ($action instanceof ShowstreamAction) {
111 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
112 $url = common_local_url('xrd');
113 $url.= '?uri='. $acct;
115 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
120 * Set up a PuSH hub link to our internal link for canonical timeline
121 * Atom feeds for users and groups.
123 function onStartApiAtom($feed)
127 if ($feed instanceof AtomUserNoticeFeed) {
128 $salmonAction = 'usersalmon';
129 $user = $feed->getUser();
131 $profile = $user->getProfile();
132 $feed->setActivitySubject($profile->asActivityNoun('subject'));
133 } else if ($feed instanceof AtomGroupNoticeFeed) {
134 $salmonAction = 'groupsalmon';
135 $group = $feed->getGroup();
137 $feed->setActivitySubject($group->asActivitySubject());
143 $hub = common_config('ostatus', 'hub');
145 // Updates will be handled through our internal PuSH hub.
146 $hub = common_local_url('pushhub');
148 $feed->addLink($hub, array('rel' => 'hub'));
150 // Also, we'll add in the salmon link
151 $salmon = common_local_url($salmonAction, array('id' => $id));
152 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
153 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
160 * Automatically load the actions and libraries used by the plugin
162 * @param Class $cls the class
164 * @return boolean hook return
167 function onAutoload($cls)
169 $base = dirname(__FILE__);
170 $lower = strtolower($cls);
171 $map = array('activityverb' => 'activity',
172 'activityobject' => 'activity',
173 'activityutils' => 'activity');
174 if (isset($map[$lower])) {
175 $lower = $map[$lower];
177 $files = array("$base/classes/$cls.php",
178 "$base/lib/$lower.php");
179 if (substr($lower, -6) == 'action') {
180 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
182 foreach ($files as $file) {
183 if (file_exists($file)) {
192 * Add in an OStatus subscribe button
194 function onStartProfileRemoteSubscribe($output, $profile)
196 $cur = common_current_user();
199 // Add an OStatus subscribe
200 $output->elementStart('li', 'entity_subscribe');
201 $url = common_local_url('ostatusinit',
202 array('nickname' => $profile->nickname));
203 $output->element('a', array('href' => $url,
204 'class' => 'entity_remote_subscribe'),
207 $output->elementEnd('li');
214 * Check if we've got remote replies to send via Salmon.
216 * @fixme push webfinger lookup & sending to a background queue
217 * @fixme also detect short-form name for remote subscribees where not ambiguous
220 function onEndNoticeSave($notice)
225 * Find any explicit remote mentions. Accepted forms:
226 * Webfinger: @user@example.com
227 * Profile link: @example.com/mublog/user
228 * @param Profile $sender (os user?)
229 * @param string $text input markup text
230 * @param array &$mention in/out param: set of found mentions
231 * @return boolean hook return value
234 function onEndFindMentions($sender, $text, &$mentions)
236 preg_match_all('!(?:^|\s+)
240 (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ # domain
242 (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ # domain
243 (?:/\w+)+ # /path1(/path2...)
247 PREG_OFFSET_CAPTURE);
249 foreach ($wmatches[1] as $wmatch) {
250 $target = $wmatch[0];
253 if (strpos($target, '/') === false) {
254 $this->log(LOG_INFO, "Checking Webfinger for address '$target'");
256 $oprofile = Ostatus_profile::ensureWebfinger($target);
257 } catch (Exception $e) {
258 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
261 $schemes = array('https', 'http');
262 foreach ($schemes as $scheme) {
263 $url = "$scheme://$target";
264 $this->log(LOG_INFO, "Checking profile address '$url'");
266 $oprofile = Ostatus_profile::ensureProfile($url);
270 } catch (Exception $e) {
271 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
276 if (empty($oprofile)) {
277 $this->log(LOG_INFO, "No Ostatus_profile found for address '$target'");
280 $this->log(LOG_INFO, "Ostatus_profile found for address '$target'");
282 if ($oprofile->isGroup()) {
285 $profile = $oprofile->localProfile();
288 foreach ($mentions as $i => $other) {
289 // If we share a common prefix with a local user, override it!
290 if ($other['position'] == $pos) {
291 unset($mentions[$i]);
294 $mentions[] = array('mentioned' => array($profile),
297 'url' => $profile->profileurl);
305 * Make sure necessary tables are filled out.
307 function onCheckSchema() {
308 $schema = Schema::get();
309 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
310 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
311 $schema->ensureTable('feedsub', FeedSub::schemaDef());
312 $schema->ensureTable('hubsub', HubSub::schemaDef());
313 $schema->ensureTable('magicsig', Magicsig::schemaDef());
317 function onEndShowStatusNetStyles($action) {
318 $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
322 function onEndShowStatusNetScripts($action) {
323 $action->script(common_path('plugins/OStatus/js/ostatus.js'));
328 * Override the "from ostatus" bit in notice lists to link to the
329 * original post and show the domain it came from.
331 * @param Notice in $notice
332 * @param string out &$name
333 * @param string out &$url
334 * @param string out &$title
335 * @return mixed hook return code
337 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
339 if ($notice->source == 'ostatus') {
341 $bits = parse_url($notice->url);
342 $domain = $bits['host'];
343 if (substr($domain, 0, 4) == 'www.') {
344 $name = substr($domain, 4);
350 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
357 * Send incoming PuSH feeds for OStatus endpoints in for processing.
359 * @param FeedSub $feedsub
360 * @param DOMDocument $feed
361 * @return mixed hook return code
363 function onStartFeedSubReceive($feedsub, $feed)
365 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
367 $oprofile->processFeed($feed, 'push');
369 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
374 * When about to subscribe to a remote user, start a server-to-server
375 * PuSH subscription if needed. If we can't establish that, abort.
377 * @fixme If something else aborts later, we could end up with a stray
378 * PuSH subscription. This is relatively harmless, though.
380 * @param Profile $subscriber
381 * @param Profile $other
383 * @return hook return code
387 function onStartSubscribe($subscriber, $other)
389 $user = User::staticGet('id', $subscriber->id);
395 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
397 if (empty($oprofile)) {
401 if (!$oprofile->subscribe()) {
402 throw new Exception(_m('Could not set up remote subscription.'));
407 * Having established a remote subscription, send a notification to the
408 * remote OStatus profile's endpoint.
410 * @param Profile $subscriber
411 * @param Profile $other
413 * @return hook return code
417 function onEndSubscribe($subscriber, $other)
419 $user = User::staticGet('id', $subscriber->id);
425 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
427 if (empty($oprofile)) {
431 $act = new Activity();
433 $act->verb = ActivityVerb::FOLLOW;
435 $act->id = TagURI::mint('follow:%d:%d:%s',
438 common_date_iso8601(time()));
441 $act->title = _("Follow");
442 $act->content = sprintf(_("%s is now following %s."),
443 $subscriber->getBestName(),
444 $other->getBestName());
446 $act->actor = ActivityObject::fromProfile($subscriber);
447 $act->object = ActivityObject::fromProfile($other);
449 $oprofile->notifyActivity($act, $subscriber);
455 * Notify remote server and garbage collect unused feeds on unsubscribe.
456 * @fixme send these operations to background queues
459 * @param Profile $other
460 * @return hook return value
462 function onEndUnsubscribe($profile, $other)
464 $user = User::staticGet('id', $profile->id);
470 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
472 if (empty($oprofile)) {
476 // Drop the PuSH subscription if there are no other subscribers.
477 $oprofile->garbageCollect();
479 $act = new Activity();
481 $act->verb = ActivityVerb::UNFOLLOW;
483 $act->id = TagURI::mint('unfollow:%d:%d:%s',
486 common_date_iso8601(time()));
489 $act->title = _("Unfollow");
490 $act->content = sprintf(_("%s stopped following %s."),
491 $profile->getBestName(),
492 $other->getBestName());
494 $act->actor = ActivityObject::fromProfile($profile);
495 $act->object = ActivityObject::fromProfile($other);
497 $oprofile->notifyActivity($act, $profile);
503 * When one of our local users tries to join a remote group,
504 * notify the remote server. If the notification is rejected,
507 * @param User_group $group
510 * @return mixed hook return value
513 function onStartJoinGroup($group, $user)
515 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
517 if (!$oprofile->subscribe()) {
518 throw new Exception(_m('Could not set up remote group membership.'));
521 $member = Profile::staticGet($user->id);
523 $act = new Activity();
524 $act->id = TagURI::mint('join:%d:%d:%s',
527 common_date_iso8601(time()));
529 $act->actor = ActivityObject::fromProfile($member);
530 $act->verb = ActivityVerb::JOIN;
531 $act->object = $oprofile->asActivityObject();
534 $act->title = _m("Join");
535 $act->content = sprintf(_m("%s has joined group %s."),
536 $member->getBestName(),
537 $oprofile->getBestName());
539 if ($oprofile->notifyActivity($act, $member)) {
542 $oprofile->garbageCollect();
543 throw new Exception(_m("Failed joining remote group."));
549 * When one of our local users leaves a remote group, notify the remote
552 * @fixme Might be good to schedule a resend of the leave notification
553 * if it failed due to a transitory error. We've canceled the local
554 * membership already anyway, but if the remote server comes back up
555 * it'll be left with a stray membership record.
557 * @param User_group $group
560 * @return mixed hook return value
563 function onEndLeaveGroup($group, $user)
565 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
567 // Drop the PuSH subscription if there are no other subscribers.
568 $oprofile->garbageCollect();
571 $member = Profile::staticGet($user->id);
573 $act = new Activity();
574 $act->id = TagURI::mint('leave:%d:%d:%s',
577 common_date_iso8601(time()));
579 $act->actor = ActivityObject::fromProfile($member);
580 $act->verb = ActivityVerb::LEAVE;
581 $act->object = $oprofile->asActivityObject();
584 $act->title = _m("Leave");
585 $act->content = sprintf(_m("%s has left group %s."),
586 $member->getBestName(),
587 $oprofile->getBestName());
589 $oprofile->notifyActivity($act, $member);
594 * Notify remote users when their notices get favorited.
596 * @param Profile or User $profile of local user doing the faving
597 * @param Notice $notice being favored
598 * @return hook return value
601 function onEndFavorNotice(Profile $profile, Notice $notice)
603 $user = User::staticGet('id', $profile->id);
609 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
611 if (empty($oprofile)) {
615 $act = new Activity();
617 $act->verb = ActivityVerb::FAVORITE;
618 $act->id = TagURI::mint('favor:%d:%d:%s',
621 common_date_iso8601(time()));
624 $act->title = _("Favor");
625 $act->content = sprintf(_("%s marked notice %s as a favorite."),
626 $profile->getBestName(),
629 $act->actor = ActivityObject::fromProfile($profile);
630 $act->object = ActivityObject::fromNotice($notice);
632 $oprofile->notifyActivity($act, $profile);
638 * Notify remote users when their notices get de-favorited.
640 * @param Profile $profile Profile person doing the de-faving
641 * @param Notice $notice Notice being favored
643 * @return hook return value
646 function onEndDisfavorNotice(Profile $profile, Notice $notice)
648 $user = User::staticGet('id', $profile->id);
654 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
656 if (empty($oprofile)) {
660 $act = new Activity();
662 $act->verb = ActivityVerb::UNFAVORITE;
663 $act->id = TagURI::mint('disfavor:%d:%d:%s',
666 common_date_iso8601(time()));
668 $act->title = _("Disfavor");
669 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
670 $profile->getBestName(),
673 $act->actor = ActivityObject::fromProfile($profile);
674 $act->object = ActivityObject::fromNotice($notice);
676 $oprofile->notifyActivity($act, $profile);
681 function onStartGetProfileUri($profile, &$uri)
683 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
684 if (!empty($oprofile)) {
685 $uri = $oprofile->uri;
691 function onStartUserGroupHomeUrl($group, &$url)
693 return $this->onStartUserGroupPermalink($group, $url);
696 function onStartUserGroupPermalink($group, &$url)
698 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
700 // @fixme this should probably be in the user_group table
701 // @fixme this uri not guaranteed to be a profile page
702 $url = $oprofile->uri;
707 function onStartShowSubscriptionsContent($action)
709 $user = common_current_user();
710 if ($user && ($user->id == $action->profile->id)) {
711 $action->elementStart('div', 'entity_actions');
712 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
713 'class' => 'entity_subscribe'));
714 $action->element('a', array('href' => common_local_url('ostatussub'),
715 'class' => 'entity_remote_subscribe')
716 , _m('Subscribe to remote user'));
717 $action->elementEnd('p');
718 $action->elementEnd('div');
725 * Ping remote profiles with updates to this profile.
726 * Salmon pings are queued for background processing.
728 function onEndBroadcastProfile(Profile $profile)
730 $user = User::staticGet('id', $profile->id);
732 // Find foreign accounts I'm subscribed to that support Salmon pings.
734 // @fixme we could run updates through the PuSH feed too,
735 // in which case we can skip Salmon pings to folks who
736 // are also subscribed to me.
737 $sql = "SELECT * FROM ostatus_profile " .
738 "WHERE profile_id IN " .
739 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
741 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
742 $oprofile = new Ostatus_profile();
743 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
745 if ($oprofile->N == 0) {
746 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
750 $act = new Activity();
752 $act->verb = ActivityVerb::UPDATE_PROFILE;
753 $act->id = TagURI::mint('update-profile:%d:%s',
755 common_date_iso8601(time()));
757 $act->title = _m("Profile update");
758 $act->content = sprintf(_m("%s has updated their profile page."),
759 $profile->getBestName());
761 $act->actor = ActivityObject::fromProfile($profile);
762 $act->object = $act->actor;
764 while ($oprofile->fetch()) {
765 $oprofile->notifyDeferred($act, $profile);