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' => 'userxrd'));
48 $m->connect('main/ownerxrd',
49 array('action' => 'ownerxrd'));
50 $m->connect('main/ostatus',
51 array('action' => 'ostatusinit'));
52 $m->connect('main/ostatus?nickname=:nickname',
53 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
54 $m->connect('main/ostatus?group=:group',
55 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
56 $m->connect('main/ostatussub',
57 array('action' => 'ostatussub'));
58 $m->connect('main/ostatusgroup',
59 array('action' => 'ostatusgroup'));
62 $m->connect('main/push/hub', array('action' => 'pushhub'));
64 $m->connect('main/push/callback/:feed',
65 array('action' => 'pushcallback'),
66 array('feed' => '[0-9]+'));
69 $m->connect('main/salmon/user/:id',
70 array('action' => 'usersalmon'),
71 array('id' => '[0-9]+'));
72 $m->connect('main/salmon/group/:id',
73 array('action' => 'groupsalmon'),
74 array('id' => '[0-9]+'));
79 * Set up queue handlers for outgoing hub pushes
80 * @param QueueManager $qm
81 * @return boolean hook return
83 function onEndInitializeQueueManager(QueueManager $qm)
85 // Prepare outgoing distributions after notice save.
86 $qm->connect('ostatus', 'OStatusQueueHandler');
88 // Outgoing from our internal PuSH hub
89 $qm->connect('hubconf', 'HubConfQueueHandler');
90 $qm->connect('hubprep', 'HubPrepQueueHandler');
92 $qm->connect('hubout', 'HubOutQueueHandler');
94 // Outgoing Salmon replies (when we don't need a return value)
95 $qm->connect('salmon', 'SalmonQueueHandler');
97 // Incoming from a foreign PuSH hub
98 $qm->connect('pushin', 'PushInQueueHandler');
103 * Put saved notices into the queue for pubsub distribution.
105 function onStartEnqueueNotice($notice, &$transports)
107 if ($notice->isLocal()) {
108 // put our transport first, in case there's any conflict (like OMB)
109 array_unshift($transports, 'ostatus');
115 * Add a link header for LRDD Discovery
117 function onStartShowHTML($action)
119 if ($action instanceof ShowstreamAction) {
120 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
121 $url = common_local_url('userxrd');
122 $url.= '?uri='. $acct;
124 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
129 * Set up a PuSH hub link to our internal link for canonical timeline
130 * Atom feeds for users and groups.
132 function onStartApiAtom($feed)
136 if ($feed instanceof AtomUserNoticeFeed) {
137 $salmonAction = 'usersalmon';
138 $user = $feed->getUser();
140 $profile = $user->getProfile();
141 $feed->setActivitySubject($profile->asActivityNoun('subject'));
142 } else if ($feed instanceof AtomGroupNoticeFeed) {
143 $salmonAction = 'groupsalmon';
144 $group = $feed->getGroup();
146 $feed->setActivitySubject($group->asActivitySubject());
152 $hub = common_config('ostatus', 'hub');
154 // Updates will be handled through our internal PuSH hub.
155 $hub = common_local_url('pushhub');
157 $feed->addLink($hub, array('rel' => 'hub'));
159 // Also, we'll add in the salmon link
160 $salmon = common_local_url($salmonAction, array('id' => $id));
161 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
163 // XXX: these are deprecated
164 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
165 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
172 * Automatically load the actions and libraries used by the plugin
174 * @param Class $cls the class
176 * @return boolean hook return
179 function onAutoload($cls)
181 $base = dirname(__FILE__);
182 $lower = strtolower($cls);
183 $map = array('activityverb' => 'activity',
184 'activityobject' => 'activity',
185 'activityutils' => 'activity');
186 if (isset($map[$lower])) {
187 $lower = $map[$lower];
189 $files = array("$base/classes/$cls.php",
190 "$base/lib/$lower.php");
191 if (substr($lower, -6) == 'action') {
192 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
194 foreach ($files as $file) {
195 if (file_exists($file)) {
204 * Add in an OStatus subscribe button
206 function onStartProfileRemoteSubscribe($output, $profile)
208 $cur = common_current_user();
211 // Add an OStatus subscribe
212 $output->elementStart('li', 'entity_subscribe');
213 $url = common_local_url('ostatusinit',
214 array('nickname' => $profile->nickname));
215 $output->element('a', array('href' => $url,
216 'class' => 'entity_remote_subscribe'),
219 $output->elementEnd('li');
225 function onStartGroupSubscribe($output, $group)
227 $cur = common_current_user();
230 // Add an OStatus subscribe
231 $url = common_local_url('ostatusinit',
232 array('group' => $group->nickname));
233 $output->element('a', array('href' => $url,
234 'class' => 'entity_remote_subscribe'),
242 * Check if we've got remote replies to send via Salmon.
244 * @fixme push webfinger lookup & sending to a background queue
245 * @fixme also detect short-form name for remote subscribees where not ambiguous
248 function onEndNoticeSave($notice)
253 * Find any explicit remote mentions. Accepted forms:
254 * Webfinger: @user@example.com
255 * Profile link: @example.com/mublog/user
256 * @param Profile $sender (os user?)
257 * @param string $text input markup text
258 * @param array &$mention in/out param: set of found mentions
259 * @return boolean hook return value
262 function onEndFindMentions($sender, $text, &$mentions)
266 // Webfinger matches: @user@example.com
267 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
270 PREG_OFFSET_CAPTURE)) {
271 foreach ($wmatches[1] as $wmatch) {
272 list($target, $pos) = $wmatch;
273 $this->log(LOG_INFO, "Checking webfinger '$target'");
275 $oprofile = Ostatus_profile::ensureWebfinger($target);
276 if ($oprofile && !$oprofile->isGroup()) {
277 $profile = $oprofile->localProfile();
278 $matches[$pos] = array('mentioned' => array($profile),
281 'url' => $profile->profileurl);
283 } catch (Exception $e) {
284 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
289 // Profile matches: @example.com/mublog/user
290 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
293 PREG_OFFSET_CAPTURE)) {
294 foreach ($wmatches[1] as $wmatch) {
295 list($target, $pos) = $wmatch;
296 $schemes = array('http', 'https');
297 foreach ($schemes as $scheme) {
298 $url = "$scheme://$target";
299 $this->log(LOG_INFO, "Checking profile address '$url'");
301 $oprofile = Ostatus_profile::ensureProfileURL($url);
302 if ($oprofile && !$oprofile->isGroup()) {
303 $profile = $oprofile->localProfile();
304 $matches[$pos] = array('mentioned' => array($profile),
307 'url' => $profile->profileurl);
310 } catch (Exception $e) {
311 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
317 foreach ($mentions as $i => $other) {
318 // If we share a common prefix with a local user, override it!
319 $pos = $other['position'];
320 if (isset($matches[$pos])) {
321 $mentions[$i] = $matches[$pos];
322 unset($matches[$pos]);
325 foreach ($matches as $mention) {
326 $mentions[] = $mention;
333 * Allow remote profile references to be used in commands:
334 * sub update@status.net
335 * whois evan@identi.ca
336 * reply http://identi.ca/evan hey what's up
338 * @param Command $command
340 * @param Profile &$profile
341 * @return hook return code
343 function onStartCommandGetProfile($command, $arg, &$profile)
345 $oprofile = $this->pullRemoteProfile($arg);
346 if ($oprofile && !$oprofile->isGroup()) {
347 $profile = $oprofile->localProfile();
355 * Allow remote group references to be used in commands:
356 * join group+statusnet@identi.ca
357 * join http://identi.ca/group/statusnet
358 * drop identi.ca/group/statusnet
360 * @param Command $command
362 * @param User_group &$group
363 * @return hook return code
365 function onStartCommandGetGroup($command, $arg, &$group)
367 $oprofile = $this->pullRemoteProfile($arg);
368 if ($oprofile && $oprofile->isGroup()) {
369 $group = $oprofile->localGroup();
376 protected function pullRemoteProfile($arg)
379 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
382 return Ostatus_profile::ensureWebfinger($arg);
383 } catch (Exception $e) {
384 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
385 $arg . ': ' . $e->getMessage());
389 // Look for profile URLs, with or without scheme:
391 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
394 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
395 $schemes = array('http', 'https');
396 foreach ($schemes as $scheme) {
397 $urls[] = "$scheme://$arg";
401 foreach ($urls as $url) {
403 return Ostatus_profile::ensureProfileURL($url);
404 } catch (Exception $e) {
405 common_log(LOG_ERR, 'Profile lookup failed for ' .
406 $arg . ': ' . $e->getMessage());
413 * Make sure necessary tables are filled out.
415 function onCheckSchema() {
416 $schema = Schema::get();
417 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
418 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
419 $schema->ensureTable('feedsub', FeedSub::schemaDef());
420 $schema->ensureTable('hubsub', HubSub::schemaDef());
421 $schema->ensureTable('magicsig', Magicsig::schemaDef());
425 function onEndShowStatusNetStyles($action) {
426 $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
430 function onEndShowStatusNetScripts($action) {
431 $action->script('plugins/OStatus/js/ostatus.js');
436 * Override the "from ostatus" bit in notice lists to link to the
437 * original post and show the domain it came from.
439 * @param Notice in $notice
440 * @param string out &$name
441 * @param string out &$url
442 * @param string out &$title
443 * @return mixed hook return code
445 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
447 if ($notice->source == 'ostatus') {
449 $bits = parse_url($notice->url);
450 $domain = $bits['host'];
451 if (substr($domain, 0, 4) == 'www.') {
452 $name = substr($domain, 4);
458 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
466 * Send incoming PuSH feeds for OStatus endpoints in for processing.
468 * @param FeedSub $feedsub
469 * @param DOMDocument $feed
470 * @return mixed hook return code
472 function onStartFeedSubReceive($feedsub, $feed)
474 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
476 $oprofile->processFeed($feed, 'push');
478 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
483 * When about to subscribe to a remote user, start a server-to-server
484 * PuSH subscription if needed. If we can't establish that, abort.
486 * @fixme If something else aborts later, we could end up with a stray
487 * PuSH subscription. This is relatively harmless, though.
489 * @param Profile $subscriber
490 * @param Profile $other
492 * @return hook return code
496 function onStartSubscribe($subscriber, $other)
498 $user = User::staticGet('id', $subscriber->id);
504 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
506 if (empty($oprofile)) {
510 if (!$oprofile->subscribe()) {
511 throw new Exception(_m('Could not set up remote subscription.'));
516 * Having established a remote subscription, send a notification to the
517 * remote OStatus profile's endpoint.
519 * @param Profile $subscriber
520 * @param Profile $other
522 * @return hook return code
526 function onEndSubscribe($subscriber, $other)
528 $user = User::staticGet('id', $subscriber->id);
534 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
536 if (empty($oprofile)) {
540 $act = new Activity();
542 $act->verb = ActivityVerb::FOLLOW;
544 $act->id = TagURI::mint('follow:%d:%d:%s',
547 common_date_iso8601(time()));
550 $act->title = _("Follow");
551 $act->content = sprintf(_("%s is now following %s."),
552 $subscriber->getBestName(),
553 $other->getBestName());
555 $act->actor = ActivityObject::fromProfile($subscriber);
556 $act->object = ActivityObject::fromProfile($other);
558 $oprofile->notifyActivity($act, $subscriber);
564 * Notify remote server and garbage collect unused feeds on unsubscribe.
565 * @fixme send these operations to background queues
568 * @param Profile $other
569 * @return hook return value
571 function onEndUnsubscribe($profile, $other)
573 $user = User::staticGet('id', $profile->id);
579 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
581 if (empty($oprofile)) {
585 // Drop the PuSH subscription if there are no other subscribers.
586 $oprofile->garbageCollect();
588 $act = new Activity();
590 $act->verb = ActivityVerb::UNFOLLOW;
592 $act->id = TagURI::mint('unfollow:%d:%d:%s',
595 common_date_iso8601(time()));
598 $act->title = _("Unfollow");
599 $act->content = sprintf(_("%s stopped following %s."),
600 $profile->getBestName(),
601 $other->getBestName());
603 $act->actor = ActivityObject::fromProfile($profile);
604 $act->object = ActivityObject::fromProfile($other);
606 $oprofile->notifyActivity($act, $profile);
612 * When one of our local users tries to join a remote group,
613 * notify the remote server. If the notification is rejected,
616 * @param User_group $group
619 * @return mixed hook return value
622 function onStartJoinGroup($group, $user)
624 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
626 if (!$oprofile->subscribe()) {
627 throw new Exception(_m('Could not set up remote group membership.'));
630 $member = Profile::staticGet($user->id);
632 $act = new Activity();
633 $act->id = TagURI::mint('join:%d:%d:%s',
636 common_date_iso8601(time()));
638 $act->actor = ActivityObject::fromProfile($member);
639 $act->verb = ActivityVerb::JOIN;
640 $act->object = $oprofile->asActivityObject();
643 $act->title = _m("Join");
644 $act->content = sprintf(_m("%s has joined group %s."),
645 $member->getBestName(),
646 $oprofile->getBestName());
648 if ($oprofile->notifyActivity($act, $member)) {
651 $oprofile->garbageCollect();
652 throw new Exception(_m("Failed joining remote group."));
658 * When one of our local users leaves a remote group, notify the remote
661 * @fixme Might be good to schedule a resend of the leave notification
662 * if it failed due to a transitory error. We've canceled the local
663 * membership already anyway, but if the remote server comes back up
664 * it'll be left with a stray membership record.
666 * @param User_group $group
669 * @return mixed hook return value
672 function onEndLeaveGroup($group, $user)
674 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
676 // Drop the PuSH subscription if there are no other subscribers.
677 $oprofile->garbageCollect();
679 $member = Profile::staticGet($user->id);
681 $act = new Activity();
682 $act->id = TagURI::mint('leave:%d:%d:%s',
685 common_date_iso8601(time()));
687 $act->actor = ActivityObject::fromProfile($member);
688 $act->verb = ActivityVerb::LEAVE;
689 $act->object = $oprofile->asActivityObject();
692 $act->title = _m("Leave");
693 $act->content = sprintf(_m("%s has left group %s."),
694 $member->getBestName(),
695 $oprofile->getBestName());
697 $oprofile->notifyActivity($act, $member);
702 * Notify remote users when their notices get favorited.
704 * @param Profile or User $profile of local user doing the faving
705 * @param Notice $notice being favored
706 * @return hook return value
709 function onEndFavorNotice(Profile $profile, Notice $notice)
711 $user = User::staticGet('id', $profile->id);
717 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
719 if (empty($oprofile)) {
723 $act = new Activity();
725 $act->verb = ActivityVerb::FAVORITE;
726 $act->id = TagURI::mint('favor:%d:%d:%s',
729 common_date_iso8601(time()));
732 $act->title = _("Favor");
733 $act->content = sprintf(_("%s marked notice %s as a favorite."),
734 $profile->getBestName(),
737 $act->actor = ActivityObject::fromProfile($profile);
738 $act->object = ActivityObject::fromNotice($notice);
740 $oprofile->notifyActivity($act, $profile);
746 * Notify remote users when their notices get de-favorited.
748 * @param Profile $profile Profile person doing the de-faving
749 * @param Notice $notice Notice being favored
751 * @return hook return value
754 function onEndDisfavorNotice(Profile $profile, Notice $notice)
756 $user = User::staticGet('id', $profile->id);
762 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
764 if (empty($oprofile)) {
768 $act = new Activity();
770 $act->verb = ActivityVerb::UNFAVORITE;
771 $act->id = TagURI::mint('disfavor:%d:%d:%s',
774 common_date_iso8601(time()));
776 $act->title = _("Disfavor");
777 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
778 $profile->getBestName(),
781 $act->actor = ActivityObject::fromProfile($profile);
782 $act->object = ActivityObject::fromNotice($notice);
784 $oprofile->notifyActivity($act, $profile);
789 function onStartGetProfileUri($profile, &$uri)
791 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
792 if (!empty($oprofile)) {
793 $uri = $oprofile->uri;
799 function onStartUserGroupHomeUrl($group, &$url)
801 return $this->onStartUserGroupPermalink($group, $url);
804 function onStartUserGroupPermalink($group, &$url)
806 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
808 // @fixme this should probably be in the user_group table
809 // @fixme this uri not guaranteed to be a profile page
810 $url = $oprofile->uri;
815 function onStartShowSubscriptionsContent($action)
817 $this->showEntityRemoteSubscribe($action);
822 function onStartShowUserGroupsContent($action)
824 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
829 function onEndShowSubscriptionsMiniList($action)
831 $this->showEntityRemoteSubscribe($action);
836 function onEndShowGroupsMiniList($action)
838 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
843 function showEntityRemoteSubscribe($action, $target='ostatussub')
845 $user = common_current_user();
846 if ($user && ($user->id == $action->profile->id)) {
847 $action->elementStart('div', 'entity_actions');
848 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
849 'class' => 'entity_subscribe'));
850 $action->element('a', array('href' => common_local_url($target),
851 'class' => 'entity_remote_subscribe')
853 $action->elementEnd('p');
854 $action->elementEnd('div');
859 * Ping remote profiles with updates to this profile.
860 * Salmon pings are queued for background processing.
862 function onEndBroadcastProfile(Profile $profile)
864 $user = User::staticGet('id', $profile->id);
866 // Find foreign accounts I'm subscribed to that support Salmon pings.
868 // @fixme we could run updates through the PuSH feed too,
869 // in which case we can skip Salmon pings to folks who
870 // are also subscribed to me.
871 $sql = "SELECT * FROM ostatus_profile " .
872 "WHERE profile_id IN " .
873 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
875 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
876 $oprofile = new Ostatus_profile();
877 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
879 if ($oprofile->N == 0) {
880 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
884 $act = new Activity();
886 $act->verb = ActivityVerb::UPDATE_PROFILE;
887 $act->id = TagURI::mint('update-profile:%d:%s',
889 common_date_iso8601(time()));
891 $act->title = _m("Profile update");
892 $act->content = sprintf(_m("%s has updated their profile page."),
893 $profile->getBestName());
895 $act->actor = ActivityObject::fromProfile($profile);
896 $act->object = $act->actor;
898 while ($oprofile->fetch()) {
899 $oprofile->notifyDeferred($act, $profile);
905 function onStartProfileListItemActionElements($item)
907 if (!common_logged_in()) {
909 $profileUser = User::staticGet('id', $item->profile->id);
911 if (!empty($profileUser)) {
913 $output = $item->out;
915 // Add an OStatus subscribe
916 $output->elementStart('li', 'entity_subscribe');
917 $url = common_local_url('ostatusinit',
918 array('nickname' => $profileUser->nickname));
919 $output->element('a', array('href' => $url,
920 'class' => 'entity_remote_subscribe'),
922 $output->elementEnd('li');
929 function onPluginVersion(&$versions)
931 $versions[] = array('name' => 'OStatus',
932 'version' => STATUSNET_VERSION,
933 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
934 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
936 _m('Follow people across social networks that implement '.
937 '<a href="http://ostatus.org/">OStatus</a>.'));
943 * Utility function to check if the given URL is a canonical group profile
944 * page, and if so return the ID number.
947 * @return mixed int or false
949 public static function localGroupFromUrl($url)
951 $template = common_local_url('groupbyid', array('id' => '31337'));
952 $template = preg_quote($template, '/');
953 $template = str_replace('31337', '(\d+)', $template);
954 if (preg_match("/$template/", $url, $matches)) {
955 return intval($matches[1]);
960 public function onStartProfileGetAtomFeed($profile, &$feed)
962 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
964 if (empty($oprofile)) {
968 $feed = $oprofile->feeduri;