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 * OStatusPlugin implementation for GNU Social
23 * Depends on: WebFinger plugin
25 * @package OStatusPlugin
26 * @maintainer Brion Vibber <brion@status.net>
29 if (!defined('GNUSOCIAL')) { exit(1); }
31 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpseclib');
33 class FeedSubException extends Exception
35 function __construct($msg=null)
37 $type = get_class($this);
39 parent::__construct("$type: $msg");
41 parent::__construct($type);
46 class OStatusPlugin extends Plugin
49 * Hook for RouterInitialized event.
51 * @param Net_URL_Mapper $m path-to-action mapper
52 * @return boolean hook return
54 function onRouterInitialized($m)
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->inScope(null)) {
129 // put our transport first, in case there's any conflict (like OMB)
130 array_unshift($transports, 'ostatus');
131 $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
133 // FIXME: we don't do privacy-controlled OStatus updates yet.
134 // once that happens, finer grain of control here.
135 $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
141 * Set up a PuSH hub link to our internal link for canonical timeline
142 * Atom feeds for users and groups.
144 function onStartApiAtom($feed)
148 if ($feed instanceof AtomUserNoticeFeed) {
149 $salmonAction = 'usersalmon';
150 $user = $feed->getUser();
152 $profile = $user->getProfile();
153 } else if ($feed instanceof AtomGroupNoticeFeed) {
154 $salmonAction = 'groupsalmon';
155 $group = $feed->getGroup();
157 } else if ($feed instanceof AtomListNoticeFeed) {
158 $salmonAction = 'peopletagsalmon';
159 $peopletag = $feed->getList();
160 $id = $peopletag->id;
166 $hub = common_config('ostatus', 'hub');
168 // Updates will be handled through our internal PuSH hub.
169 $hub = common_local_url('pushhub');
171 $feed->addLink($hub, array('rel' => 'hub'));
173 // Also, we'll add in the salmon link
174 $salmon = common_local_url($salmonAction, array('id' => $id));
175 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
177 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
178 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
179 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
186 * Add in an OStatus subscribe button
188 function onStartProfileRemoteSubscribe($output, $profile)
190 $this->onStartProfileListItemActionElements($output, $profile);
194 function onStartGroupSubscribe($widget, $group)
196 $cur = common_current_user();
199 $widget->out->elementStart('li', 'entity_subscribe');
201 $url = common_local_url('ostatusinit',
202 array('group' => $group->nickname));
203 $widget->out->element('a', array('href' => $url,
204 'class' => 'entity_remote_subscribe'),
205 // TRANS: Link to subscribe to a remote entity.
208 $widget->out->elementEnd('li');
215 function onStartSubscribePeopletagForm($output, $peopletag)
217 $cur = common_current_user();
220 $output->elementStart('li', 'entity_subscribe');
221 $profile = $peopletag->getTagger();
222 $url = common_local_url('ostatusinit',
223 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
224 $output->element('a', array('href' => $url,
225 'class' => 'entity_remote_subscribe'),
226 // TRANS: Link to subscribe to a remote entity.
229 $output->elementEnd('li');
236 function onStartShowTagProfileForm($action, $profile)
238 $action->elementStart('form', array('method' => 'post',
239 'id' => 'form_tag_user',
240 'class' => 'form_settings',
241 'name' => 'tagprofile',
242 'action' => common_local_url('tagprofile', array('id' => @$profile->id))));
244 $action->elementStart('fieldset');
245 // TRANS: Fieldset legend.
246 $action->element('legend', null, _m('List remote profile'));
247 $action->hidden('token', common_session_token());
249 $user = common_current_user();
251 $action->elementStart('ul', 'form_data');
252 $action->elementStart('li');
254 // TRANS: Field label.
255 $action->input('uri', _m('LABEL','Remote profile'), $action->trimmed('uri'),
256 // TRANS: Field title.
257 _m('OStatus user\'s address, like nickname@example.com or http://example.net/nickname.'));
258 $action->elementEnd('li');
259 $action->elementEnd('ul');
260 // TRANS: Button text to fetch remote profile.
261 $action->submit('fetch', _m('BUTTON','Fetch'));
262 $action->elementEnd('fieldset');
263 $action->elementEnd('form');
266 function onStartTagProfileAction($action, $profile)
269 $uri = $action->trimmed('uri');
271 if (!$profile && $uri) {
273 if (Validate::email($uri)) {
274 $oprofile = Ostatus_profile::ensureWebfinger($uri);
275 } else if (Validate::uri($uri)) {
276 $oprofile = Ostatus_profile::ensureProfileURL($uri);
278 // TRANS: Exception in OStatus when invalid URI was entered.
279 throw new Exception(_m('Invalid URI.'));
282 // redirect to the new profile.
283 common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
285 } catch (Exception $e) {
286 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
287 // TRANS: and example.net, as these are official standard domain names for use in examples.
288 $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.");
291 $action->showForm($err);
298 * If the field being looked for is URI look for the profile
300 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
301 if ($action->field == 'uri') {
302 $profile->joinAdd(array('id', 'user:id'));
303 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
306 if ($profile->N == 0) {
308 if (Validate::email($q)) {
309 $oprofile = Ostatus_profile::ensureWebfinger($q);
310 } else if (Validate::uri($q)) {
311 $oprofile = Ostatus_profile::ensureProfileURL($q);
313 // TRANS: Exception in OStatus when invalid URI was entered.
314 throw new Exception(_m('Invalid URI.'));
316 return $this->filter(array($oprofile->localProfile()));
318 } catch (Exception $e) {
319 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
320 // TRANS: and example.net, as these are official standard domain names for use in examples.
321 $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.");
331 * Find any explicit remote mentions. Accepted forms:
332 * Webfinger: @user@example.com
333 * Profile link: @example.com/mublog/user
334 * @param Profile $sender
335 * @param string $text input markup text
336 * @param array &$mention in/out param: set of found mentions
337 * @return boolean hook return value
339 function onEndFindMentions(Profile $sender, $text, &$mentions)
343 // Webfinger matches: @user@example.com
344 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
347 PREG_OFFSET_CAPTURE)) {
348 foreach ($wmatches[1] as $wmatch) {
349 list($target, $pos) = $wmatch;
350 $this->log(LOG_INFO, "Checking webfinger '$target'");
352 $oprofile = Ostatus_profile::ensureWebfinger($target);
353 if ($oprofile && !$oprofile->isGroup()) {
354 $profile = $oprofile->localProfile();
355 $matches[$pos] = array('mentioned' => array($profile),
359 'url' => $profile->profileurl);
361 } catch (Exception $e) {
362 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
367 // Profile matches: @example.com/mublog/user
368 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
371 PREG_OFFSET_CAPTURE)) {
372 foreach ($wmatches[1] as $wmatch) {
373 list($target, $pos) = $wmatch;
374 $schemes = array('http', 'https');
375 foreach ($schemes as $scheme) {
376 $url = "$scheme://$target";
377 $this->log(LOG_INFO, "Checking profile address '$url'");
379 $oprofile = Ostatus_profile::ensureProfileURL($url);
380 if ($oprofile && !$oprofile->isGroup()) {
381 $profile = $oprofile->localProfile();
382 $matches[$pos] = array('mentioned' => array($profile),
386 'url' => $profile->profileurl);
389 } catch (Exception $e) {
390 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
396 foreach ($mentions as $i => $other) {
397 // If we share a common prefix with a local user, override it!
398 $pos = $other['position'];
399 if (isset($matches[$pos])) {
400 $mentions[$i] = $matches[$pos];
401 unset($matches[$pos]);
404 foreach ($matches as $mention) {
405 $mentions[] = $mention;
412 * Allow remote profile references to be used in commands:
413 * sub update@status.net
414 * whois evan@identi.ca
415 * reply http://identi.ca/evan hey what's up
417 * @param Command $command
419 * @param Profile &$profile
420 * @return hook return code
422 function onStartCommandGetProfile($command, $arg, &$profile)
424 $oprofile = $this->pullRemoteProfile($arg);
425 if ($oprofile && !$oprofile->isGroup()) {
426 $profile = $oprofile->localProfile();
434 * Allow remote group references to be used in commands:
435 * join group+statusnet@identi.ca
436 * join http://identi.ca/group/statusnet
437 * drop identi.ca/group/statusnet
439 * @param Command $command
441 * @param User_group &$group
442 * @return hook return code
444 function onStartCommandGetGroup($command, $arg, &$group)
446 $oprofile = $this->pullRemoteProfile($arg);
447 if ($oprofile && $oprofile->isGroup()) {
448 $group = $oprofile->localGroup();
455 protected function pullRemoteProfile($arg)
458 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
461 return Ostatus_profile::ensureWebfinger($arg);
462 } catch (Exception $e) {
463 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
464 $arg . ': ' . $e->getMessage());
468 // Look for profile URLs, with or without scheme:
470 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
473 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
474 $schemes = array('http', 'https');
475 foreach ($schemes as $scheme) {
476 $urls[] = "$scheme://$arg";
480 foreach ($urls as $url) {
482 return Ostatus_profile::ensureProfileURL($url);
483 } catch (Exception $e) {
484 common_log(LOG_ERR, 'Profile lookup failed for ' .
485 $arg . ': ' . $e->getMessage());
492 * Make sure necessary tables are filled out.
494 function onCheckSchema() {
495 $schema = Schema::get();
496 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
497 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
498 $schema->ensureTable('feedsub', FeedSub::schemaDef());
499 $schema->ensureTable('hubsub', HubSub::schemaDef());
500 $schema->ensureTable('magicsig', Magicsig::schemaDef());
504 public function onEndShowStylesheets(Action $action) {
505 $action->cssLink($this->path('theme/base/css/ostatus.css'));
509 function onEndShowStatusNetScripts($action) {
510 $action->script($this->path('js/ostatus.js'));
515 * Override the "from ostatus" bit in notice lists to link to the
516 * original post and show the domain it came from.
518 * @param Notice in $notice
519 * @param string out &$name
520 * @param string out &$url
521 * @param string out &$title
522 * @return mixed hook return code
524 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
526 // If we don't handle this, keep the event handler going
527 if ($notice->source != 'ostatus') {
532 $url = $notice->getUrl();
533 // If getUrl() throws exception, $url is never set
535 $bits = parse_url($url);
536 $domain = $bits['host'];
537 if (substr($domain, 0, 4) == 'www.') {
538 $name = substr($domain, 4);
543 // TRANS: Title. %s is a domain name.
544 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
546 // Abort event handler, we have a name and URL!
548 } catch (InvalidUrlException $e) {
549 // This just means we don't have the notice source data
555 * Send incoming PuSH feeds for OStatus endpoints in for processing.
557 * @param FeedSub $feedsub
558 * @param DOMDocument $feed
559 * @return mixed hook return code
561 function onStartFeedSubReceive($feedsub, $feed)
563 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
564 if ($oprofile instanceof Ostatus_profile) {
565 $oprofile->processFeed($feed, 'push');
567 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
572 * Tell the FeedSub infrastructure whether we have any active OStatus
573 * usage for the feed; if not it'll be able to garbage-collect the
576 * @param FeedSub $feedsub
577 * @param integer $count in/out
578 * @return mixed hook return code
580 function onFeedSubSubscriberCount($feedsub, &$count)
582 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
584 $count += $oprofile->subscriberCount();
590 * When about to subscribe to a remote user, start a server-to-server
591 * PuSH subscription if needed. If we can't establish that, abort.
593 * @fixme If something else aborts later, we could end up with a stray
594 * PuSH subscription. This is relatively harmless, though.
596 * @param Profile $profile subscriber
597 * @param Profile $other subscribee
599 * @return hook return code
603 function onStartSubscribe(Profile $profile, Profile $other)
605 if (!$profile->isLocal()) {
609 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
611 if (empty($oprofile)) {
615 if (!$oprofile->subscribe()) {
616 // TRANS: Exception thrown when setup of remote subscription fails.
617 throw new Exception(_m('Could not set up remote subscription.'));
622 * Having established a remote subscription, send a notification to the
623 * remote OStatus profile's endpoint.
625 * @param Profile $profile subscriber
626 * @param Profile $other subscribee
628 * @return hook return code
632 function onEndSubscribe(Profile $profile, Profile $other)
634 if (!$profile->isLocal()) {
638 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
640 if (empty($oprofile)) {
644 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
645 'subscribed' => $other->id));
647 $act = $sub->asActivity();
649 $oprofile->notifyActivity($act, $profile);
655 * Notify remote server and garbage collect unused feeds on unsubscribe.
656 * @todo FIXME: Send these operations to background queues
659 * @param Profile $other
660 * @return hook return value
662 function onEndUnsubscribe(Profile $profile, Profile $other)
664 if (!$profile->isLocal()) {
668 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
670 if (empty($oprofile)) {
674 // Drop the PuSH subscription if there are no other subscribers.
675 $oprofile->garbageCollect();
677 $act = new Activity();
679 $act->verb = ActivityVerb::UNFOLLOW;
681 $act->id = TagURI::mint('unfollow:%d:%d:%s',
684 common_date_iso8601(time()));
687 // TRANS: Title for unfollowing a remote profile.
688 $act->title = _m('TITLE','Unfollow');
689 // TRANS: Success message for unsubscribe from user attempt through OStatus.
690 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
691 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
692 $profile->getBestName(),
693 $other->getBestName());
695 $act->actor = ActivityObject::fromProfile($profile);
696 $act->object = ActivityObject::fromProfile($other);
698 $oprofile->notifyActivity($act, $profile);
704 * When one of our local users tries to join a remote group,
705 * notify the remote server. If the notification is rejected,
708 * @param User_group $group
709 * @param Profile $profile
711 * @return mixed hook return value
713 function onStartJoinGroup($group, $profile)
715 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
717 if (!$oprofile->subscribe()) {
718 // TRANS: Exception thrown when setup of remote group membership fails.
719 throw new Exception(_m('Could not set up remote group membership.'));
722 // NOTE: we don't use Group_member::asActivity() since that record
723 // has not yet been created.
725 $act = new Activity();
726 $act->id = TagURI::mint('join:%d:%d:%s',
729 common_date_iso8601(time()));
731 $act->actor = ActivityObject::fromProfile($profile);
732 $act->verb = ActivityVerb::JOIN;
733 $act->object = $oprofile->asActivityObject();
736 // TRANS: Title for joining a remote groep.
737 $act->title = _m('TITLE','Join');
738 // TRANS: Success message for subscribe to group attempt through OStatus.
739 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
740 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
741 $profile->getBestName(),
742 $oprofile->getBestName());
744 if ($oprofile->notifyActivity($act, $profile)) {
747 $oprofile->garbageCollect();
748 // TRANS: Exception thrown when joining a remote group fails.
749 throw new Exception(_m('Failed joining remote group.'));
755 * When one of our local users leaves a remote group, notify the remote
758 * @fixme Might be good to schedule a resend of the leave notification
759 * if it failed due to a transitory error. We've canceled the local
760 * membership already anyway, but if the remote server comes back up
761 * it'll be left with a stray membership record.
763 * @param User_group $group
764 * @param Profile $profile
766 * @return mixed hook return value
768 function onEndLeaveGroup($group, $profile)
770 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
772 // Drop the PuSH subscription if there are no other subscribers.
773 $oprofile->garbageCollect();
777 $act = new Activity();
778 $act->id = TagURI::mint('leave:%d:%d:%s',
781 common_date_iso8601(time()));
783 $act->actor = ActivityObject::fromProfile($member);
784 $act->verb = ActivityVerb::LEAVE;
785 $act->object = $oprofile->asActivityObject();
788 // TRANS: Title for leaving a remote group.
789 $act->title = _m('TITLE','Leave');
790 // TRANS: Success message for unsubscribe from group attempt through OStatus.
791 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
792 $act->content = sprintf(_m('%1$s has left group %2$s.'),
793 $member->getBestName(),
794 $oprofile->getBestName());
796 $oprofile->notifyActivity($act, $member);
801 * When one of our local users tries to subscribe to a remote peopletag,
802 * notify the remote server. If the notification is rejected,
803 * deny the subscription.
805 * @param Profile_list $peopletag
808 * @return mixed hook return value
811 function onStartSubscribePeopletag($peopletag, $user)
813 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
815 if (!$oprofile->subscribe()) {
816 // TRANS: Exception thrown when setup of remote list subscription fails.
817 throw new Exception(_m('Could not set up remote list subscription.'));
820 $sub = $user->getProfile();
821 $tagger = Profile::getKV($peopletag->tagger);
823 $act = new Activity();
824 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
827 common_date_iso8601(time()));
829 $act->actor = ActivityObject::fromProfile($sub);
830 $act->verb = ActivityVerb::FOLLOW;
831 $act->object = $oprofile->asActivityObject();
834 // TRANS: Title for following a remote list.
835 $act->title = _m('TITLE','Follow list');
836 // TRANS: Success message for remote list follow through OStatus.
837 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
838 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
840 $oprofile->getBestName(),
841 $tagger->getBestName());
843 if ($oprofile->notifyActivity($act, $sub)) {
846 $oprofile->garbageCollect();
847 // TRANS: Exception thrown when subscription to remote list fails.
848 throw new Exception(_m('Failed subscribing to remote list.'));
854 * When one of our local users unsubscribes to a remote peopletag, notify the remote
857 * @param Profile_list $peopletag
860 * @return mixed hook return value
863 function onEndUnsubscribePeopletag($peopletag, $user)
865 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
867 // Drop the PuSH subscription if there are no other subscribers.
868 $oprofile->garbageCollect();
870 $sub = Profile::getKV($user->id);
871 $tagger = Profile::getKV($peopletag->tagger);
873 $act = new Activity();
874 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
877 common_date_iso8601(time()));
879 $act->actor = ActivityObject::fromProfile($member);
880 $act->verb = ActivityVerb::UNFOLLOW;
881 $act->object = $oprofile->asActivityObject();
884 // TRANS: Title for unfollowing a remote list.
885 $act->title = _m('Unfollow list');
886 // TRANS: Success message for remote list unfollow through OStatus.
887 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
888 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
890 $oprofile->getBestName(),
891 $tagger->getBestName());
893 $oprofile->notifyActivity($act, $user);
898 * Notify remote users when their notices get favorited.
900 * @param Profile or User $profile of local user doing the faving
901 * @param Notice $notice being favored
902 * @return hook return value
904 function onEndFavorNotice(Profile $profile, Notice $notice)
906 $user = User::getKV('id', $profile->id);
912 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
914 if (empty($oprofile)) {
918 $fav = Fave::pkeyGet(array('user_id' => $user->id,
919 'notice_id' => $notice->id));
926 $act = $fav->asActivity();
928 $oprofile->notifyActivity($act, $profile);
934 * Notify remote user it has got a new people tag
935 * - tag verb is queued
936 * - the subscription is done immediately if not present
938 * @param Profile_tag $ptag the people tag that was created
939 * @return hook return value
941 function onEndTagProfile($ptag)
943 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
945 if (empty($oprofile)) {
949 $plist = $ptag->getMeta();
950 if ($plist->private) {
954 $act = new Activity();
956 $tagger = $plist->getTagger();
957 $tagged = Profile::getKV('id', $ptag->tagged);
959 $act->verb = ActivityVerb::TAG;
960 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
961 $plist->tagger, $plist->id,
962 common_date_iso8601(time()));
964 // TRANS: Title for listing a remote profile.
965 $act->title = _m('TITLE','List');
966 // TRANS: Success message for remote list addition through OStatus.
967 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
968 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
969 $tagger->getBestName(),
970 $tagged->getBestName(),
971 $plist->getBestName());
973 $act->actor = ActivityObject::fromProfile($tagger);
974 $act->objects = array(ActivityObject::fromProfile($tagged));
975 $act->target = ActivityObject::fromPeopletag($plist);
977 $oprofile->notifyDeferred($act, $tagger);
979 // initiate a PuSH subscription for the person being tagged
980 if (!$oprofile->subscribe()) {
981 // TRANS: Exception thrown when subscribing to a remote list fails.
982 throw new Exception(sprintf(_m('Could not complete subscription to remote '.
983 'profile\'s feed. List %s could not be saved.'), $ptag->tag));
990 * Notify remote user that a people tag has been removed
991 * - untag verb is queued
992 * - the subscription is undone immediately if not required
993 * i.e garbageCollect()'d
995 * @param Profile_tag $ptag the people tag that was deleted
996 * @return hook return value
998 function onEndUntagProfile($ptag)
1000 $oprofile = Ostatus_profile::getKV('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::getKV('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 // TRANS: Title for unlisting a remote profile.
1022 $act->title = _m('TITLE','Unlist');
1023 // TRANS: Success message for remote list removal through OStatus.
1024 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1025 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1026 $tagger->getBestName(),
1027 $tagged->getBestName(),
1028 $plist->getBestName());
1030 $act->actor = ActivityObject::fromProfile($tagger);
1031 $act->objects = array(ActivityObject::fromProfile($tagged));
1032 $act->target = ActivityObject::fromPeopletag($plist);
1034 $oprofile->notifyDeferred($act, $tagger);
1036 // unsubscribe to PuSH feed if no more required
1037 $oprofile->garbageCollect();
1043 * Notify remote users when their notices get de-favorited.
1045 * @param Profile $profile Profile person doing the de-faving
1046 * @param Notice $notice Notice being favored
1048 * @return hook return value
1050 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1052 $user = User::getKV('id', $profile->id);
1058 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1060 if (empty($oprofile)) {
1064 $act = new Activity();
1066 $act->verb = ActivityVerb::UNFAVORITE;
1067 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1070 common_date_iso8601(time()));
1071 $act->time = time();
1072 // TRANS: Title for unliking a remote notice.
1073 $act->title = _m('Unlike');
1074 // TRANS: Success message for remove a favorite notice through OStatus.
1075 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1076 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1077 $profile->getBestName(),
1080 $act->actor = ActivityObject::fromProfile($profile);
1081 $act->object = ActivityObject::fromNotice($notice);
1083 $oprofile->notifyActivity($act, $profile);
1088 function onStartGetProfileUri($profile, &$uri)
1090 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1091 if ($oprofile instanceof Ostatus_profile) {
1092 $uri = $oprofile->uri;
1098 function onStartUserGroupHomeUrl($group, &$url)
1100 return $this->onStartUserGroupPermalink($group, $url);
1103 function onStartUserGroupPermalink($group, &$url)
1105 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1107 // @fixme this should probably be in the user_group table
1108 // @fixme this uri not guaranteed to be a profile page
1109 $url = $oprofile->uri;
1114 function onStartShowSubscriptionsContent($action)
1116 $this->showEntityRemoteSubscribe($action);
1121 function onStartShowUserGroupsContent($action)
1123 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1128 function onEndShowSubscriptionsMiniList($action)
1130 $this->showEntityRemoteSubscribe($action);
1135 function onEndShowGroupsMiniList($action)
1137 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1142 function showEntityRemoteSubscribe($action, $target='ostatussub')
1144 $user = common_current_user();
1145 if ($user && ($user->id == $action->profile->id)) {
1146 $action->elementStart('div', 'entity_actions');
1147 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1148 'class' => 'entity_subscribe'));
1149 $action->element('a', array('href' => common_local_url($target),
1150 'class' => 'entity_remote_subscribe'),
1151 // TRANS: Link text for link to remote subscribe.
1153 $action->elementEnd('p');
1154 $action->elementEnd('div');
1159 * Ping remote profiles with updates to this profile.
1160 * Salmon pings are queued for background processing.
1162 function onEndBroadcastProfile(Profile $profile)
1164 $user = User::getKV('id', $profile->id);
1166 // Find foreign accounts I'm subscribed to that support Salmon pings.
1168 // @fixme we could run updates through the PuSH feed too,
1169 // in which case we can skip Salmon pings to folks who
1170 // are also subscribed to me.
1171 $sql = "SELECT * FROM ostatus_profile " .
1172 "WHERE profile_id IN " .
1173 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1175 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1176 $oprofile = new Ostatus_profile();
1177 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1179 if ($oprofile->N == 0) {
1180 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1184 $act = new Activity();
1186 $act->verb = ActivityVerb::UPDATE_PROFILE;
1187 $act->id = TagURI::mint('update-profile:%d:%s',
1189 common_date_iso8601(time()));
1190 $act->time = time();
1191 // TRANS: Title for activity.
1192 $act->title = _m('Profile update');
1193 // TRANS: Ping text for remote profile update through OStatus.
1194 // TRANS: %s is user that updated their profile.
1195 $act->content = sprintf(_m('%s has updated their profile page.'),
1196 $profile->getBestName());
1198 $act->actor = ActivityObject::fromProfile($profile);
1199 $act->object = $act->actor;
1201 while ($oprofile->fetch()) {
1202 $oprofile->notifyDeferred($act, $profile);
1208 function onStartProfileListItemActionElements($item, $profile=null)
1210 if (!common_logged_in()) {
1212 $profileUser = User::getKV('id', $item->profile->id);
1214 if (!empty($profileUser)) {
1216 if ($item instanceof Action) {
1218 $profile = $item->profile;
1220 $output = $item->out;
1223 // Add an OStatus subscribe
1224 $output->elementStart('li', 'entity_subscribe');
1225 $url = common_local_url('ostatusinit',
1226 array('nickname' => $profileUser->nickname));
1227 $output->element('a', array('href' => $url,
1228 'class' => 'entity_remote_subscribe'),
1229 // TRANS: Link text for a user to subscribe to an OStatus user.
1231 $output->elementEnd('li');
1233 $output->elementStart('li', 'entity_tag');
1234 $url = common_local_url('ostatustag',
1235 array('nickname' => $profileUser->nickname));
1236 $output->element('a', array('href' => $url,
1237 'class' => 'entity_remote_tag'),
1238 // TRANS: Link text for a user to list an OStatus user.
1240 $output->elementEnd('li');
1247 function onPluginVersion(&$versions)
1249 $versions[] = array('name' => 'OStatus',
1250 'version' => GNUSOCIAL_VERSION,
1251 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1252 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1253 // TRANS: Plugin description.
1254 'rawdescription' => _m('Follow people across social networks that implement '.
1255 '<a href="http://ostatus.org/">OStatus</a>.'));
1261 * Utility function to check if the given URI is a canonical group profile
1262 * page, and if so return the ID number.
1264 * @param string $url
1265 * @return mixed int or false
1267 public static function localGroupFromUrl($url)
1269 $group = User_group::getKV('uri', $url);
1271 $local = Local_group::getKV('group_id', $group->id);
1276 // To find local groups which haven't had their uri fields filled out...
1277 // If the domain has changed since a subscriber got the URI, it'll
1279 $template = common_local_url('groupbyid', array('id' => '31337'));
1280 $template = preg_quote($template, '/');
1281 $template = str_replace('31337', '(\d+)', $template);
1282 if (preg_match("/$template/", $url, $matches)) {
1283 return intval($matches[1]);
1289 public function onStartProfileGetAtomFeed($profile, &$feed)
1291 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1293 if (empty($oprofile)) {
1297 $feed = $oprofile->feeduri;
1301 function onStartGetProfileFromURI($uri, &$profile)
1303 // Don't want to do Web-based discovery on our own server,
1304 // so we check locally first.
1306 $user = User::getKV('uri', $uri);
1308 if (!empty($user)) {
1309 $profile = $user->getProfile();
1313 // Now, check remotely
1316 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1317 $profile = $oprofile->localProfile();
1318 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1319 } catch (Exception $e) {
1320 return true; // It's not an OStatus profile as far as we know, continue event handling
1324 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1326 $author = $target->getProfile();
1327 $salmon_url = common_local_url('usersalmon', array('id' => $author->id));
1328 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1332 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1334 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1335 common_local_url('ApiTimelineUser',
1336 array('id' => $target->id, 'format' => 'atom')),
1337 'application/atom+xml');
1340 $salmon_url = common_local_url('usersalmon',
1341 array('id' => $target->id));
1343 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1345 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1346 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1347 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1349 // Get this user's keypair
1350 $magickey = Magicsig::getKV('user_id', $target->id);
1351 if (!($magickey instanceof Magicsig)) {
1352 // No keypair yet, let's generate one.
1353 $magickey = new Magicsig();
1354 $magickey->generate($target->id);
1357 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1358 'data:application/magic-public-key,'. $magickey->toString(false));
1360 // TODO - finalize where the redirect should go on the publisher
1361 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1362 common_local_url('ostatussub') . '?profile={uri}',
1363 null, // type not set
1364 true); // isTemplate