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');
213 function onStartGroupSubscribe($output, $group)
215 $cur = common_current_user();
218 // Add an OStatus subscribe
219 $output->elementStart('li', 'entity_subscribe');
220 $url = common_local_url('ostatusinit',
221 array('nickname' => $group->nickname));
222 $output->element('a', array('href' => $url,
223 'class' => 'entity_remote_subscribe'),
226 $output->elementEnd('li');
234 * Check if we've got remote replies to send via Salmon.
236 * @fixme push webfinger lookup & sending to a background queue
237 * @fixme also detect short-form name for remote subscribees where not ambiguous
240 function onEndNoticeSave($notice)
245 * Find any explicit remote mentions. Accepted forms:
246 * Webfinger: @user@example.com
247 * Profile link: @example.com/mublog/user
248 * @param Profile $sender (os user?)
249 * @param string $text input markup text
250 * @param array &$mention in/out param: set of found mentions
251 * @return boolean hook return value
254 function onEndFindMentions($sender, $text, &$mentions)
256 preg_match_all('!(?:^|\s+)
260 (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ # domain
262 (?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+ # domain
263 (?:/\w+)+ # /path1(/path2...)
267 PREG_OFFSET_CAPTURE);
269 foreach ($wmatches[1] as $wmatch) {
270 $target = $wmatch[0];
273 if (strpos($target, '/') === false) {
274 $this->log(LOG_INFO, "Checking Webfinger for address '$target'");
276 $oprofile = Ostatus_profile::ensureWebfinger($target);
277 } catch (Exception $e) {
278 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
281 $schemes = array('https', 'http');
282 foreach ($schemes as $scheme) {
283 $url = "$scheme://$target";
284 $this->log(LOG_INFO, "Checking profile address '$url'");
286 $oprofile = Ostatus_profile::ensureProfile($url);
290 } catch (Exception $e) {
291 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
296 if (empty($oprofile)) {
297 $this->log(LOG_INFO, "No Ostatus_profile found for address '$target'");
300 $this->log(LOG_INFO, "Ostatus_profile found for address '$target'");
302 if ($oprofile->isGroup()) {
305 $profile = $oprofile->localProfile();
308 foreach ($mentions as $i => $other) {
309 // If we share a common prefix with a local user, override it!
310 if ($other['position'] == $pos) {
311 unset($mentions[$i]);
314 $mentions[] = array('mentioned' => array($profile),
317 'url' => $profile->profileurl);
325 * Make sure necessary tables are filled out.
327 function onCheckSchema() {
328 $schema = Schema::get();
329 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
330 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
331 $schema->ensureTable('feedsub', FeedSub::schemaDef());
332 $schema->ensureTable('hubsub', HubSub::schemaDef());
333 $schema->ensureTable('magicsig', Magicsig::schemaDef());
337 function onEndShowStatusNetStyles($action) {
338 $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
342 function onEndShowStatusNetScripts($action) {
343 $action->script(common_path('plugins/OStatus/js/ostatus.js'));
348 * Override the "from ostatus" bit in notice lists to link to the
349 * original post and show the domain it came from.
351 * @param Notice in $notice
352 * @param string out &$name
353 * @param string out &$url
354 * @param string out &$title
355 * @return mixed hook return code
357 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
359 if ($notice->source == 'ostatus') {
361 $bits = parse_url($notice->url);
362 $domain = $bits['host'];
363 if (substr($domain, 0, 4) == 'www.') {
364 $name = substr($domain, 4);
370 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
377 * Send incoming PuSH feeds for OStatus endpoints in for processing.
379 * @param FeedSub $feedsub
380 * @param DOMDocument $feed
381 * @return mixed hook return code
383 function onStartFeedSubReceive($feedsub, $feed)
385 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
387 $oprofile->processFeed($feed, 'push');
389 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
394 * When about to subscribe to a remote user, start a server-to-server
395 * PuSH subscription if needed. If we can't establish that, abort.
397 * @fixme If something else aborts later, we could end up with a stray
398 * PuSH subscription. This is relatively harmless, though.
400 * @param Profile $subscriber
401 * @param Profile $other
403 * @return hook return code
407 function onStartSubscribe($subscriber, $other)
409 $user = User::staticGet('id', $subscriber->id);
415 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
417 if (empty($oprofile)) {
421 if (!$oprofile->subscribe()) {
422 throw new Exception(_m('Could not set up remote subscription.'));
427 * Having established a remote subscription, send a notification to the
428 * remote OStatus profile's endpoint.
430 * @param Profile $subscriber
431 * @param Profile $other
433 * @return hook return code
437 function onEndSubscribe($subscriber, $other)
439 $user = User::staticGet('id', $subscriber->id);
445 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
447 if (empty($oprofile)) {
451 $act = new Activity();
453 $act->verb = ActivityVerb::FOLLOW;
455 $act->id = TagURI::mint('follow:%d:%d:%s',
458 common_date_iso8601(time()));
461 $act->title = _("Follow");
462 $act->content = sprintf(_("%s is now following %s."),
463 $subscriber->getBestName(),
464 $other->getBestName());
466 $act->actor = ActivityObject::fromProfile($subscriber);
467 $act->object = ActivityObject::fromProfile($other);
469 $oprofile->notifyActivity($act, $subscriber);
475 * Notify remote server and garbage collect unused feeds on unsubscribe.
476 * @fixme send these operations to background queues
479 * @param Profile $other
480 * @return hook return value
482 function onEndUnsubscribe($profile, $other)
484 $user = User::staticGet('id', $profile->id);
490 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
492 if (empty($oprofile)) {
496 // Drop the PuSH subscription if there are no other subscribers.
497 $oprofile->garbageCollect();
499 $act = new Activity();
501 $act->verb = ActivityVerb::UNFOLLOW;
503 $act->id = TagURI::mint('unfollow:%d:%d:%s',
506 common_date_iso8601(time()));
509 $act->title = _("Unfollow");
510 $act->content = sprintf(_("%s stopped following %s."),
511 $profile->getBestName(),
512 $other->getBestName());
514 $act->actor = ActivityObject::fromProfile($profile);
515 $act->object = ActivityObject::fromProfile($other);
517 $oprofile->notifyActivity($act, $profile);
523 * When one of our local users tries to join a remote group,
524 * notify the remote server. If the notification is rejected,
527 * @param User_group $group
530 * @return mixed hook return value
533 function onStartJoinGroup($group, $user)
535 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
537 if (!$oprofile->subscribe()) {
538 throw new Exception(_m('Could not set up remote group membership.'));
541 $member = Profile::staticGet($user->id);
543 $act = new Activity();
544 $act->id = TagURI::mint('join:%d:%d:%s',
547 common_date_iso8601(time()));
549 $act->actor = ActivityObject::fromProfile($member);
550 $act->verb = ActivityVerb::JOIN;
551 $act->object = $oprofile->asActivityObject();
554 $act->title = _m("Join");
555 $act->content = sprintf(_m("%s has joined group %s."),
556 $member->getBestName(),
557 $oprofile->getBestName());
559 if ($oprofile->notifyActivity($act, $member)) {
562 $oprofile->garbageCollect();
563 throw new Exception(_m("Failed joining remote group."));
569 * When one of our local users leaves a remote group, notify the remote
572 * @fixme Might be good to schedule a resend of the leave notification
573 * if it failed due to a transitory error. We've canceled the local
574 * membership already anyway, but if the remote server comes back up
575 * it'll be left with a stray membership record.
577 * @param User_group $group
580 * @return mixed hook return value
583 function onEndLeaveGroup($group, $user)
585 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
587 // Drop the PuSH subscription if there are no other subscribers.
588 $oprofile->garbageCollect();
591 $member = Profile::staticGet($user->id);
593 $act = new Activity();
594 $act->id = TagURI::mint('leave:%d:%d:%s',
597 common_date_iso8601(time()));
599 $act->actor = ActivityObject::fromProfile($member);
600 $act->verb = ActivityVerb::LEAVE;
601 $act->object = $oprofile->asActivityObject();
604 $act->title = _m("Leave");
605 $act->content = sprintf(_m("%s has left group %s."),
606 $member->getBestName(),
607 $oprofile->getBestName());
609 $oprofile->notifyActivity($act, $member);
614 * Notify remote users when their notices get favorited.
616 * @param Profile or User $profile of local user doing the faving
617 * @param Notice $notice being favored
618 * @return hook return value
621 function onEndFavorNotice(Profile $profile, Notice $notice)
623 $user = User::staticGet('id', $profile->id);
629 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
631 if (empty($oprofile)) {
635 $act = new Activity();
637 $act->verb = ActivityVerb::FAVORITE;
638 $act->id = TagURI::mint('favor:%d:%d:%s',
641 common_date_iso8601(time()));
644 $act->title = _("Favor");
645 $act->content = sprintf(_("%s marked notice %s as a favorite."),
646 $profile->getBestName(),
649 $act->actor = ActivityObject::fromProfile($profile);
650 $act->object = ActivityObject::fromNotice($notice);
652 $oprofile->notifyActivity($act, $profile);
658 * Notify remote users when their notices get de-favorited.
660 * @param Profile $profile Profile person doing the de-faving
661 * @param Notice $notice Notice being favored
663 * @return hook return value
666 function onEndDisfavorNotice(Profile $profile, Notice $notice)
668 $user = User::staticGet('id', $profile->id);
674 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
676 if (empty($oprofile)) {
680 $act = new Activity();
682 $act->verb = ActivityVerb::UNFAVORITE;
683 $act->id = TagURI::mint('disfavor:%d:%d:%s',
686 common_date_iso8601(time()));
688 $act->title = _("Disfavor");
689 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
690 $profile->getBestName(),
693 $act->actor = ActivityObject::fromProfile($profile);
694 $act->object = ActivityObject::fromNotice($notice);
696 $oprofile->notifyActivity($act, $profile);
701 function onStartGetProfileUri($profile, &$uri)
703 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
704 if (!empty($oprofile)) {
705 $uri = $oprofile->uri;
711 function onStartUserGroupHomeUrl($group, &$url)
713 return $this->onStartUserGroupPermalink($group, $url);
716 function onStartUserGroupPermalink($group, &$url)
718 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
720 // @fixme this should probably be in the user_group table
721 // @fixme this uri not guaranteed to be a profile page
722 $url = $oprofile->uri;
727 function onStartShowSubscriptionsContent($action)
729 $this->showEntityRemoteSubscribe($action);
734 function onEndShowSubscriptionsMiniList($action)
736 $this->showEntityRemoteSubscribe($action);
741 function showEntityRemoteSubscribe($action)
743 $user = common_current_user();
744 if ($user && ($user->id == $action->profile->id)) {
745 $action->elementStart('div', 'entity_actions');
746 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
747 'class' => 'entity_subscribe'));
748 $action->element('a', array('href' => common_local_url('ostatussub'),
749 'class' => 'entity_remote_subscribe')
751 $action->elementEnd('p');
752 $action->elementEnd('div');
757 * Ping remote profiles with updates to this profile.
758 * Salmon pings are queued for background processing.
760 function onEndBroadcastProfile(Profile $profile)
762 $user = User::staticGet('id', $profile->id);
764 // Find foreign accounts I'm subscribed to that support Salmon pings.
766 // @fixme we could run updates through the PuSH feed too,
767 // in which case we can skip Salmon pings to folks who
768 // are also subscribed to me.
769 $sql = "SELECT * FROM ostatus_profile " .
770 "WHERE profile_id IN " .
771 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
773 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
774 $oprofile = new Ostatus_profile();
775 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
777 if ($oprofile->N == 0) {
778 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
782 $act = new Activity();
784 $act->verb = ActivityVerb::UPDATE_PROFILE;
785 $act->id = TagURI::mint('update-profile:%d:%s',
787 common_date_iso8601(time()));
789 $act->title = _m("Profile update");
790 $act->content = sprintf(_m("%s has updated their profile page."),
791 $profile->getBestName());
793 $act->actor = ActivityObject::fromProfile($profile);
794 $act->object = $act->actor;
796 while ($oprofile->fetch()) {
797 $oprofile->notifyDeferred($act, $profile);