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('hubout', 'HubOutQueueHandler');
92 // Outgoing Salmon replies (when we don't need a return value)
93 $qm->connect('salmon', 'SalmonQueueHandler');
95 // Incoming from a foreign PuSH hub
96 $qm->connect('pushin', 'PushInQueueHandler');
101 * Put saved notices into the queue for pubsub distribution.
103 function onStartEnqueueNotice($notice, &$transports)
105 // put our transport first, in case there's any conflict (like OMB)
106 array_unshift($transports, 'ostatus');
111 * Add a link header for LRDD Discovery
113 function onStartShowHTML($action)
115 if ($action instanceof ShowstreamAction) {
116 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
117 $url = common_local_url('userxrd');
118 $url.= '?uri='. $acct;
120 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
125 * Set up a PuSH hub link to our internal link for canonical timeline
126 * Atom feeds for users and groups.
128 function onStartApiAtom($feed)
132 if ($feed instanceof AtomUserNoticeFeed) {
133 $salmonAction = 'usersalmon';
134 $user = $feed->getUser();
136 $profile = $user->getProfile();
137 $feed->setActivitySubject($profile->asActivityNoun('subject'));
138 } else if ($feed instanceof AtomGroupNoticeFeed) {
139 $salmonAction = 'groupsalmon';
140 $group = $feed->getGroup();
142 $feed->setActivitySubject($group->asActivitySubject());
148 $hub = common_config('ostatus', 'hub');
150 // Updates will be handled through our internal PuSH hub.
151 $hub = common_local_url('pushhub');
153 $feed->addLink($hub, array('rel' => 'hub'));
155 // Also, we'll add in the salmon link
156 $salmon = common_local_url($salmonAction, array('id' => $id));
157 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
158 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
165 * Automatically load the actions and libraries used by the plugin
167 * @param Class $cls the class
169 * @return boolean hook return
172 function onAutoload($cls)
174 $base = dirname(__FILE__);
175 $lower = strtolower($cls);
176 $map = array('activityverb' => 'activity',
177 'activityobject' => 'activity',
178 'activityutils' => 'activity');
179 if (isset($map[$lower])) {
180 $lower = $map[$lower];
182 $files = array("$base/classes/$cls.php",
183 "$base/lib/$lower.php");
184 if (substr($lower, -6) == 'action') {
185 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
187 foreach ($files as $file) {
188 if (file_exists($file)) {
197 * Add in an OStatus subscribe button
199 function onStartProfileRemoteSubscribe($output, $profile)
201 $cur = common_current_user();
204 // Add an OStatus subscribe
205 $output->elementStart('li', 'entity_subscribe');
206 $url = common_local_url('ostatusinit',
207 array('nickname' => $profile->nickname));
208 $output->element('a', array('href' => $url,
209 'class' => 'entity_remote_subscribe'),
212 $output->elementEnd('li');
218 function onStartGroupSubscribe($output, $group)
220 $cur = common_current_user();
223 // Add an OStatus subscribe
224 $url = common_local_url('ostatusinit',
225 array('group' => $group->nickname));
226 $output->element('a', array('href' => $url,
227 'class' => 'entity_remote_subscribe'),
235 * Check if we've got remote replies to send via Salmon.
237 * @fixme push webfinger lookup & sending to a background queue
238 * @fixme also detect short-form name for remote subscribees where not ambiguous
241 function onEndNoticeSave($notice)
246 * Find any explicit remote mentions. Accepted forms:
247 * Webfinger: @user@example.com
248 * Profile link: @example.com/mublog/user
249 * @param Profile $sender (os user?)
250 * @param string $text input markup text
251 * @param array &$mention in/out param: set of found mentions
252 * @return boolean hook return value
255 function onEndFindMentions($sender, $text, &$mentions)
259 // Webfinger matches: @user@example.com
260 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
263 PREG_OFFSET_CAPTURE)) {
264 foreach ($wmatches[1] as $wmatch) {
265 list($target, $pos) = $wmatch;
266 $this->log(LOG_INFO, "Checking webfinger '$target'");
268 $oprofile = Ostatus_profile::ensureWebfinger($target);
269 if ($oprofile && !$oprofile->isGroup()) {
270 $profile = $oprofile->localProfile();
271 $matches[$pos] = array('mentioned' => array($profile),
274 'url' => $profile->profileurl);
276 } catch (Exception $e) {
277 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
282 // Profile matches: @example.com/mublog/user
283 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
286 PREG_OFFSET_CAPTURE)) {
287 foreach ($wmatches[1] as $wmatch) {
288 list($target, $pos) = $wmatch;
289 $schemes = array('http', 'https');
290 foreach ($schemes as $scheme) {
291 $url = "$scheme://$target";
292 $this->log(LOG_INFO, "Checking profile address '$url'");
294 $oprofile = Ostatus_profile::ensureProfileURL($url);
295 if ($oprofile && !$oprofile->isGroup()) {
296 $profile = $oprofile->localProfile();
297 $matches[$pos] = array('mentioned' => array($profile),
300 'url' => $profile->profileurl);
303 } catch (Exception $e) {
304 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
310 foreach ($mentions as $i => $other) {
311 // If we share a common prefix with a local user, override it!
312 $pos = $other['position'];
313 if (isset($matches[$pos])) {
314 $mentions[$i] = $matches[$pos];
315 unset($matches[$pos]);
318 foreach ($matches as $mention) {
319 $mentions[] = $mention;
326 * Allow remote profile references to be used in commands:
327 * sub update@status.net
328 * whois evan@identi.ca
329 * reply http://identi.ca/evan hey what's up
331 * @param Command $command
333 * @param Profile &$profile
334 * @return hook return code
336 function onStartCommandGetProfile($command, $arg, &$profile)
338 $oprofile = $this->pullRemoteProfile($arg);
339 if ($oprofile && !$oprofile->isGroup()) {
340 $profile = $oprofile->localProfile();
348 * Allow remote group references to be used in commands:
349 * join group+statusnet@identi.ca
350 * join http://identi.ca/group/statusnet
351 * drop identi.ca/group/statusnet
353 * @param Command $command
355 * @param User_group &$group
356 * @return hook return code
358 function onStartCommandGetGroup($command, $arg, &$group)
360 $oprofile = $this->pullRemoteProfile($arg);
361 if ($oprofile && $oprofile->isGroup()) {
362 $group = $oprofile->localGroup();
369 protected function pullRemoteProfile($arg)
372 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
375 return Ostatus_profile::ensureWebfinger($arg);
376 } catch (Exception $e) {
377 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
378 $arg . ': ' . $e->getMessage());
382 // Look for profile URLs, with or without scheme:
384 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
387 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
388 $schemes = array('http', 'https');
389 foreach ($schemes as $scheme) {
390 $urls[] = "$scheme://$arg";
394 foreach ($urls as $url) {
396 return Ostatus_profile::ensureProfileURL($url);
397 } catch (Exception $e) {
398 common_log(LOG_ERR, 'Profile lookup failed for ' .
399 $arg . ': ' . $e->getMessage());
406 * Make sure necessary tables are filled out.
408 function onCheckSchema() {
409 $schema = Schema::get();
410 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
411 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
412 $schema->ensureTable('feedsub', FeedSub::schemaDef());
413 $schema->ensureTable('hubsub', HubSub::schemaDef());
414 $schema->ensureTable('magicsig', Magicsig::schemaDef());
418 function onEndShowStatusNetStyles($action) {
419 $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
423 function onEndShowStatusNetScripts($action) {
424 $action->script('plugins/OStatus/js/ostatus.js');
429 * Override the "from ostatus" bit in notice lists to link to the
430 * original post and show the domain it came from.
432 * @param Notice in $notice
433 * @param string out &$name
434 * @param string out &$url
435 * @param string out &$title
436 * @return mixed hook return code
438 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
440 if ($notice->source == 'ostatus') {
442 $bits = parse_url($notice->url);
443 $domain = $bits['host'];
444 if (substr($domain, 0, 4) == 'www.') {
445 $name = substr($domain, 4);
451 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
458 * Send incoming PuSH feeds for OStatus endpoints in for processing.
460 * @param FeedSub $feedsub
461 * @param DOMDocument $feed
462 * @return mixed hook return code
464 function onStartFeedSubReceive($feedsub, $feed)
466 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
468 $oprofile->processFeed($feed, 'push');
470 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
475 * When about to subscribe to a remote user, start a server-to-server
476 * PuSH subscription if needed. If we can't establish that, abort.
478 * @fixme If something else aborts later, we could end up with a stray
479 * PuSH subscription. This is relatively harmless, though.
481 * @param Profile $subscriber
482 * @param Profile $other
484 * @return hook return code
488 function onStartSubscribe($subscriber, $other)
490 $user = User::staticGet('id', $subscriber->id);
496 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
498 if (empty($oprofile)) {
502 if (!$oprofile->subscribe()) {
503 throw new Exception(_m('Could not set up remote subscription.'));
508 * Having established a remote subscription, send a notification to the
509 * remote OStatus profile's endpoint.
511 * @param Profile $subscriber
512 * @param Profile $other
514 * @return hook return code
518 function onEndSubscribe($subscriber, $other)
520 $user = User::staticGet('id', $subscriber->id);
526 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
528 if (empty($oprofile)) {
532 $act = new Activity();
534 $act->verb = ActivityVerb::FOLLOW;
536 $act->id = TagURI::mint('follow:%d:%d:%s',
539 common_date_iso8601(time()));
542 $act->title = _("Follow");
543 $act->content = sprintf(_("%s is now following %s."),
544 $subscriber->getBestName(),
545 $other->getBestName());
547 $act->actor = ActivityObject::fromProfile($subscriber);
548 $act->object = ActivityObject::fromProfile($other);
550 $oprofile->notifyActivity($act, $subscriber);
556 * Notify remote server and garbage collect unused feeds on unsubscribe.
557 * @fixme send these operations to background queues
560 * @param Profile $other
561 * @return hook return value
563 function onEndUnsubscribe($profile, $other)
565 $user = User::staticGet('id', $profile->id);
571 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
573 if (empty($oprofile)) {
577 // Drop the PuSH subscription if there are no other subscribers.
578 $oprofile->garbageCollect();
580 $act = new Activity();
582 $act->verb = ActivityVerb::UNFOLLOW;
584 $act->id = TagURI::mint('unfollow:%d:%d:%s',
587 common_date_iso8601(time()));
590 $act->title = _("Unfollow");
591 $act->content = sprintf(_("%s stopped following %s."),
592 $profile->getBestName(),
593 $other->getBestName());
595 $act->actor = ActivityObject::fromProfile($profile);
596 $act->object = ActivityObject::fromProfile($other);
598 $oprofile->notifyActivity($act, $profile);
604 * When one of our local users tries to join a remote group,
605 * notify the remote server. If the notification is rejected,
608 * @param User_group $group
611 * @return mixed hook return value
614 function onStartJoinGroup($group, $user)
616 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
618 if (!$oprofile->subscribe()) {
619 throw new Exception(_m('Could not set up remote group membership.'));
622 $member = Profile::staticGet($user->id);
624 $act = new Activity();
625 $act->id = TagURI::mint('join:%d:%d:%s',
628 common_date_iso8601(time()));
630 $act->actor = ActivityObject::fromProfile($member);
631 $act->verb = ActivityVerb::JOIN;
632 $act->object = $oprofile->asActivityObject();
635 $act->title = _m("Join");
636 $act->content = sprintf(_m("%s has joined group %s."),
637 $member->getBestName(),
638 $oprofile->getBestName());
640 if ($oprofile->notifyActivity($act, $member)) {
643 $oprofile->garbageCollect();
644 throw new Exception(_m("Failed joining remote group."));
650 * When one of our local users leaves a remote group, notify the remote
653 * @fixme Might be good to schedule a resend of the leave notification
654 * if it failed due to a transitory error. We've canceled the local
655 * membership already anyway, but if the remote server comes back up
656 * it'll be left with a stray membership record.
658 * @param User_group $group
661 * @return mixed hook return value
664 function onEndLeaveGroup($group, $user)
666 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
668 // Drop the PuSH subscription if there are no other subscribers.
669 $oprofile->garbageCollect();
671 $member = Profile::staticGet($user->id);
673 $act = new Activity();
674 $act->id = TagURI::mint('leave:%d:%d:%s',
677 common_date_iso8601(time()));
679 $act->actor = ActivityObject::fromProfile($member);
680 $act->verb = ActivityVerb::LEAVE;
681 $act->object = $oprofile->asActivityObject();
684 $act->title = _m("Leave");
685 $act->content = sprintf(_m("%s has left group %s."),
686 $member->getBestName(),
687 $oprofile->getBestName());
689 $oprofile->notifyActivity($act, $member);
694 * Notify remote users when their notices get favorited.
696 * @param Profile or User $profile of local user doing the faving
697 * @param Notice $notice being favored
698 * @return hook return value
701 function onEndFavorNotice(Profile $profile, Notice $notice)
703 $user = User::staticGet('id', $profile->id);
709 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
711 if (empty($oprofile)) {
715 $act = new Activity();
717 $act->verb = ActivityVerb::FAVORITE;
718 $act->id = TagURI::mint('favor:%d:%d:%s',
721 common_date_iso8601(time()));
724 $act->title = _("Favor");
725 $act->content = sprintf(_("%s marked notice %s as a favorite."),
726 $profile->getBestName(),
729 $act->actor = ActivityObject::fromProfile($profile);
730 $act->object = ActivityObject::fromNotice($notice);
732 $oprofile->notifyActivity($act, $profile);
738 * Notify remote users when their notices get de-favorited.
740 * @param Profile $profile Profile person doing the de-faving
741 * @param Notice $notice Notice being favored
743 * @return hook return value
746 function onEndDisfavorNotice(Profile $profile, Notice $notice)
748 $user = User::staticGet('id', $profile->id);
754 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
756 if (empty($oprofile)) {
760 $act = new Activity();
762 $act->verb = ActivityVerb::UNFAVORITE;
763 $act->id = TagURI::mint('disfavor:%d:%d:%s',
766 common_date_iso8601(time()));
768 $act->title = _("Disfavor");
769 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
770 $profile->getBestName(),
773 $act->actor = ActivityObject::fromProfile($profile);
774 $act->object = ActivityObject::fromNotice($notice);
776 $oprofile->notifyActivity($act, $profile);
781 function onStartGetProfileUri($profile, &$uri)
783 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
784 if (!empty($oprofile)) {
785 $uri = $oprofile->uri;
791 function onStartUserGroupHomeUrl($group, &$url)
793 return $this->onStartUserGroupPermalink($group, $url);
796 function onStartUserGroupPermalink($group, &$url)
798 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
800 // @fixme this should probably be in the user_group table
801 // @fixme this uri not guaranteed to be a profile page
802 $url = $oprofile->uri;
807 function onStartShowSubscriptionsContent($action)
809 $this->showEntityRemoteSubscribe($action);
814 function onStartShowUserGroupsContent($action)
816 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
821 function onEndShowSubscriptionsMiniList($action)
823 $this->showEntityRemoteSubscribe($action);
828 function onEndShowGroupsMiniList($action)
830 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
835 function showEntityRemoteSubscribe($action, $target='ostatussub')
837 $user = common_current_user();
838 if ($user && ($user->id == $action->profile->id)) {
839 $action->elementStart('div', 'entity_actions');
840 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
841 'class' => 'entity_subscribe'));
842 $action->element('a', array('href' => common_local_url($target),
843 'class' => 'entity_remote_subscribe')
845 $action->elementEnd('p');
846 $action->elementEnd('div');
851 * Ping remote profiles with updates to this profile.
852 * Salmon pings are queued for background processing.
854 function onEndBroadcastProfile(Profile $profile)
856 $user = User::staticGet('id', $profile->id);
858 // Find foreign accounts I'm subscribed to that support Salmon pings.
860 // @fixme we could run updates through the PuSH feed too,
861 // in which case we can skip Salmon pings to folks who
862 // are also subscribed to me.
863 $sql = "SELECT * FROM ostatus_profile " .
864 "WHERE profile_id IN " .
865 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
867 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
868 $oprofile = new Ostatus_profile();
869 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
871 if ($oprofile->N == 0) {
872 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
876 $act = new Activity();
878 $act->verb = ActivityVerb::UPDATE_PROFILE;
879 $act->id = TagURI::mint('update-profile:%d:%s',
881 common_date_iso8601(time()));
883 $act->title = _m("Profile update");
884 $act->content = sprintf(_m("%s has updated their profile page."),
885 $profile->getBestName());
887 $act->actor = ActivityObject::fromProfile($profile);
888 $act->object = $act->actor;
890 while ($oprofile->fetch()) {
891 $oprofile->notifyDeferred($act, $profile);
897 function onStartProfileListItemActionElements($item)
899 if (!common_logged_in()) {
901 $profileUser = User::staticGet('id', $item->profile->id);
903 if (!empty($profileUser)) {
905 $output = $item->out;
907 // Add an OStatus subscribe
908 $output->elementStart('li', 'entity_subscribe');
909 $url = common_local_url('ostatusinit',
910 array('nickname' => $profileUser->nickname));
911 $output->element('a', array('href' => $url,
912 'class' => 'entity_remote_subscribe'),
914 $output->elementEnd('li');
921 function onPluginVersion(&$versions)
923 $versions[] = array('name' => 'OStatus',
924 'version' => STATUSNET_VERSION,
925 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
926 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
928 _m('Follow people across social networks that implement '.
929 '<a href="http://ostatus.org/">OStatus</a>.'));
935 * Utility function to check if the given URL is a canonical group profile
936 * page, and if so return the ID number.
939 * @return mixed int or false
941 public static function localGroupFromUrl($url)
943 $template = common_local_url('groupbyid', array('id' => '31337'));
944 $template = preg_quote($template, '/');
945 $template = str_replace('31337', '(\d+)', $template);
946 if (preg_match("/$template/", $url, $matches)) {
947 return intval($matches[1]);