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');
233 * Check if we've got remote replies to send via Salmon.
235 * @fixme push webfinger lookup & sending to a background queue
236 * @fixme also detect short-form name for remote subscribees where not ambiguous
239 function onEndNoticeSave($notice)
244 * Find any explicit remote mentions. Accepted forms:
245 * Webfinger: @user@example.com
246 * Profile link: @example.com/mublog/user
247 * @param Profile $sender (os user?)
248 * @param string $text input markup text
249 * @param array &$mention in/out param: set of found mentions
250 * @return boolean hook return value
253 function onEndFindMentions($sender, $text, &$mentions)
257 // Webfinger matches: @user@example.com
258 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
261 PREG_OFFSET_CAPTURE)) {
262 foreach ($wmatches[1] as $wmatch) {
263 list($target, $pos) = $wmatch;
264 $this->log(LOG_INFO, "Checking webfinger '$target'");
266 $oprofile = Ostatus_profile::ensureWebfinger($target);
267 if ($oprofile && !$oprofile->isGroup()) {
268 $profile = $oprofile->localProfile();
269 $matches[$pos] = array('mentioned' => array($profile),
272 'url' => $profile->profileurl);
274 } catch (Exception $e) {
275 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
280 // Profile matches: @example.com/mublog/user
281 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
284 PREG_OFFSET_CAPTURE)) {
285 foreach ($wmatches[1] as $wmatch) {
286 list($target, $pos) = $wmatch;
287 $schemes = array('http', 'https');
288 foreach ($schemes as $scheme) {
289 $url = "$scheme://$target";
290 $this->log(LOG_INFO, "Checking profile address '$url'");
292 $oprofile = Ostatus_profile::ensureProfile($url);
293 if ($oprofile && !$oprofile->isGroup()) {
294 $profile = $oprofile->localProfile();
295 $matches[$pos] = array('mentioned' => array($profile),
298 'url' => $profile->profileurl);
301 } catch (Exception $e) {
302 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
308 foreach ($mentions as $i => $other) {
309 // If we share a common prefix with a local user, override it!
310 $pos = $other['position'];
311 if (isset($matches[$pos])) {
312 $mentions[$i] = $matches[$pos];
313 unset($matches[$pos]);
316 foreach ($matches as $mention) {
317 $mentions[] = $mention;
324 * Make sure necessary tables are filled out.
326 function onCheckSchema() {
327 $schema = Schema::get();
328 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
329 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
330 $schema->ensureTable('feedsub', FeedSub::schemaDef());
331 $schema->ensureTable('hubsub', HubSub::schemaDef());
332 $schema->ensureTable('magicsig', Magicsig::schemaDef());
336 function onEndShowStatusNetStyles($action) {
337 $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
341 function onEndShowStatusNetScripts($action) {
342 $action->script(common_path('plugins/OStatus/js/ostatus.js'));
347 * Override the "from ostatus" bit in notice lists to link to the
348 * original post and show the domain it came from.
350 * @param Notice in $notice
351 * @param string out &$name
352 * @param string out &$url
353 * @param string out &$title
354 * @return mixed hook return code
356 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
358 if ($notice->source == 'ostatus') {
360 $bits = parse_url($notice->url);
361 $domain = $bits['host'];
362 if (substr($domain, 0, 4) == 'www.') {
363 $name = substr($domain, 4);
369 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
376 * Send incoming PuSH feeds for OStatus endpoints in for processing.
378 * @param FeedSub $feedsub
379 * @param DOMDocument $feed
380 * @return mixed hook return code
382 function onStartFeedSubReceive($feedsub, $feed)
384 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
386 $oprofile->processFeed($feed, 'push');
388 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
393 * When about to subscribe to a remote user, start a server-to-server
394 * PuSH subscription if needed. If we can't establish that, abort.
396 * @fixme If something else aborts later, we could end up with a stray
397 * PuSH subscription. This is relatively harmless, though.
399 * @param Profile $subscriber
400 * @param Profile $other
402 * @return hook return code
406 function onStartSubscribe($subscriber, $other)
408 $user = User::staticGet('id', $subscriber->id);
414 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
416 if (empty($oprofile)) {
420 if (!$oprofile->subscribe()) {
421 throw new Exception(_m('Could not set up remote subscription.'));
426 * Having established a remote subscription, send a notification to the
427 * remote OStatus profile's endpoint.
429 * @param Profile $subscriber
430 * @param Profile $other
432 * @return hook return code
436 function onEndSubscribe($subscriber, $other)
438 $user = User::staticGet('id', $subscriber->id);
444 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
446 if (empty($oprofile)) {
450 $act = new Activity();
452 $act->verb = ActivityVerb::FOLLOW;
454 $act->id = TagURI::mint('follow:%d:%d:%s',
457 common_date_iso8601(time()));
460 $act->title = _("Follow");
461 $act->content = sprintf(_("%s is now following %s."),
462 $subscriber->getBestName(),
463 $other->getBestName());
465 $act->actor = ActivityObject::fromProfile($subscriber);
466 $act->object = ActivityObject::fromProfile($other);
468 $oprofile->notifyActivity($act, $subscriber);
474 * Notify remote server and garbage collect unused feeds on unsubscribe.
475 * @fixme send these operations to background queues
478 * @param Profile $other
479 * @return hook return value
481 function onEndUnsubscribe($profile, $other)
483 $user = User::staticGet('id', $profile->id);
489 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
491 if (empty($oprofile)) {
495 // Drop the PuSH subscription if there are no other subscribers.
496 $oprofile->garbageCollect();
498 $act = new Activity();
500 $act->verb = ActivityVerb::UNFOLLOW;
502 $act->id = TagURI::mint('unfollow:%d:%d:%s',
505 common_date_iso8601(time()));
508 $act->title = _("Unfollow");
509 $act->content = sprintf(_("%s stopped following %s."),
510 $profile->getBestName(),
511 $other->getBestName());
513 $act->actor = ActivityObject::fromProfile($profile);
514 $act->object = ActivityObject::fromProfile($other);
516 $oprofile->notifyActivity($act, $profile);
522 * When one of our local users tries to join a remote group,
523 * notify the remote server. If the notification is rejected,
526 * @param User_group $group
529 * @return mixed hook return value
532 function onStartJoinGroup($group, $user)
534 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
536 if (!$oprofile->subscribe()) {
537 throw new Exception(_m('Could not set up remote group membership.'));
540 $member = Profile::staticGet($user->id);
542 $act = new Activity();
543 $act->id = TagURI::mint('join:%d:%d:%s',
546 common_date_iso8601(time()));
548 $act->actor = ActivityObject::fromProfile($member);
549 $act->verb = ActivityVerb::JOIN;
550 $act->object = $oprofile->asActivityObject();
553 $act->title = _m("Join");
554 $act->content = sprintf(_m("%s has joined group %s."),
555 $member->getBestName(),
556 $oprofile->getBestName());
558 if ($oprofile->notifyActivity($act, $member)) {
561 $oprofile->garbageCollect();
562 throw new Exception(_m("Failed joining remote group."));
568 * When one of our local users leaves a remote group, notify the remote
571 * @fixme Might be good to schedule a resend of the leave notification
572 * if it failed due to a transitory error. We've canceled the local
573 * membership already anyway, but if the remote server comes back up
574 * it'll be left with a stray membership record.
576 * @param User_group $group
579 * @return mixed hook return value
582 function onEndLeaveGroup($group, $user)
584 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
586 // Drop the PuSH subscription if there are no other subscribers.
587 $oprofile->garbageCollect();
589 $member = Profile::staticGet($user->id);
591 $act = new Activity();
592 $act->id = TagURI::mint('leave:%d:%d:%s',
595 common_date_iso8601(time()));
597 $act->actor = ActivityObject::fromProfile($member);
598 $act->verb = ActivityVerb::LEAVE;
599 $act->object = $oprofile->asActivityObject();
602 $act->title = _m("Leave");
603 $act->content = sprintf(_m("%s has left group %s."),
604 $member->getBestName(),
605 $oprofile->getBestName());
607 $oprofile->notifyActivity($act, $member);
612 * Notify remote users when their notices get favorited.
614 * @param Profile or User $profile of local user doing the faving
615 * @param Notice $notice being favored
616 * @return hook return value
619 function onEndFavorNotice(Profile $profile, Notice $notice)
621 $user = User::staticGet('id', $profile->id);
627 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
629 if (empty($oprofile)) {
633 $act = new Activity();
635 $act->verb = ActivityVerb::FAVORITE;
636 $act->id = TagURI::mint('favor:%d:%d:%s',
639 common_date_iso8601(time()));
642 $act->title = _("Favor");
643 $act->content = sprintf(_("%s marked notice %s as a favorite."),
644 $profile->getBestName(),
647 $act->actor = ActivityObject::fromProfile($profile);
648 $act->object = ActivityObject::fromNotice($notice);
650 $oprofile->notifyActivity($act, $profile);
656 * Notify remote users when their notices get de-favorited.
658 * @param Profile $profile Profile person doing the de-faving
659 * @param Notice $notice Notice being favored
661 * @return hook return value
664 function onEndDisfavorNotice(Profile $profile, Notice $notice)
666 $user = User::staticGet('id', $profile->id);
672 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
674 if (empty($oprofile)) {
678 $act = new Activity();
680 $act->verb = ActivityVerb::UNFAVORITE;
681 $act->id = TagURI::mint('disfavor:%d:%d:%s',
684 common_date_iso8601(time()));
686 $act->title = _("Disfavor");
687 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
688 $profile->getBestName(),
691 $act->actor = ActivityObject::fromProfile($profile);
692 $act->object = ActivityObject::fromNotice($notice);
694 $oprofile->notifyActivity($act, $profile);
699 function onStartGetProfileUri($profile, &$uri)
701 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
702 if (!empty($oprofile)) {
703 $uri = $oprofile->uri;
709 function onStartUserGroupHomeUrl($group, &$url)
711 return $this->onStartUserGroupPermalink($group, $url);
714 function onStartUserGroupPermalink($group, &$url)
716 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
718 // @fixme this should probably be in the user_group table
719 // @fixme this uri not guaranteed to be a profile page
720 $url = $oprofile->uri;
725 function onStartShowSubscriptionsContent($action)
727 $this->showEntityRemoteSubscribe($action);
732 function onEndShowSubscriptionsMiniList($action)
734 $this->showEntityRemoteSubscribe($action);
739 function onEndShowGroupsMiniList($action)
741 $this->showEntityRemoteSubscribe($action);
746 function showEntityRemoteSubscribe($action)
748 $user = common_current_user();
749 if ($user && ($user->id == $action->profile->id)) {
750 $action->elementStart('div', 'entity_actions');
751 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
752 'class' => 'entity_subscribe'));
753 $action->element('a', array('href' => common_local_url('ostatussub'),
754 'class' => 'entity_remote_subscribe')
756 $action->elementEnd('p');
757 $action->elementEnd('div');
762 * Ping remote profiles with updates to this profile.
763 * Salmon pings are queued for background processing.
765 function onEndBroadcastProfile(Profile $profile)
767 $user = User::staticGet('id', $profile->id);
769 // Find foreign accounts I'm subscribed to that support Salmon pings.
771 // @fixme we could run updates through the PuSH feed too,
772 // in which case we can skip Salmon pings to folks who
773 // are also subscribed to me.
774 $sql = "SELECT * FROM ostatus_profile " .
775 "WHERE profile_id IN " .
776 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
778 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
779 $oprofile = new Ostatus_profile();
780 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
782 if ($oprofile->N == 0) {
783 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
787 $act = new Activity();
789 $act->verb = ActivityVerb::UPDATE_PROFILE;
790 $act->id = TagURI::mint('update-profile:%d:%s',
792 common_date_iso8601(time()));
794 $act->title = _m("Profile update");
795 $act->content = sprintf(_m("%s has updated their profile page."),
796 $profile->getBestName());
798 $act->actor = ActivityObject::fromProfile($profile);
799 $act->object = $act->actor;
801 while ($oprofile->fetch()) {
802 $oprofile->notifyDeferred($act, $profile);
808 function onStartProfileListItemActionElements($item)
810 if (!common_logged_in()) {
812 $profileUser = User::staticGet('id', $item->profile->id);
814 if (!empty($profileUser)) {
816 $output = $item->out;
818 // Add an OStatus subscribe
819 $output->elementStart('li', 'entity_subscribe');
820 $url = common_local_url('ostatusinit',
821 array('nickname' => $profileUser->nickname));
822 $output->element('a', array('href' => $url,
823 'class' => 'entity_remote_subscribe'),
825 $output->elementEnd('li');