3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @package OStatusPlugin
22 * @maintainer Brion Vibber <brion@status.net>
25 if (!defined('STATUSNET')) {
29 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/');
31 class FeedSubException extends Exception
33 function __construct($msg=null)
35 $type = get_class($this);
37 parent::__construct("$type: $msg");
39 parent::__construct($type);
44 class OStatusPlugin extends Plugin
47 * Hook for RouterInitialized event.
49 * @param Net_URL_Mapper $m path-to-action mapper
50 * @return boolean hook return
52 function onRouterInitialized($m)
55 $m->connect('main/ownerxrd',
56 array('action' => 'ownerxrd'));
57 $m->connect('main/ostatus',
58 array('action' => 'ostatusinit'));
59 $m->connect('main/ostatustag',
60 array('action' => 'ostatustag'));
61 $m->connect('main/ostatustag?nickname=:nickname',
62 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
63 $m->connect('main/ostatus?nickname=:nickname',
64 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
65 $m->connect('main/ostatus?group=:group',
66 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
67 $m->connect('main/ostatus?peopletag=:peopletag&tagger=:tagger',
68 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
69 'peopletag' => '[A-Za-z0-9_-]+'));
71 // Remote subscription actions
72 $m->connect('main/ostatussub',
73 array('action' => 'ostatussub'));
74 $m->connect('main/ostatusgroup',
75 array('action' => 'ostatusgroup'));
76 $m->connect('main/ostatuspeopletag',
77 array('action' => 'ostatuspeopletag'));
80 $m->connect('main/push/hub', array('action' => 'pushhub'));
82 $m->connect('main/push/callback/:feed',
83 array('action' => 'pushcallback'),
84 array('feed' => '[0-9]+'));
87 $m->connect('main/salmon/user/:id',
88 array('action' => 'usersalmon'),
89 array('id' => '[0-9]+'));
90 $m->connect('main/salmon/group/:id',
91 array('action' => 'groupsalmon'),
92 array('id' => '[0-9]+'));
93 $m->connect('main/salmon/peopletag/:id',
94 array('action' => 'peopletagsalmon'),
95 array('id' => '[0-9]+'));
100 * Set up queue handlers for outgoing hub pushes
101 * @param QueueManager $qm
102 * @return boolean hook return
104 function onEndInitializeQueueManager(QueueManager $qm)
106 // Prepare outgoing distributions after notice save.
107 $qm->connect('ostatus', 'OStatusQueueHandler');
109 // Outgoing from our internal PuSH hub
110 $qm->connect('hubconf', 'HubConfQueueHandler');
111 $qm->connect('hubprep', 'HubPrepQueueHandler');
113 $qm->connect('hubout', 'HubOutQueueHandler');
115 // Outgoing Salmon replies (when we don't need a return value)
116 $qm->connect('salmon', 'SalmonQueueHandler');
118 // Incoming from a foreign PuSH hub
119 $qm->connect('pushin', 'PushInQueueHandler');
124 * Put saved notices into the queue for pubsub distribution.
126 function onStartEnqueueNotice($notice, &$transports)
128 // FIXME: we don't do privacy-controlled OStatus updates yet.
129 // once that happens, finer grain of control here.
130 if ($notice->isLocal() && $notice->inScope(null)) {
131 // put our transport first, in case there's any conflict (like OMB)
132 array_unshift($transports, 'ostatus');
138 * Add a link header for LRDD Discovery
140 function onStartShowHTML($action)
142 if ($action instanceof ShowstreamAction) {
143 $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
144 $url = common_local_url('userxrd');
145 $url.= '?uri='. $acct;
147 header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
152 * Set up a PuSH hub link to our internal link for canonical timeline
153 * Atom feeds for users and groups.
155 function onStartApiAtom($feed)
159 if ($feed instanceof AtomUserNoticeFeed) {
160 $salmonAction = 'usersalmon';
161 $user = $feed->getUser();
163 $profile = $user->getProfile();
164 } else if ($feed instanceof AtomGroupNoticeFeed) {
165 $salmonAction = 'groupsalmon';
166 $group = $feed->getGroup();
168 } else if ($feed instanceof AtomListNoticeFeed) {
169 $salmonAction = 'peopletagsalmon';
170 $peopletag = $feed->getList();
171 $id = $peopletag->id;
177 $hub = common_config('ostatus', 'hub');
179 // Updates will be handled through our internal PuSH hub.
180 $hub = common_local_url('pushhub');
182 $feed->addLink($hub, array('rel' => 'hub'));
184 // Also, we'll add in the salmon link
185 $salmon = common_local_url($salmonAction, array('id' => $id));
186 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
188 // XXX: these are deprecated
189 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
190 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
197 * Automatically load the actions and libraries used by the plugin
199 * @param Class $cls the class
201 * @return boolean hook return
204 function onAutoload($cls)
206 $base = dirname(__FILE__);
207 $lower = strtolower($cls);
208 $map = array('activityverb' => 'activity',
209 'activityobject' => 'activity',
210 'activityutils' => 'activity');
211 if (isset($map[$lower])) {
212 $lower = $map[$lower];
214 $files = array("$base/classes/$cls.php",
215 "$base/lib/$lower.php");
216 if (substr($lower, -6) == 'action') {
217 $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
219 foreach ($files as $file) {
220 if (file_exists($file)) {
229 * Add in an OStatus subscribe button
231 function onStartProfileRemoteSubscribe($output, $profile)
233 $this->onStartProfileListItemActionElements($output, $profile);
237 function onStartGroupSubscribe($widget, $group)
239 $cur = common_current_user();
242 $output->elementStart('li', 'entity_subscribe');
243 $profile = $peopletag->getTagger();
244 $url = common_local_url('ostatusinit',
245 array('group' => $group->nickname));
246 $widget->out->element('a', array('href' => $url,
247 'class' => 'entity_remote_subscribe'),
250 $output->elementEnd('li');
257 function onStartSubscribePeopletagForm($output, $peopletag)
259 $cur = common_current_user();
262 $output->elementStart('li', 'entity_subscribe');
263 $profile = $peopletag->getTagger();
264 $url = common_local_url('ostatusinit',
265 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
266 $output->element('a', array('href' => $url,
267 'class' => 'entity_remote_subscribe'),
270 $output->elementEnd('li');
277 function onStartShowTagProfileForm($action, $profile)
279 $action->elementStart('form', array('method' => 'post',
280 'id' => 'form_tag_user',
281 'class' => 'form_settings',
282 'name' => 'tagprofile',
283 'action' => common_local_url('tagprofile', array('id' => @$profile->id))));
285 $action->elementStart('fieldset');
286 $action->element('legend', null, _('Tag remote profile'));
287 $action->hidden('token', common_session_token());
289 $user = common_current_user();
291 $action->elementStart('ul', 'form_data');
292 $action->elementStart('li');
294 $action->input('uri', _('Remote profile'), $action->trimmed('uri'),
295 _('OStatus user\'s address, like nickname@example.com or http://example.net/nickname'));
296 $action->elementEnd('li');
297 $action->elementEnd('ul');
298 $action->submit('fetch', _('Fetch'));
299 $action->elementEnd('fieldset');
300 $action->elementEnd('form');
303 function onStartTagProfileAction($action, $profile)
306 $uri = $action->trimmed('uri');
308 if (!$profile && $uri) {
310 if (Validate::email($uri)) {
311 $oprofile = Ostatus_profile::ensureWebfinger($uri);
312 } else if (Validate::uri($uri)) {
313 $oprofile = Ostatus_profile::ensureProfileURL($uri);
315 throw new Exception('Invalid URI');
318 // redirect to the new profile.
319 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
322 } catch (Exception $e) {
323 $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");
326 $action->showForm($err);
333 * If the field being looked for is URI look for the profile
335 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
336 if ($action->field == 'uri') {
338 $profile->joinAdd($user);
339 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
342 if ($profile->N == 0) {
344 if (Validate::email($q)) {
345 $oprofile = Ostatus_profile::ensureWebfinger($q);
346 } else if (Validate::uri($q)) {
347 $oprofile = Ostatus_profile::ensureProfileURL($q);
349 throw new Exception('Invalid URI');
351 return $this->filter(array($oprofile->localProfile()));
353 } catch (Exception $e) {
354 $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");
364 * Find any explicit remote mentions. Accepted forms:
365 * Webfinger: @user@example.com
366 * Profile link: @example.com/mublog/user
367 * @param Profile $sender (os user?)
368 * @param string $text input markup text
369 * @param array &$mention in/out param: set of found mentions
370 * @return boolean hook return value
373 function onEndFindMentions($sender, $text, &$mentions)
377 // Webfinger matches: @user@example.com
378 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
381 PREG_OFFSET_CAPTURE)) {
382 foreach ($wmatches[1] as $wmatch) {
383 list($target, $pos) = $wmatch;
384 $this->log(LOG_INFO, "Checking webfinger '$target'");
386 $oprofile = Ostatus_profile::ensureWebfinger($target);
387 if ($oprofile && !$oprofile->isGroup()) {
388 $profile = $oprofile->localProfile();
389 $matches[$pos] = array('mentioned' => array($profile),
392 'url' => $profile->profileurl);
394 } catch (Exception $e) {
395 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
400 // Profile matches: @example.com/mublog/user
401 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
404 PREG_OFFSET_CAPTURE)) {
405 foreach ($wmatches[1] as $wmatch) {
406 list($target, $pos) = $wmatch;
407 $schemes = array('http', 'https');
408 foreach ($schemes as $scheme) {
409 $url = "$scheme://$target";
410 $this->log(LOG_INFO, "Checking profile address '$url'");
412 $oprofile = Ostatus_profile::ensureProfileURL($url);
413 if ($oprofile && !$oprofile->isGroup()) {
414 $profile = $oprofile->localProfile();
415 $matches[$pos] = array('mentioned' => array($profile),
418 'url' => $profile->profileurl);
421 } catch (Exception $e) {
422 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
428 foreach ($mentions as $i => $other) {
429 // If we share a common prefix with a local user, override it!
430 $pos = $other['position'];
431 if (isset($matches[$pos])) {
432 $mentions[$i] = $matches[$pos];
433 unset($matches[$pos]);
436 foreach ($matches as $mention) {
437 $mentions[] = $mention;
444 * Allow remote profile references to be used in commands:
445 * sub update@status.net
446 * whois evan@identi.ca
447 * reply http://identi.ca/evan hey what's up
449 * @param Command $command
451 * @param Profile &$profile
452 * @return hook return code
454 function onStartCommandGetProfile($command, $arg, &$profile)
456 $oprofile = $this->pullRemoteProfile($arg);
457 if ($oprofile && !$oprofile->isGroup()) {
458 $profile = $oprofile->localProfile();
466 * Allow remote group references to be used in commands:
467 * join group+statusnet@identi.ca
468 * join http://identi.ca/group/statusnet
469 * drop identi.ca/group/statusnet
471 * @param Command $command
473 * @param User_group &$group
474 * @return hook return code
476 function onStartCommandGetGroup($command, $arg, &$group)
478 $oprofile = $this->pullRemoteProfile($arg);
479 if ($oprofile && $oprofile->isGroup()) {
480 $group = $oprofile->localGroup();
487 protected function pullRemoteProfile($arg)
490 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
493 return Ostatus_profile::ensureWebfinger($arg);
494 } catch (Exception $e) {
495 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
496 $arg . ': ' . $e->getMessage());
500 // Look for profile URLs, with or without scheme:
502 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
505 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
506 $schemes = array('http', 'https');
507 foreach ($schemes as $scheme) {
508 $urls[] = "$scheme://$arg";
512 foreach ($urls as $url) {
514 return Ostatus_profile::ensureProfileURL($url);
515 } catch (Exception $e) {
516 common_log(LOG_ERR, 'Profile lookup failed for ' .
517 $arg . ': ' . $e->getMessage());
524 * Make sure necessary tables are filled out.
526 function onCheckSchema() {
527 $schema = Schema::get();
528 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
529 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
530 $schema->ensureTable('feedsub', FeedSub::schemaDef());
531 $schema->ensureTable('hubsub', HubSub::schemaDef());
532 $schema->ensureTable('magicsig', Magicsig::schemaDef());
536 function onEndShowStatusNetStyles($action) {
537 $action->cssLink($this->path('theme/base/css/ostatus.css'));
541 function onEndShowStatusNetScripts($action) {
542 $action->script($this->path('js/ostatus.js'));
547 * Override the "from ostatus" bit in notice lists to link to the
548 * original post and show the domain it came from.
550 * @param Notice in $notice
551 * @param string out &$name
552 * @param string out &$url
553 * @param string out &$title
554 * @return mixed hook return code
556 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
558 if ($notice->source == 'ostatus') {
560 $bits = parse_url($notice->url);
561 $domain = $bits['host'];
562 if (substr($domain, 0, 4) == 'www.') {
563 $name = substr($domain, 4);
569 // TRANSLATE: %s is a domain.
570 $title = sprintf(_m("Sent from %s via OStatus"), $domain);
578 * Send incoming PuSH feeds for OStatus endpoints in for processing.
580 * @param FeedSub $feedsub
581 * @param DOMDocument $feed
582 * @return mixed hook return code
584 function onStartFeedSubReceive($feedsub, $feed)
586 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
588 $oprofile->processFeed($feed, 'push');
590 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
595 * Tell the FeedSub infrastructure whether we have any active OStatus
596 * usage for the feed; if not it'll be able to garbage-collect the
599 * @param FeedSub $feedsub
600 * @param integer $count in/out
601 * @return mixed hook return code
603 function onFeedSubSubscriberCount($feedsub, &$count)
605 $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
607 $count += $oprofile->subscriberCount();
613 * When about to subscribe to a remote user, start a server-to-server
614 * PuSH subscription if needed. If we can't establish that, abort.
616 * @fixme If something else aborts later, we could end up with a stray
617 * PuSH subscription. This is relatively harmless, though.
619 * @param Profile $subscriber
620 * @param Profile $other
622 * @return hook return code
626 function onStartSubscribe($subscriber, $other)
628 $user = User::staticGet('id', $subscriber->id);
634 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
636 if (empty($oprofile)) {
640 if (!$oprofile->subscribe()) {
642 throw new Exception(_m('Could not set up remote subscription.'));
647 * Having established a remote subscription, send a notification to the
648 * remote OStatus profile's endpoint.
650 * @param Profile $subscriber
651 * @param Profile $other
653 * @return hook return code
657 function onEndSubscribe($subscriber, $other)
659 $user = User::staticGet('id', $subscriber->id);
665 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
667 if (empty($oprofile)) {
671 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
672 'subscribed' => $other->id));
674 $act = $sub->asActivity();
676 $oprofile->notifyActivity($act, $subscriber);
682 * Notify remote server and garbage collect unused feeds on unsubscribe.
683 * @fixme send these operations to background queues
686 * @param Profile $other
687 * @return hook return value
689 function onEndUnsubscribe($profile, $other)
691 $user = User::staticGet('id', $profile->id);
697 $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);
699 if (empty($oprofile)) {
703 // Drop the PuSH subscription if there are no other subscribers.
704 $oprofile->garbageCollect();
706 $act = new Activity();
708 $act->verb = ActivityVerb::UNFOLLOW;
710 $act->id = TagURI::mint('unfollow:%d:%d:%s',
713 common_date_iso8601(time()));
716 $act->title = _m('Unfollow');
717 // TRANS: Success message for unsubscribe from user attempt through OStatus.
718 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
719 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
720 $profile->getBestName(),
721 $other->getBestName());
723 $act->actor = ActivityObject::fromProfile($profile);
724 $act->object = ActivityObject::fromProfile($other);
726 $oprofile->notifyActivity($act, $profile);
732 * When one of our local users tries to join a remote group,
733 * notify the remote server. If the notification is rejected,
736 * @param User_group $group
739 * @return mixed hook return value
742 function onStartJoinGroup($group, $user)
744 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
746 if (!$oprofile->subscribe()) {
747 throw new Exception(_m('Could not set up remote group membership.'));
750 // NOTE: we don't use Group_member::asActivity() since that record
751 // has not yet been created.
753 $member = Profile::staticGet($user->id);
755 $act = new Activity();
756 $act->id = TagURI::mint('join:%d:%d:%s',
759 common_date_iso8601(time()));
761 $act->actor = ActivityObject::fromProfile($member);
762 $act->verb = ActivityVerb::JOIN;
763 $act->object = $oprofile->asActivityObject();
766 $act->title = _m("Join");
767 // TRANS: Success message for subscribe to group attempt through OStatus.
768 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
769 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
770 $member->getBestName(),
771 $oprofile->getBestName());
773 if ($oprofile->notifyActivity($act, $member)) {
776 $oprofile->garbageCollect();
778 throw new Exception(_m("Failed joining remote group."));
784 * When one of our local users leaves a remote group, notify the remote
787 * @fixme Might be good to schedule a resend of the leave notification
788 * if it failed due to a transitory error. We've canceled the local
789 * membership already anyway, but if the remote server comes back up
790 * it'll be left with a stray membership record.
792 * @param User_group $group
793 * @param Profile $user
795 * @return mixed hook return value
798 function onEndLeaveGroup($group, $user)
800 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
802 // Drop the PuSH subscription if there are no other subscribers.
803 $oprofile->garbageCollect();
805 $member = Profile::staticGet($user->id);
807 $act = new Activity();
808 $act->id = TagURI::mint('leave:%d:%d:%s',
811 common_date_iso8601(time()));
813 $act->actor = ActivityObject::fromProfile($member);
814 $act->verb = ActivityVerb::LEAVE;
815 $act->object = $oprofile->asActivityObject();
818 $act->title = _m("Leave");
819 // TRANS: Success message for unsubscribe from group attempt through OStatus.
820 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
821 $act->content = sprintf(_m('%1$s has left group %2$s.'),
822 $member->getBestName(),
823 $oprofile->getBestName());
825 $oprofile->notifyActivity($act, $member);
830 * When one of our local users tries to subscribe to a remote peopletag,
831 * notify the remote server. If the notification is rejected,
832 * deny the subscription.
834 * @param Profile_list $peopletag
837 * @return mixed hook return value
840 function onStartSubscribePeopletag($peopletag, $user)
842 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
844 if (!$oprofile->subscribe()) {
845 throw new Exception(_m('Could not set up remote peopletag subscription.'));
848 $sub = $user->getProfile();
849 $tagger = Profile::staticGet($peopletag->tagger);
851 $act = new Activity();
852 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
855 common_date_iso8601(time()));
857 $act->actor = ActivityObject::fromProfile($sub);
858 $act->verb = ActivityVerb::FOLLOW;
859 $act->object = $oprofile->asActivityObject();
862 $act->title = _m("Follow list");
863 $act->content = sprintf(_m("%s is now following people tagged %s by %s."),
865 $oprofile->getBestName(),
866 $tagger->getBestName());
868 if ($oprofile->notifyActivity($act, $sub)) {
871 $oprofile->garbageCollect();
872 throw new Exception(_m("Failed subscribing to remote peopletag."));
878 * When one of our local users unsubscribes to a remote peopletag, notify the remote
881 * @param Profile_list $peopletag
884 * @return mixed hook return value
887 function onEndUnsubscribePeopletag($peopletag, $user)
889 $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
891 // Drop the PuSH subscription if there are no other subscribers.
892 $oprofile->garbageCollect();
894 $sub = Profile::staticGet($user->id);
895 $tagger = Profile::staticGet($peopletag->tagger);
897 $act = new Activity();
898 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
901 common_date_iso8601(time()));
903 $act->actor = ActivityObject::fromProfile($member);
904 $act->verb = ActivityVerb::UNFOLLOW;
905 $act->object = $oprofile->asActivityObject();
908 $act->title = _m("Unfollow peopletag");
909 $act->content = sprintf(_m("%s stopped following the list %s by %s."),
911 $oprofile->getBestName(),
912 $tagger->getBestName());
914 $oprofile->notifyActivity($act, $user);
919 * Notify remote users when their notices get favorited.
921 * @param Profile or User $profile of local user doing the faving
922 * @param Notice $notice being favored
923 * @return hook return value
925 function onEndFavorNotice(Profile $profile, Notice $notice)
927 $user = User::staticGet('id', $profile->id);
933 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
935 if (empty($oprofile)) {
939 $fav = Fave::pkeyGet(array('user_id' => $user->id,
940 'notice_id' => $notice->id));
947 $act = $fav->asActivity();
949 $oprofile->notifyActivity($act, $profile);
954 function onEndTagProfile($ptag)
956 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
958 if (empty($oprofile)) {
962 $plist = $ptag->getMeta();
963 if ($plist->private) {
967 $act = new Activity();
969 $tagger = $plist->getTagger();
970 $tagged = Profile::staticGet('id', $ptag->tagged);
972 $act->verb = ActivityVerb::TAG;
973 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
974 $plist->tagger, $plist->id,
975 common_date_iso8601(time()));
977 $act->title = _("Tag");
978 $act->content = sprintf(_("%s tagged %s in the list %s"),
979 $tagger->getBestName(),
980 $tagged->getBestName(),
981 $plist->getBestName());
983 $act->actor = ActivityObject::fromProfile($tagger);
984 $act->objects = array(ActivityObject::fromProfile($tagged));
985 $act->target = ActivityObject::fromPeopletag($plist);
987 $oprofile->notifyActivity($act, $tagger);
989 // initiate a PuSH subscription for the person being tagged
990 if (!$oprofile->subscribe()) {
991 throw new Exception(sprintf(_('Could not complete subscription to remote '.
992 'profile\'s feed. Tag %s could not be saved.'), $ptag->tag));
998 function onEndUntagProfile($ptag)
1000 $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);
1002 if (empty($oprofile)) {
1006 $plist = $ptag->getMeta();
1007 if ($plist->private) {
1011 $act = new Activity();
1013 $tagger = $plist->getTagger();
1014 $tagged = Profile::staticGet('id', $ptag->tagged);
1016 $act->verb = ActivityVerb::UNTAG;
1017 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1018 $plist->tagger, $plist->id,
1019 common_date_iso8601(time()));
1020 $act->time = time();
1021 $act->title = _("Untag");
1022 $act->content = sprintf(_("%s untagged %s from the list %s"),
1023 $tagger->getBestName(),
1024 $tagged->getBestName(),
1025 $plist->getBestName());
1027 $act->actor = ActivityObject::fromProfile($tagger);
1028 $act->objects = array(ActivityObject::fromProfile($tagged));
1029 $act->target = ActivityObject::fromPeopletag($plist);
1031 $oprofile->notifyActivity($act, $tagger);
1033 // unsubscribe to PuSH feed if no more required
1034 $oprofile->garbageCollect();
1040 * Notify remote users when their notices get de-favorited.
1042 * @param Profile $profile Profile person doing the de-faving
1043 * @param Notice $notice Notice being favored
1045 * @return hook return value
1048 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1050 $user = User::staticGet('id', $profile->id);
1056 $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
1058 if (empty($oprofile)) {
1062 $act = new Activity();
1064 $act->verb = ActivityVerb::UNFAVORITE;
1065 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1068 common_date_iso8601(time()));
1069 $act->time = time();
1070 $act->title = _m('Disfavor');
1071 // TRANS: Success message for remove a favorite notice through OStatus.
1072 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1073 $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
1074 $profile->getBestName(),
1077 $act->actor = ActivityObject::fromProfile($profile);
1078 $act->object = ActivityObject::fromNotice($notice);
1080 $oprofile->notifyActivity($act, $profile);
1085 function onStartGetProfileUri($profile, &$uri)
1087 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1088 if (!empty($oprofile)) {
1089 $uri = $oprofile->uri;
1095 function onStartUserGroupHomeUrl($group, &$url)
1097 return $this->onStartUserGroupPermalink($group, $url);
1100 function onStartUserGroupPermalink($group, &$url)
1102 $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
1104 // @fixme this should probably be in the user_group table
1105 // @fixme this uri not guaranteed to be a profile page
1106 $url = $oprofile->uri;
1111 function onStartShowSubscriptionsContent($action)
1113 $this->showEntityRemoteSubscribe($action);
1118 function onStartShowUserGroupsContent($action)
1120 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1125 function onEndShowSubscriptionsMiniList($action)
1127 $this->showEntityRemoteSubscribe($action);
1132 function onEndShowGroupsMiniList($action)
1134 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1139 function showEntityRemoteSubscribe($action, $target='ostatussub')
1141 $user = common_current_user();
1142 if ($user && ($user->id == $action->profile->id)) {
1143 $action->elementStart('div', 'entity_actions');
1144 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1145 'class' => 'entity_subscribe'));
1146 $action->element('a', array('href' => common_local_url($target),
1147 'class' => 'entity_remote_subscribe'),
1148 // TRANS: Link text for link to remote subscribe.
1150 $action->elementEnd('p');
1151 $action->elementEnd('div');
1156 * Ping remote profiles with updates to this profile.
1157 * Salmon pings are queued for background processing.
1159 function onEndBroadcastProfile(Profile $profile)
1161 $user = User::staticGet('id', $profile->id);
1163 // Find foreign accounts I'm subscribed to that support Salmon pings.
1165 // @fixme we could run updates through the PuSH feed too,
1166 // in which case we can skip Salmon pings to folks who
1167 // are also subscribed to me.
1168 $sql = "SELECT * FROM ostatus_profile " .
1169 "WHERE profile_id IN " .
1170 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1172 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1173 $oprofile = new Ostatus_profile();
1174 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1176 if ($oprofile->N == 0) {
1177 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1181 $act = new Activity();
1183 $act->verb = ActivityVerb::UPDATE_PROFILE;
1184 $act->id = TagURI::mint('update-profile:%d:%s',
1186 common_date_iso8601(time()));
1187 $act->time = time();
1188 // TRANS: Title for activity.
1189 $act->title = _m("Profile update");
1190 // TRANS: Ping text for remote profile update through OStatus.
1191 // TRANS: %s is user that updated their profile.
1192 $act->content = sprintf(_m("%s has updated their profile page."),
1193 $profile->getBestName());
1195 $act->actor = ActivityObject::fromProfile($profile);
1196 $act->object = $act->actor;
1198 while ($oprofile->fetch()) {
1199 $oprofile->notifyDeferred($act, $profile);
1205 function onStartProfileListItemActionElements($item, $profile=null)
1207 if (!common_logged_in()) {
1209 $profileUser = User::staticGet('id', $item->profile->id);
1211 if (!empty($profileUser)) {
1213 if ($item instanceof Action) {
1215 $profile = $item->profile;
1217 $output = $item->out;
1220 // Add an OStatus subscribe
1221 $output->elementStart('li', 'entity_subscribe');
1222 $url = common_local_url('ostatusinit',
1223 array('nickname' => $profileUser->nickname));
1224 $output->element('a', array('href' => $url,
1225 'class' => 'entity_remote_subscribe'),
1226 // TRANS: Link text for a user to subscribe to an OStatus user.
1228 $output->elementEnd('li');
1230 $output->elementStart('li', 'entity_tag');
1231 $url = common_local_url('ostatustag',
1232 array('nickname' => $profileUser->nickname));
1233 $output->element('a', array('href' => $url,
1234 'class' => 'entity_remote_tag'),
1236 $output->elementEnd('li');
1243 function onPluginVersion(&$versions)
1245 $versions[] = array('name' => 'OStatus',
1246 'version' => STATUSNET_VERSION,
1247 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1248 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1249 // TRANS: Plugin description.
1250 'rawdescription' => _m('Follow people across social networks that implement '.
1251 '<a href="http://ostatus.org/">OStatus</a>.'));
1257 * Utility function to check if the given URI is a canonical group profile
1258 * page, and if so return the ID number.
1260 * @param string $url
1261 * @return mixed int or false
1263 public static function localGroupFromUrl($url)
1265 $group = User_group::staticGet('uri', $url);
1267 $local = Local_group::staticGet('group_id', $group->id);
1272 // To find local groups which haven't had their uri fields filled out...
1273 // If the domain has changed since a subscriber got the URI, it'll
1275 $template = common_local_url('groupbyid', array('id' => '31337'));
1276 $template = preg_quote($template, '/');
1277 $template = str_replace('31337', '(\d+)', $template);
1278 if (preg_match("/$template/", $url, $matches)) {
1279 return intval($matches[1]);
1285 public function onStartProfileGetAtomFeed($profile, &$feed)
1287 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1289 if (empty($oprofile)) {
1293 $feed = $oprofile->feeduri;
1297 function onStartGetProfileFromURI($uri, &$profile)
1299 // Don't want to do Web-based discovery on our own server,
1300 // so we check locally first.
1302 $user = User::staticGet('uri', $uri);
1304 if (!empty($user)) {
1305 $profile = $user->getProfile();
1309 // Now, check remotely
1311 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1313 if (!empty($oprofile)) {
1314 $profile = $oprofile->localProfile();
1318 // Still not a hit, so give up.
1323 function onEndXrdActionLinks(&$xrd, $user)
1325 $xrd->links[] = array('rel' => Discovery::UPDATESFROM,
1326 'href' => common_local_url('ApiTimelineUser',
1327 array('id' => $user->id,
1328 'format' => 'atom')),
1329 'type' => 'application/atom+xml');
1332 $salmon_url = common_local_url('usersalmon',
1333 array('id' => $user->id));
1335 $xrd->links[] = array('rel' => Salmon::REL_SALMON,
1336 'href' => $salmon_url);
1337 // XXX : Deprecated - to be removed.
1338 $xrd->links[] = array('rel' => Salmon::NS_REPLIES,
1339 'href' => $salmon_url);
1341 $xrd->links[] = array('rel' => Salmon::NS_MENTIONS,
1342 'href' => $salmon_url);
1344 // Get this user's keypair
1345 $magickey = Magicsig::staticGet('user_id', $user->id);
1347 // No keypair yet, let's generate one.
1348 $magickey = new Magicsig();
1349 $magickey->generate($user->id);
1352 $xrd->links[] = array('rel' => Magicsig::PUBLICKEYREL,
1353 'href' => 'data:application/magic-public-key,'. $magickey->toString(false));
1355 // TODO - finalize where the redirect should go on the publisher
1356 $url = common_local_url('ostatussub') . '?profile={uri}';
1357 $xrd->links[] = array('rel' => 'http://ostatus.org/schema/1.0/subscribe',
1358 'template' => $url );