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)
88 if (mb_substr($cls, 0, 10) === 'phpseclib\\') {
89 // These are saved under extlib/phpseclib with \ as /,
90 // phpseclib has already been added to our include_path
91 require_once str_replace('\\', '/', str_replace('phpseclib\\', '', $cls) . '.php');
95 return parent::onAutoload($cls);
99 * Set up queue handlers for outgoing hub pushes
100 * @param QueueManager $qm
101 * @return boolean hook return
103 function onEndInitializeQueueManager(QueueManager $qm)
105 // Prepare outgoing distributions after notice save.
106 $qm->connect('ostatus', 'OStatusQueueHandler');
108 // Outgoing from our internal PuSH hub
109 $qm->connect('hubconf', 'HubConfQueueHandler');
110 $qm->connect('hubprep', 'HubPrepQueueHandler');
112 $qm->connect('hubout', 'HubOutQueueHandler');
114 // Outgoing Salmon replies (when we don't need a return value)
115 $qm->connect('salmon', 'SalmonQueueHandler');
117 // Incoming from a foreign PuSH hub
118 $qm->connect('pushin', 'PushInQueueHandler');
120 // Re-subscribe feeds that need renewal
121 $qm->connect('pushrenew', 'PushRenewQueueHandler');
126 * Put saved notices into the queue for pubsub distribution.
128 function onStartEnqueueNotice($notice, &$transports)
130 if ($notice->inScope(null) && $notice->getProfile()->hasRight(Right::PUBLICNOTICE)) {
131 // put our transport first, in case there's any conflict (like OMB)
132 array_unshift($transports, 'ostatus');
133 $this->log(LOG_INFO, "OSTATUS [{$notice->getID()}]: queued for OStatus processing");
135 // FIXME: we don't do privacy-controlled OStatus updates yet.
136 // once that happens, finer grain of control here.
137 $this->log(LOG_NOTICE, "OSTATUS [{$notice->getID()}]: Not queueing because of privacy; scope = {$notice->scope}");
143 * Set up a PuSH hub link to our internal link for canonical timeline
144 * Atom feeds for users and groups.
146 function onStartApiAtom($feed)
150 if ($feed instanceof AtomUserNoticeFeed) {
151 $salmonAction = 'usersalmon';
152 $user = $feed->getUser();
154 $profile = $user->getProfile();
155 } else if ($feed instanceof AtomGroupNoticeFeed) {
156 $salmonAction = 'groupsalmon';
157 $group = $feed->getGroup();
159 } else if ($feed instanceof AtomListNoticeFeed) {
160 $salmonAction = 'peopletagsalmon';
161 $peopletag = $feed->getList();
162 $id = $peopletag->id;
168 $hub = common_config('ostatus', 'hub');
170 // Updates will be handled through our internal PuSH hub.
171 $hub = common_local_url('pushhub');
173 $feed->addLink($hub, array('rel' => 'hub'));
175 // Also, we'll add in the salmon link
176 $salmon = common_local_url($salmonAction, array('id' => $id));
177 $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));
179 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
180 $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
181 $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
188 * Add in an OStatus subscribe button
190 function onStartProfileRemoteSubscribe($output, $profile)
192 $this->onStartProfileListItemActionElements($output, $profile);
196 function onStartGroupSubscribe($widget, $group)
198 $cur = common_current_user();
201 $widget->out->elementStart('li', 'entity_subscribe');
203 $url = common_local_url('ostatusinit',
204 array('group' => $group->nickname));
205 $widget->out->element('a', array('href' => $url,
206 'class' => 'entity_remote_subscribe'),
207 // TRANS: Link to subscribe to a remote entity.
210 $widget->out->elementEnd('li');
217 function onStartSubscribePeopletagForm($output, $peopletag)
219 $cur = common_current_user();
222 $output->elementStart('li', 'entity_subscribe');
223 $profile = $peopletag->getTagger();
224 $url = common_local_url('ostatusinit',
225 array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
226 $output->element('a', array('href' => $url,
227 'class' => 'entity_remote_subscribe'),
228 // TRANS: Link to subscribe to a remote entity.
231 $output->elementEnd('li');
239 * If the field being looked for is URI look for the profile
241 function onStartProfileCompletionSearch($action, $profile, $search_engine) {
242 if ($action->field == 'uri') {
243 $profile->joinAdd(array('id', 'user:id'));
244 $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
247 $validate = new Validate();
249 if ($profile->N == 0) {
251 if ($validate->email($q)) {
252 $oprofile = Ostatus_profile::ensureWebfinger($q);
253 } else if ($validate->uri($q)) {
254 $oprofile = Ostatus_profile::ensureProfileURL($q);
256 // TRANS: Exception in OStatus when invalid URI was entered.
257 throw new Exception(_m('Invalid URI.'));
259 return $this->filter(array($oprofile->localProfile()));
261 } catch (Exception $e) {
262 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
263 // TRANS: and example.net, as these are official standard domain names for use in examples.
264 $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.");
274 * Find any explicit remote mentions. Accepted forms:
275 * Webfinger: @user@example.com
276 * Profile link: @example.com/mublog/user
277 * @param Profile $sender
278 * @param string $text input markup text
279 * @param array &$mention in/out param: set of found mentions
280 * @return boolean hook return value
282 function onEndFindMentions(Profile $sender, $text, &$mentions)
287 // Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
288 if (preg_match_all('!(?:^|\s+)@((?:\w+[\w\-\_\.]?)*(?:[\w\-\_\.]*\w+)@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
291 PREG_OFFSET_CAPTURE)) {
292 foreach ($wmatches[1] as $wmatch) {
293 list($target, $pos) = $wmatch;
294 $this->log(LOG_INFO, "Checking webfinger '$target'");
297 $oprofile = Ostatus_profile::ensureWebfinger($target);
298 if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
301 $profile = $oprofile->localProfile();
302 } catch (OStatusShadowException $e) {
303 // This means we got a local user in the webfinger lookup
304 $profile = $e->profile;
305 } catch (Exception $e) {
306 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
310 assert($profile instanceof Profile);
312 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
313 ? $profile->getNickname() // TODO: we could do getBestName() or getFullname() here
315 $url = $profile->getUri();
316 if (!common_valid_http_url($url)) {
317 $url = $profile->getUrl();
319 $matches[$pos] = array('mentioned' => array($profile),
323 'length' => mb_strlen($target),
328 // Profile matches: @example.com/mublog/user
329 if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)*)!',
332 PREG_OFFSET_CAPTURE)) {
333 foreach ($wmatches[1] as $wmatch) {
334 list($target, $pos) = $wmatch;
335 $schemes = array('http', 'https');
336 foreach ($schemes as $scheme) {
337 $url = "$scheme://$target";
338 $this->log(LOG_INFO, "Checking profile address '$url'");
340 $oprofile = Ostatus_profile::ensureProfileURL($url);
341 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
342 $profile = $oprofile->localProfile();
343 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
344 $profile->nickname : $target;
345 $matches[$pos] = array('mentioned' => array($profile),
349 'length' => mb_strlen($target),
350 'url' => $profile->getUrl());
353 } catch (Exception $e) {
354 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
360 foreach ($mentions as $i => $other) {
361 // If we share a common prefix with a local user, override it!
362 $pos = $other['position'];
363 if (isset($matches[$pos])) {
364 $mentions[$i] = $matches[$pos];
365 unset($matches[$pos]);
368 foreach ($matches as $mention) {
369 $mentions[] = $mention;
376 * Allow remote profile references to be used in commands:
377 * sub update@status.net
378 * whois evan@identi.ca
379 * reply http://identi.ca/evan hey what's up
381 * @param Command $command
383 * @param Profile &$profile
384 * @return hook return code
386 function onStartCommandGetProfile($command, $arg, &$profile)
388 $oprofile = $this->pullRemoteProfile($arg);
389 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
391 $profile = $oprofile->localProfile();
392 } catch (NoProfileException $e) {
393 // No locally stored profile found for remote profile
403 * Allow remote group references to be used in commands:
404 * join group+statusnet@identi.ca
405 * join http://identi.ca/group/statusnet
406 * drop identi.ca/group/statusnet
408 * @param Command $command
410 * @param User_group &$group
411 * @return hook return code
413 function onStartCommandGetGroup($command, $arg, &$group)
415 $oprofile = $this->pullRemoteProfile($arg);
416 if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
417 $group = $oprofile->localGroup();
424 protected function pullRemoteProfile($arg)
427 if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
430 return Ostatus_profile::ensureWebfinger($arg);
431 } catch (Exception $e) {
432 common_log(LOG_ERR, 'Webfinger lookup failed for ' .
433 $arg . ': ' . $e->getMessage());
437 // Look for profile URLs, with or without scheme:
439 if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
442 if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
443 $schemes = array('http', 'https');
444 foreach ($schemes as $scheme) {
445 $urls[] = "$scheme://$arg";
449 foreach ($urls as $url) {
451 return Ostatus_profile::ensureProfileURL($url);
452 } catch (Exception $e) {
453 common_log(LOG_ERR, 'Profile lookup failed for ' .
454 $arg . ': ' . $e->getMessage());
460 function onEndProfileSettingsActions($out) {
461 $siteName = common_config('site', 'name');
462 $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
463 $out->elementStart('li');
465 array('href' => 'javascript:'.$js),
466 // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
467 _('Add to Firefox as feedreader'));
468 $out->elementEnd('li');
472 * Make sure necessary tables are filled out.
474 function onCheckSchema() {
475 $schema = Schema::get();
476 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
477 $schema->ensureTable('feedsub', FeedSub::schemaDef());
478 $schema->ensureTable('hubsub', HubSub::schemaDef());
479 $schema->ensureTable('magicsig', Magicsig::schemaDef());
483 public function onEndShowStylesheets(Action $action) {
484 $action->cssLink($this->path('theme/base/css/ostatus.css'));
488 function onEndShowStatusNetScripts($action) {
489 $action->script($this->path('js/ostatus.js'));
494 * Override the "from ostatus" bit in notice lists to link to the
495 * original post and show the domain it came from.
497 * @param Notice in $notice
498 * @param string out &$name
499 * @param string out &$url
500 * @param string out &$title
501 * @return mixed hook return code
503 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
505 // If we don't handle this, keep the event handler going
506 if (!in_array($notice->source, array('ostatus', 'share'))) {
511 $url = $notice->getUrl();
512 // If getUrl() throws exception, $url is never set
514 $bits = parse_url($url);
515 $domain = $bits['host'];
516 if (substr($domain, 0, 4) == 'www.') {
517 $name = substr($domain, 4);
522 // TRANS: Title. %s is a domain name.
523 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
525 // Abort event handler, we have a name and URL!
527 } catch (InvalidUrlException $e) {
528 // This just means we don't have the notice source data
534 * Send incoming PuSH feeds for OStatus endpoints in for processing.
536 * @param FeedSub $feedsub
537 * @param DOMDocument $feed
538 * @return mixed hook return code
540 function onStartFeedSubReceive($feedsub, $feed)
542 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
543 if ($oprofile instanceof Ostatus_profile) {
544 $oprofile->processFeed($feed, 'push');
546 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
551 * Tell the FeedSub infrastructure whether we have any active OStatus
552 * usage for the feed; if not it'll be able to garbage-collect the
555 * @param FeedSub $feedsub
556 * @param integer $count in/out
557 * @return mixed hook return code
559 function onFeedSubSubscriberCount($feedsub, &$count)
561 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
562 if ($oprofile instanceof Ostatus_profile) {
563 $count += $oprofile->subscriberCount();
569 * When about to subscribe to a remote user, start a server-to-server
570 * PuSH subscription if needed. If we can't establish that, abort.
572 * @fixme If something else aborts later, we could end up with a stray
573 * PuSH subscription. This is relatively harmless, though.
575 * @param Profile $profile subscriber
576 * @param Profile $other subscribee
578 * @return hook return code
582 function onStartSubscribe(Profile $profile, Profile $other)
584 if (!$profile->isLocal()) {
588 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
589 if (!$oprofile instanceof Ostatus_profile) {
593 $oprofile->subscribe();
597 * Having established a remote subscription, send a notification to the
598 * remote OStatus profile's endpoint.
600 * @param Profile $profile subscriber
601 * @param Profile $other subscribee
603 * @return hook return code
607 function onEndSubscribe(Profile $profile, Profile $other)
609 if (!$profile->isLocal()) {
613 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
614 if (!$oprofile instanceof Ostatus_profile) {
618 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
619 'subscribed' => $other->id));
621 $act = $sub->asActivity();
623 $oprofile->notifyActivity($act, $profile);
629 * Notify remote server and garbage collect unused feeds on unsubscribe.
630 * @todo FIXME: Send these operations to background queues
633 * @param Profile $other
634 * @return hook return value
636 function onEndUnsubscribe(Profile $profile, Profile $other)
638 if (!$profile->isLocal()) {
642 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
643 if (!$oprofile instanceof Ostatus_profile) {
647 // Drop the PuSH subscription if there are no other subscribers.
648 $oprofile->garbageCollect();
650 $act = new Activity();
652 $act->verb = ActivityVerb::UNFOLLOW;
654 $act->id = TagURI::mint('unfollow:%d:%d:%s',
657 common_date_iso8601(time()));
660 // TRANS: Title for unfollowing a remote profile.
661 $act->title = _m('TITLE','Unfollow');
662 // TRANS: Success message for unsubscribe from user attempt through OStatus.
663 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
664 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
665 $profile->getBestName(),
666 $other->getBestName());
668 $act->actor = $profile->asActivityObject();
669 $act->objects[] = $other->asActivityObject();
671 $oprofile->notifyActivity($act, $profile);
677 * When one of our local users tries to join a remote group,
678 * notify the remote server. If the notification is rejected,
681 * @param User_group $group
682 * @param Profile $profile
684 * @return mixed hook return value
685 * @throws Exception of various kinds, some from $oprofile->subscribe();
687 function onStartJoinGroup($group, $profile)
689 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
690 if (!$oprofile instanceof Ostatus_profile) {
694 $oprofile->subscribe();
696 // NOTE: we don't use Group_member::asActivity() since that record
697 // has not yet been created.
699 $act = new Activity();
700 $act->id = TagURI::mint('join:%d:%d:%s',
703 common_date_iso8601(time()));
705 $act->actor = $profile->asActivityObject();
706 $act->verb = ActivityVerb::JOIN;
707 $act->objects[] = $oprofile->asActivityObject();
710 // TRANS: Title for joining a remote groep.
711 $act->title = _m('TITLE','Join');
712 // TRANS: Success message for subscribe to group attempt through OStatus.
713 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
714 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
715 $profile->getBestName(),
716 $oprofile->getBestName());
718 if ($oprofile->notifyActivity($act, $profile)) {
721 $oprofile->garbageCollect();
722 // TRANS: Exception thrown when joining a remote group fails.
723 throw new Exception(_m('Failed joining remote group.'));
728 * When one of our local users leaves a remote group, notify the remote
731 * @fixme Might be good to schedule a resend of the leave notification
732 * if it failed due to a transitory error. We've canceled the local
733 * membership already anyway, but if the remote server comes back up
734 * it'll be left with a stray membership record.
736 * @param User_group $group
737 * @param Profile $profile
739 * @return mixed hook return value
741 function onEndLeaveGroup($group, $profile)
743 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
744 if (!$oprofile instanceof Ostatus_profile) {
748 // Drop the PuSH subscription if there are no other subscribers.
749 $oprofile->garbageCollect();
753 $act = new Activity();
754 $act->id = TagURI::mint('leave:%d:%d:%s',
757 common_date_iso8601(time()));
759 $act->actor = $member->asActivityObject();
760 $act->verb = ActivityVerb::LEAVE;
761 $act->objects[] = $oprofile->asActivityObject();
764 // TRANS: Title for leaving a remote group.
765 $act->title = _m('TITLE','Leave');
766 // TRANS: Success message for unsubscribe from group attempt through OStatus.
767 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
768 $act->content = sprintf(_m('%1$s has left group %2$s.'),
769 $member->getBestName(),
770 $oprofile->getBestName());
772 $oprofile->notifyActivity($act, $member);
776 * When one of our local users tries to subscribe to a remote peopletag,
777 * notify the remote server. If the notification is rejected,
778 * deny the subscription.
780 * @param Profile_list $peopletag
783 * @return mixed hook return value
784 * @throws Exception of various kinds, some from $oprofile->subscribe();
787 function onStartSubscribePeopletag($peopletag, $user)
789 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
790 if (!$oprofile instanceof Ostatus_profile) {
794 $oprofile->subscribe();
796 $sub = $user->getProfile();
797 $tagger = Profile::getKV($peopletag->tagger);
799 $act = new Activity();
800 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
803 common_date_iso8601(time()));
805 $act->actor = $sub->asActivityObject();
806 $act->verb = ActivityVerb::FOLLOW;
807 $act->objects[] = $oprofile->asActivityObject();
810 // TRANS: Title for following a remote list.
811 $act->title = _m('TITLE','Follow list');
812 // TRANS: Success message for remote list follow through OStatus.
813 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
814 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
816 $oprofile->getBestName(),
817 $tagger->getBestName());
819 if ($oprofile->notifyActivity($act, $sub)) {
822 $oprofile->garbageCollect();
823 // TRANS: Exception thrown when subscription to remote list fails.
824 throw new Exception(_m('Failed subscribing to remote list.'));
829 * When one of our local users unsubscribes to a remote peopletag, notify the remote
832 * @param Profile_list $peopletag
835 * @return mixed hook return value
838 function onEndUnsubscribePeopletag($peopletag, $user)
840 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
841 if (!$oprofile instanceof Ostatus_profile) {
845 // Drop the PuSH subscription if there are no other subscribers.
846 $oprofile->garbageCollect();
848 $sub = Profile::getKV($user->id);
849 $tagger = Profile::getKV($peopletag->tagger);
851 $act = new Activity();
852 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
855 common_date_iso8601(time()));
857 $act->actor = $member->asActivityObject();
858 $act->verb = ActivityVerb::UNFOLLOW;
859 $act->objects[] = $oprofile->asActivityObject();
862 // TRANS: Title for unfollowing a remote list.
863 $act->title = _m('Unfollow list');
864 // TRANS: Success message for remote list unfollow through OStatus.
865 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
866 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
868 $oprofile->getBestName(),
869 $tagger->getBestName());
871 $oprofile->notifyActivity($act, $user);
875 * Notify remote users when their notices get favorited.
877 * @param Profile or User $profile of local user doing the faving
878 * @param Notice $notice being favored
879 * @return hook return value
881 function onEndFavorNotice(Profile $profile, Notice $notice)
883 // Only distribute local users' favor actions, remote users
884 // will have already distributed theirs.
885 if (!$profile->isLocal()) {
889 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
890 if (!$oprofile instanceof Ostatus_profile) {
894 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
895 'notice_id' => $notice->id));
897 if (!$fav instanceof Fave) {
899 // TODO: Make pkeyGet throw exception, since this is a critical failure.
903 $act = $fav->asActivity();
905 $oprofile->notifyActivity($act, $profile);
911 * Notify remote user it has got a new people tag
912 * - tag verb is queued
913 * - the subscription is done immediately if not present
915 * @param Profile_tag $ptag the people tag that was created
916 * @return hook return value
917 * @throws Exception of various kinds, some from $oprofile->subscribe();
919 function onEndTagProfile($ptag)
921 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
922 if (!$oprofile instanceof Ostatus_profile) {
926 $plist = $ptag->getMeta();
927 if ($plist->private) {
931 $act = new Activity();
933 $tagger = $plist->getTagger();
934 $tagged = Profile::getKV('id', $ptag->tagged);
936 $act->verb = ActivityVerb::TAG;
937 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
938 $plist->tagger, $plist->id,
939 common_date_iso8601(time()));
941 // TRANS: Title for listing a remote profile.
942 $act->title = _m('TITLE','List');
943 // TRANS: Success message for remote list addition through OStatus.
944 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
945 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
946 $tagger->getBestName(),
947 $tagged->getBestName(),
948 $plist->getBestName());
950 $act->actor = $tagger->asActivityObject();
951 $act->objects = array($tagged->asActivityObject());
952 $act->target = ActivityObject::fromPeopletag($plist);
954 $oprofile->notifyDeferred($act, $tagger);
956 // initiate a PuSH subscription for the person being tagged
957 $oprofile->subscribe();
962 * Notify remote user that a people tag has been removed
963 * - untag verb is queued
964 * - the subscription is undone immediately if not required
965 * i.e garbageCollect()'d
967 * @param Profile_tag $ptag the people tag that was deleted
968 * @return hook return value
970 function onEndUntagProfile($ptag)
972 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
973 if (!$oprofile instanceof Ostatus_profile) {
977 $plist = $ptag->getMeta();
978 if ($plist->private) {
982 $act = new Activity();
984 $tagger = $plist->getTagger();
985 $tagged = Profile::getKV('id', $ptag->tagged);
987 $act->verb = ActivityVerb::UNTAG;
988 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
989 $plist->tagger, $plist->id,
990 common_date_iso8601(time()));
992 // TRANS: Title for unlisting a remote profile.
993 $act->title = _m('TITLE','Unlist');
994 // TRANS: Success message for remote list removal through OStatus.
995 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
996 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
997 $tagger->getBestName(),
998 $tagged->getBestName(),
999 $plist->getBestName());
1001 $act->actor = $tagger->asActivityObject();
1002 $act->objects = array($tagged->asActivityObject());
1003 $act->target = ActivityObject::fromPeopletag($plist);
1005 $oprofile->notifyDeferred($act, $tagger);
1007 // unsubscribe to PuSH feed if no more required
1008 $oprofile->garbageCollect();
1014 * Notify remote users when their notices get de-favorited.
1016 * @param Profile $profile Profile person doing the de-faving
1017 * @param Notice $notice Notice being favored
1019 * @return hook return value
1021 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1023 // Only distribute local users' disfavor actions, remote users
1024 // will have already distributed theirs.
1025 if (!$profile->isLocal()) {
1029 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1030 if (!$oprofile instanceof Ostatus_profile) {
1034 $act = new Activity();
1036 $act->verb = ActivityVerb::UNFAVORITE;
1037 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1040 common_date_iso8601(time()));
1041 $act->time = time();
1042 // TRANS: Title for unliking a remote notice.
1043 $act->title = _m('Unlike');
1044 // TRANS: Success message for remove a favorite notice through OStatus.
1045 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1046 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1047 $profile->getBestName(),
1050 $act->actor = $profile->asActivityObject();
1051 $act->objects[] = $notice->asActivityObject();
1053 $oprofile->notifyActivity($act, $profile);
1058 function onStartGetProfileUri($profile, &$uri)
1060 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1061 if ($oprofile instanceof Ostatus_profile) {
1062 $uri = $oprofile->uri;
1068 function onStartUserGroupHomeUrl($group, &$url)
1070 return $this->onStartUserGroupPermalink($group, $url);
1073 function onStartUserGroupPermalink($group, &$url)
1075 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1076 if ($oprofile instanceof Ostatus_profile) {
1077 // @fixme this should probably be in the user_group table
1078 // @fixme this uri not guaranteed to be a profile page
1079 $url = $oprofile->uri;
1084 function onStartShowSubscriptionsContent($action)
1086 $this->showEntityRemoteSubscribe($action);
1091 function onStartShowUserGroupsContent($action)
1093 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1098 function onEndShowSubscriptionsMiniList($action)
1100 $this->showEntityRemoteSubscribe($action);
1105 function onEndShowGroupsMiniList($action)
1107 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1112 function showEntityRemoteSubscribe($action, $target='ostatussub')
1114 if (!$action->getScoped() instanceof Profile) {
1115 // early return if we're not logged in
1119 if ($action->getScoped()->sameAs($action->getTarget())) {
1120 $action->elementStart('div', 'entity_actions');
1121 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1122 'class' => 'entity_subscribe'));
1123 $action->element('a', array('href' => common_local_url($target),
1124 'class' => 'entity_remote_subscribe'),
1125 // TRANS: Link text for link to remote subscribe.
1127 $action->elementEnd('p');
1128 $action->elementEnd('div');
1133 * Ping remote profiles with updates to this profile.
1134 * Salmon pings are queued for background processing.
1136 function onEndBroadcastProfile(Profile $profile)
1138 $user = User::getKV('id', $profile->id);
1140 // Find foreign accounts I'm subscribed to that support Salmon pings.
1142 // @fixme we could run updates through the PuSH feed too,
1143 // in which case we can skip Salmon pings to folks who
1144 // are also subscribed to me.
1145 $sql = "SELECT * FROM ostatus_profile " .
1146 "WHERE profile_id IN " .
1147 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1149 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1150 $oprofile = new Ostatus_profile();
1151 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1153 if ($oprofile->N == 0) {
1154 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1158 $act = new Activity();
1160 $act->verb = ActivityVerb::UPDATE_PROFILE;
1161 $act->id = TagURI::mint('update-profile:%d:%s',
1163 common_date_iso8601(time()));
1164 $act->time = time();
1165 // TRANS: Title for activity.
1166 $act->title = _m('Profile update');
1167 // TRANS: Ping text for remote profile update through OStatus.
1168 // TRANS: %s is user that updated their profile.
1169 $act->content = sprintf(_m('%s has updated their profile page.'),
1170 $profile->getBestName());
1172 $act->actor = $profile->asActivityObject();
1173 $act->objects[] = $act->actor;
1175 while ($oprofile->fetch()) {
1176 $oprofile->notifyDeferred($act, $profile);
1182 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1183 function onStartProfileListItemActionElements($item)
1185 if (common_logged_in()) {
1186 // only non-logged in users get to see the "remote subscribe" form
1188 } elseif (!$item->getTarget()->isLocal()) {
1189 // we can (for now) only provide remote subscribe forms for local users
1193 if ($item instanceof ProfileAction) {
1195 } elseif ($item instanceof Widget) {
1196 $output = $item->out;
1198 // Bad $item class, don't know how to use this for outputting!
1199 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1202 // Add an OStatus subscribe
1203 $output->elementStart('li', 'entity_subscribe');
1204 $url = common_local_url('ostatusinit',
1205 array('nickname' => $item->getTarget()->getNickname()));
1206 $output->element('a', array('href' => $url,
1207 'class' => 'entity_remote_subscribe'),
1208 // TRANS: Link text for a user to subscribe to an OStatus user.
1210 $output->elementEnd('li');
1212 $output->elementStart('li', 'entity_tag');
1213 $url = common_local_url('ostatustag',
1214 array('nickname' => $item->getTarget()->getNickname()));
1215 $output->element('a', array('href' => $url,
1216 'class' => 'entity_remote_tag'),
1217 // TRANS: Link text for a user to list an OStatus user.
1219 $output->elementEnd('li');
1224 function onPluginVersion(array &$versions)
1226 $versions[] = array('name' => 'OStatus',
1227 'version' => GNUSOCIAL_VERSION,
1228 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1229 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/OStatus',
1230 // TRANS: Plugin description.
1231 'rawdescription' => _m('Follow people across social networks that implement '.
1232 '<a href="http://ostatus.org/">OStatus</a>.'));
1238 * Utility function to check if the given URI is a canonical group profile
1239 * page, and if so return the ID number.
1241 * @param string $url
1242 * @return mixed int or false
1244 public static function localGroupFromUrl($url)
1246 $group = User_group::getKV('uri', $url);
1247 if ($group instanceof User_group) {
1248 if ($group->isLocal()) {
1252 // To find local groups which haven't had their uri fields filled out...
1253 // If the domain has changed since a subscriber got the URI, it'll
1255 $template = common_local_url('groupbyid', array('id' => '31337'));
1256 $template = preg_quote($template, '/');
1257 $template = str_replace('31337', '(\d+)', $template);
1258 if (preg_match("/$template/", $url, $matches)) {
1259 return intval($matches[1]);
1265 public function onStartProfileGetAtomFeed($profile, &$feed)
1267 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1269 if (!$oprofile instanceof Ostatus_profile) {
1273 $feed = $oprofile->feeduri;
1277 function onStartGetProfileFromURI($uri, &$profile)
1279 // Don't want to do Web-based discovery on our own server,
1280 // so we check locally first. This duplicates the functionality
1281 // in the Profile class, since the plugin always runs before
1282 // that local lookup, but since we return false it won't run double.
1284 $user = User::getKV('uri', $uri);
1285 if ($user instanceof User) {
1286 $profile = $user->getProfile();
1289 $group = User_group::getKV('uri', $uri);
1290 if ($group instanceof User_group) {
1291 $profile = $group->getProfile();
1296 // Now, check remotely
1298 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1299 $profile = $oprofile->localProfile();
1300 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1301 } catch (Exception $e) {
1302 return true; // It's not an OStatus profile as far as we know, continue event handling
1306 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1309 $actor = $target->getProfile();
1310 if ($actor->isLocal()) {
1311 $profiletype = $this->profileTypeString($actor);
1312 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $actor->getID()));
1315 $oprofile = Ostatus_profile::fromProfile($actor);
1316 $salmon_url = $oprofile->salmonuri;
1317 } catch (Exception $e) {
1318 // Even though it's not a local user, we couldn't get an Ostatus_profile?!
1321 // Ostatus_profile salmon URL may be empty
1322 if (!empty($salmon_url)) {
1323 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1328 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1330 if ($target->getObjectType() === ActivityObject::PERSON) {
1331 $this->addWebFingerPersonLinks($xrd, $target);
1335 $profiletype = $this->profileTypeString($target);
1336 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1338 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1340 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1341 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1342 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1344 // TODO - finalize where the redirect should go on the publisher
1345 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1346 common_local_url('ostatussub') . '?profile={uri}',
1347 null, // type not set
1348 true); // isTemplate
1353 protected function profileTypeString(Profile $target)
1355 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1356 switch ($target->getObjectType()) {
1357 case ActivityObject::PERSON:
1359 case ActivityObject::GROUP:
1362 throw new ServerException('Unknown profile type for WebFinger profile links');
1366 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1368 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1369 common_local_url('ApiTimelineUser',
1370 array('id' => $target->id, 'format' => 'atom')),
1371 'application/atom+xml');
1373 // Get this profile's keypair
1374 $magicsig = Magicsig::getKV('user_id', $target->id);
1375 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1376 $magicsig = Magicsig::generate($target->getUser());
1379 if (!$magicsig instanceof Magicsig) {
1380 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1382 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1383 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1384 'data:application/magic-public-key,'. $magicsig->toString());
1385 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1386 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1390 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1392 list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1395 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1396 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1399 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1400 $profile = $oprofile->checkAuthorship($activity);
1401 } catch (Exception $e) {
1402 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1409 public function onProfileDeleteRelated($profile, &$related)
1411 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1412 $related[] = 'Ostatus_profile';
1414 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1415 $magicsig = Magicsig::getKV('user_id', $profile->id);
1416 if ($magicsig instanceof Magicsig) {
1417 $magicsig->delete();
1422 public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1424 $envxml = $magic_env->toXML($target);
1426 $headers = array('Content-Type: application/magic-envelope+xml');
1429 $client = new HTTPClient();
1430 $client->setBody($envxml);
1431 $response = $client->post($endpoint_uri, $headers);
1432 } catch (Exception $e) {
1433 common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1436 if ($response->getStatus() === 422) {
1437 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()));
1441 // 200 OK is the best response
1442 // 202 Accepted is what we get from Diaspora for example
1443 if (!in_array($response->getStatus(), array(200, 202))) {
1444 common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1445 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1449 // Since we completed the salmon slap, we discontinue the event
1453 public function onCronDaily()
1456 $sub = FeedSub::renewalCheck();
1457 } catch (NoResultException $e) {
1458 common_log(LOG_INFO, "There were no expiring feeds.");
1462 $qm = QueueManager::get();
1463 while ($sub->fetch()) {
1464 $item = array('feedsub_id' => $sub->id);
1465 $qm->enqueue($item, 'pushrenew');