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 if ($notice->isLocal()) {
106 // put our transport first, in case there's any conflict (like OMB)
107 array_unshift($transports, 'ostatus');
113 * Add a link header for LRDD Discovery
115 function onStartShowHTML($action)
117 if ($action instanceof ShowstreamAction) {
118 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
119 $url = common_local_url('userxrd');
120 $url.= '?uri='. $acct;
122 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
127 * Set up a PuSH hub link to our internal link for canonical timeline
128 * Atom feeds for users and groups.
130 function onStartApiAtom($feed)
134 if ($feed instanceof AtomUserNoticeFeed) {
135 $salmonAction = 'usersalmon';
136 $user = $feed->getUser();
138 $profile = $user->getProfile();
139 $feed->setActivitySubject($profile->asActivityNoun('subject'));
140 } else if ($feed instanceof AtomGroupNoticeFeed) {
141 $salmonAction = 'groupsalmon';
142 $group = $feed->getGroup();
144 $feed->setActivitySubject($group->asActivitySubject());
150 $hub = common_config('ostatus', 'hub');
152 // Updates will be handled through our internal PuSH hub.
153 $hub = common_local_url('pushhub');
155 $feed->addLink($hub, array('rel' => 'hub'));
157 // Also, we'll add in the salmon link
158 $salmon = common_local_url($salmonAction, array('id' => $id));
159 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
160 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
167 * Automatically load the actions and libraries used by the plugin
169 * @param Class $cls the class
171 * @return boolean hook return
174 function onAutoload($cls)
176 $base = dirname(__FILE__);
177 $lower = strtolower($cls);
178 $map = array('activityverb' => 'activity',
179 'activityobject' => 'activity',
180 'activityutils' => 'activity');
181 if (isset($map[$lower])) {
182 $lower = $map[$lower];
184 $files = array("$base/classes/$cls.php",
185 "$base/lib/$lower.php");
186 if (substr($lower, -6) == 'action') {
187 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
189 foreach ($files as $file) {
190 if (file_exists($file)) {
199 * Add in an OStatus subscribe button
201 function onStartProfileRemoteSubscribe($output, $profile)
203 $cur = common_current_user();
206 // Add an OStatus subscribe
207 $output->elementStart('li', 'entity_subscribe');
208 $url = common_local_url('ostatusinit',
209 array('nickname' => $profile->nickname));
210 $output->element('a', array('href' => $url,
211 'class' => 'entity_remote_subscribe'),
214 $output->elementEnd('li');
220 function onStartGroupSubscribe($output, $group)
222 $cur = common_current_user();
225 // Add an OStatus subscribe
226 $url = common_local_url('ostatusinit',
227 array('group' => $group->nickname));
228 $output->element('a', array('href' => $url,
229 'class' => 'entity_remote_subscribe'),
237 * Check if we've got remote replies to send via Salmon.
239 * @fixme push webfinger lookup & sending to a background queue
240 * @fixme also detect short-form name for remote subscribees where not ambiguous
243 function onEndNoticeSave($notice)
248 * Find any explicit remote mentions. Accepted forms:
249 * Webfinger: @user@example.com
250 * Profile link: @example.com/mublog/user
251 * @param Profile $sender (os user?)
252 * @param string $text input markup text
253 * @param array &$mention in/out param: set of found mentions
254 * @return boolean hook return value
257 function onEndFindMentions($sender, $text, &$mentions)
261 // Webfinger matches: @user@example.com
262 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
265 PREG_OFFSET_CAPTURE)) {
266 foreach ($wmatches[1] as $wmatch) {
267 list($target, $pos) = $wmatch;
268 $this->log(LOG_INFO, "Checking webfinger '$target'");
270 $oprofile = Ostatus_profile::ensureWebfinger($target);
271 if ($oprofile && !$oprofile->isGroup()) {
272 $profile = $oprofile->localProfile();
273 $matches[$pos] = array('mentioned' => array($profile),
276 'url' => $profile->profileurl);
278 } catch (Exception $e) {
279 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
284 // Profile matches: @example.com/mublog/user
285 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
288 PREG_OFFSET_CAPTURE)) {
289 foreach ($wmatches[1] as $wmatch) {
290 list($target, $pos) = $wmatch;
291 $schemes = array('http', 'https');
292 foreach ($schemes as $scheme) {
293 $url = "$scheme://$target";
294 $this->log(LOG_INFO, "Checking profile address '$url'");
296 $oprofile = Ostatus_profile::ensureProfileURL($url);
297 if ($oprofile && !$oprofile->isGroup()) {
298 $profile = $oprofile->localProfile();
299 $matches[$pos] = array('mentioned' => array($profile),
302 'url' => $profile->profileurl);
305 } catch (Exception $e) {
306 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
312 foreach ($mentions as $i => $other) {
313 // If we share a common prefix with a local user, override it!
314 $pos = $other['position'];
315 if (isset($matches[$pos])) {
316 $mentions[$i] = $matches[$pos];
317 unset($matches[$pos]);
320 foreach ($matches as $mention) {
321 $mentions[] = $mention;
328 * Allow remote profile references to be used in commands:
329 * sub update@status.net
330 * whois evan@identi.ca
331 * reply http://identi.ca/evan hey what's up
333 * @param Command $command
335 * @param Profile &$profile
336 * @return hook return code
338 function onStartCommandGetProfile($command, $arg, &$profile)
340 $oprofile = $this->pullRemoteProfile($arg);
341 if ($oprofile && !$oprofile->isGroup()) {
342 $profile = $oprofile->localProfile();
350 * Allow remote group references to be used in commands:
351 * join group+statusnet@identi.ca
352 * join http://identi.ca/group/statusnet
353 * drop identi.ca/group/statusnet
355 * @param Command $command
357 * @param User_group &$group
358 * @return hook return code
360 function onStartCommandGetGroup($command, $arg, &$group)
362 $oprofile = $this->pullRemoteProfile($arg);
363 if ($oprofile && $oprofile->isGroup()) {
364 $group = $oprofile->localGroup();
371 protected function pullRemoteProfile($arg)
374 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
377 return Ostatus_profile::ensureWebfinger($arg);
378 } catch (Exception $e) {
379 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
380 $arg . ': ' . $e->getMessage());
384 // Look for profile URLs, with or without scheme:
386 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
389 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
390 $schemes = array('http', 'https');
391 foreach ($schemes as $scheme) {
392 $urls[] = "$scheme://$arg";
396 foreach ($urls as $url) {
398 return Ostatus_profile::ensureProfileURL($url);
399 } catch (Exception $e) {
400 common_log(LOG_ERR, 'Profile lookup failed for ' .
401 $arg . ': ' . $e->getMessage());
408 * Make sure necessary tables are filled out.
410 function onCheckSchema() {
411 $schema = Schema::get();
412 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
413 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
414 $schema->ensureTable('feedsub', FeedSub::schemaDef());
415 $schema->ensureTable('hubsub', HubSub::schemaDef());
416 $schema->ensureTable('magicsig', Magicsig::schemaDef());
420 function onEndShowStatusNetStyles($action) {
421 $action->cssLink('plugins/OStatus/theme/base/css/ostatus.css');
425 function onEndShowStatusNetScripts($action) {
426 $action->script('plugins/OStatus/js/ostatus.js');
431 * Override the "from ostatus" bit in notice lists to link to the
432 * original post and show the domain it came from.
434 * @param Notice in $notice
435 * @param string out &$name
436 * @param string out &$url
437 * @param string out &$title
438 * @return mixed hook return code
440 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
442 if ($notice->source == 'ostatus') {
444 $bits = parse_url($notice->url);
445 $domain = $bits['host'];
446 if (substr($domain, 0, 4) == 'www.') {
447 $name = substr($domain, 4);
453 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
461 * Send incoming PuSH feeds for OStatus endpoints in for processing.
463 * @param FeedSub $feedsub
464 * @param DOMDocument $feed
465 * @return mixed hook return code
467 function onStartFeedSubReceive($feedsub, $feed)
469 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
471 $oprofile->processFeed($feed, 'push');
473 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
478 * When about to subscribe to a remote user, start a server-to-server
479 * PuSH subscription if needed. If we can't establish that, abort.
481 * @fixme If something else aborts later, we could end up with a stray
482 * PuSH subscription. This is relatively harmless, though.
484 * @param Profile $subscriber
485 * @param Profile $other
487 * @return hook return code
491 function onStartSubscribe($subscriber, $other)
493 $user = User::staticGet('id', $subscriber->id);
499 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
501 if (empty($oprofile)) {
505 if (!$oprofile->subscribe()) {
506 throw new Exception(_m('Could not set up remote subscription.'));
511 * Having established a remote subscription, send a notification to the
512 * remote OStatus profile's endpoint.
514 * @param Profile $subscriber
515 * @param Profile $other
517 * @return hook return code
521 function onEndSubscribe($subscriber, $other)
523 $user = User::staticGet('id', $subscriber->id);
529 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
531 if (empty($oprofile)) {
535 $act = new Activity();
537 $act->verb = ActivityVerb::FOLLOW;
539 $act->id = TagURI::mint('follow:%d:%d:%s',
542 common_date_iso8601(time()));
545 $act->title = _("Follow");
546 $act->content = sprintf(_("%s is now following %s."),
547 $subscriber->getBestName(),
548 $other->getBestName());
550 $act->actor = ActivityObject::fromProfile($subscriber);
551 $act->object = ActivityObject::fromProfile($other);
553 $oprofile->notifyActivity($act, $subscriber);
559 * Notify remote server and garbage collect unused feeds on unsubscribe.
560 * @fixme send these operations to background queues
563 * @param Profile $other
564 * @return hook return value
566 function onEndUnsubscribe($profile, $other)
568 $user = User::staticGet('id', $profile->id);
574 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
576 if (empty($oprofile)) {
580 // Drop the PuSH subscription if there are no other subscribers.
581 $oprofile->garbageCollect();
583 $act = new Activity();
585 $act->verb = ActivityVerb::UNFOLLOW;
587 $act->id = TagURI::mint('unfollow:%d:%d:%s',
590 common_date_iso8601(time()));
593 $act->title = _("Unfollow");
594 $act->content = sprintf(_("%s stopped following %s."),
595 $profile->getBestName(),
596 $other->getBestName());
598 $act->actor = ActivityObject::fromProfile($profile);
599 $act->object = ActivityObject::fromProfile($other);
601 $oprofile->notifyActivity($act, $profile);
607 * When one of our local users tries to join a remote group,
608 * notify the remote server. If the notification is rejected,
611 * @param User_group $group
614 * @return mixed hook return value
617 function onStartJoinGroup($group, $user)
619 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
621 if (!$oprofile->subscribe()) {
622 throw new Exception(_m('Could not set up remote group membership.'));
625 $member = Profile::staticGet($user->id);
627 $act = new Activity();
628 $act->id = TagURI::mint('join:%d:%d:%s',
631 common_date_iso8601(time()));
633 $act->actor = ActivityObject::fromProfile($member);
634 $act->verb = ActivityVerb::JOIN;
635 $act->object = $oprofile->asActivityObject();
638 $act->title = _m("Join");
639 $act->content = sprintf(_m("%s has joined group %s."),
640 $member->getBestName(),
641 $oprofile->getBestName());
643 if ($oprofile->notifyActivity($act, $member)) {
646 $oprofile->garbageCollect();
647 throw new Exception(_m("Failed joining remote group."));
653 * When one of our local users leaves a remote group, notify the remote
656 * @fixme Might be good to schedule a resend of the leave notification
657 * if it failed due to a transitory error. We've canceled the local
658 * membership already anyway, but if the remote server comes back up
659 * it'll be left with a stray membership record.
661 * @param User_group $group
664 * @return mixed hook return value
667 function onEndLeaveGroup($group, $user)
669 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
671 // Drop the PuSH subscription if there are no other subscribers.
672 $oprofile->garbageCollect();
674 $member = Profile::staticGet($user->id);
676 $act = new Activity();
677 $act->id = TagURI::mint('leave:%d:%d:%s',
680 common_date_iso8601(time()));
682 $act->actor = ActivityObject::fromProfile($member);
683 $act->verb = ActivityVerb::LEAVE;
684 $act->object = $oprofile->asActivityObject();
687 $act->title = _m("Leave");
688 $act->content = sprintf(_m("%s has left group %s."),
689 $member->getBestName(),
690 $oprofile->getBestName());
692 $oprofile->notifyActivity($act, $member);
697 * Notify remote users when their notices get favorited.
699 * @param Profile or User $profile of local user doing the faving
700 * @param Notice $notice being favored
701 * @return hook return value
704 function onEndFavorNotice(Profile $profile, Notice $notice)
706 $user = User::staticGet('id', $profile->id);
712 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
714 if (empty($oprofile)) {
718 $act = new Activity();
720 $act->verb = ActivityVerb::FAVORITE;
721 $act->id = TagURI::mint('favor:%d:%d:%s',
724 common_date_iso8601(time()));
727 $act->title = _("Favor");
728 $act->content = sprintf(_("%s marked notice %s as a favorite."),
729 $profile->getBestName(),
732 $act->actor = ActivityObject::fromProfile($profile);
733 $act->object = ActivityObject::fromNotice($notice);
735 $oprofile->notifyActivity($act, $profile);
741 * Notify remote users when their notices get de-favorited.
743 * @param Profile $profile Profile person doing the de-faving
744 * @param Notice $notice Notice being favored
746 * @return hook return value
749 function onEndDisfavorNotice(Profile $profile, Notice $notice)
751 $user = User::staticGet('id', $profile->id);
757 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
759 if (empty($oprofile)) {
763 $act = new Activity();
765 $act->verb = ActivityVerb::UNFAVORITE;
766 $act->id = TagURI::mint('disfavor:%d:%d:%s',
769 common_date_iso8601(time()));
771 $act->title = _("Disfavor");
772 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
773 $profile->getBestName(),
776 $act->actor = ActivityObject::fromProfile($profile);
777 $act->object = ActivityObject::fromNotice($notice);
779 $oprofile->notifyActivity($act, $profile);
784 function onStartGetProfileUri($profile, &$uri)
786 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
787 if (!empty($oprofile)) {
788 $uri = $oprofile->uri;
794 function onStartUserGroupHomeUrl($group, &$url)
796 return $this->onStartUserGroupPermalink($group, $url);
799 function onStartUserGroupPermalink($group, &$url)
801 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
803 // @fixme this should probably be in the user_group table
804 // @fixme this uri not guaranteed to be a profile page
805 $url = $oprofile->uri;
810 function onStartShowSubscriptionsContent($action)
812 $this->showEntityRemoteSubscribe($action);
817 function onStartShowUserGroupsContent($action)
819 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
824 function onEndShowSubscriptionsMiniList($action)
826 $this->showEntityRemoteSubscribe($action);
831 function onEndShowGroupsMiniList($action)
833 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
838 function showEntityRemoteSubscribe($action, $target='ostatussub')
840 $user = common_current_user();
841 if ($user && ($user->id == $action->profile->id)) {
842 $action->elementStart('div', 'entity_actions');
843 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
844 'class' => 'entity_subscribe'));
845 $action->element('a', array('href' => common_local_url($target),
846 'class' => 'entity_remote_subscribe')
848 $action->elementEnd('p');
849 $action->elementEnd('div');
854 * Ping remote profiles with updates to this profile.
855 * Salmon pings are queued for background processing.
857 function onEndBroadcastProfile(Profile $profile)
859 $user = User::staticGet('id', $profile->id);
861 // Find foreign accounts I'm subscribed to that support Salmon pings.
863 // @fixme we could run updates through the PuSH feed too,
864 // in which case we can skip Salmon pings to folks who
865 // are also subscribed to me.
866 $sql = "SELECT * FROM ostatus_profile " .
867 "WHERE profile_id IN " .
868 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
870 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
871 $oprofile = new Ostatus_profile();
872 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
874 if ($oprofile->N == 0) {
875 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
879 $act = new Activity();
881 $act->verb = ActivityVerb::UPDATE_PROFILE;
882 $act->id = TagURI::mint('update-profile:%d:%s',
884 common_date_iso8601(time()));
886 $act->title = _m("Profile update");
887 $act->content = sprintf(_m("%s has updated their profile page."),
888 $profile->getBestName());
890 $act->actor = ActivityObject::fromProfile($profile);
891 $act->object = $act->actor;
893 while ($oprofile->fetch()) {
894 $oprofile->notifyDeferred($act, $profile);
900 function onStartProfileListItemActionElements($item)
902 if (!common_logged_in()) {
904 $profileUser = User::staticGet('id', $item->profile->id);
906 if (!empty($profileUser)) {
908 $output = $item->out;
910 // Add an OStatus subscribe
911 $output->elementStart('li', 'entity_subscribe');
912 $url = common_local_url('ostatusinit',
913 array('nickname' => $profileUser->nickname));
914 $output->element('a', array('href' => $url,
915 'class' => 'entity_remote_subscribe'),
917 $output->elementEnd('li');
924 function onPluginVersion(&$versions)
926 $versions[] = array('name' => 'OStatus',
927 'version' => STATUSNET_VERSION,
928 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
929 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
931 _m('Follow people across social networks that implement '.
932 '<a href="http://ostatus.org/">OStatus</a>.'));
938 * Utility function to check if the given URL is a canonical group profile
939 * page, and if so return the ID number.
942 * @return mixed int or false
944 public static function localGroupFromUrl($url)
946 $template = common_local_url('groupbyid', array('id' => '31337'));
947 $template = preg_quote($template, '/');
948 $template = str_replace('31337', '(\d+)', $template);
949 if (preg_match("/$template/", $url, $matches)) {
950 return intval($matches[1]);