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')) {
29 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/');
31 class FeedSubException extends Exception
33 function __construct($msg=null)
35 $type = get_class($this);
37 parent::__construct("$type: $msg");
39 parent::__construct($type);
44 class OStatusPlugin extends Plugin
47 * Hook for RouterInitialized event.
49 * @param Net_URL_Mapper $m path-to-action mapper
50 * @return boolean hook return
52 function onRouterInitialized($m)
55 $m->connect('main/ownerxrd',
56 array('action' => 'ownerxrd'));
57 $m->connect('main/ostatus',
58 array('action' => 'ostatusinit'));
59 $m->connect('main/ostatustag',
60 array('action' => 'ostatustag'));
61 $m->connect('main/ostatustag?nickname=:nickname',
62 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
63 $m->connect('main/ostatus?nickname=:nickname',
64 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
65 $m->connect('main/ostatus?group=:group',
66 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
67 $m->connect('main/ostatus?peopletag=:peopletag&tagger=:tagger',
68 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
69 'peopletag' => '[A-Za-z0-9_-]+'));
71 // Remote subscription actions
72 $m->connect('main/ostatussub',
73 array('action' => 'ostatussub'));
74 $m->connect('main/ostatusgroup',
75 array('action' => 'ostatusgroup'));
76 $m->connect('main/ostatuspeopletag',
77 array('action' => 'ostatuspeopletag'));
80 $m->connect('main/push/hub', array('action' => 'pushhub'));
82 $m->connect('main/push/callback/:feed',
83 array('action' => 'pushcallback'),
84 array('feed' => '[0-9]+'));
87 $m->connect('main/salmon/user/:id',
88 array('action' => 'usersalmon'),
89 array('id' => '[0-9]+'));
90 $m->connect('main/salmon/group/:id',
91 array('action' => 'groupsalmon'),
92 array('id' => '[0-9]+'));
93 $m->connect('main/salmon/peopletag/:id',
94 array('action' => 'peopletagsalmon'),
95 array('id' => '[0-9]+'));
100 * Set up queue handlers for outgoing hub pushes
101 * @param QueueManager $qm
102 * @return boolean hook return
104 function onEndInitializeQueueManager(QueueManager $qm)
106 // Prepare outgoing distributions after notice save.
107 $qm->connect('ostatus', 'OStatusQueueHandler');
109 // Outgoing from our internal PuSH hub
110 $qm->connect('hubconf', 'HubConfQueueHandler');
111 $qm->connect('hubprep', 'HubPrepQueueHandler');
113 $qm->connect('hubout', 'HubOutQueueHandler');
115 // Outgoing Salmon replies (when we don't need a return value)
116 $qm->connect('salmon', 'SalmonQueueHandler');
118 // Incoming from a foreign PuSH hub
119 $qm->connect('pushin', 'PushInQueueHandler');
124 * Put saved notices into the queue for pubsub distribution.
126 function onStartEnqueueNotice($notice, &$transports)
128 // FIXME: we don't do privacy-controlled OStatus updates yet.
129 // once that happens, finer grain of control here.
130 if ($notice->isLocal() && $notice->inScope(null)) {
131 // put our transport first, in case there's any conflict (like OMB)
132 array_unshift($transports, 'ostatus');
138 * Add a link header for LRDD Discovery
140 function onStartShowHTML($action)
142 if ($action instanceof ShowstreamAction) {
143 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
144 $url = common_local_url('userxrd');
145 $url.= '?uri='. $acct;
147 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
152 * Set up a PuSH hub link to our internal link for canonical timeline
153 * Atom feeds for users and groups.
155 function onStartApiAtom($feed)
159 if ($feed instanceof AtomUserNoticeFeed) {
160 $salmonAction = 'usersalmon';
161 $user = $feed->getUser();
163 $profile = $user->getProfile();
164 } else if ($feed instanceof AtomGroupNoticeFeed) {
165 $salmonAction = 'groupsalmon';
166 $group = $feed->getGroup();
168 } else if ($feed instanceof AtomListNoticeFeed) {
169 $salmonAction = 'peopletagsalmon';
170 $peopletag = $feed->getList();
171 $id = $peopletag->id;
177 $hub = common_config('ostatus', 'hub');
179 // Updates will be handled through our internal PuSH hub.
180 $hub = common_local_url('pushhub');
182 $feed->addLink($hub, array('rel' => 'hub'));
184 // Also, we'll add in the salmon link
185 $salmon = common_local_url($salmonAction, array('id' => $id));
186 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
188 // XXX: these are deprecated
189 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
190 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
197 * Automatically load the actions and libraries used by the plugin
199 * @param Class $cls the class
201 * @return boolean hook return
204 function onAutoload($cls)
206 $base = dirname(__FILE__);
207 $lower = strtolower($cls);
208 $map = array('activityverb' => 'activity',
209 'activityobject' => 'activity',
210 'activityutils' => 'activity');
211 if (isset($map[$lower])) {
212 $lower = $map[$lower];
214 $files = array("$base/classes/$cls.php",
215 "$base/lib/$lower.php");
216 if (substr($lower, -6) == 'action') {
217 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
219 foreach ($files as $file) {
220 if (file_exists($file)) {
229 * Add in an OStatus subscribe button
231 function onStartProfileRemoteSubscribe($output, $profile)
233 $this->onStartProfileListItemActionElements($output, $profile);
237 function onStartGroupSubscribe($widget, $group)
239 $cur = common_current_user();
242 $output->elementStart('li', 'entity_subscribe');
243 $profile = $peopletag->getTagger();
244 $url = common_local_url('ostatusinit',
245 array('group' => $group->nickname));
246 $widget->out->element('a', array('href' => $url,
247 'class' => 'entity_remote_subscribe'),
248 // TRANS: Link to subscribe to a remote entity.
251 $output->elementEnd('li');
258 function onStartSubscribePeopletagForm($output, $peopletag)
260 $cur = common_current_user();
263 $output->elementStart('li', 'entity_subscribe');
264 $profile = $peopletag->getTagger();
265 $url = common_local_url('ostatusinit',
266 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
267 $output->element('a', array('href' => $url,
268 'class' => 'entity_remote_subscribe'),
269 // TRANS: Link to subscribe to a remote entity.
272 $output->elementEnd('li');
279 function onStartShowTagProfileForm($action, $profile)
281 $action->elementStart('form', array('method' => 'post',
282 'id' => 'form_tag_user',
283 'class' => 'form_settings',
284 'name' => 'tagprofile',
285 'action' => common_local_url('tagprofile', array('id' => @$profile->id))));
287 $action->elementStart('fieldset');
288 // TRANS: Fieldset legend.
289 $action->element('legend', null, _m('Tag remote profile'));
290 $action->hidden('token', common_session_token());
292 $user = common_current_user();
294 $action->elementStart('ul', 'form_data');
295 $action->elementStart('li');
297 // TRANS: Field label.
298 $action->input('uri', _m('LABEL','Remote profile'), $action->trimmed('uri'),
299 // TRANS: Field title.
300 _m('OStatus user\'s address, like nickname@example.com or http://example.net/nickname.'));
301 $action->elementEnd('li');
302 $action->elementEnd('ul');
303 // TRANS: Button text to fetch remote profile.
304 $action->submit('fetch', _m('BUTTON','Fetch'));
305 $action->elementEnd('fieldset');
306 $action->elementEnd('form');
309 function onStartTagProfileAction($action, $profile)
312 $uri = $action->trimmed('uri');
314 if (!$profile && $uri) {
316 if (Validate::email($uri)) {
317 $oprofile = Ostatus_profile::ensureWebfinger($uri);
318 } else if (Validate::uri($uri)) {
319 $oprofile = Ostatus_profile::ensureProfileURL($uri);
321 // TRANS: Exception in OStatus when invalid URI was entered.
322 throw new Exception(_m('Invalid URI.'));
325 // redirect to the new profile.
326 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
329 } catch (Exception $e) {
330 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
331 // TRANS: and example.net, as these are official standard domain names for use in examples.
332 $err = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
335 $action->showForm($err);
342 * If the field being looked for is URI look for the profile
344 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
345 if ($action->field == 'uri') {
347 $profile->joinAdd($user);
348 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
351 if ($profile->N == 0) {
353 if (Validate::email($q)) {
354 $oprofile = Ostatus_profile::ensureWebfinger($q);
355 } else if (Validate::uri($q)) {
356 $oprofile = Ostatus_profile::ensureProfileURL($q);
358 // TRANS: Exception in OStatus when invalid URI was entered.
359 throw new Exception(_m('Invalid URI.'));
361 return $this->filter(array($oprofile->localProfile()));
363 } catch (Exception $e) {
364 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
365 // TRANS: and example.net, as these are official standard domain names for use in examples.
366 $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
376 * Find any explicit remote mentions. Accepted forms:
377 * Webfinger: @user@example.com
378 * Profile link: @example.com/mublog/user
379 * @param Profile $sender (os user?)
380 * @param string $text input markup text
381 * @param array &$mention in/out param: set of found mentions
382 * @return boolean hook return value
384 function onEndFindMentions($sender, $text, &$mentions)
388 // Webfinger matches: @user@example.com
389 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
392 PREG_OFFSET_CAPTURE)) {
393 foreach ($wmatches[1] as $wmatch) {
394 list($target, $pos) = $wmatch;
395 $this->log(LOG_INFO, "Checking webfinger '$target'");
397 $oprofile = Ostatus_profile::ensureWebfinger($target);
398 if ($oprofile && !$oprofile->isGroup()) {
399 $profile = $oprofile->localProfile();
400 $matches[$pos] = array('mentioned' => array($profile),
403 'url' => $profile->profileurl);
405 } catch (Exception $e) {
406 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
411 // Profile matches: @example.com/mublog/user
412 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
415 PREG_OFFSET_CAPTURE)) {
416 foreach ($wmatches[1] as $wmatch) {
417 list($target, $pos) = $wmatch;
418 $schemes = array('http', 'https');
419 foreach ($schemes as $scheme) {
420 $url = "$scheme://$target";
421 $this->log(LOG_INFO, "Checking profile address '$url'");
423 $oprofile = Ostatus_profile::ensureProfileURL($url);
424 if ($oprofile && !$oprofile->isGroup()) {
425 $profile = $oprofile->localProfile();
426 $matches[$pos] = array('mentioned' => array($profile),
429 'url' => $profile->profileurl);
432 } catch (Exception $e) {
433 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
439 foreach ($mentions as $i => $other) {
440 // If we share a common prefix with a local user, override it!
441 $pos = $other['position'];
442 if (isset($matches[$pos])) {
443 $mentions[$i] = $matches[$pos];
444 unset($matches[$pos]);
447 foreach ($matches as $mention) {
448 $mentions[] = $mention;
455 * Allow remote profile references to be used in commands:
456 * sub update@status.net
457 * whois evan@identi.ca
458 * reply http://identi.ca/evan hey what's up
460 * @param Command $command
462 * @param Profile &$profile
463 * @return hook return code
465 function onStartCommandGetProfile($command, $arg, &$profile)
467 $oprofile = $this->pullRemoteProfile($arg);
468 if ($oprofile && !$oprofile->isGroup()) {
469 $profile = $oprofile->localProfile();
477 * Allow remote group references to be used in commands:
478 * join group+statusnet@identi.ca
479 * join http://identi.ca/group/statusnet
480 * drop identi.ca/group/statusnet
482 * @param Command $command
484 * @param User_group &$group
485 * @return hook return code
487 function onStartCommandGetGroup($command, $arg, &$group)
489 $oprofile = $this->pullRemoteProfile($arg);
490 if ($oprofile && $oprofile->isGroup()) {
491 $group = $oprofile->localGroup();
498 protected function pullRemoteProfile($arg)
501 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
504 return Ostatus_profile::ensureWebfinger($arg);
505 } catch (Exception $e) {
506 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
507 $arg . ': ' . $e->getMessage());
511 // Look for profile URLs, with or without scheme:
513 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
516 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
517 $schemes = array('http', 'https');
518 foreach ($schemes as $scheme) {
519 $urls[] = "$scheme://$arg";
523 foreach ($urls as $url) {
525 return Ostatus_profile::ensureProfileURL($url);
526 } catch (Exception $e) {
527 common_log(LOG_ERR, 'Profile lookup failed for ' .
528 $arg . ': ' . $e->getMessage());
535 * Make sure necessary tables are filled out.
537 function onCheckSchema() {
538 $schema = Schema::get();
539 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
540 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
541 $schema->ensureTable('feedsub', FeedSub::schemaDef());
542 $schema->ensureTable('hubsub', HubSub::schemaDef());
543 $schema->ensureTable('magicsig', Magicsig::schemaDef());
547 function onEndShowStatusNetStyles($action) {
548 $action->cssLink($this->path('theme/base/css/ostatus.css'));
552 function onEndShowStatusNetScripts($action) {
553 $action->script($this->path('js/ostatus.js'));
558 * Override the "from ostatus" bit in notice lists to link to the
559 * original post and show the domain it came from.
561 * @param Notice in $notice
562 * @param string out &$name
563 * @param string out &$url
564 * @param string out &$title
565 * @return mixed hook return code
567 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
569 if ($notice->source == 'ostatus') {
571 $bits = parse_url($notice->url);
572 $domain = $bits['host'];
573 if (substr($domain, 0, 4) == 'www.') {
574 $name = substr($domain, 4);
580 // TRANS: Title. %s is a domain name.
581 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
589 * Send incoming PuSH feeds for OStatus endpoints in for processing.
591 * @param FeedSub $feedsub
592 * @param DOMDocument $feed
593 * @return mixed hook return code
595 function onStartFeedSubReceive($feedsub, $feed)
597 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
599 $oprofile->processFeed($feed, 'push');
601 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
606 * Tell the FeedSub infrastructure whether we have any active OStatus
607 * usage for the feed; if not it'll be able to garbage-collect the
610 * @param FeedSub $feedsub
611 * @param integer $count in/out
612 * @return mixed hook return code
614 function onFeedSubSubscriberCount($feedsub, &$count)
616 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
618 $count += $oprofile->subscriberCount();
624 * When about to subscribe to a remote user, start a server-to-server
625 * PuSH subscription if needed. If we can't establish that, abort.
627 * @fixme If something else aborts later, we could end up with a stray
628 * PuSH subscription. This is relatively harmless, though.
630 * @param Profile $subscriber
631 * @param Profile $other
633 * @return hook return code
637 function onStartSubscribe($subscriber, $other)
639 $user = User::staticGet('id', $subscriber->id);
645 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
647 if (empty($oprofile)) {
651 if (!$oprofile->subscribe()) {
652 // TRANS: Exception thrown when setup of remote subscription fails.
653 throw new Exception(_m('Could not set up remote subscription.'));
658 * Having established a remote subscription, send a notification to the
659 * remote OStatus profile's endpoint.
661 * @param Profile $subscriber
662 * @param Profile $other
664 * @return hook return code
668 function onEndSubscribe($subscriber, $other)
670 $user = User::staticGet('id', $subscriber->id);
676 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
678 if (empty($oprofile)) {
682 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
683 'subscribed' => $other->id));
685 $act = $sub->asActivity();
687 $oprofile->notifyActivity($act, $subscriber);
693 * Notify remote server and garbage collect unused feeds on unsubscribe.
694 * @todo FIXME: Send these operations to background queues
697 * @param Profile $other
698 * @return hook return value
700 function onEndUnsubscribe($profile, $other)
702 $user = User::staticGet('id', $profile->id);
708 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
710 if (empty($oprofile)) {
714 // Drop the PuSH subscription if there are no other subscribers.
715 $oprofile->garbageCollect();
717 $act = new Activity();
719 $act->verb = ActivityVerb::UNFOLLOW;
721 $act->id = TagURI::mint('unfollow:%d:%d:%s',
724 common_date_iso8601(time()));
727 // TRANS: Title for unfollowing a remote profile.
728 $act->title = _m('TITLE','Unfollow');
729 // TRANS: Success message for unsubscribe from user attempt through OStatus.
730 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
731 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
732 $profile->getBestName(),
733 $other->getBestName());
735 $act->actor = ActivityObject::fromProfile($profile);
736 $act->object = ActivityObject::fromProfile($other);
738 $oprofile->notifyActivity($act, $profile);
744 * When one of our local users tries to join a remote group,
745 * notify the remote server. If the notification is rejected,
748 * @param User_group $group
751 * @return mixed hook return value
753 function onStartJoinGroup($group, $user)
755 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
757 if (!$oprofile->subscribe()) {
758 // TRANS: Exception thrown when setup of remote group membership fails.
759 throw new Exception(_m('Could not set up remote group membership.'));
762 // NOTE: we don't use Group_member::asActivity() since that record
763 // has not yet been created.
765 $member = Profile::staticGet($user->id);
767 $act = new Activity();
768 $act->id = TagURI::mint('join:%d:%d:%s',
771 common_date_iso8601(time()));
773 $act->actor = ActivityObject::fromProfile($member);
774 $act->verb = ActivityVerb::JOIN;
775 $act->object = $oprofile->asActivityObject();
778 // TRANS: Title for joining a remote groep.
779 $act->title = _m('TITLE','Join');
780 // TRANS: Success message for subscribe to group attempt through OStatus.
781 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
782 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
783 $member->getBestName(),
784 $oprofile->getBestName());
786 if ($oprofile->notifyActivity($act, $member)) {
789 $oprofile->garbageCollect();
790 // TRANS: Exception thrown when joining a remote group fails.
791 throw new Exception(_m('Failed joining remote group.'));
797 * When one of our local users leaves a remote group, notify the remote
800 * @fixme Might be good to schedule a resend of the leave notification
801 * if it failed due to a transitory error. We've canceled the local
802 * membership already anyway, but if the remote server comes back up
803 * it'll be left with a stray membership record.
805 * @param User_group $group
806 * @param Profile $user
808 * @return mixed hook return value
810 function onEndLeaveGroup($group, $user)
812 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
814 // Drop the PuSH subscription if there are no other subscribers.
815 $oprofile->garbageCollect();
817 $member = Profile::staticGet($user->id);
819 $act = new Activity();
820 $act->id = TagURI::mint('leave:%d:%d:%s',
823 common_date_iso8601(time()));
825 $act->actor = ActivityObject::fromProfile($member);
826 $act->verb = ActivityVerb::LEAVE;
827 $act->object = $oprofile->asActivityObject();
830 // TRANS: Title for leaving a remote group.
831 $act->title = _m('TITLE','Leave');
832 // TRANS: Success message for unsubscribe from group attempt through OStatus.
833 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
834 $act->content = sprintf(_m('%1$s has left group %2$s.'),
835 $member->getBestName(),
836 $oprofile->getBestName());
838 $oprofile->notifyActivity($act, $member);
843 * When one of our local users tries to subscribe to a remote peopletag,
844 * notify the remote server. If the notification is rejected,
845 * deny the subscription.
847 * @param Profile_list $peopletag
850 * @return mixed hook return value
853 function onStartSubscribePeopletag($peopletag, $user)
855 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
857 if (!$oprofile->subscribe()) {
858 // TRANS: Exception thrown when setup of remote list subscription fails.
859 throw new Exception(_m('Could not set up remote list subscription.'));
862 $sub = $user->getProfile();
863 $tagger = Profile::staticGet($peopletag->tagger);
865 $act = new Activity();
866 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
869 common_date_iso8601(time()));
871 $act->actor = ActivityObject::fromProfile($sub);
872 $act->verb = ActivityVerb::FOLLOW;
873 $act->object = $oprofile->asActivityObject();
876 // TRANS: Title for following a remote list.
877 $act->title = _m('TITLE','Follow list');
878 // TRANS: Success message for remote list follow through OStatus.
879 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the tagger's name.
880 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
882 $oprofile->getBestName(),
883 $tagger->getBestName());
885 if ($oprofile->notifyActivity($act, $sub)) {
888 $oprofile->garbageCollect();
889 // TRANS: Exception thrown when subscription to remote list fails.
890 throw new Exception(_m('Failed subscribing to remote list.'));
896 * When one of our local users unsubscribes to a remote peopletag, notify the remote
899 * @param Profile_list $peopletag
902 * @return mixed hook return value
905 function onEndUnsubscribePeopletag($peopletag, $user)
907 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
909 // Drop the PuSH subscription if there are no other subscribers.
910 $oprofile->garbageCollect();
912 $sub = Profile::staticGet($user->id);
913 $tagger = Profile::staticGet($peopletag->tagger);
915 $act = new Activity();
916 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
919 common_date_iso8601(time()));
921 $act->actor = ActivityObject::fromProfile($member);
922 $act->verb = ActivityVerb::UNFOLLOW;
923 $act->object = $oprofile->asActivityObject();
926 // TRANS: Title for unfollowing a remote list.
927 $act->title = _m('Unfollow list');
928 // TRANS: Success message for remote list unfollow through OStatus.
929 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the tagger's name.
930 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
932 $oprofile->getBestName(),
933 $tagger->getBestName());
935 $oprofile->notifyActivity($act, $user);
940 * Notify remote users when their notices get favorited.
942 * @param Profile or User $profile of local user doing the faving
943 * @param Notice $notice being favored
944 * @return hook return value
946 function onEndFavorNotice(Profile $profile, Notice $notice)
948 $user = User::staticGet('id', $profile->id);
954 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
956 if (empty($oprofile)) {
960 $fav = Fave::pkeyGet(array('user_id' => $user->id,
961 'notice_id' => $notice->id));
968 $act = $fav->asActivity();
970 $oprofile->notifyActivity($act, $profile);
976 * Notify remote user it has got a new people tag
977 * - tag verb is queued
978 * - the subscription is done immediately if not present
980 * @param Profile_tag $ptag the people tag that was created
981 * @return hook return value
983 function onEndTagProfile($ptag)
985 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
987 if (empty($oprofile)) {
991 $plist = $ptag->getMeta();
992 if ($plist->private) {
996 $act = new Activity();
998 $tagger = $plist->getTagger();
999 $tagged = Profile::staticGet('id', $ptag->tagged);
1001 $act->verb = ActivityVerb::TAG;
1002 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
1003 $plist->tagger, $plist->id,
1004 common_date_iso8601(time()));
1005 $act->time = time();
1006 // TRANS: Title for listing a remote profile.
1007 $act->title = _m('TITLE','List');
1008 // TRANS: Success message for remote list addition through OStatus.
1009 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
1010 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
1011 $tagger->getBestName(),
1012 $tagged->getBestName(),
1013 $plist->getBestName());
1015 $act->actor = ActivityObject::fromProfile($tagger);
1016 $act->objects = array(ActivityObject::fromProfile($tagged));
1017 $act->target = ActivityObject::fromPeopletag($plist);
1019 $oprofile->notifyDeferred($act, $tagger);
1021 // initiate a PuSH subscription for the person being tagged
1022 if (!$oprofile->subscribe()) {
1023 // TRANS: Exception thrown when subscribing to a remote list fails.
1024 throw new Exception(sprintf(_m('Could not complete subscription to remote '.
1025 'profile\'s feed. List %s could not be saved.'), $ptag->tag));
1032 * Notify remote user that a people tag has been removed
1033 * - untag verb is queued
1034 * - the subscription is undone immediately if not required
1035 * i.e garbageCollect()'d
1037 * @param Profile_tag $ptag the people tag that was deleted
1038 * @return hook return value
1040 function onEndUntagProfile($ptag)
1042 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
1044 if (empty($oprofile)) {
1048 $plist = $ptag->getMeta();
1049 if ($plist->private) {
1053 $act = new Activity();
1055 $tagger = $plist->getTagger();
1056 $tagged = Profile::staticGet('id', $ptag->tagged);
1058 $act->verb = ActivityVerb::UNTAG;
1059 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1060 $plist->tagger, $plist->id,
1061 common_date_iso8601(time()));
1062 $act->time = time();
1063 // TRANS: Title for unlisting a remote profile.
1064 $act->title = _m('TITLE','Unlist');
1065 // TRANS: Success message for remote list removal through OStatus.
1066 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1067 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1068 $tagger->getBestName(),
1069 $tagged->getBestName(),
1070 $plist->getBestName());
1072 $act->actor = ActivityObject::fromProfile($tagger);
1073 $act->objects = array(ActivityObject::fromProfile($tagged));
1074 $act->target = ActivityObject::fromPeopletag($plist);
1076 $oprofile->notifyDeferred($act, $tagger);
1078 // unsubscribe to PuSH feed if no more required
1079 $oprofile->garbageCollect();
1085 * Notify remote users when their notices get de-favorited.
1087 * @param Profile $profile Profile person doing the de-faving
1088 * @param Notice $notice Notice being favored
1090 * @return hook return value
1092 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1094 $user = User::staticGet('id', $profile->id);
1100 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
1102 if (empty($oprofile)) {
1106 $act = new Activity();
1108 $act->verb = ActivityVerb::UNFAVORITE;
1109 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1112 common_date_iso8601(time()));
1113 $act->time = time();
1114 // TRANS: Title for unliking a remote notice.
1115 $act->title = _m('Unlike');
1116 // TRANS: Success message for remove a favorite notice through OStatus.
1117 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1118 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1119 $profile->getBestName(),
1122 $act->actor = ActivityObject::fromProfile($profile);
1123 $act->object = ActivityObject::fromNotice($notice);
1125 $oprofile->notifyActivity($act, $profile);
1130 function onStartGetProfileUri($profile, &$uri)
1132 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1133 if (!empty($oprofile)) {
1134 $uri = $oprofile->uri;
1140 function onStartUserGroupHomeUrl($group, &$url)
1142 return $this->onStartUserGroupPermalink($group, $url);
1145 function onStartUserGroupPermalink($group, &$url)
1147 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
1149 // @fixme this should probably be in the user_group table
1150 // @fixme this uri not guaranteed to be a profile page
1151 $url = $oprofile->uri;
1156 function onStartShowSubscriptionsContent($action)
1158 $this->showEntityRemoteSubscribe($action);
1163 function onStartShowUserGroupsContent($action)
1165 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1170 function onEndShowSubscriptionsMiniList($action)
1172 $this->showEntityRemoteSubscribe($action);
1177 function onEndShowGroupsMiniList($action)
1179 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1184 function showEntityRemoteSubscribe($action, $target='ostatussub')
1186 $user = common_current_user();
1187 if ($user && ($user->id == $action->profile->id)) {
1188 $action->elementStart('div', 'entity_actions');
1189 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1190 'class' => 'entity_subscribe'));
1191 $action->element('a', array('href' => common_local_url($target),
1192 'class' => 'entity_remote_subscribe'),
1193 // TRANS: Link text for link to remote subscribe.
1195 $action->elementEnd('p');
1196 $action->elementEnd('div');
1201 * Ping remote profiles with updates to this profile.
1202 * Salmon pings are queued for background processing.
1204 function onEndBroadcastProfile(Profile $profile)
1206 $user = User::staticGet('id', $profile->id);
1208 // Find foreign accounts I'm subscribed to that support Salmon pings.
1210 // @fixme we could run updates through the PuSH feed too,
1211 // in which case we can skip Salmon pings to folks who
1212 // are also subscribed to me.
1213 $sql = "SELECT * FROM ostatus_profile " .
1214 "WHERE profile_id IN " .
1215 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1217 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1218 $oprofile = new Ostatus_profile();
1219 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1221 if ($oprofile->N == 0) {
1222 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1226 $act = new Activity();
1228 $act->verb = ActivityVerb::UPDATE_PROFILE;
1229 $act->id = TagURI::mint('update-profile:%d:%s',
1231 common_date_iso8601(time()));
1232 $act->time = time();
1233 // TRANS: Title for activity.
1234 $act->title = _m('Profile update');
1235 // TRANS: Ping text for remote profile update through OStatus.
1236 // TRANS: %s is user that updated their profile.
1237 $act->content = sprintf(_m('%s has updated their profile page.'),
1238 $profile->getBestName());
1240 $act->actor = ActivityObject::fromProfile($profile);
1241 $act->object = $act->actor;
1243 while ($oprofile->fetch()) {
1244 $oprofile->notifyDeferred($act, $profile);
1250 function onStartProfileListItemActionElements($item, $profile=null)
1252 if (!common_logged_in()) {
1254 $profileUser = User::staticGet('id', $item->profile->id);
1256 if (!empty($profileUser)) {
1258 if ($item instanceof Action) {
1260 $profile = $item->profile;
1262 $output = $item->out;
1265 // Add an OStatus subscribe
1266 $output->elementStart('li', 'entity_subscribe');
1267 $url = common_local_url('ostatusinit',
1268 array('nickname' => $profileUser->nickname));
1269 $output->element('a', array('href' => $url,
1270 'class' => 'entity_remote_subscribe'),
1271 // TRANS: Link text for a user to subscribe to an OStatus user.
1273 $output->elementEnd('li');
1275 $output->elementStart('li', 'entity_tag');
1276 $url = common_local_url('ostatustag',
1277 array('nickname' => $profileUser->nickname));
1278 $output->element('a', array('href' => $url,
1279 'class' => 'entity_remote_tag'),
1280 // TRANS: Link text for a user to tag an OStatus user.
1282 $output->elementEnd('li');
1289 function onPluginVersion(&$versions)
1291 $versions[] = array('name' => 'OStatus',
1292 'version' => STATUSNET_VERSION,
1293 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1294 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1295 // TRANS: Plugin description.
1296 'rawdescription' => _m('Follow people across social networks that implement '.
1297 '<a href="http://ostatus.org/">OStatus</a>.'));
1303 * Utility function to check if the given URI is a canonical group profile
1304 * page, and if so return the ID number.
1306 * @param string $url
1307 * @return mixed int or false
1309 public static function localGroupFromUrl($url)
1311 $group = User_group::staticGet('uri', $url);
1313 $local = Local_group::staticGet('group_id', $group->id);
1318 // To find local groups which haven't had their uri fields filled out...
1319 // If the domain has changed since a subscriber got the URI, it'll
1321 $template = common_local_url('groupbyid', array('id' => '31337'));
1322 $template = preg_quote($template, '/');
1323 $template = str_replace('31337', '(\d+)', $template);
1324 if (preg_match("/$template/", $url, $matches)) {
1325 return intval($matches[1]);
1331 public function onStartProfileGetAtomFeed($profile, &$feed)
1333 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1335 if (empty($oprofile)) {
1339 $feed = $oprofile->feeduri;
1343 function onStartGetProfileFromURI($uri, &$profile)
1345 // Don't want to do Web-based discovery on our own server,
1346 // so we check locally first.
1348 $user = User::staticGet('uri', $uri);
1350 if (!empty($user)) {
1351 $profile = $user->getProfile();
1355 // Now, check remotely
1357 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1359 if (!empty($oprofile)) {
1360 $profile = $oprofile->localProfile();
1364 // Still not a hit, so give up.
1369 function onEndXrdActionLinks(&$xrd, $user)
1371 $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1372 'href' => common_local_url('ApiTimelineUser',
1373 array('id' => $user->id,
1374 'format' => 'atom')),
1375 'type' => 'application/atom+xml');
1378 $salmon_url = common_local_url('usersalmon',
1379 array('id' => $user->id));
1381 $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1382 'href' => $salmon_url);
1383 // XXX : Deprecated - to be removed.
1384 $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1385 'href' => $salmon_url);
1387 $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1388 'href' => $salmon_url);
1390 // Get this user's keypair
1391 $magickey = Magicsig::staticGet('user_id', $user->id);
1393 // No keypair yet, let's generate one.
1394 $magickey = new Magicsig();
1395 $magickey->generate($user->id);
1398 $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1399 'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1401 // TODO - finalize where the redirect should go on the publisher
1402 $url = common_local_url('ostatussub') . '?profile={uri}';
1403 $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1404 'template' => $url );