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/ostatustag',
58 array('action' => 'ostatustag'));
59 $m->connect('main/ostatustag?nickname=:nickname',
60 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
61 $m->connect('main/ostatus/nickname/:nickname',
62 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
63 $m->connect('main/ostatus/group/:group',
64 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
65 $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
66 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
67 'peopletag' => '[A-Za-z0-9_-]+'));
68 $m->connect('main/ostatus',
69 array('action' => 'ostatusinit'));
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 if ($notice->isLocal()) {
129 if ($notice->inScope(null)) {
130 // put our transport first, in case there's any conflict (like OMB)
131 array_unshift($transports, 'ostatus');
132 $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
134 // FIXME: we don't do privacy-controlled OStatus updates yet.
135 // once that happens, finer grain of control here.
136 $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
139 $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because it's not local.");
145 * Add a link header for LRDD Discovery
147 function onStartShowHTML($action)
149 if ($action instanceof ShowstreamAction) {
150 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
151 $url = common_local_url('userxrd');
152 $url.= '?uri='. $acct;
154 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
159 * Set up a PuSH hub link to our internal link for canonical timeline
160 * Atom feeds for users and groups.
162 function onStartApiAtom($feed)
166 if ($feed instanceof AtomUserNoticeFeed) {
167 $salmonAction = 'usersalmon';
168 $user = $feed->getUser();
170 $profile = $user->getProfile();
171 } else if ($feed instanceof AtomGroupNoticeFeed) {
172 $salmonAction = 'groupsalmon';
173 $group = $feed->getGroup();
175 } else if ($feed instanceof AtomListNoticeFeed) {
176 $salmonAction = 'peopletagsalmon';
177 $peopletag = $feed->getList();
178 $id = $peopletag->id;
184 $hub = common_config('ostatus', 'hub');
186 // Updates will be handled through our internal PuSH hub.
187 $hub = common_local_url('pushhub');
189 $feed->addLink($hub, array('rel' => 'hub'));
191 // Also, we'll add in the salmon link
192 $salmon = common_local_url($salmonAction, array('id' => $id));
193 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
195 // XXX: these are deprecated
196 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
197 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
204 * Add in an OStatus subscribe button
206 function onStartProfileRemoteSubscribe($output, $profile)
208 $this->onStartProfileListItemActionElements($output, $profile);
212 function onStartGroupSubscribe($widget, $group)
214 $cur = common_current_user();
217 $widget->out->elementStart('li', 'entity_subscribe');
219 $url = common_local_url('ostatusinit',
220 array('group' => $group->nickname));
221 $widget->out->element('a', array('href' => $url,
222 'class' => 'entity_remote_subscribe'),
223 // TRANS: Link to subscribe to a remote entity.
226 $widget->out->elementEnd('li');
233 function onStartSubscribePeopletagForm($output, $peopletag)
235 $cur = common_current_user();
238 $output->elementStart('li', 'entity_subscribe');
239 $profile = $peopletag->getTagger();
240 $url = common_local_url('ostatusinit',
241 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
242 $output->element('a', array('href' => $url,
243 'class' => 'entity_remote_subscribe'),
244 // TRANS: Link to subscribe to a remote entity.
247 $output->elementEnd('li');
254 function onStartShowTagProfileForm($action, $profile)
256 $action->elementStart('form', array('method' => 'post',
257 'id' => 'form_tag_user',
258 'class' => 'form_settings',
259 'name' => 'tagprofile',
260 'action' => common_local_url('tagprofile', array('id' => @$profile->id))));
262 $action->elementStart('fieldset');
263 // TRANS: Fieldset legend.
264 $action->element('legend', null, _m('List remote profile'));
265 $action->hidden('token', common_session_token());
267 $user = common_current_user();
269 $action->elementStart('ul', 'form_data');
270 $action->elementStart('li');
272 // TRANS: Field label.
273 $action->input('uri', _m('LABEL','Remote profile'), $action->trimmed('uri'),
274 // TRANS: Field title.
275 _m('OStatus user\'s address, like nickname@example.com or http://example.net/nickname.'));
276 $action->elementEnd('li');
277 $action->elementEnd('ul');
278 // TRANS: Button text to fetch remote profile.
279 $action->submit('fetch', _m('BUTTON','Fetch'));
280 $action->elementEnd('fieldset');
281 $action->elementEnd('form');
284 function onStartTagProfileAction($action, $profile)
287 $uri = $action->trimmed('uri');
289 if (!$profile && $uri) {
291 if (Validate::email($uri)) {
292 $oprofile = Ostatus_profile::ensureWebfinger($uri);
293 } else if (Validate::uri($uri)) {
294 $oprofile = Ostatus_profile::ensureProfileURL($uri);
296 // TRANS: Exception in OStatus when invalid URI was entered.
297 throw new Exception(_m('Invalid URI.'));
300 // redirect to the new profile.
301 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
304 } catch (Exception $e) {
305 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
306 // TRANS: and example.net, as these are official standard domain names for use in examples.
307 $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.");
310 $action->showForm($err);
317 * If the field being looked for is URI look for the profile
319 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
320 if ($action->field == 'uri') {
321 $profile->joinAdd(array('id', 'user:id'));
322 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
325 if ($profile->N == 0) {
327 if (Validate::email($q)) {
328 $oprofile = Ostatus_profile::ensureWebfinger($q);
329 } else if (Validate::uri($q)) {
330 $oprofile = Ostatus_profile::ensureProfileURL($q);
332 // TRANS: Exception in OStatus when invalid URI was entered.
333 throw new Exception(_m('Invalid URI.'));
335 return $this->filter(array($oprofile->localProfile()));
337 } catch (Exception $e) {
338 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
339 // TRANS: and example.net, as these are official standard domain names for use in examples.
340 $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.");
350 * Find any explicit remote mentions. Accepted forms:
351 * Webfinger: @user@example.com
352 * Profile link: @example.com/mublog/user
353 * @param Profile $sender (os user?)
354 * @param string $text input markup text
355 * @param array &$mention in/out param: set of found mentions
356 * @return boolean hook return value
358 function onEndFindMentions($sender, $text, &$mentions)
362 // Webfinger matches: @user@example.com
363 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
366 PREG_OFFSET_CAPTURE)) {
367 foreach ($wmatches[1] as $wmatch) {
368 list($target, $pos) = $wmatch;
369 $this->log(LOG_INFO, "Checking webfinger '$target'");
371 $oprofile = Ostatus_profile::ensureWebfinger($target);
372 if ($oprofile && !$oprofile->isGroup()) {
373 $profile = $oprofile->localProfile();
374 $matches[$pos] = array('mentioned' => array($profile),
377 'url' => $profile->profileurl);
379 } catch (Exception $e) {
380 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
385 // Profile matches: @example.com/mublog/user
386 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
389 PREG_OFFSET_CAPTURE)) {
390 foreach ($wmatches[1] as $wmatch) {
391 list($target, $pos) = $wmatch;
392 $schemes = array('http', 'https');
393 foreach ($schemes as $scheme) {
394 $url = "$scheme://$target";
395 $this->log(LOG_INFO, "Checking profile address '$url'");
397 $oprofile = Ostatus_profile::ensureProfileURL($url);
398 if ($oprofile && !$oprofile->isGroup()) {
399 $profile = $oprofile->localProfile();
400 $matches[$pos] = array('mentioned' => array($profile),
403 'url' => $profile->profileurl);
406 } catch (Exception $e) {
407 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
413 foreach ($mentions as $i => $other) {
414 // If we share a common prefix with a local user, override it!
415 $pos = $other['position'];
416 if (isset($matches[$pos])) {
417 $mentions[$i] = $matches[$pos];
418 unset($matches[$pos]);
421 foreach ($matches as $mention) {
422 $mentions[] = $mention;
429 * Allow remote profile references to be used in commands:
430 * sub update@status.net
431 * whois evan@identi.ca
432 * reply http://identi.ca/evan hey what's up
434 * @param Command $command
436 * @param Profile &$profile
437 * @return hook return code
439 function onStartCommandGetProfile($command, $arg, &$profile)
441 $oprofile = $this->pullRemoteProfile($arg);
442 if ($oprofile && !$oprofile->isGroup()) {
443 $profile = $oprofile->localProfile();
451 * Allow remote group references to be used in commands:
452 * join group+statusnet@identi.ca
453 * join http://identi.ca/group/statusnet
454 * drop identi.ca/group/statusnet
456 * @param Command $command
458 * @param User_group &$group
459 * @return hook return code
461 function onStartCommandGetGroup($command, $arg, &$group)
463 $oprofile = $this->pullRemoteProfile($arg);
464 if ($oprofile && $oprofile->isGroup()) {
465 $group = $oprofile->localGroup();
472 protected function pullRemoteProfile($arg)
475 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
478 return Ostatus_profile::ensureWebfinger($arg);
479 } catch (Exception $e) {
480 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
481 $arg . ': ' . $e->getMessage());
485 // Look for profile URLs, with or without scheme:
487 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
490 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
491 $schemes = array('http', 'https');
492 foreach ($schemes as $scheme) {
493 $urls[] = "$scheme://$arg";
497 foreach ($urls as $url) {
499 return Ostatus_profile::ensureProfileURL($url);
500 } catch (Exception $e) {
501 common_log(LOG_ERR, 'Profile lookup failed for ' .
502 $arg . ': ' . $e->getMessage());
509 * Make sure necessary tables are filled out.
511 function onCheckSchema() {
512 $schema = Schema::get();
513 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
514 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
515 $schema->ensureTable('feedsub', FeedSub::schemaDef());
516 $schema->ensureTable('hubsub', HubSub::schemaDef());
517 $schema->ensureTable('magicsig', Magicsig::schemaDef());
521 function onEndShowStatusNetStyles($action) {
522 $action->cssLink($this->path('theme/base/css/ostatus.css'));
526 function onEndShowStatusNetScripts($action) {
527 $action->script($this->path('js/ostatus.js'));
532 * Override the "from ostatus" bit in notice lists to link to the
533 * original post and show the domain it came from.
535 * @param Notice in $notice
536 * @param string out &$name
537 * @param string out &$url
538 * @param string out &$title
539 * @return mixed hook return code
541 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
543 if ($notice->source == 'ostatus') {
545 $bits = parse_url($notice->url);
546 $domain = $bits['host'];
547 if (substr($domain, 0, 4) == 'www.') {
548 $name = substr($domain, 4);
554 // TRANS: Title. %s is a domain name.
555 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
563 * Send incoming PuSH feeds for OStatus endpoints in for processing.
565 * @param FeedSub $feedsub
566 * @param DOMDocument $feed
567 * @return mixed hook return code
569 function onStartFeedSubReceive($feedsub, $feed)
571 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
573 $oprofile->processFeed($feed, 'push');
575 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
580 * Tell the FeedSub infrastructure whether we have any active OStatus
581 * usage for the feed; if not it'll be able to garbage-collect the
584 * @param FeedSub $feedsub
585 * @param integer $count in/out
586 * @return mixed hook return code
588 function onFeedSubSubscriberCount($feedsub, &$count)
590 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
592 $count += $oprofile->subscriberCount();
598 * When about to subscribe to a remote user, start a server-to-server
599 * PuSH subscription if needed. If we can't establish that, abort.
601 * @fixme If something else aborts later, we could end up with a stray
602 * PuSH subscription. This is relatively harmless, though.
604 * @param Profile $subscriber
605 * @param Profile $other
607 * @return hook return code
611 function onStartSubscribe($subscriber, $other)
613 $user = User::getKV('id', $subscriber->id);
619 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
621 if (empty($oprofile)) {
625 if (!$oprofile->subscribe()) {
626 // TRANS: Exception thrown when setup of remote subscription fails.
627 throw new Exception(_m('Could not set up remote subscription.'));
632 * Having established a remote subscription, send a notification to the
633 * remote OStatus profile's endpoint.
635 * @param Profile $subscriber
636 * @param Profile $other
638 * @return hook return code
642 function onEndSubscribe($subscriber, $other)
644 $user = User::getKV('id', $subscriber->id);
650 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
652 if (empty($oprofile)) {
656 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
657 'subscribed' => $other->id));
659 $act = $sub->asActivity();
661 $oprofile->notifyActivity($act, $subscriber);
667 * Notify remote server and garbage collect unused feeds on unsubscribe.
668 * @todo FIXME: Send these operations to background queues
671 * @param Profile $other
672 * @return hook return value
674 function onEndUnsubscribe($profile, $other)
676 $user = User::getKV('id', $profile->id);
682 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
684 if (empty($oprofile)) {
688 // Drop the PuSH subscription if there are no other subscribers.
689 $oprofile->garbageCollect();
691 $act = new Activity();
693 $act->verb = ActivityVerb::UNFOLLOW;
695 $act->id = TagURI::mint('unfollow:%d:%d:%s',
698 common_date_iso8601(time()));
701 // TRANS: Title for unfollowing a remote profile.
702 $act->title = _m('TITLE','Unfollow');
703 // TRANS: Success message for unsubscribe from user attempt through OStatus.
704 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
705 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
706 $profile->getBestName(),
707 $other->getBestName());
709 $act->actor = ActivityObject::fromProfile($profile);
710 $act->object = ActivityObject::fromProfile($other);
712 $oprofile->notifyActivity($act, $profile);
718 * When one of our local users tries to join a remote group,
719 * notify the remote server. If the notification is rejected,
722 * @param User_group $group
723 * @param Profile $profile
725 * @return mixed hook return value
727 function onStartJoinGroup($group, $profile)
729 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
731 if (!$oprofile->subscribe()) {
732 // TRANS: Exception thrown when setup of remote group membership fails.
733 throw new Exception(_m('Could not set up remote group membership.'));
736 // NOTE: we don't use Group_member::asActivity() since that record
737 // has not yet been created.
739 $act = new Activity();
740 $act->id = TagURI::mint('join:%d:%d:%s',
743 common_date_iso8601(time()));
745 $act->actor = ActivityObject::fromProfile($profile);
746 $act->verb = ActivityVerb::JOIN;
747 $act->object = $oprofile->asActivityObject();
750 // TRANS: Title for joining a remote groep.
751 $act->title = _m('TITLE','Join');
752 // TRANS: Success message for subscribe to group attempt through OStatus.
753 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
754 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
755 $profile->getBestName(),
756 $oprofile->getBestName());
758 if ($oprofile->notifyActivity($act, $profile)) {
761 $oprofile->garbageCollect();
762 // TRANS: Exception thrown when joining a remote group fails.
763 throw new Exception(_m('Failed joining remote group.'));
769 * When one of our local users leaves a remote group, notify the remote
772 * @fixme Might be good to schedule a resend of the leave notification
773 * if it failed due to a transitory error. We've canceled the local
774 * membership already anyway, but if the remote server comes back up
775 * it'll be left with a stray membership record.
777 * @param User_group $group
778 * @param Profile $profile
780 * @return mixed hook return value
782 function onEndLeaveGroup($group, $profile)
784 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
786 // Drop the PuSH subscription if there are no other subscribers.
787 $oprofile->garbageCollect();
791 $act = new Activity();
792 $act->id = TagURI::mint('leave:%d:%d:%s',
795 common_date_iso8601(time()));
797 $act->actor = ActivityObject::fromProfile($member);
798 $act->verb = ActivityVerb::LEAVE;
799 $act->object = $oprofile->asActivityObject();
802 // TRANS: Title for leaving a remote group.
803 $act->title = _m('TITLE','Leave');
804 // TRANS: Success message for unsubscribe from group attempt through OStatus.
805 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
806 $act->content = sprintf(_m('%1$s has left group %2$s.'),
807 $member->getBestName(),
808 $oprofile->getBestName());
810 $oprofile->notifyActivity($act, $member);
815 * When one of our local users tries to subscribe to a remote peopletag,
816 * notify the remote server. If the notification is rejected,
817 * deny the subscription.
819 * @param Profile_list $peopletag
822 * @return mixed hook return value
825 function onStartSubscribePeopletag($peopletag, $user)
827 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
829 if (!$oprofile->subscribe()) {
830 // TRANS: Exception thrown when setup of remote list subscription fails.
831 throw new Exception(_m('Could not set up remote list subscription.'));
834 $sub = $user->getProfile();
835 $tagger = Profile::getKV($peopletag->tagger);
837 $act = new Activity();
838 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
841 common_date_iso8601(time()));
843 $act->actor = ActivityObject::fromProfile($sub);
844 $act->verb = ActivityVerb::FOLLOW;
845 $act->object = $oprofile->asActivityObject();
848 // TRANS: Title for following a remote list.
849 $act->title = _m('TITLE','Follow list');
850 // TRANS: Success message for remote list follow through OStatus.
851 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
852 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
854 $oprofile->getBestName(),
855 $tagger->getBestName());
857 if ($oprofile->notifyActivity($act, $sub)) {
860 $oprofile->garbageCollect();
861 // TRANS: Exception thrown when subscription to remote list fails.
862 throw new Exception(_m('Failed subscribing to remote list.'));
868 * When one of our local users unsubscribes to a remote peopletag, notify the remote
871 * @param Profile_list $peopletag
874 * @return mixed hook return value
877 function onEndUnsubscribePeopletag($peopletag, $user)
879 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
881 // Drop the PuSH subscription if there are no other subscribers.
882 $oprofile->garbageCollect();
884 $sub = Profile::getKV($user->id);
885 $tagger = Profile::getKV($peopletag->tagger);
887 $act = new Activity();
888 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
891 common_date_iso8601(time()));
893 $act->actor = ActivityObject::fromProfile($member);
894 $act->verb = ActivityVerb::UNFOLLOW;
895 $act->object = $oprofile->asActivityObject();
898 // TRANS: Title for unfollowing a remote list.
899 $act->title = _m('Unfollow list');
900 // TRANS: Success message for remote list unfollow through OStatus.
901 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
902 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
904 $oprofile->getBestName(),
905 $tagger->getBestName());
907 $oprofile->notifyActivity($act, $user);
912 * Notify remote users when their notices get favorited.
914 * @param Profile or User $profile of local user doing the faving
915 * @param Notice $notice being favored
916 * @return hook return value
918 function onEndFavorNotice(Profile $profile, Notice $notice)
920 $user = User::getKV('id', $profile->id);
926 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
928 if (empty($oprofile)) {
932 $fav = Fave::pkeyGet(array('user_id' => $user->id,
933 'notice_id' => $notice->id));
940 $act = $fav->asActivity();
942 $oprofile->notifyActivity($act, $profile);
948 * Notify remote user it has got a new people tag
949 * - tag verb is queued
950 * - the subscription is done immediately if not present
952 * @param Profile_tag $ptag the people tag that was created
953 * @return hook return value
955 function onEndTagProfile($ptag)
957 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
959 if (empty($oprofile)) {
963 $plist = $ptag->getMeta();
964 if ($plist->private) {
968 $act = new Activity();
970 $tagger = $plist->getTagger();
971 $tagged = Profile::getKV('id', $ptag->tagged);
973 $act->verb = ActivityVerb::TAG;
974 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
975 $plist->tagger, $plist->id,
976 common_date_iso8601(time()));
978 // TRANS: Title for listing a remote profile.
979 $act->title = _m('TITLE','List');
980 // TRANS: Success message for remote list addition through OStatus.
981 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
982 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
983 $tagger->getBestName(),
984 $tagged->getBestName(),
985 $plist->getBestName());
987 $act->actor = ActivityObject::fromProfile($tagger);
988 $act->objects = array(ActivityObject::fromProfile($tagged));
989 $act->target = ActivityObject::fromPeopletag($plist);
991 $oprofile->notifyDeferred($act, $tagger);
993 // initiate a PuSH subscription for the person being tagged
994 if (!$oprofile->subscribe()) {
995 // TRANS: Exception thrown when subscribing to a remote list fails.
996 throw new Exception(sprintf(_m('Could not complete subscription to remote '.
997 'profile\'s feed. List %s could not be saved.'), $ptag->tag));
1004 * Notify remote user that a people tag has been removed
1005 * - untag verb is queued
1006 * - the subscription is undone immediately if not required
1007 * i.e garbageCollect()'d
1009 * @param Profile_tag $ptag the people tag that was deleted
1010 * @return hook return value
1012 function onEndUntagProfile($ptag)
1014 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
1016 if (empty($oprofile)) {
1020 $plist = $ptag->getMeta();
1021 if ($plist->private) {
1025 $act = new Activity();
1027 $tagger = $plist->getTagger();
1028 $tagged = Profile::getKV('id', $ptag->tagged);
1030 $act->verb = ActivityVerb::UNTAG;
1031 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1032 $plist->tagger, $plist->id,
1033 common_date_iso8601(time()));
1034 $act->time = time();
1035 // TRANS: Title for unlisting a remote profile.
1036 $act->title = _m('TITLE','Unlist');
1037 // TRANS: Success message for remote list removal through OStatus.
1038 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1039 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1040 $tagger->getBestName(),
1041 $tagged->getBestName(),
1042 $plist->getBestName());
1044 $act->actor = ActivityObject::fromProfile($tagger);
1045 $act->objects = array(ActivityObject::fromProfile($tagged));
1046 $act->target = ActivityObject::fromPeopletag($plist);
1048 $oprofile->notifyDeferred($act, $tagger);
1050 // unsubscribe to PuSH feed if no more required
1051 $oprofile->garbageCollect();
1057 * Notify remote users when their notices get de-favorited.
1059 * @param Profile $profile Profile person doing the de-faving
1060 * @param Notice $notice Notice being favored
1062 * @return hook return value
1064 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1066 $user = User::getKV('id', $profile->id);
1072 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1074 if (empty($oprofile)) {
1078 $act = new Activity();
1080 $act->verb = ActivityVerb::UNFAVORITE;
1081 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1084 common_date_iso8601(time()));
1085 $act->time = time();
1086 // TRANS: Title for unliking a remote notice.
1087 $act->title = _m('Unlike');
1088 // TRANS: Success message for remove a favorite notice through OStatus.
1089 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1090 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1091 $profile->getBestName(),
1094 $act->actor = ActivityObject::fromProfile($profile);
1095 $act->object = ActivityObject::fromNotice($notice);
1097 $oprofile->notifyActivity($act, $profile);
1102 function onStartGetProfileUri($profile, &$uri)
1104 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1105 if (!empty($oprofile)) {
1106 $uri = $oprofile->uri;
1112 function onStartUserGroupHomeUrl($group, &$url)
1114 return $this->onStartUserGroupPermalink($group, $url);
1117 function onStartUserGroupPermalink($group, &$url)
1119 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1121 // @fixme this should probably be in the user_group table
1122 // @fixme this uri not guaranteed to be a profile page
1123 $url = $oprofile->uri;
1128 function onStartShowSubscriptionsContent($action)
1130 $this->showEntityRemoteSubscribe($action);
1135 function onStartShowUserGroupsContent($action)
1137 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1142 function onEndShowSubscriptionsMiniList($action)
1144 $this->showEntityRemoteSubscribe($action);
1149 function onEndShowGroupsMiniList($action)
1151 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1156 function showEntityRemoteSubscribe($action, $target='ostatussub')
1158 $user = common_current_user();
1159 if ($user && ($user->id == $action->profile->id)) {
1160 $action->elementStart('div', 'entity_actions');
1161 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1162 'class' => 'entity_subscribe'));
1163 $action->element('a', array('href' => common_local_url($target),
1164 'class' => 'entity_remote_subscribe'),
1165 // TRANS: Link text for link to remote subscribe.
1167 $action->elementEnd('p');
1168 $action->elementEnd('div');
1173 * Ping remote profiles with updates to this profile.
1174 * Salmon pings are queued for background processing.
1176 function onEndBroadcastProfile(Profile $profile)
1178 $user = User::getKV('id', $profile->id);
1180 // Find foreign accounts I'm subscribed to that support Salmon pings.
1182 // @fixme we could run updates through the PuSH feed too,
1183 // in which case we can skip Salmon pings to folks who
1184 // are also subscribed to me.
1185 $sql = "SELECT * FROM ostatus_profile " .
1186 "WHERE profile_id IN " .
1187 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1189 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1190 $oprofile = new Ostatus_profile();
1191 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1193 if ($oprofile->N == 0) {
1194 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1198 $act = new Activity();
1200 $act->verb = ActivityVerb::UPDATE_PROFILE;
1201 $act->id = TagURI::mint('update-profile:%d:%s',
1203 common_date_iso8601(time()));
1204 $act->time = time();
1205 // TRANS: Title for activity.
1206 $act->title = _m('Profile update');
1207 // TRANS: Ping text for remote profile update through OStatus.
1208 // TRANS: %s is user that updated their profile.
1209 $act->content = sprintf(_m('%s has updated their profile page.'),
1210 $profile->getBestName());
1212 $act->actor = ActivityObject::fromProfile($profile);
1213 $act->object = $act->actor;
1215 while ($oprofile->fetch()) {
1216 $oprofile->notifyDeferred($act, $profile);
1222 function onStartProfileListItemActionElements($item, $profile=null)
1224 if (!common_logged_in()) {
1226 $profileUser = User::getKV('id', $item->profile->id);
1228 if (!empty($profileUser)) {
1230 if ($item instanceof Action) {
1232 $profile = $item->profile;
1234 $output = $item->out;
1237 // Add an OStatus subscribe
1238 $output->elementStart('li', 'entity_subscribe');
1239 $url = common_local_url('ostatusinit',
1240 array('nickname' => $profileUser->nickname));
1241 $output->element('a', array('href' => $url,
1242 'class' => 'entity_remote_subscribe'),
1243 // TRANS: Link text for a user to subscribe to an OStatus user.
1245 $output->elementEnd('li');
1247 $output->elementStart('li', 'entity_tag');
1248 $url = common_local_url('ostatustag',
1249 array('nickname' => $profileUser->nickname));
1250 $output->element('a', array('href' => $url,
1251 'class' => 'entity_remote_tag'),
1252 // TRANS: Link text for a user to list an OStatus user.
1254 $output->elementEnd('li');
1261 function onPluginVersion(&$versions)
1263 $versions[] = array('name' => 'OStatus',
1264 'version' => STATUSNET_VERSION,
1265 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1266 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1267 // TRANS: Plugin description.
1268 'rawdescription' => _m('Follow people across social networks that implement '.
1269 '<a href="http://ostatus.org/">OStatus</a>.'));
1275 * Utility function to check if the given URI is a canonical group profile
1276 * page, and if so return the ID number.
1278 * @param string $url
1279 * @return mixed int or false
1281 public static function localGroupFromUrl($url)
1283 $group = User_group::getKV('uri', $url);
1285 $local = Local_group::getKV('group_id', $group->id);
1290 // To find local groups which haven't had their uri fields filled out...
1291 // If the domain has changed since a subscriber got the URI, it'll
1293 $template = common_local_url('groupbyid', array('id' => '31337'));
1294 $template = preg_quote($template, '/');
1295 $template = str_replace('31337', '(\d+)', $template);
1296 if (preg_match("/$template/", $url, $matches)) {
1297 return intval($matches[1]);
1303 public function onStartProfileGetAtomFeed($profile, &$feed)
1305 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1307 if (empty($oprofile)) {
1311 $feed = $oprofile->feeduri;
1315 function onStartGetProfileFromURI($uri, &$profile)
1317 // Don't want to do Web-based discovery on our own server,
1318 // so we check locally first.
1320 $user = User::getKV('uri', $uri);
1322 if (!empty($user)) {
1323 $profile = $user->getProfile();
1327 // Now, check remotely
1329 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1331 if (!empty($oprofile)) {
1332 $profile = $oprofile->localProfile();
1336 // Still not a hit, so give up.
1341 function onEndXrdActionLinks(&$xrd, $user)
1343 $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1344 'href' => common_local_url('ApiTimelineUser',
1345 array('id' => $user->id,
1346 'format' => 'atom')),
1347 'type' => 'application/atom+xml');
1350 $salmon_url = common_local_url('usersalmon',
1351 array('id' => $user->id));
1353 $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1354 'href' => $salmon_url);
1355 // XXX : Deprecated - to be removed.
1356 $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1357 'href' => $salmon_url);
1359 $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1360 'href' => $salmon_url);
1362 // Get this user's keypair
1363 $magickey = Magicsig::getKV('user_id', $user->id);
1365 // No keypair yet, let's generate one.
1366 $magickey = new Magicsig();
1367 $magickey->generate($user->id);
1370 $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1371 'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1373 // TODO - finalize where the redirect should go on the publisher
1374 $url = common_local_url('ostatussub') . '?profile={uri}';
1375 $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1376 'template' => $url );