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'));
159 * Automatically load the actions and libraries used by the plugin
161 * @param Class $cls the class
163 * @return boolean hook return
166 function onAutoload($cls)
168 $base = dirname(__FILE__);
169 $lower = strtolower($cls);
170 $map = array('activityverb' => 'activity',
171 'activityobject' => 'activity',
172 'activityutils' => 'activity');
173 if (isset($map[$lower])) {
174 $lower = $map[$lower];
176 $files = array("$base/classes/$cls.php",
177 "$base/lib/$lower.php");
178 if (substr($lower, -6) == 'action') {
179 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
181 foreach ($files as $file) {
182 if (file_exists($file)) {
191 * Add in an OStatus subscribe button
193 function onStartProfileRemoteSubscribe($output, $profile)
195 $cur = common_current_user();
198 // Add an OStatus subscribe
199 $output->elementStart('li', 'entity_subscribe');
200 $url = common_local_url('ostatusinit',
201 array('nickname' => $profile->nickname));
202 $output->element('a', array('href' => $url,
203 'class' => 'entity_remote_subscribe'),
206 $output->elementEnd('li');
213 * Check if we've got remote replies to send via Salmon.
215 * @fixme push webfinger lookup & sending to a background queue
216 * @fixme also detect short-form name for remote subscribees where not ambiguous
219 function onEndNoticeSave($notice)
227 function onEndFindMentions($sender, $text, &$mentions)
229 preg_match_all('/(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)/',
232 PREG_OFFSET_CAPTURE);
234 foreach ($wmatches[1] as $wmatch) {
236 $webfinger = $wmatch[0];
238 $this->log(LOG_INFO, "Checking Webfinger for address '$webfinger'");
240 $oprofile = Ostatus_profile::ensureWebfinger($webfinger);
242 if (empty($oprofile)) {
244 $this->log(LOG_INFO, "No Ostatus_profile found for address '$webfinger'");
248 $this->log(LOG_INFO, "Ostatus_profile found for address '$webfinger'");
250 if ($oprofile->isGroup()) {
253 $profile = $oprofile->localProfile();
256 foreach ($mentions as $i => $other) {
257 // If we share a common prefix with a local user, override it!
258 if ($other['position'] == $pos) {
259 unset($mentions[$i]);
262 $mentions[] = array('mentioned' => array($profile),
263 'text' => $wmatch[0],
265 'url' => $profile->profileurl);
273 * Make sure necessary tables are filled out.
275 function onCheckSchema() {
276 $schema = Schema::get();
277 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
278 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
279 $schema->ensureTable('feedsub', FeedSub::schemaDef());
280 $schema->ensureTable('hubsub', HubSub::schemaDef());
281 $schema->ensureTable('magicsig', Magicsig::schemaDef());
285 function onEndShowStatusNetStyles($action) {
286 $action->cssLink(common_path('plugins/OStatus/theme/base/css/ostatus.css'));
290 function onEndShowStatusNetScripts($action) {
291 $action->script(common_path('plugins/OStatus/js/ostatus.js'));
296 * Override the "from ostatus" bit in notice lists to link to the
297 * original post and show the domain it came from.
299 * @param Notice in $notice
300 * @param string out &$name
301 * @param string out &$url
302 * @param string out &$title
303 * @return mixed hook return code
305 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
307 if ($notice->source == 'ostatus') {
309 $bits = parse_url($notice->url);
310 $domain = $bits['host'];
311 if (substr($domain, 0, 4) == 'www.') {
312 $name = substr($domain, 4);
318 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
325 * Send incoming PuSH feeds for OStatus endpoints in for processing.
327 * @param FeedSub $feedsub
328 * @param DOMDocument $feed
329 * @return mixed hook return code
331 function onStartFeedSubReceive($feedsub, $feed)
333 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
335 $oprofile->processFeed($feed, 'push');
337 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
342 * When about to subscribe to a remote user, start a server-to-server
343 * PuSH subscription if needed. If we can't establish that, abort.
345 * @fixme If something else aborts later, we could end up with a stray
346 * PuSH subscription. This is relatively harmless, though.
348 * @param Profile $subscriber
349 * @param Profile $other
351 * @return hook return code
355 function onStartSubscribe($subscriber, $other)
357 $user = User::staticGet('id', $subscriber->id);
363 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
365 if (empty($oprofile)) {
369 if (!$oprofile->subscribe()) {
370 throw new Exception(_m('Could not set up remote subscription.'));
375 * Having established a remote subscription, send a notification to the
376 * remote OStatus profile's endpoint.
378 * @param Profile $subscriber
379 * @param Profile $other
381 * @return hook return code
385 function onEndSubscribe($subscriber, $other)
387 $user = User::staticGet('id', $subscriber->id);
393 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
395 if (empty($oprofile)) {
399 $act = new Activity();
401 $act->verb = ActivityVerb::FOLLOW;
403 $act->id = TagURI::mint('follow:%d:%d:%s',
406 common_date_iso8601(time()));
409 $act->title = _("Follow");
410 $act->content = sprintf(_("%s is now following %s."),
411 $subscriber->getBestName(),
412 $other->getBestName());
414 $act->actor = ActivityObject::fromProfile($subscriber);
415 $act->object = ActivityObject::fromProfile($other);
417 $oprofile->notifyActivity($act);
423 * Notify remote server and garbage collect unused feeds on unsubscribe.
424 * @fixme send these operations to background queues
427 * @param Profile $other
428 * @return hook return value
430 function onEndUnsubscribe($profile, $other)
432 $user = User::staticGet('id', $profile->id);
438 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
440 if (empty($oprofile)) {
444 // Drop the PuSH subscription if there are no other subscribers.
445 $oprofile->garbageCollect();
447 $act = new Activity();
449 $act->verb = ActivityVerb::UNFOLLOW;
451 $act->id = TagURI::mint('unfollow:%d:%d:%s',
454 common_date_iso8601(time()));
457 $act->title = _("Unfollow");
458 $act->content = sprintf(_("%s stopped following %s."),
459 $profile->getBestName(),
460 $other->getBestName());
462 $act->actor = ActivityObject::fromProfile($profile);
463 $act->object = ActivityObject::fromProfile($other);
465 $oprofile->notifyActivity($act);
471 * When one of our local users tries to join a remote group,
472 * notify the remote server. If the notification is rejected,
475 * @param User_group $group
478 * @return mixed hook return value
481 function onStartJoinGroup($group, $user)
483 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
485 if (!$oprofile->subscribe()) {
486 throw new Exception(_m('Could not set up remote group membership.'));
489 $member = Profile::staticGet($user->id);
491 $act = new Activity();
492 $act->id = TagURI::mint('join:%d:%d:%s',
495 common_date_iso8601(time()));
497 $act->actor = ActivityObject::fromProfile($member);
498 $act->verb = ActivityVerb::JOIN;
499 $act->object = $oprofile->asActivityObject();
502 $act->title = _m("Join");
503 $act->content = sprintf(_m("%s has joined group %s."),
504 $member->getBestName(),
505 $oprofile->getBestName());
507 if ($oprofile->notifyActivity($act)) {
510 $oprofile->garbageCollect();
511 throw new Exception(_m("Failed joining remote group."));
517 * When one of our local users leaves a remote group, notify the remote
520 * @fixme Might be good to schedule a resend of the leave notification
521 * if it failed due to a transitory error. We've canceled the local
522 * membership already anyway, but if the remote server comes back up
523 * it'll be left with a stray membership record.
525 * @param User_group $group
528 * @return mixed hook return value
531 function onEndLeaveGroup($group, $user)
533 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
535 // Drop the PuSH subscription if there are no other subscribers.
536 $oprofile->garbageCollect();
539 $member = Profile::staticGet($user->id);
541 $act = new Activity();
542 $act->id = TagURI::mint('leave:%d:%d:%s',
545 common_date_iso8601(time()));
547 $act->actor = ActivityObject::fromProfile($member);
548 $act->verb = ActivityVerb::LEAVE;
549 $act->object = $oprofile->asActivityObject();
552 $act->title = _m("Leave");
553 $act->content = sprintf(_m("%s has left group %s."),
554 $member->getBestName(),
555 $oprofile->getBestName());
557 $oprofile->notifyActivity($act);
562 * Notify remote users when their notices get favorited.
564 * @param Profile or User $profile of local user doing the faving
565 * @param Notice $notice being favored
566 * @return hook return value
569 function onEndFavorNotice(Profile $profile, Notice $notice)
571 $user = User::staticGet('id', $profile->id);
577 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
579 if (empty($oprofile)) {
583 $act = new Activity();
585 $act->verb = ActivityVerb::FAVORITE;
586 $act->id = TagURI::mint('favor:%d:%d:%s',
589 common_date_iso8601(time()));
592 $act->title = _("Favor");
593 $act->content = sprintf(_("%s marked notice %s as a favorite."),
594 $profile->getBestName(),
597 $act->actor = ActivityObject::fromProfile($profile);
598 $act->object = ActivityObject::fromNotice($notice);
600 $oprofile->notifyActivity($act);
606 * Notify remote users when their notices get de-favorited.
608 * @param Profile $profile Profile person doing the de-faving
609 * @param Notice $notice Notice being favored
611 * @return hook return value
614 function onEndDisfavorNotice(Profile $profile, Notice $notice)
616 $user = User::staticGet('id', $profile->id);
622 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
624 if (empty($oprofile)) {
628 $act = new Activity();
630 $act->verb = ActivityVerb::UNFAVORITE;
631 $act->id = TagURI::mint('disfavor:%d:%d:%s',
634 common_date_iso8601(time()));
636 $act->title = _("Disfavor");
637 $act->content = sprintf(_("%s marked notice %s as no longer a favorite."),
638 $profile->getBestName(),
641 $act->actor = ActivityObject::fromProfile($profile);
642 $act->object = ActivityObject::fromNotice($notice);
644 $oprofile->notifyActivity($act);
649 function onStartGetProfileUri($profile, &$uri)
651 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
652 if (!empty($oprofile)) {
653 $uri = $oprofile->uri;
659 function onStartUserGroupHomeUrl($group, &$url)
661 return $this->onStartUserGroupPermalink($group, $url);
664 function onStartUserGroupPermalink($group, &$url)
666 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
668 // @fixme this should probably be in the user_group table
669 // @fixme this uri not guaranteed to be a profile page
670 $url = $oprofile->uri;
675 function onStartShowSubscriptionsContent($action)
677 $user = common_current_user();
678 if ($user && ($user->id == $action->profile->id)) {
679 $action->elementStart('div', 'entity_actions');
680 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
681 'class' => 'entity_subscribe'));
682 $action->element('a', array('href' => common_local_url('ostatussub'),
683 'class' => 'entity_remote_subscribe')
684 , _m('Subscribe to remote user'));
685 $action->elementEnd('p');
686 $action->elementEnd('div');
693 * Ping remote profiles with updates to this profile.
694 * Salmon pings are queued for background processing.
696 function onEndBroadcastProfile(Profile $profile)
698 $user = User::staticGet('id', $profile->id);
700 // Find foreign accounts I'm subscribed to that support Salmon pings.
702 // @fixme we could run updates through the PuSH feed too,
703 // in which case we can skip Salmon pings to folks who
704 // are also subscribed to me.
705 $sql = "SELECT * FROM ostatus_profile " .
706 "WHERE profile_id IN " .
707 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
709 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
710 $oprofile = new Ostatus_profile();
711 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
713 if ($oprofile->N == 0) {
714 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
718 $act = new Activity();
720 $act->verb = ActivityVerb::UPDATE_PROFILE;
721 $act->id = TagURI::mint('update-profile:%d:%s',
723 common_date_iso8601(time()));
725 $act->title = _m("Profile update");
726 $act->content = sprintf(_m("%s has updated their profile page."),
727 $profile->getBestName());
729 $act->actor = ActivityObject::fromProfile($profile);
730 $act->object = $act->actor;
732 while ($oprofile->fetch()) {
733 $oprofile->notifyDeferred($act);