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 OStatusPlugin extends Plugin
36 * Hook for RouterInitialized event.
38 * @param URLMapper $m path-to-action mapper
39 * @return boolean hook return
41 public function onRouterInitialized(URLMapper $m)
44 $m->connect('main/ostatustag',
45 array('action' => 'ostatustag'));
46 $m->connect('main/ostatustag?nickname=:nickname',
47 array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
48 $m->connect('main/ostatus/nickname/:nickname',
49 array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
50 $m->connect('main/ostatus/group/:group',
51 array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
52 $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
53 array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
54 'peopletag' => '[A-Za-z0-9_-]+'));
55 $m->connect('main/ostatus',
56 array('action' => 'ostatusinit'));
58 // Remote subscription actions
59 $m->connect('main/ostatussub',
60 array('action' => 'ostatussub'));
61 $m->connect('main/ostatusgroup',
62 array('action' => 'ostatusgroup'));
63 $m->connect('main/ostatuspeopletag',
64 array('action' => 'ostatuspeopletag'));
67 $m->connect('main/push/hub', array('action' => 'pushhub'));
69 $m->connect('main/push/callback/:feed',
70 array('action' => 'pushcallback'),
71 array('feed' => '[0-9]+'));
74 $m->connect('main/salmon/user/:id',
75 array('action' => 'usersalmon'),
76 array('id' => '[0-9]+'));
77 $m->connect('main/salmon/group/:id',
78 array('action' => 'groupsalmon'),
79 array('id' => '[0-9]+'));
80 $m->connect('main/salmon/peopletag/:id',
81 array('action' => 'peopletagsalmon'),
82 array('id' => '[0-9]+'));
86 public function onAutoload($cls)
91 // Crypt_AES becomes Crypt/AES.php which is found in extlib/phpseclib/
92 // which has been added to our include_path before
93 require_once str_replace('_', '/', $cls) . '.php';
97 return parent::onAutoload($cls);
101 * Set up queue handlers for outgoing hub pushes
102 * @param QueueManager $qm
103 * @return boolean hook return
105 function onEndInitializeQueueManager(QueueManager $qm)
107 // Prepare outgoing distributions after notice save.
108 $qm->connect('ostatus', 'OStatusQueueHandler');
110 // Outgoing from our internal PuSH hub
111 $qm->connect('hubconf', 'HubConfQueueHandler');
112 $qm->connect('hubprep', 'HubPrepQueueHandler');
114 $qm->connect('hubout', 'HubOutQueueHandler');
116 // Outgoing Salmon replies (when we don't need a return value)
117 $qm->connect('salmon', 'SalmonQueueHandler');
119 // Incoming from a foreign PuSH hub
120 $qm->connect('pushin', 'PushInQueueHandler');
122 // Re-subscribe feeds that need renewal
123 $qm->connect('pushrenew', 'PushRenewQueueHandler');
128 * Put saved notices into the queue for pubsub distribution.
130 function onStartEnqueueNotice($notice, &$transports)
132 if ($notice->inScope(null)) {
133 // put our transport first, in case there's any conflict (like OMB)
134 array_unshift($transports, 'ostatus');
135 $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
137 // FIXME: we don't do privacy-controlled OStatus updates yet.
138 // once that happens, finer grain of control here.
139 $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
145 * Set up a PuSH hub link to our internal link for canonical timeline
146 * Atom feeds for users and groups.
148 function onStartApiAtom($feed)
152 if ($feed instanceof AtomUserNoticeFeed) {
153 $salmonAction = 'usersalmon';
154 $user = $feed->getUser();
156 $profile = $user->getProfile();
157 } else if ($feed instanceof AtomGroupNoticeFeed) {
158 $salmonAction = 'groupsalmon';
159 $group = $feed->getGroup();
161 } else if ($feed instanceof AtomListNoticeFeed) {
162 $salmonAction = 'peopletagsalmon';
163 $peopletag = $feed->getList();
164 $id = $peopletag->id;
170 $hub = common_config('ostatus', 'hub');
172 // Updates will be handled through our internal PuSH hub.
173 $hub = common_local_url('pushhub');
175 $feed->addLink($hub, array('rel' => 'hub'));
177 // Also, we'll add in the salmon link
178 $salmon = common_local_url($salmonAction, array('id' => $id));
179 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
181 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
182 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
183 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
190 * Add in an OStatus subscribe button
192 function onStartProfileRemoteSubscribe($output, $profile)
194 $this->onStartProfileListItemActionElements($output, $profile);
198 function onStartGroupSubscribe($widget, $group)
200 $cur = common_current_user();
203 $widget->out->elementStart('li', 'entity_subscribe');
205 $url = common_local_url('ostatusinit',
206 array('group' => $group->nickname));
207 $widget->out->element('a', array('href' => $url,
208 'class' => 'entity_remote_subscribe'),
209 // TRANS: Link to subscribe to a remote entity.
212 $widget->out->elementEnd('li');
219 function onStartSubscribePeopletagForm($output, $peopletag)
221 $cur = common_current_user();
224 $output->elementStart('li', 'entity_subscribe');
225 $profile = $peopletag->getTagger();
226 $url = common_local_url('ostatusinit',
227 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
228 $output->element('a', array('href' => $url,
229 'class' => 'entity_remote_subscribe'),
230 // TRANS: Link to subscribe to a remote entity.
233 $output->elementEnd('li');
241 * If the field being looked for is URI look for the profile
243 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
244 if ($action->field == 'uri') {
245 $profile->joinAdd(array('id', 'user:id'));
246 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
249 $validate = new Validate();
251 if ($profile->N == 0) {
253 if ($validate->email($q)) {
254 $oprofile = Ostatus_profile::ensureWebfinger($q);
255 } else if ($validate->uri($q)) {
256 $oprofile = Ostatus_profile::ensureProfileURL($q);
258 // TRANS: Exception in OStatus when invalid URI was entered.
259 throw new Exception(_m('Invalid URI.'));
261 return $this->filter(array($oprofile->localProfile()));
263 } catch (Exception $e) {
264 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
265 // TRANS: and example.net, as these are official standard domain names for use in examples.
266 $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.");
276 * Find any explicit remote mentions. Accepted forms:
277 * Webfinger: @user@example.com
278 * Profile link: @example.com/mublog/user
279 * @param Profile $sender
280 * @param string $text input markup text
281 * @param array &$mention in/out param: set of found mentions
282 * @return boolean hook return value
284 function onEndFindMentions(Profile $sender, $text, &$mentions)
289 // Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
290 if (preg_match_all('!(?:^|\s+)@((?:\w+[\w\-\_\.]?)*(?:[\w\-\_\.]*\w+)@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
293 PREG_OFFSET_CAPTURE)) {
294 foreach ($wmatches[1] as $wmatch) {
295 list($target, $pos) = $wmatch;
296 $this->log(LOG_INFO, "Checking webfinger '$target'");
299 $oprofile = Ostatus_profile::ensureWebfinger($target);
300 if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
303 $profile = $oprofile->localProfile();
304 } catch (OStatusShadowException $e) {
305 // This means we got a local user in the webfinger lookup
306 $profile = $e->profile;
307 } catch (Exception $e) {
308 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
312 assert($profile instanceof Profile);
314 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
315 ? $profile->getNickname() // TODO: we could do getFancyName() or getFullname() here
317 $url = $profile->getUri();
318 if (!common_valid_http_url($url)) {
319 $url = $profile->getUrl();
321 $matches[$pos] = array('mentioned' => array($profile),
325 'length' => mb_strlen($target),
330 // Profile matches: @example.com/mublog/user
331 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
334 PREG_OFFSET_CAPTURE)) {
335 foreach ($wmatches[1] as $wmatch) {
336 list($target, $pos) = $wmatch;
337 $schemes = array('http', 'https');
338 foreach ($schemes as $scheme) {
339 $url = "$scheme://$target";
340 $this->log(LOG_INFO, "Checking profile address '$url'");
342 $oprofile = Ostatus_profile::ensureProfileURL($url);
343 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
344 $profile = $oprofile->localProfile();
345 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
346 $profile->nickname : $target;
347 $matches[$pos] = array('mentioned' => array($profile),
351 'length' => mb_strlen($target),
352 'url' => $profile->getUrl());
355 } catch (Exception $e) {
356 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
362 foreach ($mentions as $i => $other) {
363 // If we share a common prefix with a local user, override it!
364 $pos = $other['position'];
365 if (isset($matches[$pos])) {
366 $mentions[$i] = $matches[$pos];
367 unset($matches[$pos]);
370 foreach ($matches as $mention) {
371 $mentions[] = $mention;
378 * Allow remote profile references to be used in commands:
379 * sub update@status.net
380 * whois evan@identi.ca
381 * reply http://identi.ca/evan hey what's up
383 * @param Command $command
385 * @param Profile &$profile
386 * @return hook return code
388 function onStartCommandGetProfile($command, $arg, &$profile)
390 $oprofile = $this->pullRemoteProfile($arg);
391 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
393 $profile = $oprofile->localProfile();
394 } catch (NoProfileException $e) {
395 // No locally stored profile found for remote profile
405 * Allow remote group references to be used in commands:
406 * join group+statusnet@identi.ca
407 * join http://identi.ca/group/statusnet
408 * drop identi.ca/group/statusnet
410 * @param Command $command
412 * @param User_group &$group
413 * @return hook return code
415 function onStartCommandGetGroup($command, $arg, &$group)
417 $oprofile = $this->pullRemoteProfile($arg);
418 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
419 $group = $oprofile->localGroup();
426 protected function pullRemoteProfile($arg)
429 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
432 return Ostatus_profile::ensureWebfinger($arg);
433 } catch (Exception $e) {
434 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
435 $arg . ': ' . $e->getMessage());
439 // Look for profile URLs, with or without scheme:
441 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
444 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
445 $schemes = array('http', 'https');
446 foreach ($schemes as $scheme) {
447 $urls[] = "$scheme://$arg";
451 foreach ($urls as $url) {
453 return Ostatus_profile::ensureProfileURL($url);
454 } catch (Exception $e) {
455 common_log(LOG_ERR, 'Profile lookup failed for ' .
456 $arg . ': ' . $e->getMessage());
462 function onEndProfileSettingsActions($out) {
463 $siteName = common_config('site', 'name');
464 $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
465 $out->elementStart('li');
467 array('href' => 'javascript:'.$js),
468 // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
469 _('Add to Firefox as feedreader'));
470 $out->elementEnd('li');
474 * Make sure necessary tables are filled out.
476 function onCheckSchema() {
477 $schema = Schema::get();
478 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
479 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
480 $schema->ensureTable('feedsub', FeedSub::schemaDef());
481 $schema->ensureTable('hubsub', HubSub::schemaDef());
482 $schema->ensureTable('magicsig', Magicsig::schemaDef());
486 public function onEndShowStylesheets(Action $action) {
487 $action->cssLink($this->path('theme/base/css/ostatus.css'));
491 function onEndShowStatusNetScripts($action) {
492 $action->script($this->path('js/ostatus.js'));
497 * Override the "from ostatus" bit in notice lists to link to the
498 * original post and show the domain it came from.
500 * @param Notice in $notice
501 * @param string out &$name
502 * @param string out &$url
503 * @param string out &$title
504 * @return mixed hook return code
506 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
508 // If we don't handle this, keep the event handler going
509 if (!in_array($notice->source, array('ostatus', 'share'))) {
514 $url = $notice->getUrl();
515 // If getUrl() throws exception, $url is never set
517 $bits = parse_url($url);
518 $domain = $bits['host'];
519 if (substr($domain, 0, 4) == 'www.') {
520 $name = substr($domain, 4);
525 // TRANS: Title. %s is a domain name.
526 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
528 // Abort event handler, we have a name and URL!
530 } catch (InvalidUrlException $e) {
531 // This just means we don't have the notice source data
537 * Send incoming PuSH feeds for OStatus endpoints in for processing.
539 * @param FeedSub $feedsub
540 * @param DOMDocument $feed
541 * @return mixed hook return code
543 function onStartFeedSubReceive($feedsub, $feed)
545 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
546 if ($oprofile instanceof Ostatus_profile) {
547 $oprofile->processFeed($feed, 'push');
549 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
554 * Tell the FeedSub infrastructure whether we have any active OStatus
555 * usage for the feed; if not it'll be able to garbage-collect the
558 * @param FeedSub $feedsub
559 * @param integer $count in/out
560 * @return mixed hook return code
562 function onFeedSubSubscriberCount($feedsub, &$count)
564 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
565 if ($oprofile instanceof Ostatus_profile) {
566 $count += $oprofile->subscriberCount();
572 * When about to subscribe to a remote user, start a server-to-server
573 * PuSH subscription if needed. If we can't establish that, abort.
575 * @fixme If something else aborts later, we could end up with a stray
576 * PuSH subscription. This is relatively harmless, though.
578 * @param Profile $profile subscriber
579 * @param Profile $other subscribee
581 * @return hook return code
585 function onStartSubscribe(Profile $profile, Profile $other)
587 if (!$profile->isLocal()) {
591 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
592 if (!$oprofile instanceof Ostatus_profile) {
596 $oprofile->subscribe();
600 * Having established a remote subscription, send a notification to the
601 * remote OStatus profile's endpoint.
603 * @param Profile $profile subscriber
604 * @param Profile $other subscribee
606 * @return hook return code
610 function onEndSubscribe(Profile $profile, Profile $other)
612 if (!$profile->isLocal()) {
616 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
617 if (!$oprofile instanceof Ostatus_profile) {
621 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
622 'subscribed' => $other->id));
624 $act = $sub->asActivity();
626 $oprofile->notifyActivity($act, $profile);
632 * Notify remote server and garbage collect unused feeds on unsubscribe.
633 * @todo FIXME: Send these operations to background queues
636 * @param Profile $other
637 * @return hook return value
639 function onEndUnsubscribe(Profile $profile, Profile $other)
641 if (!$profile->isLocal()) {
645 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
646 if (!$oprofile instanceof Ostatus_profile) {
650 // Drop the PuSH subscription if there are no other subscribers.
651 $oprofile->garbageCollect();
653 $act = new Activity();
655 $act->verb = ActivityVerb::UNFOLLOW;
657 $act->id = TagURI::mint('unfollow:%d:%d:%s',
660 common_date_iso8601(time()));
663 // TRANS: Title for unfollowing a remote profile.
664 $act->title = _m('TITLE','Unfollow');
665 // TRANS: Success message for unsubscribe from user attempt through OStatus.
666 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
667 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
668 $profile->getBestName(),
669 $other->getBestName());
671 $act->actor = $profile->asActivityObject();
672 $act->objects[] = $other->asActivityObject();
674 $oprofile->notifyActivity($act, $profile);
680 * When one of our local users tries to join a remote group,
681 * notify the remote server. If the notification is rejected,
684 * @param User_group $group
685 * @param Profile $profile
687 * @return mixed hook return value
688 * @throws Exception of various kinds, some from $oprofile->subscribe();
690 function onStartJoinGroup($group, $profile)
692 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
693 if (!$oprofile instanceof Ostatus_profile) {
697 $oprofile->subscribe();
699 // NOTE: we don't use Group_member::asActivity() since that record
700 // has not yet been created.
702 $act = new Activity();
703 $act->id = TagURI::mint('join:%d:%d:%s',
706 common_date_iso8601(time()));
708 $act->actor = $profile->asActivityObject();
709 $act->verb = ActivityVerb::JOIN;
710 $act->objects[] = $oprofile->asActivityObject();
713 // TRANS: Title for joining a remote groep.
714 $act->title = _m('TITLE','Join');
715 // TRANS: Success message for subscribe to group attempt through OStatus.
716 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
717 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
718 $profile->getBestName(),
719 $oprofile->getBestName());
721 if ($oprofile->notifyActivity($act, $profile)) {
724 $oprofile->garbageCollect();
725 // TRANS: Exception thrown when joining a remote group fails.
726 throw new Exception(_m('Failed joining remote group.'));
731 * When one of our local users leaves a remote group, notify the remote
734 * @fixme Might be good to schedule a resend of the leave notification
735 * if it failed due to a transitory error. We've canceled the local
736 * membership already anyway, but if the remote server comes back up
737 * it'll be left with a stray membership record.
739 * @param User_group $group
740 * @param Profile $profile
742 * @return mixed hook return value
744 function onEndLeaveGroup($group, $profile)
746 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
747 if (!$oprofile instanceof Ostatus_profile) {
751 // Drop the PuSH subscription if there are no other subscribers.
752 $oprofile->garbageCollect();
756 $act = new Activity();
757 $act->id = TagURI::mint('leave:%d:%d:%s',
760 common_date_iso8601(time()));
762 $act->actor = $member->asActivityObject();
763 $act->verb = ActivityVerb::LEAVE;
764 $act->objects[] = $oprofile->asActivityObject();
767 // TRANS: Title for leaving a remote group.
768 $act->title = _m('TITLE','Leave');
769 // TRANS: Success message for unsubscribe from group attempt through OStatus.
770 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
771 $act->content = sprintf(_m('%1$s has left group %2$s.'),
772 $member->getBestName(),
773 $oprofile->getBestName());
775 $oprofile->notifyActivity($act, $member);
779 * When one of our local users tries to subscribe to a remote peopletag,
780 * notify the remote server. If the notification is rejected,
781 * deny the subscription.
783 * @param Profile_list $peopletag
786 * @return mixed hook return value
787 * @throws Exception of various kinds, some from $oprofile->subscribe();
790 function onStartSubscribePeopletag($peopletag, $user)
792 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
793 if (!$oprofile instanceof Ostatus_profile) {
797 $oprofile->subscribe();
799 $sub = $user->getProfile();
800 $tagger = Profile::getKV($peopletag->tagger);
802 $act = new Activity();
803 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
806 common_date_iso8601(time()));
808 $act->actor = $sub->asActivityObject();
809 $act->verb = ActivityVerb::FOLLOW;
810 $act->objects[] = $oprofile->asActivityObject();
813 // TRANS: Title for following a remote list.
814 $act->title = _m('TITLE','Follow list');
815 // TRANS: Success message for remote list follow through OStatus.
816 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
817 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
819 $oprofile->getBestName(),
820 $tagger->getBestName());
822 if ($oprofile->notifyActivity($act, $sub)) {
825 $oprofile->garbageCollect();
826 // TRANS: Exception thrown when subscription to remote list fails.
827 throw new Exception(_m('Failed subscribing to remote list.'));
832 * When one of our local users unsubscribes to a remote peopletag, notify the remote
835 * @param Profile_list $peopletag
838 * @return mixed hook return value
841 function onEndUnsubscribePeopletag($peopletag, $user)
843 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
844 if (!$oprofile instanceof Ostatus_profile) {
848 // Drop the PuSH subscription if there are no other subscribers.
849 $oprofile->garbageCollect();
851 $sub = Profile::getKV($user->id);
852 $tagger = Profile::getKV($peopletag->tagger);
854 $act = new Activity();
855 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
858 common_date_iso8601(time()));
860 $act->actor = $member->asActivityObject();
861 $act->verb = ActivityVerb::UNFOLLOW;
862 $act->objects[] = $oprofile->asActivityObject();
865 // TRANS: Title for unfollowing a remote list.
866 $act->title = _m('Unfollow list');
867 // TRANS: Success message for remote list unfollow through OStatus.
868 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
869 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
871 $oprofile->getBestName(),
872 $tagger->getBestName());
874 $oprofile->notifyActivity($act, $user);
878 * Notify remote users when their notices get favorited.
880 * @param Profile or User $profile of local user doing the faving
881 * @param Notice $notice being favored
882 * @return hook return value
884 function onEndFavorNotice(Profile $profile, Notice $notice)
886 // Only distribute local users' favor actions, remote users
887 // will have already distributed theirs.
888 if (!$profile->isLocal()) {
892 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
893 if (!$oprofile instanceof Ostatus_profile) {
897 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
898 'notice_id' => $notice->id));
900 if (!$fav instanceof Fave) {
902 // TODO: Make pkeyGet throw exception, since this is a critical failure.
906 $act = $fav->asActivity();
908 $oprofile->notifyActivity($act, $profile);
914 * Notify remote user it has got a new people tag
915 * - tag verb is queued
916 * - the subscription is done immediately if not present
918 * @param Profile_tag $ptag the people tag that was created
919 * @return hook return value
920 * @throws Exception of various kinds, some from $oprofile->subscribe();
922 function onEndTagProfile($ptag)
924 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
925 if (!$oprofile instanceof Ostatus_profile) {
929 $plist = $ptag->getMeta();
930 if ($plist->private) {
934 $act = new Activity();
936 $tagger = $plist->getTagger();
937 $tagged = Profile::getKV('id', $ptag->tagged);
939 $act->verb = ActivityVerb::TAG;
940 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
941 $plist->tagger, $plist->id,
942 common_date_iso8601(time()));
944 // TRANS: Title for listing a remote profile.
945 $act->title = _m('TITLE','List');
946 // TRANS: Success message for remote list addition through OStatus.
947 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
948 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
949 $tagger->getBestName(),
950 $tagged->getBestName(),
951 $plist->getBestName());
953 $act->actor = $tagger->asActivityObject();
954 $act->objects = array($tagged->asActivityObject());
955 $act->target = ActivityObject::fromPeopletag($plist);
957 $oprofile->notifyDeferred($act, $tagger);
959 // initiate a PuSH subscription for the person being tagged
960 $oprofile->subscribe();
965 * Notify remote user that a people tag has been removed
966 * - untag verb is queued
967 * - the subscription is undone immediately if not required
968 * i.e garbageCollect()'d
970 * @param Profile_tag $ptag the people tag that was deleted
971 * @return hook return value
973 function onEndUntagProfile($ptag)
975 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
976 if (!$oprofile instanceof Ostatus_profile) {
980 $plist = $ptag->getMeta();
981 if ($plist->private) {
985 $act = new Activity();
987 $tagger = $plist->getTagger();
988 $tagged = Profile::getKV('id', $ptag->tagged);
990 $act->verb = ActivityVerb::UNTAG;
991 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
992 $plist->tagger, $plist->id,
993 common_date_iso8601(time()));
995 // TRANS: Title for unlisting a remote profile.
996 $act->title = _m('TITLE','Unlist');
997 // TRANS: Success message for remote list removal through OStatus.
998 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
999 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1000 $tagger->getBestName(),
1001 $tagged->getBestName(),
1002 $plist->getBestName());
1004 $act->actor = $tagger->asActivityObject();
1005 $act->objects = array($tagged->asActivityObject());
1006 $act->target = ActivityObject::fromPeopletag($plist);
1008 $oprofile->notifyDeferred($act, $tagger);
1010 // unsubscribe to PuSH feed if no more required
1011 $oprofile->garbageCollect();
1017 * Notify remote users when their notices get de-favorited.
1019 * @param Profile $profile Profile person doing the de-faving
1020 * @param Notice $notice Notice being favored
1022 * @return hook return value
1024 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1026 // Only distribute local users' disfavor actions, remote users
1027 // will have already distributed theirs.
1028 if (!$profile->isLocal()) {
1032 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1033 if (!$oprofile instanceof Ostatus_profile) {
1037 $act = new Activity();
1039 $act->verb = ActivityVerb::UNFAVORITE;
1040 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1043 common_date_iso8601(time()));
1044 $act->time = time();
1045 // TRANS: Title for unliking a remote notice.
1046 $act->title = _m('Unlike');
1047 // TRANS: Success message for remove a favorite notice through OStatus.
1048 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1049 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1050 $profile->getBestName(),
1053 $act->actor = $profile->asActivityObject();
1054 $act->objects[] = $notice->asActivityObject();
1056 $oprofile->notifyActivity($act, $profile);
1061 function onStartGetProfileUri($profile, &$uri)
1063 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1064 if ($oprofile instanceof Ostatus_profile) {
1065 $uri = $oprofile->uri;
1071 function onStartUserGroupHomeUrl($group, &$url)
1073 return $this->onStartUserGroupPermalink($group, $url);
1076 function onStartUserGroupPermalink($group, &$url)
1078 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1079 if ($oprofile instanceof Ostatus_profile) {
1080 // @fixme this should probably be in the user_group table
1081 // @fixme this uri not guaranteed to be a profile page
1082 $url = $oprofile->uri;
1087 function onStartShowSubscriptionsContent($action)
1089 $this->showEntityRemoteSubscribe($action);
1094 function onStartShowUserGroupsContent($action)
1096 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1101 function onEndShowSubscriptionsMiniList($action)
1103 $this->showEntityRemoteSubscribe($action);
1108 function onEndShowGroupsMiniList($action)
1110 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1115 function showEntityRemoteSubscribe($action, $target='ostatussub')
1117 if (!$action->getScoped() instanceof Profile) {
1118 // early return if we're not logged in
1122 if ($action->getScoped()->sameAs($action->getTarget())) {
1123 $action->elementStart('div', 'entity_actions');
1124 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1125 'class' => 'entity_subscribe'));
1126 $action->element('a', array('href' => common_local_url($target),
1127 'class' => 'entity_remote_subscribe'),
1128 // TRANS: Link text for link to remote subscribe.
1130 $action->elementEnd('p');
1131 $action->elementEnd('div');
1136 * Ping remote profiles with updates to this profile.
1137 * Salmon pings are queued for background processing.
1139 function onEndBroadcastProfile(Profile $profile)
1141 $user = User::getKV('id', $profile->id);
1143 // Find foreign accounts I'm subscribed to that support Salmon pings.
1145 // @fixme we could run updates through the PuSH feed too,
1146 // in which case we can skip Salmon pings to folks who
1147 // are also subscribed to me.
1148 $sql = "SELECT * FROM ostatus_profile " .
1149 "WHERE profile_id IN " .
1150 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1152 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1153 $oprofile = new Ostatus_profile();
1154 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1156 if ($oprofile->N == 0) {
1157 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1161 $act = new Activity();
1163 $act->verb = ActivityVerb::UPDATE_PROFILE;
1164 $act->id = TagURI::mint('update-profile:%d:%s',
1166 common_date_iso8601(time()));
1167 $act->time = time();
1168 // TRANS: Title for activity.
1169 $act->title = _m('Profile update');
1170 // TRANS: Ping text for remote profile update through OStatus.
1171 // TRANS: %s is user that updated their profile.
1172 $act->content = sprintf(_m('%s has updated their profile page.'),
1173 $profile->getBestName());
1175 $act->actor = $profile->asActivityObject();
1176 $act->objects[] = $act->actor;
1178 while ($oprofile->fetch()) {
1179 $oprofile->notifyDeferred($act, $profile);
1185 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1186 function onStartProfileListItemActionElements($item)
1188 if (common_logged_in()) {
1189 // only non-logged in users get to see the "remote subscribe" form
1191 } elseif (!$item->getTarget()->isLocal()) {
1192 // we can (for now) only provide remote subscribe forms for local users
1196 if ($item instanceof ProfileAction) {
1198 } elseif ($item instanceof Widget) {
1199 $output = $item->out;
1201 // Bad $item class, don't know how to use this for outputting!
1202 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1205 // Add an OStatus subscribe
1206 $output->elementStart('li', 'entity_subscribe');
1207 $url = common_local_url('ostatusinit',
1208 array('nickname' => $item->getTarget()->getNickname()));
1209 $output->element('a', array('href' => $url,
1210 'class' => 'entity_remote_subscribe'),
1211 // TRANS: Link text for a user to subscribe to an OStatus user.
1213 $output->elementEnd('li');
1215 $output->elementStart('li', 'entity_tag');
1216 $url = common_local_url('ostatustag',
1217 array('nickname' => $item->getTarget()->getNickname()));
1218 $output->element('a', array('href' => $url,
1219 'class' => 'entity_remote_tag'),
1220 // TRANS: Link text for a user to list an OStatus user.
1222 $output->elementEnd('li');
1227 function onPluginVersion(array &$versions)
1229 $versions[] = array('name' => 'OStatus',
1230 'version' => GNUSOCIAL_VERSION,
1231 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1232 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1233 // TRANS: Plugin description.
1234 'rawdescription' => _m('Follow people across social networks that implement '.
1235 '<a href="http://ostatus.org/">OStatus</a>.'));
1241 * Utility function to check if the given URI is a canonical group profile
1242 * page, and if so return the ID number.
1244 * @param string $url
1245 * @return mixed int or false
1247 public static function localGroupFromUrl($url)
1249 $group = User_group::getKV('uri', $url);
1250 if ($group instanceof User_group) {
1251 if ($group->isLocal()) {
1255 // To find local groups which haven't had their uri fields filled out...
1256 // If the domain has changed since a subscriber got the URI, it'll
1258 $template = common_local_url('groupbyid', array('id' => '31337'));
1259 $template = preg_quote($template, '/');
1260 $template = str_replace('31337', '(\d+)', $template);
1261 if (preg_match("/$template/", $url, $matches)) {
1262 return intval($matches[1]);
1268 public function onStartProfileGetAtomFeed($profile, &$feed)
1270 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1272 if (!$oprofile instanceof Ostatus_profile) {
1276 $feed = $oprofile->feeduri;
1280 function onStartGetProfileFromURI($uri, &$profile)
1282 // Don't want to do Web-based discovery on our own server,
1283 // so we check locally first. This duplicates the functionality
1284 // in the Profile class, since the plugin always runs before
1285 // that local lookup, but since we return false it won't run double.
1287 $user = User::getKV('uri', $uri);
1288 if ($user instanceof User) {
1289 $profile = $user->getProfile();
1292 $group = User_group::getKV('uri', $uri);
1293 if ($group instanceof User_group) {
1294 $profile = $group->getProfile();
1299 // Now, check remotely
1301 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1302 $profile = $oprofile->localProfile();
1303 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1304 } catch (Exception $e) {
1305 return true; // It's not an OStatus profile as far as we know, continue event handling
1309 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1311 $author = $target->getProfile();
1312 $profiletype = $this->profileTypeString($author);
1313 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1314 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1318 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1320 if ($target->getObjectType() === ActivityObject::PERSON) {
1321 $this->addWebFingerPersonLinks($xrd, $target);
1325 $profiletype = $this->profileTypeString($target);
1326 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1328 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1330 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1331 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1332 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1334 // TODO - finalize where the redirect should go on the publisher
1335 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1336 common_local_url('ostatussub') . '?profile={uri}',
1337 null, // type not set
1338 true); // isTemplate
1343 protected function profileTypeString(Profile $target)
1345 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1346 switch ($target->getObjectType()) {
1347 case ActivityObject::PERSON:
1349 case ActivityObject::GROUP:
1352 throw new ServerException('Unknown profile type for WebFinger profile links');
1356 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1358 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1359 common_local_url('ApiTimelineUser',
1360 array('id' => $target->id, 'format' => 'atom')),
1361 'application/atom+xml');
1363 // Get this profile's keypair
1364 $magicsig = Magicsig::getKV('user_id', $target->id);
1365 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1366 $magicsig = Magicsig::generate($target->getUser());
1369 if (!$magicsig instanceof Magicsig) {
1370 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1372 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1373 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1374 'data:application/magic-public-key,'. $magicsig->toString());
1375 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1376 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1380 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1382 list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1385 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1386 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1389 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1390 $profile = $oprofile->checkAuthorship($activity);
1391 } catch (Exception $e) {
1392 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1399 public function onProfileDeleteRelated($profile, &$related)
1401 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1402 $related[] = 'Ostatus_profile';
1404 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1405 $magicsig = Magicsig::getKV('user_id', $profile->id);
1406 if ($magicsig instanceof Magicsig) {
1407 $magicsig->delete();
1412 public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1414 $envxml = $magic_env->toXML($target);
1416 $headers = array('Content-Type: application/magic-envelope+xml');
1419 $client = new HTTPClient();
1420 $client->setBody($envxml);
1421 $response = $client->post($endpoint_uri, $headers);
1422 } catch (Exception $e) {
1423 common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1426 if ($response->getStatus() === 422) {
1427 common_debug(sprintf('Salmon (from profile %d) endpoint %s returned status %s. We assume it is a Diaspora seed; will adapt and try again if that plugin is enabled!', $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus()));
1431 // 200 OK is the best response
1432 // 202 Accepted is what we get from Diaspora for example
1433 if (!in_array($response->getStatus(), array(200, 202))) {
1434 common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1435 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1439 // Since we completed the salmon slap, we discontinue the event
1443 public function onCronDaily()
1446 $sub = FeedSub::renewalCheck();
1447 } catch (NoResultException $e) {
1448 common_log(LOG_INFO, "There were no expiring feeds.");
1452 $qm = QueueManager::get();
1453 while ($sub->fetch()) {
1454 $item = array('feedsub_id' => $sub->id);
1455 $qm->enqueue($item, 'pushrenew');