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 * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
278 * @return array The matching IDs (without @ or acct:) and each respective position in the given string.
280 static function extractWebfingerIds($text)
283 $result = preg_match_all('/(?:^|\s+)@((?:\w+[\w\-\_\.]?)*(?:[\w\-\_\.]*\w+)@'.URL_REGEX_DOMAIN_NAME.')/',
286 PREG_OFFSET_CAPTURE);
287 if ($result === false) {
288 common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').');
290 common_debug(sprintf('Found %i matches for WebFinger IDs: %s', count($wmatches), _ve($wmatches)));
296 * Profile URL matches: @example.com/mublog/user
298 * @return array The matching URLs (without @ or acct:) and each respective position in the given string.
300 static function extractUrlMentions($text)
303 // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
304 // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
305 $result = preg_match_all('/(?:^|\s+)@('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/',
308 PREG_OFFSET_CAPTURE);
309 if ($result === false) {
310 common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').');
312 common_debug(sprintf('Found %i matches for profile URL mentions: %s', count($wmatches), _ve($wmatches)));
318 * Find any explicit remote mentions. Accepted forms:
319 * Webfinger: @user@example.com
320 * Profile link: @example.com/mublog/user
321 * @param Profile $sender
322 * @param string $text input markup text
323 * @param array &$mention in/out param: set of found mentions
324 * @return boolean hook return value
326 function onEndFindMentions(Profile $sender, $text, &$mentions)
330 foreach (self::extractWebfingerIds($text) as $wmatch) {
331 list($target, $pos) = $wmatch;
332 $this->log(LOG_INFO, "Checking webfinger '$target'");
335 $oprofile = Ostatus_profile::ensureWebfinger($target);
336 if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
339 $profile = $oprofile->localProfile();
340 } catch (OStatusShadowException $e) {
341 // This means we got a local user in the webfinger lookup
342 $profile = $e->profile;
343 } catch (Exception $e) {
344 $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
348 assert($profile instanceof Profile);
350 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
351 ? $profile->getNickname() // TODO: we could do getBestName() or getFullname() here
353 $url = $profile->getUri();
354 if (!common_valid_http_url($url)) {
355 $url = $profile->getUrl();
357 $matches[$pos] = array('mentioned' => array($profile),
361 'length' => mb_strlen($target),
365 foreach (self::extractUrlMentions($text) as $wmatch) {
366 list($target, $pos) = $wmatch;
367 $schemes = array('http', 'https');
368 foreach ($schemes as $scheme) {
369 $url = "$scheme://$target";
370 $this->log(LOG_INFO, "Checking profile address '$url'");
372 $oprofile = Ostatus_profile::ensureProfileURL($url);
373 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
374 $profile = $oprofile->localProfile();
375 $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
376 $profile->nickname : $target;
377 $matches[$pos] = array('mentioned' => array($profile),
381 'length' => mb_strlen($target),
382 'url' => $profile->getUrl());
385 } catch (Exception $e) {
386 $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
391 foreach ($mentions as $i => $other) {
392 // If we share a common prefix with a local user, override it!
393 $pos = $other['position'];
394 if (isset($matches[$pos])) {
395 $mentions[$i] = $matches[$pos];
396 unset($matches[$pos]);
399 foreach ($matches as $mention) {
400 $mentions[] = $mention;
407 * Allow remote profile references to be used in commands:
408 * sub update@status.net
409 * whois evan@identi.ca
410 * reply http://identi.ca/evan hey what's up
412 * @param Command $command
414 * @param Profile &$profile
415 * @return hook return code
417 function onStartCommandGetProfile($command, $arg, &$profile)
419 $oprofile = $this->pullRemoteProfile($arg);
420 if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
422 $profile = $oprofile->localProfile();
423 } catch (NoProfileException $e) {
424 // No locally stored profile found for remote profile
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 instanceof Ostatus_profile && $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());
491 function onEndProfileSettingsActions($out) {
492 $siteName = common_config('site', 'name');
493 $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
494 $out->elementStart('li');
496 array('href' => 'javascript:'.$js),
497 // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
498 _('Add to Firefox as feedreader'));
499 $out->elementEnd('li');
503 * Make sure necessary tables are filled out.
505 function onCheckSchema() {
506 $schema = Schema::get();
507 $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
508 $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
509 $schema->ensureTable('feedsub', FeedSub::schemaDef());
510 $schema->ensureTable('hubsub', HubSub::schemaDef());
511 $schema->ensureTable('magicsig', Magicsig::schemaDef());
515 public function onEndShowStylesheets(Action $action) {
516 $action->cssLink($this->path('theme/base/css/ostatus.css'));
520 function onEndShowStatusNetScripts($action) {
521 $action->script($this->path('js/ostatus.js'));
526 * Override the "from ostatus" bit in notice lists to link to the
527 * original post and show the domain it came from.
529 * @param Notice in $notice
530 * @param string out &$name
531 * @param string out &$url
532 * @param string out &$title
533 * @return mixed hook return code
535 function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
537 // If we don't handle this, keep the event handler going
538 if (!in_array($notice->source, array('ostatus', 'share'))) {
543 $url = $notice->getUrl();
544 // If getUrl() throws exception, $url is never set
546 $bits = parse_url($url);
547 $domain = $bits['host'];
548 if (substr($domain, 0, 4) == 'www.') {
549 $name = substr($domain, 4);
554 // TRANS: Title. %s is a domain name.
555 $title = sprintf(_m('Sent from %s via OStatus'), $domain);
557 // Abort event handler, we have a name and URL!
559 } catch (InvalidUrlException $e) {
560 // This just means we don't have the notice source data
566 * Send incoming PuSH feeds for OStatus endpoints in for processing.
568 * @param FeedSub $feedsub
569 * @param DOMDocument $feed
570 * @return mixed hook return code
572 function onStartFeedSubReceive($feedsub, $feed)
574 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
575 if ($oprofile instanceof Ostatus_profile) {
576 $oprofile->processFeed($feed, 'push');
578 common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
583 * Tell the FeedSub infrastructure whether we have any active OStatus
584 * usage for the feed; if not it'll be able to garbage-collect the
587 * @param FeedSub $feedsub
588 * @param integer $count in/out
589 * @return mixed hook return code
591 function onFeedSubSubscriberCount($feedsub, &$count)
593 $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
594 if ($oprofile instanceof Ostatus_profile) {
595 $count += $oprofile->subscriberCount();
601 * When about to subscribe to a remote user, start a server-to-server
602 * PuSH subscription if needed. If we can't establish that, abort.
604 * @fixme If something else aborts later, we could end up with a stray
605 * PuSH subscription. This is relatively harmless, though.
607 * @param Profile $profile subscriber
608 * @param Profile $other subscribee
610 * @return hook return code
614 function onStartSubscribe(Profile $profile, Profile $other)
616 if (!$profile->isLocal()) {
620 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
621 if (!$oprofile instanceof Ostatus_profile) {
625 $oprofile->subscribe();
629 * Having established a remote subscription, send a notification to the
630 * remote OStatus profile's endpoint.
632 * @param Profile $profile subscriber
633 * @param Profile $other subscribee
635 * @return hook return code
639 function onEndSubscribe(Profile $profile, Profile $other)
641 if (!$profile->isLocal()) {
645 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
646 if (!$oprofile instanceof Ostatus_profile) {
650 $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
651 'subscribed' => $other->id));
653 $act = $sub->asActivity();
655 $oprofile->notifyActivity($act, $profile);
661 * Notify remote server and garbage collect unused feeds on unsubscribe.
662 * @todo FIXME: Send these operations to background queues
665 * @param Profile $other
666 * @return hook return value
668 function onEndUnsubscribe(Profile $profile, Profile $other)
670 if (!$profile->isLocal()) {
674 $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
675 if (!$oprofile instanceof Ostatus_profile) {
679 // Drop the PuSH subscription if there are no other subscribers.
680 $oprofile->garbageCollect();
682 $act = new Activity();
684 $act->verb = ActivityVerb::UNFOLLOW;
686 $act->id = TagURI::mint('unfollow:%d:%d:%s',
689 common_date_iso8601(time()));
692 // TRANS: Title for unfollowing a remote profile.
693 $act->title = _m('TITLE','Unfollow');
694 // TRANS: Success message for unsubscribe from user attempt through OStatus.
695 // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
696 $act->content = sprintf(_m('%1$s stopped following %2$s.'),
697 $profile->getBestName(),
698 $other->getBestName());
700 $act->actor = $profile->asActivityObject();
701 $act->objects[] = $other->asActivityObject();
703 $oprofile->notifyActivity($act, $profile);
709 * When one of our local users tries to join a remote group,
710 * notify the remote server. If the notification is rejected,
713 * @param User_group $group
714 * @param Profile $profile
716 * @return mixed hook return value
717 * @throws Exception of various kinds, some from $oprofile->subscribe();
719 function onStartJoinGroup($group, $profile)
721 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
722 if (!$oprofile instanceof Ostatus_profile) {
726 $oprofile->subscribe();
728 // NOTE: we don't use Group_member::asActivity() since that record
729 // has not yet been created.
731 $act = new Activity();
732 $act->id = TagURI::mint('join:%d:%d:%s',
735 common_date_iso8601(time()));
737 $act->actor = $profile->asActivityObject();
738 $act->verb = ActivityVerb::JOIN;
739 $act->objects[] = $oprofile->asActivityObject();
742 // TRANS: Title for joining a remote groep.
743 $act->title = _m('TITLE','Join');
744 // TRANS: Success message for subscribe to group attempt through OStatus.
745 // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
746 $act->content = sprintf(_m('%1$s has joined group %2$s.'),
747 $profile->getBestName(),
748 $oprofile->getBestName());
750 if ($oprofile->notifyActivity($act, $profile)) {
753 $oprofile->garbageCollect();
754 // TRANS: Exception thrown when joining a remote group fails.
755 throw new Exception(_m('Failed joining remote group.'));
760 * When one of our local users leaves a remote group, notify the remote
763 * @fixme Might be good to schedule a resend of the leave notification
764 * if it failed due to a transitory error. We've canceled the local
765 * membership already anyway, but if the remote server comes back up
766 * it'll be left with a stray membership record.
768 * @param User_group $group
769 * @param Profile $profile
771 * @return mixed hook return value
773 function onEndLeaveGroup($group, $profile)
775 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
776 if (!$oprofile instanceof Ostatus_profile) {
780 // Drop the PuSH subscription if there are no other subscribers.
781 $oprofile->garbageCollect();
785 $act = new Activity();
786 $act->id = TagURI::mint('leave:%d:%d:%s',
789 common_date_iso8601(time()));
791 $act->actor = $member->asActivityObject();
792 $act->verb = ActivityVerb::LEAVE;
793 $act->objects[] = $oprofile->asActivityObject();
796 // TRANS: Title for leaving a remote group.
797 $act->title = _m('TITLE','Leave');
798 // TRANS: Success message for unsubscribe from group attempt through OStatus.
799 // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
800 $act->content = sprintf(_m('%1$s has left group %2$s.'),
801 $member->getBestName(),
802 $oprofile->getBestName());
804 $oprofile->notifyActivity($act, $member);
808 * When one of our local users tries to subscribe to a remote peopletag,
809 * notify the remote server. If the notification is rejected,
810 * deny the subscription.
812 * @param Profile_list $peopletag
815 * @return mixed hook return value
816 * @throws Exception of various kinds, some from $oprofile->subscribe();
819 function onStartSubscribePeopletag($peopletag, $user)
821 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
822 if (!$oprofile instanceof Ostatus_profile) {
826 $oprofile->subscribe();
828 $sub = $user->getProfile();
829 $tagger = Profile::getKV($peopletag->tagger);
831 $act = new Activity();
832 $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
835 common_date_iso8601(time()));
837 $act->actor = $sub->asActivityObject();
838 $act->verb = ActivityVerb::FOLLOW;
839 $act->objects[] = $oprofile->asActivityObject();
842 // TRANS: Title for following a remote list.
843 $act->title = _m('TITLE','Follow list');
844 // TRANS: Success message for remote list follow through OStatus.
845 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
846 $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
848 $oprofile->getBestName(),
849 $tagger->getBestName());
851 if ($oprofile->notifyActivity($act, $sub)) {
854 $oprofile->garbageCollect();
855 // TRANS: Exception thrown when subscription to remote list fails.
856 throw new Exception(_m('Failed subscribing to remote list.'));
861 * When one of our local users unsubscribes to a remote peopletag, notify the remote
864 * @param Profile_list $peopletag
867 * @return mixed hook return value
870 function onEndUnsubscribePeopletag($peopletag, $user)
872 $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
873 if (!$oprofile instanceof Ostatus_profile) {
877 // Drop the PuSH subscription if there are no other subscribers.
878 $oprofile->garbageCollect();
880 $sub = Profile::getKV($user->id);
881 $tagger = Profile::getKV($peopletag->tagger);
883 $act = new Activity();
884 $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
887 common_date_iso8601(time()));
889 $act->actor = $member->asActivityObject();
890 $act->verb = ActivityVerb::UNFOLLOW;
891 $act->objects[] = $oprofile->asActivityObject();
894 // TRANS: Title for unfollowing a remote list.
895 $act->title = _m('Unfollow list');
896 // TRANS: Success message for remote list unfollow through OStatus.
897 // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
898 $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
900 $oprofile->getBestName(),
901 $tagger->getBestName());
903 $oprofile->notifyActivity($act, $user);
907 * Notify remote users when their notices get favorited.
909 * @param Profile or User $profile of local user doing the faving
910 * @param Notice $notice being favored
911 * @return hook return value
913 function onEndFavorNotice(Profile $profile, Notice $notice)
915 // Only distribute local users' favor actions, remote users
916 // will have already distributed theirs.
917 if (!$profile->isLocal()) {
921 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
922 if (!$oprofile instanceof Ostatus_profile) {
926 $fav = Fave::pkeyGet(array('user_id' => $profile->id,
927 'notice_id' => $notice->id));
929 if (!$fav instanceof Fave) {
931 // TODO: Make pkeyGet throw exception, since this is a critical failure.
935 $act = $fav->asActivity();
937 $oprofile->notifyActivity($act, $profile);
943 * Notify remote user it has got a new people tag
944 * - tag verb is queued
945 * - the subscription is done immediately if not present
947 * @param Profile_tag $ptag the people tag that was created
948 * @return hook return value
949 * @throws Exception of various kinds, some from $oprofile->subscribe();
951 function onEndTagProfile($ptag)
953 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
954 if (!$oprofile instanceof Ostatus_profile) {
958 $plist = $ptag->getMeta();
959 if ($plist->private) {
963 $act = new Activity();
965 $tagger = $plist->getTagger();
966 $tagged = Profile::getKV('id', $ptag->tagged);
968 $act->verb = ActivityVerb::TAG;
969 $act->id = TagURI::mint('tag_profile:%d:%d:%s',
970 $plist->tagger, $plist->id,
971 common_date_iso8601(time()));
973 // TRANS: Title for listing a remote profile.
974 $act->title = _m('TITLE','List');
975 // TRANS: Success message for remote list addition through OStatus.
976 // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
977 $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
978 $tagger->getBestName(),
979 $tagged->getBestName(),
980 $plist->getBestName());
982 $act->actor = $tagger->asActivityObject();
983 $act->objects = array($tagged->asActivityObject());
984 $act->target = ActivityObject::fromPeopletag($plist);
986 $oprofile->notifyDeferred($act, $tagger);
988 // initiate a PuSH subscription for the person being tagged
989 $oprofile->subscribe();
994 * Notify remote user that a people tag has been removed
995 * - untag verb is queued
996 * - the subscription is undone immediately if not required
997 * i.e garbageCollect()'d
999 * @param Profile_tag $ptag the people tag that was deleted
1000 * @return hook return value
1002 function onEndUntagProfile($ptag)
1004 $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
1005 if (!$oprofile instanceof Ostatus_profile) {
1009 $plist = $ptag->getMeta();
1010 if ($plist->private) {
1014 $act = new Activity();
1016 $tagger = $plist->getTagger();
1017 $tagged = Profile::getKV('id', $ptag->tagged);
1019 $act->verb = ActivityVerb::UNTAG;
1020 $act->id = TagURI::mint('untag_profile:%d:%d:%s',
1021 $plist->tagger, $plist->id,
1022 common_date_iso8601(time()));
1023 $act->time = time();
1024 // TRANS: Title for unlisting a remote profile.
1025 $act->title = _m('TITLE','Unlist');
1026 // TRANS: Success message for remote list removal through OStatus.
1027 // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
1028 $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1029 $tagger->getBestName(),
1030 $tagged->getBestName(),
1031 $plist->getBestName());
1033 $act->actor = $tagger->asActivityObject();
1034 $act->objects = array($tagged->asActivityObject());
1035 $act->target = ActivityObject::fromPeopletag($plist);
1037 $oprofile->notifyDeferred($act, $tagger);
1039 // unsubscribe to PuSH feed if no more required
1040 $oprofile->garbageCollect();
1046 * Notify remote users when their notices get de-favorited.
1048 * @param Profile $profile Profile person doing the de-faving
1049 * @param Notice $notice Notice being favored
1051 * @return hook return value
1053 function onEndDisfavorNotice(Profile $profile, Notice $notice)
1055 // Only distribute local users' disfavor actions, remote users
1056 // will have already distributed theirs.
1057 if (!$profile->isLocal()) {
1061 $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1062 if (!$oprofile instanceof Ostatus_profile) {
1066 $act = new Activity();
1068 $act->verb = ActivityVerb::UNFAVORITE;
1069 $act->id = TagURI::mint('disfavor:%d:%d:%s',
1072 common_date_iso8601(time()));
1073 $act->time = time();
1074 // TRANS: Title for unliking a remote notice.
1075 $act->title = _m('Unlike');
1076 // TRANS: Success message for remove a favorite notice through OStatus.
1077 // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
1078 $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1079 $profile->getBestName(),
1082 $act->actor = $profile->asActivityObject();
1083 $act->objects[] = $notice->asActivityObject();
1085 $oprofile->notifyActivity($act, $profile);
1090 function onStartGetProfileUri($profile, &$uri)
1092 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1093 if ($oprofile instanceof Ostatus_profile) {
1094 $uri = $oprofile->uri;
1100 function onStartUserGroupHomeUrl($group, &$url)
1102 return $this->onStartUserGroupPermalink($group, $url);
1105 function onStartUserGroupPermalink($group, &$url)
1107 $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1108 if ($oprofile instanceof Ostatus_profile) {
1109 // @fixme this should probably be in the user_group table
1110 // @fixme this uri not guaranteed to be a profile page
1111 $url = $oprofile->uri;
1116 function onStartShowSubscriptionsContent($action)
1118 $this->showEntityRemoteSubscribe($action);
1123 function onStartShowUserGroupsContent($action)
1125 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1130 function onEndShowSubscriptionsMiniList($action)
1132 $this->showEntityRemoteSubscribe($action);
1137 function onEndShowGroupsMiniList($action)
1139 $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1144 function showEntityRemoteSubscribe($action, $target='ostatussub')
1146 if (!$action->getScoped() instanceof Profile) {
1147 // early return if we're not logged in
1151 if ($action->getScoped()->sameAs($action->getTarget())) {
1152 $action->elementStart('div', 'entity_actions');
1153 $action->elementStart('p', array('id' => 'entity_remote_subscribe',
1154 'class' => 'entity_subscribe'));
1155 $action->element('a', array('href' => common_local_url($target),
1156 'class' => 'entity_remote_subscribe'),
1157 // TRANS: Link text for link to remote subscribe.
1159 $action->elementEnd('p');
1160 $action->elementEnd('div');
1165 * Ping remote profiles with updates to this profile.
1166 * Salmon pings are queued for background processing.
1168 function onEndBroadcastProfile(Profile $profile)
1170 $user = User::getKV('id', $profile->id);
1172 // Find foreign accounts I'm subscribed to that support Salmon pings.
1174 // @fixme we could run updates through the PuSH feed too,
1175 // in which case we can skip Salmon pings to folks who
1176 // are also subscribed to me.
1177 $sql = "SELECT * FROM ostatus_profile " .
1178 "WHERE profile_id IN " .
1179 "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
1181 "(SELECT group_id FROM group_member WHERE profile_id=%d)";
1182 $oprofile = new Ostatus_profile();
1183 $oprofile->query(sprintf($sql, $profile->id, $profile->id));
1185 if ($oprofile->N == 0) {
1186 common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
1190 $act = new Activity();
1192 $act->verb = ActivityVerb::UPDATE_PROFILE;
1193 $act->id = TagURI::mint('update-profile:%d:%s',
1195 common_date_iso8601(time()));
1196 $act->time = time();
1197 // TRANS: Title for activity.
1198 $act->title = _m('Profile update');
1199 // TRANS: Ping text for remote profile update through OStatus.
1200 // TRANS: %s is user that updated their profile.
1201 $act->content = sprintf(_m('%s has updated their profile page.'),
1202 $profile->getBestName());
1204 $act->actor = $profile->asActivityObject();
1205 $act->objects[] = $act->actor;
1207 while ($oprofile->fetch()) {
1208 $oprofile->notifyDeferred($act, $profile);
1214 // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
1215 function onStartProfileListItemActionElements($item)
1217 if (common_logged_in()) {
1218 // only non-logged in users get to see the "remote subscribe" form
1220 } elseif (!$item->getTarget()->isLocal()) {
1221 // we can (for now) only provide remote subscribe forms for local users
1225 if ($item instanceof ProfileAction) {
1227 } elseif ($item instanceof Widget) {
1228 $output = $item->out;
1230 // Bad $item class, don't know how to use this for outputting!
1231 throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1234 // Add an OStatus subscribe
1235 $output->elementStart('li', 'entity_subscribe');
1236 $url = common_local_url('ostatusinit',
1237 array('nickname' => $item->getTarget()->getNickname()));
1238 $output->element('a', array('href' => $url,
1239 'class' => 'entity_remote_subscribe'),
1240 // TRANS: Link text for a user to subscribe to an OStatus user.
1242 $output->elementEnd('li');
1244 $output->elementStart('li', 'entity_tag');
1245 $url = common_local_url('ostatustag',
1246 array('nickname' => $item->getTarget()->getNickname()));
1247 $output->element('a', array('href' => $url,
1248 'class' => 'entity_remote_tag'),
1249 // TRANS: Link text for a user to list an OStatus user.
1251 $output->elementEnd('li');
1256 function onPluginVersion(array &$versions)
1258 $versions[] = array('name' => 'OStatus',
1259 'version' => GNUSOCIAL_VERSION,
1260 'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
1261 'homepage' => 'http://status.net/wiki/Plugin:OStatus',
1262 // TRANS: Plugin description.
1263 'rawdescription' => _m('Follow people across social networks that implement '.
1264 '<a href="http://ostatus.org/">OStatus</a>.'));
1270 * Utility function to check if the given URI is a canonical group profile
1271 * page, and if so return the ID number.
1273 * @param string $url
1274 * @return mixed int or false
1276 public static function localGroupFromUrl($url)
1278 $group = User_group::getKV('uri', $url);
1279 if ($group instanceof User_group) {
1280 if ($group->isLocal()) {
1284 // To find local groups which haven't had their uri fields filled out...
1285 // If the domain has changed since a subscriber got the URI, it'll
1287 $template = common_local_url('groupbyid', array('id' => '31337'));
1288 $template = preg_quote($template, '/');
1289 $template = str_replace('31337', '(\d+)', $template);
1290 if (preg_match("/$template/", $url, $matches)) {
1291 return intval($matches[1]);
1297 public function onStartProfileGetAtomFeed($profile, &$feed)
1299 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1301 if (!$oprofile instanceof Ostatus_profile) {
1305 $feed = $oprofile->feeduri;
1309 function onStartGetProfileFromURI($uri, &$profile)
1311 // Don't want to do Web-based discovery on our own server,
1312 // so we check locally first. This duplicates the functionality
1313 // in the Profile class, since the plugin always runs before
1314 // that local lookup, but since we return false it won't run double.
1316 $user = User::getKV('uri', $uri);
1317 if ($user instanceof User) {
1318 $profile = $user->getProfile();
1321 $group = User_group::getKV('uri', $uri);
1322 if ($group instanceof User_group) {
1323 $profile = $group->getProfile();
1328 // Now, check remotely
1330 $oprofile = Ostatus_profile::ensureProfileURI($uri);
1331 $profile = $oprofile->localProfile();
1332 return !($profile instanceof Profile); // localProfile won't throw exception but can return null
1333 } catch (Exception $e) {
1334 return true; // It's not an OStatus profile as far as we know, continue event handling
1338 function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
1340 $author = $target->getProfile();
1341 $profiletype = $this->profileTypeString($author);
1342 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1343 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1347 function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1349 if ($target->getObjectType() === ActivityObject::PERSON) {
1350 $this->addWebFingerPersonLinks($xrd, $target);
1354 $profiletype = $this->profileTypeString($target);
1355 $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1357 $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1359 // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1360 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
1361 $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1363 // TODO - finalize where the redirect should go on the publisher
1364 $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
1365 common_local_url('ostatussub') . '?profile={uri}',
1366 null, // type not set
1367 true); // isTemplate
1372 protected function profileTypeString(Profile $target)
1374 // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
1375 switch ($target->getObjectType()) {
1376 case ActivityObject::PERSON:
1378 case ActivityObject::GROUP:
1381 throw new ServerException('Unknown profile type for WebFinger profile links');
1385 protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
1387 $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
1388 common_local_url('ApiTimelineUser',
1389 array('id' => $target->id, 'format' => 'atom')),
1390 'application/atom+xml');
1392 // Get this profile's keypair
1393 $magicsig = Magicsig::getKV('user_id', $target->id);
1394 if (!$magicsig instanceof Magicsig && $target->isLocal()) {
1395 $magicsig = Magicsig::generate($target->getUser());
1398 if (!$magicsig instanceof Magicsig) {
1399 return false; // value doesn't mean anything, just figured I'd indicate this function didn't do anything
1401 if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1402 $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1403 'data:application/magic-public-key,'. $magicsig->toString());
1404 // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
1405 Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1409 public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
1411 list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);
1414 // FIXME: Maybe this shouldn't be so authoritative that it breaks other remote profile lookups?
1415 static public function onCheckActivityAuthorship(Activity $activity, Profile &$profile)
1418 $oprofile = Ostatus_profile::ensureProfileURL($profile->getUrl());
1419 $profile = $oprofile->checkAuthorship($activity);
1420 } catch (Exception $e) {
1421 common_log(LOG_ERR, 'Could not get a profile or check authorship ('.get_class($e).': "'.$e->getMessage().'") for activity ID: '.$activity->id);
1428 public function onProfileDeleteRelated($profile, &$related)
1430 // Ostatus_profile has a 'profile_id' property, which will be used to find the object
1431 $related[] = 'Ostatus_profile';
1433 // Magicsig has a "user_id" column instead, so we have to delete it more manually:
1434 $magicsig = Magicsig::getKV('user_id', $profile->id);
1435 if ($magicsig instanceof Magicsig) {
1436 $magicsig->delete();
1441 public function onSalmonSlap($endpoint_uri, MagicEnvelope $magic_env, Profile $target=null)
1443 $envxml = $magic_env->toXML($target);
1445 $headers = array('Content-Type: application/magic-envelope+xml');
1448 $client = new HTTPClient();
1449 $client->setBody($envxml);
1450 $response = $client->post($endpoint_uri, $headers);
1451 } catch (Exception $e) {
1452 common_log(LOG_ERR, "Salmon post to $endpoint_uri failed: " . $e->getMessage());
1455 if ($response->getStatus() === 422) {
1456 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()));
1460 // 200 OK is the best response
1461 // 202 Accepted is what we get from Diaspora for example
1462 if (!in_array($response->getStatus(), array(200, 202))) {
1463 common_log(LOG_ERR, sprintf('Salmon (from profile %d) endpoint %s returned status %s: %s',
1464 $magic_env->getActor()->getID(), $endpoint_uri, $response->getStatus(), $response->getBody()));
1468 // Since we completed the salmon slap, we discontinue the event
1472 public function onCronDaily()
1475 $sub = FeedSub::renewalCheck();
1476 } catch (NoResultException $e) {
1477 common_log(LOG_INFO, "There were no expiring feeds.");
1481 $qm = QueueManager::get();
1482 while ($sub->fetch()) {
1483 $item = array('feedsub_id' => $sub->id);
1484 $qm->enqueue($item, 'pushrenew');