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 if ($notice->isLocal()) {
129 // put our transport first, in case there's any conflict (like OMB)
130 array_unshift($transports, 'ostatus');
136 * Add a link header for LRDD Discovery
138 function onStartShowHTML($action)
140 if ($action instanceof ShowstreamAction) {
141 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
142 $url = common_local_url('userxrd');
143 $url.= '?uri='. $acct;
145 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
150 * Set up a PuSH hub link to our internal link for canonical timeline
151 * Atom feeds for users and groups.
153 function onStartApiAtom($feed)
157 if ($feed instanceof AtomUserNoticeFeed) {
158 $salmonAction = 'usersalmon';
159 $user = $feed->getUser();
161 $profile = $user->getProfile();
162 } else if ($feed instanceof AtomGroupNoticeFeed) {
163 $salmonAction = 'groupsalmon';
164 $group = $feed->getGroup();
166 } else if ($feed instanceof AtomListNoticeFeed) {
167 $salmonAction = 'peopletagsalmon';
168 $peopletag = $feed->getList();
169 $id = $peopletag->id;
175 $hub = common_config('ostatus', 'hub');
177 // Updates will be handled through our internal PuSH hub.
178 $hub = common_local_url('pushhub');
180 $feed->addLink($hub, array('rel' => 'hub'));
182 // Also, we'll add in the salmon link
183 $salmon = common_local_url($salmonAction, array('id' => $id));
184 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
186 // XXX: these are deprecated
187 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
188 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
195 * Automatically load the actions and libraries used by the plugin
197 * @param Class $cls the class
199 * @return boolean hook return
202 function onAutoload($cls)
204 $base = dirname(__FILE__);
205 $lower = strtolower($cls);
206 $map = array('activityverb' => 'activity',
207 'activityobject' => 'activity',
208 'activityutils' => 'activity');
209 if (isset($map[$lower])) {
210 $lower = $map[$lower];
212 $files = array("$base/classes/$cls.php",
213 "$base/lib/$lower.php");
214 if (substr($lower, -6) == 'action') {
215 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
217 foreach ($files as $file) {
218 if (file_exists($file)) {
227 * Add in an OStatus subscribe button
229 function onStartProfileRemoteSubscribe($output, $profile)
231 $this->onStartProfileListItemActionElements($output, $profile);
235 function onStartGroupSubscribe($widget, $group)
237 $cur = common_current_user();
240 $output->elementStart('li', 'entity_subscribe');
241 $profile = $peopletag->getTagger();
242 $url = common_local_url('ostatusinit',
243 array('group' => $group->nickname));
244 $widget->out->element('a', array('href' => $url,
245 'class' => 'entity_remote_subscribe'),
248 $output->elementEnd('li');
255 function onStartSubscribePeopletagForm($output, $peopletag)
257 $cur = common_current_user();
260 $output->elementStart('li', 'entity_subscribe');
261 $profile = $peopletag->getTagger();
262 $url = common_local_url('ostatusinit',
263 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
264 $output->element('a', array('href' => $url,
265 'class' => 'entity_remote_subscribe'),
268 $output->elementEnd('li');
275 function onStartShowTagProfileForm($action, $profile)
277 $action->elementStart('form', array('method' => 'post',
278 'id' => 'form_tag_user',
279 'class' => 'form_settings',
280 'name' => 'tagprofile',
281 'action' => common_local_url('tagprofile', array('id' => @$profile->id))));
283 $action->elementStart('fieldset');
284 $action->element('legend', null, _('Tag remote profile'));
285 $action->hidden('token', common_session_token());
287 $user = common_current_user();
289 $action->elementStart('ul', 'form_data');
290 $action->elementStart('li');
292 $action->input('uri', _('Remote profile'), $action->trimmed('uri'),
293 _('OStatus user\'s address, like nickname@example.com or http://example.net/nickname'));
294 $action->elementEnd('li');
295 $action->elementEnd('ul');
296 $action->submit('fetch', _('Fetch'));
297 $action->elementEnd('fieldset');
298 $action->elementEnd('form');
301 function onStartTagProfileAction($action, $profile)
304 $uri = $action->trimmed('uri');
306 if (!$profile && $uri) {
308 if (Validate::email($uri)) {
309 $oprofile = Ostatus_profile::ensureWebfinger($uri);
310 } else if (Validate::uri($uri)) {
311 $oprofile = Ostatus_profile::ensureProfileURL($uri);
313 throw new Exception('Invalid URI');
316 // redirect to the new profile.
317 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
320 } catch (Exception $e) {
321 $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");
324 $action->showForm($err);
331 * If the field being looked for is URI look for the profile
333 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
334 if ($action->field == 'uri') {
336 $profile->joinAdd($user);
337 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
340 if ($profile->N == 0) {
342 if (Validate::email($q)) {
343 $oprofile = Ostatus_profile::ensureWebfinger($q);
344 } else if (Validate::uri($q)) {
345 $oprofile = Ostatus_profile::ensureProfileURL($q);
347 throw new Exception('Invalid URI');
349 return $this->filter(array($oprofile->localProfile()));
351 } catch (Exception $e) {
352 $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");
362 * Find any explicit remote mentions. Accepted forms:
363 * Webfinger: @user@example.com
364 * Profile link: @example.com/mublog/user
365 * @param Profile $sender (os user?)
366 * @param string $text input markup text
367 * @param array &$mention in/out param: set of found mentions
368 * @return boolean hook return value
371 function onEndFindMentions($sender, $text, &$mentions)
375 // Webfinger matches: @user@example.com
376 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
379 PREG_OFFSET_CAPTURE)) {
380 foreach ($wmatches[1] as $wmatch) {
381 list($target, $pos) = $wmatch;
382 $this->log(LOG_INFO, "Checking webfinger '$target'");
384 $oprofile = Ostatus_profile::ensureWebfinger($target);
385 if ($oprofile && !$oprofile->isGroup()) {
386 $profile = $oprofile->localProfile();
387 $matches[$pos] = array('mentioned' => array($profile),
390 'url' => $profile->profileurl);
392 } catch (Exception $e) {
393 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
398 // Profile matches: @example.com/mublog/user
399 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
402 PREG_OFFSET_CAPTURE)) {
403 foreach ($wmatches[1] as $wmatch) {
404 list($target, $pos) = $wmatch;
405 $schemes = array('http', 'https');
406 foreach ($schemes as $scheme) {
407 $url = "$scheme://$target";
408 $this->log(LOG_INFO, "Checking profile address '$url'");
410 $oprofile = Ostatus_profile::ensureProfileURL($url);
411 if ($oprofile && !$oprofile->isGroup()) {
412 $profile = $oprofile->localProfile();
413 $matches[$pos] = array('mentioned' => array($profile),
416 'url' => $profile->profileurl);
419 } catch (Exception $e) {
420 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
426 foreach ($mentions as $i => $other) {
427 // If we share a common prefix with a local user, override it!
428 $pos = $other['position'];
429 if (isset($matches[$pos])) {
430 $mentions[$i] = $matches[$pos];
431 unset($matches[$pos]);
434 foreach ($matches as $mention) {
435 $mentions[] = $mention;
442 * Allow remote profile references to be used in commands:
443 * sub update@status.net
444 * whois evan@identi.ca
445 * reply http://identi.ca/evan hey what's up
447 * @param Command $command
449 * @param Profile &$profile
450 * @return hook return code
452 function onStartCommandGetProfile($command, $arg, &$profile)
454 $oprofile = $this->pullRemoteProfile($arg);
455 if ($oprofile && !$oprofile->isGroup()) {
456 $profile = $oprofile->localProfile();
464 * Allow remote group references to be used in commands:
465 * join group+statusnet@identi.ca
466 * join http://identi.ca/group/statusnet
467 * drop identi.ca/group/statusnet
469 * @param Command $command
471 * @param User_group &$group
472 * @return hook return code
474 function onStartCommandGetGroup($command, $arg, &$group)
476 $oprofile = $this->pullRemoteProfile($arg);
477 if ($oprofile && $oprofile->isGroup()) {
478 $group = $oprofile->localGroup();
485 protected function pullRemoteProfile($arg)
488 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
491 return Ostatus_profile::ensureWebfinger($arg);
492 } catch (Exception $e) {
493 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
494 $arg . ': ' . $e->getMessage());
498 // Look for profile URLs, with or without scheme:
500 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
503 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
504 $schemes = array('http', 'https');
505 foreach ($schemes as $scheme) {
506 $urls[] = "$scheme://$arg";
510 foreach ($urls as $url) {
512 return Ostatus_profile::ensureProfileURL($url);
513 } catch (Exception $e) {
514 common_log(LOG_ERR, 'Profile lookup failed for ' .
515 $arg . ': ' . $e->getMessage());
522 * Make sure necessary tables are filled out.
524 function onCheckSchema() {
525 $schema = Schema::get();
526 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
527 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
528 $schema->ensureTable('feedsub', FeedSub::schemaDef());
529 $schema->ensureTable('hubsub', HubSub::schemaDef());
530 $schema->ensureTable('magicsig', Magicsig::schemaDef());
534 function onEndShowStatusNetStyles($action) {
535 $action->cssLink($this->path('theme/base/css/ostatus.css'));
539 function onEndShowStatusNetScripts($action) {
540 $action->script($this->path('js/ostatus.js'));
545 * Override the "from ostatus" bit in notice lists to link to the
546 * original post and show the domain it came from.
548 * @param Notice in $notice
549 * @param string out &$name
550 * @param string out &$url
551 * @param string out &$title
552 * @return mixed hook return code
554 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
556 if ($notice->source == 'ostatus') {
558 $bits = parse_url($notice->url);
559 $domain = $bits['host'];
560 if (substr($domain, 0, 4) == 'www.') {
561 $name = substr($domain, 4);
567 // TRANSLATE: %s is a domain.
568 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
576 * Send incoming PuSH feeds for OStatus endpoints in for processing.
578 * @param FeedSub $feedsub
579 * @param DOMDocument $feed
580 * @return mixed hook return code
582 function onStartFeedSubReceive($feedsub, $feed)
584 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
586 $oprofile->processFeed($feed, 'push');
588 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
593 * Tell the FeedSub infrastructure whether we have any active OStatus
594 * usage for the feed; if not it'll be able to garbage-collect the
597 * @param FeedSub $feedsub
598 * @param integer $count in/out
599 * @return mixed hook return code
601 function onFeedSubSubscriberCount($feedsub, &$count)
603 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
605 $count += $oprofile->subscriberCount();
611 * When about to subscribe to a remote user, start a server-to-server
612 * PuSH subscription if needed. If we can't establish that, abort.
614 * @fixme If something else aborts later, we could end up with a stray
615 * PuSH subscription. This is relatively harmless, though.
617 * @param Profile $subscriber
618 * @param Profile $other
620 * @return hook return code
624 function onStartSubscribe($subscriber, $other)
626 $user = User::staticGet('id', $subscriber->id);
632 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
634 if (empty($oprofile)) {
638 if (!$oprofile->subscribe()) {
640 throw new Exception(_m('Could not set up remote subscription.'));
645 * Having established a remote subscription, send a notification to the
646 * remote OStatus profile's endpoint.
648 * @param Profile $subscriber
649 * @param Profile $other
651 * @return hook return code
655 function onEndSubscribe($subscriber, $other)
657 $user = User::staticGet('id', $subscriber->id);
663 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
665 if (empty($oprofile)) {
669 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
670 'subscribed' => $other->id));
672 $act = $sub->asActivity();
674 $oprofile->notifyActivity($act, $subscriber);
680 * Notify remote server and garbage collect unused feeds on unsubscribe.
681 * @fixme send these operations to background queues
684 * @param Profile $other
685 * @return hook return value
687 function onEndUnsubscribe($profile, $other)
689 $user = User::staticGet('id', $profile->id);
695 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
697 if (empty($oprofile)) {
701 // Drop the PuSH subscription if there are no other subscribers.
702 $oprofile->garbageCollect();
704 $act = new Activity();
706 $act->verb = ActivityVerb::UNFOLLOW;
708 $act->id = TagURI::mint('unfollow:%d:%d:%s',
711 common_date_iso8601(time()));
714 $act->title = _m('Unfollow');
715 // TRANS: Success message for unsubscribe from user attempt through OStatus.
716 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
717 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
718 $profile->getBestName(),
719 $other->getBestName());
721 $act->actor = ActivityObject::fromProfile($profile);
722 $act->object = ActivityObject::fromProfile($other);
724 $oprofile->notifyActivity($act, $profile);
730 * When one of our local users tries to join a remote group,
731 * notify the remote server. If the notification is rejected,
734 * @param User_group $group
737 * @return mixed hook return value
740 function onStartJoinGroup($group, $user)
742 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
744 if (!$oprofile->subscribe()) {
745 throw new Exception(_m('Could not set up remote group membership.'));
748 // NOTE: we don't use Group_member::asActivity() since that record
749 // has not yet been created.
751 $member = Profile::staticGet($user->id);
753 $act = new Activity();
754 $act->id = TagURI::mint('join:%d:%d:%s',
757 common_date_iso8601(time()));
759 $act->actor = ActivityObject::fromProfile($member);
760 $act->verb = ActivityVerb::JOIN;
761 $act->object = $oprofile->asActivityObject();
764 $act->title = _m("Join");
765 // TRANS: Success message for subscribe to group attempt through OStatus.
766 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
767 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
768 $member->getBestName(),
769 $oprofile->getBestName());
771 if ($oprofile->notifyActivity($act, $member)) {
774 $oprofile->garbageCollect();
776 throw new Exception(_m("Failed joining remote group."));
782 * When one of our local users leaves a remote group, notify the remote
785 * @fixme Might be good to schedule a resend of the leave notification
786 * if it failed due to a transitory error. We've canceled the local
787 * membership already anyway, but if the remote server comes back up
788 * it'll be left with a stray membership record.
790 * @param User_group $group
791 * @param Profile $user
793 * @return mixed hook return value
796 function onEndLeaveGroup($group, $user)
798 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
800 // Drop the PuSH subscription if there are no other subscribers.
801 $oprofile->garbageCollect();
803 $member = Profile::staticGet($user->id);
805 $act = new Activity();
806 $act->id = TagURI::mint('leave:%d:%d:%s',
809 common_date_iso8601(time()));
811 $act->actor = ActivityObject::fromProfile($member);
812 $act->verb = ActivityVerb::LEAVE;
813 $act->object = $oprofile->asActivityObject();
816 $act->title = _m("Leave");
817 // TRANS: Success message for unsubscribe from group attempt through OStatus.
818 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
819 $act->content = sprintf(_m('%1$s has left group %2$s.'),
820 $member->getBestName(),
821 $oprofile->getBestName());
823 $oprofile->notifyActivity($act, $member);
828 * When one of our local users tries to subscribe to a remote peopletag,
829 * notify the remote server. If the notification is rejected,
830 * deny the subscription.
832 * @param Profile_list $peopletag
835 * @return mixed hook return value
838 function onStartSubscribePeopletag($peopletag, $user)
840 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
842 if (!$oprofile->subscribe()) {
843 throw new Exception(_m('Could not set up remote peopletag subscription.'));
846 $sub = $user->getProfile();
847 $tagger = Profile::staticGet($peopletag->tagger);
849 $act = new Activity();
850 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
853 common_date_iso8601(time()));
855 $act->actor = ActivityObject::fromProfile($sub);
856 $act->verb = ActivityVerb::FOLLOW;
857 $act->object = $oprofile->asActivityObject();
860 $act->title = _m("Follow list");
861 $act->content = sprintf(_m("%s is now following people tagged %s by %s."),
863 $oprofile->getBestName(),
864 $tagger->getBestName());
866 if ($oprofile->notifyActivity($act, $sub)) {
869 $oprofile->garbageCollect();
870 throw new Exception(_m("Failed subscribing to remote peopletag."));
876 * When one of our local users unsubscribes to a remote peopletag, notify the remote
879 * @param Profile_list $peopletag
882 * @return mixed hook return value
885 function onEndUnsubscribePeopletag($peopletag, $user)
887 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
889 // Drop the PuSH subscription if there are no other subscribers.
890 $oprofile->garbageCollect();
892 $sub = Profile::staticGet($user->id);
893 $tagger = Profile::staticGet($peopletag->tagger);
895 $act = new Activity();
896 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
899 common_date_iso8601(time()));
901 $act->actor = ActivityObject::fromProfile($member);
902 $act->verb = ActivityVerb::UNFOLLOW;
903 $act->object = $oprofile->asActivityObject();
906 $act->title = _m("Unfollow peopletag");
907 $act->content = sprintf(_m("%s stopped following the list %s by %s."),
909 $oprofile->getBestName(),
910 $tagger->getBestName());
912 $oprofile->notifyActivity($act, $user);
917 * Notify remote users when their notices get favorited.
919 * @param Profile or User $profile of local user doing the faving
920 * @param Notice $notice being favored
921 * @return hook return value
923 function onEndFavorNotice(Profile $profile, Notice $notice)
925 $user = User::staticGet('id', $profile->id);
931 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
933 if (empty($oprofile)) {
937 $fav = Fave::pkeyGet(array('user_id' => $user->id,
938 'notice_id' => $notice->id));
945 $act = $fav->asActivity();
947 $oprofile->notifyActivity($act, $profile);
952 function onEndTagProfile($ptag)
954 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
956 if (empty($oprofile)) {
960 $plist = $ptag->getMeta();
961 if ($plist->private) {
965 $act = new Activity();
967 $tagger = $plist->getTagger();
968 $tagged = Profile::staticGet('id', $ptag->tagged);
970 $act->verb = ActivityVerb::TAG;
971 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
972 $plist->tagger, $plist->id,
973 common_date_iso8601(time()));
975 $act->title = _("Tag");
976 $act->content = sprintf(_("%s tagged %s in the list %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->notifyActivity($act, $tagger);
987 // initiate a PuSH subscription for the person being tagged
988 if (!$oprofile->subscribe()) {
989 throw new Exception(sprintf(_('Could not complete subscription to remote '.
990 'profile\'s feed. Tag %s could not be saved.'), $ptag->tag));
996 function onEndUntagProfile($ptag)
998 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
1000 if (empty($oprofile)) {
1004 $plist = $ptag->getMeta();
1005 if ($plist->private) {
1009 $act = new Activity();
1011 $tagger = $plist->getTagger();
1012 $tagged = Profile::staticGet('id', $ptag->tagged);
1014 $act->verb = ActivityVerb::UNTAG;
1015 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1016 $plist->tagger, $plist->id,
1017 common_date_iso8601(time()));
1018 $act->time = time();
1019 $act->title = _("Untag");
1020 $act->content = sprintf(_("%s untagged %s from the list %s"),
1021 $tagger->getBestName(),
1022 $tagged->getBestName(),
1023 $plist->getBestName());
1025 $act->actor = ActivityObject::fromProfile($tagger);
1026 $act->objects = array(ActivityObject::fromProfile($tagged));
1027 $act->target = ActivityObject::fromPeopletag($plist);
1029 $oprofile->notifyActivity($act, $tagger);
1031 // unsubscribe to PuSH feed if no more required
1032 $oprofile->garbageCollect();
1038 * Notify remote users when their notices get de-favorited.
1040 * @param Profile $profile Profile person doing the de-faving
1041 * @param Notice $notice Notice being favored
1043 * @return hook return value
1046 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1048 $user = User::staticGet('id', $profile->id);
1054 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
1056 if (empty($oprofile)) {
1060 $act = new Activity();
1062 $act->verb = ActivityVerb::UNFAVORITE;
1063 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1066 common_date_iso8601(time()));
1067 $act->time = time();
1068 $act->title = _m('Disfavor');
1069 // TRANS: Success message for remove a favorite notice through OStatus.
1070 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1071 $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
1072 $profile->getBestName(),
1075 $act->actor = ActivityObject::fromProfile($profile);
1076 $act->object = ActivityObject::fromNotice($notice);
1078 $oprofile->notifyActivity($act, $profile);
1083 function onStartGetProfileUri($profile, &$uri)
1085 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1086 if (!empty($oprofile)) {
1087 $uri = $oprofile->uri;
1093 function onStartUserGroupHomeUrl($group, &$url)
1095 return $this->onStartUserGroupPermalink($group, $url);
1098 function onStartUserGroupPermalink($group, &$url)
1100 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
1102 // @fixme this should probably be in the user_group table
1103 // @fixme this uri not guaranteed to be a profile page
1104 $url = $oprofile->uri;
1109 function onStartShowSubscriptionsContent($action)
1111 $this->showEntityRemoteSubscribe($action);
1116 function onStartShowUserGroupsContent($action)
1118 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1123 function onEndShowSubscriptionsMiniList($action)
1125 $this->showEntityRemoteSubscribe($action);
1130 function onEndShowGroupsMiniList($action)
1132 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1137 function showEntityRemoteSubscribe($action, $target='ostatussub')
1139 $user = common_current_user();
1140 if ($user && ($user->id == $action->profile->id)) {
1141 $action->elementStart('div', 'entity_actions');
1142 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1143 'class' => 'entity_subscribe'));
1144 $action->element('a', array('href' => common_local_url($target),
1145 'class' => 'entity_remote_subscribe'),
1146 // TRANS: Link text for link to remote subscribe.
1148 $action->elementEnd('p');
1149 $action->elementEnd('div');
1154 * Ping remote profiles with updates to this profile.
1155 * Salmon pings are queued for background processing.
1157 function onEndBroadcastProfile(Profile $profile)
1159 $user = User::staticGet('id', $profile->id);
1161 // Find foreign accounts I'm subscribed to that support Salmon pings.
1163 // @fixme we could run updates through the PuSH feed too,
1164 // in which case we can skip Salmon pings to folks who
1165 // are also subscribed to me.
1166 $sql = "SELECT * FROM ostatus_profile " .
1167 "WHERE profile_id IN " .
1168 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1170 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1171 $oprofile = new Ostatus_profile();
1172 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1174 if ($oprofile->N == 0) {
1175 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1179 $act = new Activity();
1181 $act->verb = ActivityVerb::UPDATE_PROFILE;
1182 $act->id = TagURI::mint('update-profile:%d:%s',
1184 common_date_iso8601(time()));
1185 $act->time = time();
1186 // TRANS: Title for activity.
1187 $act->title = _m("Profile update");
1188 // TRANS: Ping text for remote profile update through OStatus.
1189 // TRANS: %s is user that updated their profile.
1190 $act->content = sprintf(_m("%s has updated their profile page."),
1191 $profile->getBestName());
1193 $act->actor = ActivityObject::fromProfile($profile);
1194 $act->object = $act->actor;
1196 while ($oprofile->fetch()) {
1197 $oprofile->notifyDeferred($act, $profile);
1203 function onStartProfileListItemActionElements($item, $profile=null)
1205 if (!common_logged_in()) {
1207 $profileUser = User::staticGet('id', $item->profile->id);
1209 if (!empty($profileUser)) {
1211 if ($item instanceof Action) {
1213 $profile = $item->profile;
1215 $output = $item->out;
1218 // Add an OStatus subscribe
1219 $output->elementStart('li', 'entity_subscribe');
1220 $url = common_local_url('ostatusinit',
1221 array('nickname' => $profileUser->nickname));
1222 $output->element('a', array('href' => $url,
1223 'class' => 'entity_remote_subscribe'),
1224 // TRANS: Link text for a user to subscribe to an OStatus user.
1226 $output->elementEnd('li');
1228 $output->elementStart('li', 'entity_tag');
1229 $url = common_local_url('ostatustag',
1230 array('nickname' => $profileUser->nickname));
1231 $output->element('a', array('href' => $url,
1232 'class' => 'entity_remote_tag'),
1234 $output->elementEnd('li');
1241 function onPluginVersion(&$versions)
1243 $versions[] = array('name' => 'OStatus',
1244 'version' => STATUSNET_VERSION,
1245 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1246 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1247 // TRANS: Plugin description.
1248 'rawdescription' => _m('Follow people across social networks that implement '.
1249 '<a href="http://ostatus.org/">OStatus</a>.'));
1255 * Utility function to check if the given URI is a canonical group profile
1256 * page, and if so return the ID number.
1258 * @param string $url
1259 * @return mixed int or false
1261 public static function localGroupFromUrl($url)
1263 $group = User_group::staticGet('uri', $url);
1265 $local = Local_group::staticGet('group_id', $group->id);
1270 // To find local groups which haven't had their uri fields filled out...
1271 // If the domain has changed since a subscriber got the URI, it'll
1273 $template = common_local_url('groupbyid', array('id' => '31337'));
1274 $template = preg_quote($template, '/');
1275 $template = str_replace('31337', '(\d+)', $template);
1276 if (preg_match("/$template/", $url, $matches)) {
1277 return intval($matches[1]);
1283 public function onStartProfileGetAtomFeed($profile, &$feed)
1285 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1287 if (empty($oprofile)) {
1291 $feed = $oprofile->feeduri;
1295 function onStartGetProfileFromURI($uri, &$profile)
1297 // Don't want to do Web-based discovery on our own server,
1298 // so we check locally first.
1300 $user = User::staticGet('uri', $uri);
1302 if (!empty($user)) {
1303 $profile = $user->getProfile();
1307 // Now, check remotely
1309 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1311 if (!empty($oprofile)) {
1312 $profile = $oprofile->localProfile();
1316 // Still not a hit, so give up.
1321 function onEndXrdActionLinks(&$xrd, $user)
1323 $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1324 'href' => common_local_url('ApiTimelineUser',
1325 array('id' => $user->id,
1326 'format' => 'atom')),
1327 'type' => 'application/atom+xml');
1330 $salmon_url = common_local_url('usersalmon',
1331 array('id' => $user->id));
1333 $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1334 'href' => $salmon_url);
1335 // XXX : Deprecated - to be removed.
1336 $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1337 'href' => $salmon_url);
1339 $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1340 'href' => $salmon_url);
1342 // Get this user's keypair
1343 $magickey = Magicsig::staticGet('user_id', $user->id);
1345 // No keypair yet, let's generate one.
1346 $magickey = new Magicsig();
1347 $magickey->generate($user->id);
1350 $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1351 'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1353 // TODO - finalize where the redirect should go on the publisher
1354 $url = common_local_url('ostatussub') . '?profile={uri}';
1355 $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1356 'template' => $url );