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 $profile subscriber
605 * @param Profile $other subscribee
607 * @return hook return code
611 function onStartSubscribe(Profile $profile, Profile $other)
613 if (!$profile->isLocal()) {
617 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
619 if (empty($oprofile)) {
623 if (!$oprofile->subscribe()) {
624 // TRANS: Exception thrown when setup of remote subscription fails.
625 throw new Exception(_m('Could not set up remote subscription.'));
630 * Having established a remote subscription, send a notification to the
631 * remote OStatus profile's endpoint.
633 * @param Profile $profile subscriber
634 * @param Profile $other subscribee
636 * @return hook return code
640 function onEndSubscribe(Profile $profile, Profile $other)
642 if (!$profile->isLocal()) {
646 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
648 if (empty($oprofile)) {
652 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
653 'subscribed' => $other->id));
655 $act = $sub->asActivity();
657 $oprofile->notifyActivity($act, $profile);
663 * Notify remote server and garbage collect unused feeds on unsubscribe.
664 * @todo FIXME: Send these operations to background queues
667 * @param Profile $other
668 * @return hook return value
670 function onEndUnsubscribe(Profile $profile, Profile $other)
672 if (!$profile->isLocal()) {
676 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
678 if (empty($oprofile)) {
682 // Drop the PuSH subscription if there are no other subscribers.
683 $oprofile->garbageCollect();
685 $act = new Activity();
687 $act->verb = ActivityVerb::UNFOLLOW;
689 $act->id = TagURI::mint('unfollow:%d:%d:%s',
692 common_date_iso8601(time()));
695 // TRANS: Title for unfollowing a remote profile.
696 $act->title = _m('TITLE','Unfollow');
697 // TRANS: Success message for unsubscribe from user attempt through OStatus.
698 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
699 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
700 $profile->getBestName(),
701 $other->getBestName());
703 $act->actor = ActivityObject::fromProfile($profile);
704 $act->object = ActivityObject::fromProfile($other);
706 $oprofile->notifyActivity($act, $profile);
712 * When one of our local users tries to join a remote group,
713 * notify the remote server. If the notification is rejected,
716 * @param User_group $group
717 * @param Profile $profile
719 * @return mixed hook return value
721 function onStartJoinGroup($group, $profile)
723 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
725 if (!$oprofile->subscribe()) {
726 // TRANS: Exception thrown when setup of remote group membership fails.
727 throw new Exception(_m('Could not set up remote group membership.'));
730 // NOTE: we don't use Group_member::asActivity() since that record
731 // has not yet been created.
733 $act = new Activity();
734 $act->id = TagURI::mint('join:%d:%d:%s',
737 common_date_iso8601(time()));
739 $act->actor = ActivityObject::fromProfile($profile);
740 $act->verb = ActivityVerb::JOIN;
741 $act->object = $oprofile->asActivityObject();
744 // TRANS: Title for joining a remote groep.
745 $act->title = _m('TITLE','Join');
746 // TRANS: Success message for subscribe to group attempt through OStatus.
747 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
748 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
749 $profile->getBestName(),
750 $oprofile->getBestName());
752 if ($oprofile->notifyActivity($act, $profile)) {
755 $oprofile->garbageCollect();
756 // TRANS: Exception thrown when joining a remote group fails.
757 throw new Exception(_m('Failed joining remote group.'));
763 * When one of our local users leaves a remote group, notify the remote
766 * @fixme Might be good to schedule a resend of the leave notification
767 * if it failed due to a transitory error. We've canceled the local
768 * membership already anyway, but if the remote server comes back up
769 * it'll be left with a stray membership record.
771 * @param User_group $group
772 * @param Profile $profile
774 * @return mixed hook return value
776 function onEndLeaveGroup($group, $profile)
778 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
780 // Drop the PuSH subscription if there are no other subscribers.
781 $oprofile->garbageCollect();
785 $act = new Activity();
786 $act->id = TagURI::mint('leave:%d:%d:%s',
789 common_date_iso8601(time()));
791 $act->actor = ActivityObject::fromProfile($member);
792 $act->verb = ActivityVerb::LEAVE;
793 $act->object = $oprofile->asActivityObject();
796 // TRANS: Title for leaving a remote group.
797 $act->title = _m('TITLE','Leave');
798 // TRANS: Success message for unsubscribe from group attempt through OStatus.
799 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
800 $act->content = sprintf(_m('%1$s has left group %2$s.'),
801 $member->getBestName(),
802 $oprofile->getBestName());
804 $oprofile->notifyActivity($act, $member);
809 * When one of our local users tries to subscribe to a remote peopletag,
810 * notify the remote server. If the notification is rejected,
811 * deny the subscription.
813 * @param Profile_list $peopletag
816 * @return mixed hook return value
819 function onStartSubscribePeopletag($peopletag, $user)
821 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
823 if (!$oprofile->subscribe()) {
824 // TRANS: Exception thrown when setup of remote list subscription fails.
825 throw new Exception(_m('Could not set up remote list subscription.'));
828 $sub = $user->getProfile();
829 $tagger = Profile::getKV($peopletag->tagger);
831 $act = new Activity();
832 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
835 common_date_iso8601(time()));
837 $act->actor = ActivityObject::fromProfile($sub);
838 $act->verb = ActivityVerb::FOLLOW;
839 $act->object = $oprofile->asActivityObject();
842 // TRANS: Title for following a remote list.
843 $act->title = _m('TITLE','Follow list');
844 // TRANS: Success message for remote list follow through OStatus.
845 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
846 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
848 $oprofile->getBestName(),
849 $tagger->getBestName());
851 if ($oprofile->notifyActivity($act, $sub)) {
854 $oprofile->garbageCollect();
855 // TRANS: Exception thrown when subscription to remote list fails.
856 throw new Exception(_m('Failed subscribing to remote list.'));
862 * When one of our local users unsubscribes to a remote peopletag, notify the remote
865 * @param Profile_list $peopletag
868 * @return mixed hook return value
871 function onEndUnsubscribePeopletag($peopletag, $user)
873 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
875 // Drop the PuSH subscription if there are no other subscribers.
876 $oprofile->garbageCollect();
878 $sub = Profile::getKV($user->id);
879 $tagger = Profile::getKV($peopletag->tagger);
881 $act = new Activity();
882 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
885 common_date_iso8601(time()));
887 $act->actor = ActivityObject::fromProfile($member);
888 $act->verb = ActivityVerb::UNFOLLOW;
889 $act->object = $oprofile->asActivityObject();
892 // TRANS: Title for unfollowing a remote list.
893 $act->title = _m('Unfollow list');
894 // TRANS: Success message for remote list unfollow through OStatus.
895 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
896 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
898 $oprofile->getBestName(),
899 $tagger->getBestName());
901 $oprofile->notifyActivity($act, $user);
906 * Notify remote users when their notices get favorited.
908 * @param Profile or User $profile of local user doing the faving
909 * @param Notice $notice being favored
910 * @return hook return value
912 function onEndFavorNotice(Profile $profile, Notice $notice)
914 $user = User::getKV('id', $profile->id);
920 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
922 if (empty($oprofile)) {
926 $fav = Fave::pkeyGet(array('user_id' => $user->id,
927 'notice_id' => $notice->id));
934 $act = $fav->asActivity();
936 $oprofile->notifyActivity($act, $profile);
942 * Notify remote user it has got a new people tag
943 * - tag verb is queued
944 * - the subscription is done immediately if not present
946 * @param Profile_tag $ptag the people tag that was created
947 * @return hook return value
949 function onEndTagProfile($ptag)
951 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
953 if (empty($oprofile)) {
957 $plist = $ptag->getMeta();
958 if ($plist->private) {
962 $act = new Activity();
964 $tagger = $plist->getTagger();
965 $tagged = Profile::getKV('id', $ptag->tagged);
967 $act->verb = ActivityVerb::TAG;
968 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
969 $plist->tagger, $plist->id,
970 common_date_iso8601(time()));
972 // TRANS: Title for listing a remote profile.
973 $act->title = _m('TITLE','List');
974 // TRANS: Success message for remote list addition through OStatus.
975 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
976 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
977 $tagger->getBestName(),
978 $tagged->getBestName(),
979 $plist->getBestName());
981 $act->actor = ActivityObject::fromProfile($tagger);
982 $act->objects = array(ActivityObject::fromProfile($tagged));
983 $act->target = ActivityObject::fromPeopletag($plist);
985 $oprofile->notifyDeferred($act, $tagger);
987 // initiate a PuSH subscription for the person being tagged
988 if (!$oprofile->subscribe()) {
989 // TRANS: Exception thrown when subscribing to a remote list fails.
990 throw new Exception(sprintf(_m('Could not complete subscription to remote '.
991 'profile\'s feed. List %s could not be saved.'), $ptag->tag));
998 * Notify remote user that a people tag has been removed
999 * - untag verb is queued
1000 * - the subscription is undone immediately if not required
1001 * i.e garbageCollect()'d
1003 * @param Profile_tag $ptag the people tag that was deleted
1004 * @return hook return value
1006 function onEndUntagProfile($ptag)
1008 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
1010 if (empty($oprofile)) {
1014 $plist = $ptag->getMeta();
1015 if ($plist->private) {
1019 $act = new Activity();
1021 $tagger = $plist->getTagger();
1022 $tagged = Profile::getKV('id', $ptag->tagged);
1024 $act->verb = ActivityVerb::UNTAG;
1025 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1026 $plist->tagger, $plist->id,
1027 common_date_iso8601(time()));
1028 $act->time = time();
1029 // TRANS: Title for unlisting a remote profile.
1030 $act->title = _m('TITLE','Unlist');
1031 // TRANS: Success message for remote list removal through OStatus.
1032 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1033 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1034 $tagger->getBestName(),
1035 $tagged->getBestName(),
1036 $plist->getBestName());
1038 $act->actor = ActivityObject::fromProfile($tagger);
1039 $act->objects = array(ActivityObject::fromProfile($tagged));
1040 $act->target = ActivityObject::fromPeopletag($plist);
1042 $oprofile->notifyDeferred($act, $tagger);
1044 // unsubscribe to PuSH feed if no more required
1045 $oprofile->garbageCollect();
1051 * Notify remote users when their notices get de-favorited.
1053 * @param Profile $profile Profile person doing the de-faving
1054 * @param Notice $notice Notice being favored
1056 * @return hook return value
1058 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1060 $user = User::getKV('id', $profile->id);
1066 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1068 if (empty($oprofile)) {
1072 $act = new Activity();
1074 $act->verb = ActivityVerb::UNFAVORITE;
1075 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1078 common_date_iso8601(time()));
1079 $act->time = time();
1080 // TRANS: Title for unliking a remote notice.
1081 $act->title = _m('Unlike');
1082 // TRANS: Success message for remove a favorite notice through OStatus.
1083 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1084 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1085 $profile->getBestName(),
1088 $act->actor = ActivityObject::fromProfile($profile);
1089 $act->object = ActivityObject::fromNotice($notice);
1091 $oprofile->notifyActivity($act, $profile);
1096 function onStartGetProfileUri($profile, &$uri)
1098 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1099 if (!empty($oprofile)) {
1100 $uri = $oprofile->uri;
1106 function onStartUserGroupHomeUrl($group, &$url)
1108 return $this->onStartUserGroupPermalink($group, $url);
1111 function onStartUserGroupPermalink($group, &$url)
1113 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1115 // @fixme this should probably be in the user_group table
1116 // @fixme this uri not guaranteed to be a profile page
1117 $url = $oprofile->uri;
1122 function onStartShowSubscriptionsContent($action)
1124 $this->showEntityRemoteSubscribe($action);
1129 function onStartShowUserGroupsContent($action)
1131 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1136 function onEndShowSubscriptionsMiniList($action)
1138 $this->showEntityRemoteSubscribe($action);
1143 function onEndShowGroupsMiniList($action)
1145 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1150 function showEntityRemoteSubscribe($action, $target='ostatussub')
1152 $user = common_current_user();
1153 if ($user && ($user->id == $action->profile->id)) {
1154 $action->elementStart('div', 'entity_actions');
1155 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1156 'class' => 'entity_subscribe'));
1157 $action->element('a', array('href' => common_local_url($target),
1158 'class' => 'entity_remote_subscribe'),
1159 // TRANS: Link text for link to remote subscribe.
1161 $action->elementEnd('p');
1162 $action->elementEnd('div');
1167 * Ping remote profiles with updates to this profile.
1168 * Salmon pings are queued for background processing.
1170 function onEndBroadcastProfile(Profile $profile)
1172 $user = User::getKV('id', $profile->id);
1174 // Find foreign accounts I'm subscribed to that support Salmon pings.
1176 // @fixme we could run updates through the PuSH feed too,
1177 // in which case we can skip Salmon pings to folks who
1178 // are also subscribed to me.
1179 $sql = "SELECT * FROM ostatus_profile " .
1180 "WHERE profile_id IN " .
1181 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1183 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1184 $oprofile = new Ostatus_profile();
1185 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1187 if ($oprofile->N == 0) {
1188 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1192 $act = new Activity();
1194 $act->verb = ActivityVerb::UPDATE_PROFILE;
1195 $act->id = TagURI::mint('update-profile:%d:%s',
1197 common_date_iso8601(time()));
1198 $act->time = time();
1199 // TRANS: Title for activity.
1200 $act->title = _m('Profile update');
1201 // TRANS: Ping text for remote profile update through OStatus.
1202 // TRANS: %s is user that updated their profile.
1203 $act->content = sprintf(_m('%s has updated their profile page.'),
1204 $profile->getBestName());
1206 $act->actor = ActivityObject::fromProfile($profile);
1207 $act->object = $act->actor;
1209 while ($oprofile->fetch()) {
1210 $oprofile->notifyDeferred($act, $profile);
1216 function onStartProfileListItemActionElements($item, $profile=null)
1218 if (!common_logged_in()) {
1220 $profileUser = User::getKV('id', $item->profile->id);
1222 if (!empty($profileUser)) {
1224 if ($item instanceof Action) {
1226 $profile = $item->profile;
1228 $output = $item->out;
1231 // Add an OStatus subscribe
1232 $output->elementStart('li', 'entity_subscribe');
1233 $url = common_local_url('ostatusinit',
1234 array('nickname' => $profileUser->nickname));
1235 $output->element('a', array('href' => $url,
1236 'class' => 'entity_remote_subscribe'),
1237 // TRANS: Link text for a user to subscribe to an OStatus user.
1239 $output->elementEnd('li');
1241 $output->elementStart('li', 'entity_tag');
1242 $url = common_local_url('ostatustag',
1243 array('nickname' => $profileUser->nickname));
1244 $output->element('a', array('href' => $url,
1245 'class' => 'entity_remote_tag'),
1246 // TRANS: Link text for a user to list an OStatus user.
1248 $output->elementEnd('li');
1255 function onPluginVersion(&$versions)
1257 $versions[] = array('name' => 'OStatus',
1258 'version' => STATUSNET_VERSION,
1259 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1260 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1261 // TRANS: Plugin description.
1262 'rawdescription' => _m('Follow people across social networks that implement '.
1263 '<a href="http://ostatus.org/">OStatus</a>.'));
1269 * Utility function to check if the given URI is a canonical group profile
1270 * page, and if so return the ID number.
1272 * @param string $url
1273 * @return mixed int or false
1275 public static function localGroupFromUrl($url)
1277 $group = User_group::getKV('uri', $url);
1279 $local = Local_group::getKV('group_id', $group->id);
1284 // To find local groups which haven't had their uri fields filled out...
1285 // If the domain has changed since a subscriber got the URI, it'll
1287 $template = common_local_url('groupbyid', array('id' => '31337'));
1288 $template = preg_quote($template, '/');
1289 $template = str_replace('31337', '(\d+)', $template);
1290 if (preg_match("/$template/", $url, $matches)) {
1291 return intval($matches[1]);
1297 public function onStartProfileGetAtomFeed($profile, &$feed)
1299 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1301 if (empty($oprofile)) {
1305 $feed = $oprofile->feeduri;
1309 function onStartGetProfileFromURI($uri, &$profile)
1311 // Don't want to do Web-based discovery on our own server,
1312 // so we check locally first.
1314 $user = User::getKV('uri', $uri);
1316 if (!empty($user)) {
1317 $profile = $user->getProfile();
1321 // Now, check remotely
1323 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1325 if (!empty($oprofile)) {
1326 $profile = $oprofile->localProfile();
1330 // Still not a hit, so give up.
1335 function onEndXrdActionLinks(&$xrd, $user)
1337 $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1338 'href' => common_local_url('ApiTimelineUser',
1339 array('id' => $user->id,
1340 'format' => 'atom')),
1341 'type' => 'application/atom+xml');
1344 $salmon_url = common_local_url('usersalmon',
1345 array('id' => $user->id));
1347 $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1348 'href' => $salmon_url);
1349 // XXX : Deprecated - to be removed.
1350 $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1351 'href' => $salmon_url);
1353 $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1354 'href' => $salmon_url);
1356 // Get this user's keypair
1357 $magickey = Magicsig::getKV('user_id', $user->id);
1359 // No keypair yet, let's generate one.
1360 $magickey = new Magicsig();
1361 $magickey->generate($user->id);
1364 $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1365 'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1367 // TODO - finalize where the redirect should go on the publisher
1368 $url = common_local_url('ostatussub') . '?profile={uri}';
1369 $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1370 'template' => $url );