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+)*\.\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);
459 * Send incoming PuSH feeds for OStatus endpoints in for processing.
461 * @param FeedSub $feedsub
462 * @param DOMDocument $feed
463 * @return mixed hook return code
465 function onStartFeedSubReceive($feedsub, $feed)
467 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
469 $oprofile->processFeed($feed, 'push');
471 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
476 * When about to subscribe to a remote user, start a server-to-server
477 * PuSH subscription if needed. If we can't establish that, abort.
479 * @fixme If something else aborts later, we could end up with a stray
480 * PuSH subscription. This is relatively harmless, though.
482 * @param Profile $subscriber
483 * @param Profile $other
485 * @return hook return code
489 function onStartSubscribe($subscriber, $other)
491 $user = User::staticGet('id', $subscriber->id);
497 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
499 if (empty($oprofile)) {
503 if (!$oprofile->subscribe()) {
504 throw new Exception(_m('Could not set up remote subscription.'));
509 * Having established a remote subscription, send a notification to the
510 * remote OStatus profile's endpoint.
512 * @param Profile $subscriber
513 * @param Profile $other
515 * @return hook return code
519 function onEndSubscribe($subscriber, $other)
521 $user = User::staticGet('id', $subscriber->id);
527 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
529 if (empty($oprofile)) {
533 $act = new Activity();
535 $act->verb = ActivityVerb::FOLLOW;
537 $act->id = TagURI::mint('follow:%d:%d:%s',
540 common_date_iso8601(time()));
543 $act->title = _("Follow");
544 $act->content = sprintf(_("%s is now following %s."),
545 $subscriber->getBestName(),
546 $other->getBestName());
548 $act->actor = ActivityObject::fromProfile($subscriber);
549 $act->object = ActivityObject::fromProfile($other);
551 $oprofile->notifyActivity($act, $subscriber);
557 * Notify remote server and garbage collect unused feeds on unsubscribe.
558 * @fixme send these operations to background queues
561 * @param Profile $other
562 * @return hook return value
564 function onEndUnsubscribe($profile, $other)
566 $user = User::staticGet('id', $profile->id);
572 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
574 if (empty($oprofile)) {
578 // Drop the PuSH subscription if there are no other subscribers.
579 $oprofile->garbageCollect();
581 $act = new Activity();
583 $act->verb = ActivityVerb::UNFOLLOW;
585 $act->id = TagURI::mint('unfollow:%d:%d:%s',
588 common_date_iso8601(time()));
591 $act->title = _("Unfollow");
592 $act->content = sprintf(_("%s stopped following %s."),
593 $profile->getBestName(),
594 $other->getBestName());
596 $act->actor = ActivityObject::fromProfile($profile);
597 $act->object = ActivityObject::fromProfile($other);
599 $oprofile->notifyActivity($act, $profile);
605 * When one of our local users tries to join a remote group,
606 * notify the remote server. If the notification is rejected,
609 * @param User_group $group
612 * @return mixed hook return value
615 function onStartJoinGroup($group, $user)
617 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
619 if (!$oprofile->subscribe()) {
620 throw new Exception(_m('Could not set up remote group membership.'));
623 $member = Profile::staticGet($user->id);
625 $act = new Activity();
626 $act->id = TagURI::mint('join:%d:%d:%s',
629 common_date_iso8601(time()));
631 $act->actor = ActivityObject::fromProfile($member);
632 $act->verb = ActivityVerb::JOIN;
633 $act->object = $oprofile->asActivityObject();
636 $act->title = _m("Join");
637 $act->content = sprintf(_m("%s has joined group %s."),
638 $member->getBestName(),
639 $oprofile->getBestName());
641 if ($oprofile->notifyActivity($act, $member)) {
644 $oprofile->garbageCollect();
645 throw new Exception(_m("Failed joining remote group."));
651 * When one of our local users leaves a remote group, notify the remote
654 * @fixme Might be good to schedule a resend of the leave notification
655 * if it failed due to a transitory error. We've canceled the local
656 * membership already anyway, but if the remote server comes back up
657 * it'll be left with a stray membership record.
659 * @param User_group $group
662 * @return mixed hook return value
665 function onEndLeaveGroup($group, $user)
667 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
669 // Drop the PuSH subscription if there are no other subscribers.
670 $oprofile->garbageCollect();
672 $member = Profile::staticGet($user->id);
674 $act = new Activity();
675 $act->id = TagURI::mint('leave:%d:%d:%s',
678 common_date_iso8601(time()));
680 $act->actor = ActivityObject::fromProfile($member);
681 $act->verb = ActivityVerb::LEAVE;
682 $act->object = $oprofile->asActivityObject();
685 $act->title = _m("Leave");
686 $act->content = sprintf(_m("%s has left group %s."),
687 $member->getBestName(),
688 $oprofile->getBestName());
690 $oprofile->notifyActivity($act, $member);
695 * Notify remote users when their notices get favorited.
697 * @param Profile or User $profile of local user doing the faving
698 * @param Notice $notice being favored
699 * @return hook return value
702 function onEndFavorNotice(Profile $profile, Notice $notice)
704 $user = User::staticGet('id', $profile->id);
710 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
712 if (empty($oprofile)) {
716 $act = new Activity();
718 $act->verb = ActivityVerb::FAVORITE;
719 $act->id = TagURI::mint('favor:%d:%d:%s',
722 common_date_iso8601(time()));
725 $act->title = _("Favor");
726 $act->content = sprintf(_("%s marked notice %s as a favorite."),
727 $profile->getBestName(),
730 $act->actor = ActivityObject::fromProfile($profile);
731 $act->object = ActivityObject::fromNotice($notice);
733 $oprofile->notifyActivity($act, $profile);
739 * Notify remote users when their notices get de-favorited.
741 * @param Profile $profile Profile person doing the de-faving
742 * @param Notice $notice Notice being favored
744 * @return hook return value
747 function onEndDisfavorNotice(Profile $profile, Notice $notice)
749 $user = User::staticGet('id', $profile->id);
755 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
757 if (empty($oprofile)) {
761 $act = new Activity();
763 $act->verb = ActivityVerb::UNFAVORITE;
764 $act->id = TagURI::mint('disfavor:%d:%d:%s',
767 common_date_iso8601(time()));
769 $act->title = _("Disfavor");
770 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
771 $profile->getBestName(),
774 $act->actor = ActivityObject::fromProfile($profile);
775 $act->object = ActivityObject::fromNotice($notice);
777 $oprofile->notifyActivity($act, $profile);
782 function onStartGetProfileUri($profile, &$uri)
784 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
785 if (!empty($oprofile)) {
786 $uri = $oprofile->uri;
792 function onStartUserGroupHomeUrl($group, &$url)
794 return $this->onStartUserGroupPermalink($group, $url);
797 function onStartUserGroupPermalink($group, &$url)
799 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
801 // @fixme this should probably be in the user_group table
802 // @fixme this uri not guaranteed to be a profile page
803 $url = $oprofile->uri;
808 function onStartShowSubscriptionsContent($action)
810 $this->showEntityRemoteSubscribe($action);
815 function onStartShowUserGroupsContent($action)
817 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
822 function onEndShowSubscriptionsMiniList($action)
824 $this->showEntityRemoteSubscribe($action);
829 function onEndShowGroupsMiniList($action)
831 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
836 function showEntityRemoteSubscribe($action, $target='ostatussub')
838 $user = common_current_user();
839 if ($user && ($user->id == $action->profile->id)) {
840 $action->elementStart('div', 'entity_actions');
841 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
842 'class' => 'entity_subscribe'));
843 $action->element('a', array('href' => common_local_url($target),
844 'class' => 'entity_remote_subscribe')
846 $action->elementEnd('p');
847 $action->elementEnd('div');
852 * Ping remote profiles with updates to this profile.
853 * Salmon pings are queued for background processing.
855 function onEndBroadcastProfile(Profile $profile)
857 $user = User::staticGet('id', $profile->id);
859 // Find foreign accounts I'm subscribed to that support Salmon pings.
861 // @fixme we could run updates through the PuSH feed too,
862 // in which case we can skip Salmon pings to folks who
863 // are also subscribed to me.
864 $sql = "SELECT * FROM ostatus_profile " .
865 "WHERE profile_id IN " .
866 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
868 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
869 $oprofile = new Ostatus_profile();
870 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
872 if ($oprofile->N == 0) {
873 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
877 $act = new Activity();
879 $act->verb = ActivityVerb::UPDATE_PROFILE;
880 $act->id = TagURI::mint('update-profile:%d:%s',
882 common_date_iso8601(time()));
884 $act->title = _m("Profile update");
885 $act->content = sprintf(_m("%s has updated their profile page."),
886 $profile->getBestName());
888 $act->actor = ActivityObject::fromProfile($profile);
889 $act->object = $act->actor;
891 while ($oprofile->fetch()) {
892 $oprofile->notifyDeferred($act, $profile);
898 function onStartProfileListItemActionElements($item)
900 if (!common_logged_in()) {
902 $profileUser = User::staticGet('id', $item->profile->id);
904 if (!empty($profileUser)) {
906 $output = $item->out;
908 // Add an OStatus subscribe
909 $output->elementStart('li', 'entity_subscribe');
910 $url = common_local_url('ostatusinit',
911 array('nickname' => $profileUser->nickname));
912 $output->element('a', array('href' => $url,
913 'class' => 'entity_remote_subscribe'),
915 $output->elementEnd('li');
922 function onPluginVersion(&$versions)
924 $versions[] = array('name' => 'OStatus',
925 'version' => STATUSNET_VERSION,
926 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
927 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
929 _m('Follow people across social networks that implement '.
930 '<a href="http://ostatus.org/">OStatus</a>.'));
936 * Utility function to check if the given URL is a canonical group profile
937 * page, and if so return the ID number.
940 * @return mixed int or false
942 public static function localGroupFromUrl($url)
944 $template = common_local_url('groupbyid', array('id' => '31337'));
945 $template = preg_quote($template, '/');
946 $template = str_replace('31337', '(\d+)', $template);
947 if (preg_match("/$template/", $url, $matches)) {
948 return intval($matches[1]);