Enst80 has uploaded a new change for review. ( 
https://gerrit.wikimedia.org/r/349273 )

Change subject: Bug T110292 - Update Auth_remoteuser to use AuthManager
......................................................................

Bug T110292 - Update Auth_remoteuser to use AuthManager

Complete rewrite of extension to support MediaWiki 1.27 and up.

Change-Id: Ia43098ea5b1b9b1138611c59181e34ed1a080586
---
D Auth_remoteuser.body.php
D Auth_remoteuser.php
A COPYING
A README.md
A extension.json
M i18n/en.json
M i18n/qqq.json
A src/AuthRemoteuserSessionProvider.php
A src/UserNameSessionProvider.php
9 files changed, 1,505 insertions(+), 521 deletions(-)


  git pull 
ssh://gerrit.wikimedia.org:29418/mediawiki/extensions/Auth_remoteuser 
refs/changes/73/349273/1

diff --git a/Auth_remoteuser.body.php b/Auth_remoteuser.body.php
deleted file mode 100644
index 8898dc5..0000000
--- a/Auth_remoteuser.body.php
+++ /dev/null
@@ -1,380 +0,0 @@
-<?php
-
-class Auth_remoteuser extends AuthPlugin {
-       /**
-        * Pretend all users exist.  This is checked by
-        * authenticateUserData to determine if a user exists in our 'db'.
-        * By returning true we tell it that it can create a local wiki
-        * user automatically.
-        *
-        * @param $username String: username.
-        * @return bool
-        */
-       public function userExists( $username ) {
-               return true;
-       }
-
-       /**
-        * Check whether the given name matches REMOTE_USER.
-        * The name will be normalized to MediaWiki's requirements, so
-        * lower it and the REMOTE_USER before checking.
-        *
-        * @param $username String: username.
-        * @param $password String: user password.
-        * @return bool
-        */
-       public function authenticate( $username, $password ) {
-               global $wgAuthRemoteuserAuthz;
-
-               if ( !$wgAuthRemoteuserAuthz ) {
-                       return false;
-               }
-
-               $usertest = $this->getRemoteUsername();
-
-               return ( strtolower( $username ) == strtolower( $usertest ) );
-       }
-
-       /**
-        * Modify options in the login template.  This shouldn't be very
-        * important because no one should really be bothering with the
-        * login page.
-        *
-        * @param $template UserLoginTemplate object.
-        * @param $type String
-        */
-       public function modifyUITemplate( &$template, &$type ) {
-               // disable the mail new password box
-               $template->set( 'useemail', false );
-               // disable 'remember me' box
-               $template->set( 'remember', false );
-               $template->set( 'create', false );
-               $template->set( 'domain', false );
-               $template->set( 'usedomain', false );
-       }
-
-       /**
-        * Return true because the wiki should create a new local account
-        * automatically when asked to login a user who doesn't exist
-        * locally but does in the external auth database.
-        *
-        * @return bool
-        */
-       public function autoCreate() {
-               return true;
-       }
-
-       /**
-        * Do not allow various changes checked for by allowPropChange.
-        */
-       public function allowRealNameChange() {
-               return false;
-       }
-       public function allowEmailChange() {
-               return false;
-       }
-
-       /**
-        * Of course not here
-        *
-        * @return bool
-        */
-       public function allowPasswordChange() {
-               return false;
-       }
-
-       /**
-        * MediaWiki should never see passwords, but if it does, don't store 
them.
-        *
-        * @return bool
-        */
-       public function allowSetLocalPassword() {
-               return false;
-       }
-
-       /**
-        * This should not be called because we do not allow password
-        * change.  Always fail by returning false.
-        *
-        * @param $user User object.
-        * @param $password String: password.
-        * @return bool
-        */
-       public function setPassword( $user, $password ) {
-               return false;
-       }
-
-       /**
-        * We don't support this but we have to return true for
-        * preferences to save.
-        *
-        * @param $user User object.
-        * @return bool
-        */
-       public function updateExternalDB( $user ) {
-               return true;
-       }
-
-       /**
-        * Should never be called, but return false anyway.
-        */
-       public function addUser( $user, $password, $email = '', $realname = '' 
) {
-               return false;
-       }
-
-       /**
-        * Return true to prevent logins that don't authenticate here from
-        * being checked against the local database's password fields.
-        *
-        * @return bool
-        */
-       public function strict() {
-               return true;
-       }
-
-       /**
-        * When creating a user account, optionally fill in
-        * preferences and such.  For instance, you might pull the
-        * email address or real name from the external user database.
-        *
-        * @param $user User object.
-        * @param $autocreate bool
-        */
-       public function initUser( &$user, $autocreate = false ) {
-               $username = $this->getRemoteUsername();
-               if ( Hooks::run( "AuthRemoteUserInitUser",
-                               array( $user, $autocreate ) ) ) {
-
-                       $this->setRealName( $user );
-
-                       $this->setEmail( $user, $username );
-
-                       $user->mEmailAuthenticated = wfTimestampNow();
-                       $user->setToken();
-
-                       $this->setNotifications( $user );
-               }
-               $user->saveSettings();
-       }
-
-       /**
-        * Normalize user names to the MediaWiki standard to prevent
-        * duplicate accounts.
-        *
-        * @param $username String: username.
-        * @return string
-        */
-       public function getCanonicalName( $username ) {
-               // lowercase the username
-               $username = strtolower( $username );
-               // uppercase first letter to make MediaWiki happy
-               return ucfirst( $username );
-       }
-
-       /**
-        * Extension setup hook.  Run for each request.
-        */
-       public function setupExtensionForRequest() {
-               // See if we're even needed
-               if ( $this->skipPage() ) {
-                       return;
-               }
-
-               $username = $this->getRemoteUsername();
-               // Process the username only if required
-               if ( !$username ) {
-                       return;
-               }
-
-               // Check for valid session
-               $user = $this->getUserFromSession( $username );
-               if( $user === true ) {
-                       return;
-               }
-
-               $this->handleLogin( $user, $username );
-       }
-
-       /**
-        * Sets the real name of the user.
-        *
-        * @param User
-        */
-       public function setRealName( User $user ) {
-               global $wgAuthRemoteuserName;
-
-               if ( $wgAuthRemoteuserName ) {
-                       $user->setRealName( $wgAuthRemoteuserName );
-               } else {
-                       $user->setRealName( '' );
-               }
-       }
-
-       /**
-        * Sets the email address of the user.
-        *
-        * @param User
-        * @param String username
-        */
-       public function setEmail( User $user, $username ) {
-               global $wgAuthRemoteuserMail, $wgAuthRemoteuserMailDomain;
-
-               if ( $wgAuthRemoteuserMail ) {
-                       $user->setEmail( $wgAuthRemoteuserMail );
-               } elseif ( $wgAuthRemoteuserMailDomain ) {
-                       $user->setEmail( $username . '@' .
-                               $wgAuthRemoteuserMailDomain );
-               } else {
-                       $user->setEmail( $username . "@example.com" );
-               }
-       }
-
-       /**
-        * Set up notifications for the user.
-        *
-        * @param User
-        */
-       public function setNotifications( User $user ) {
-               global $wgAuthRemoteuserNotify;
-
-               // turn on e-mail notifications
-               if ( $wgAuthRemoteuserNotify ) {
-                       $user->setOption( 'enotifwatchlistpages', 1 );
-                       $user->setOption( 'enotifusertalkpages', 1 );
-                       $user->setOption( 'enotifminoredits', 1 );
-                       $user->setOption( 'enotifrevealaddr', 1 );
-               }
-       }
-
-       /**
-        * Check if we're needed.
-        *
-        * @return bool true if this page should be skipped.
-        */
-       public function skipPage() {
-               global $wgRequest;
-
-               $title = $wgRequest->getVal( 'title' );
-               if ( ( $title == Title::makeName( NS_SPECIAL, 'UserLogout' ) ) 
||
-                       ( $title == Title::makeName( NS_SPECIAL, 'UserLogin' ) 
) ) {
-                       return true;
-               }
-       }
-
-       /**
-        * Return the username to be used.  Empty string if none.
-        *
-        * @return string
-        */
-       public function getRemoteUsername( ) {
-               global $wgAuthRemoteuserDomain;
-
-               if ( isset( $_SERVER['REMOTE_USER'] ) ) {
-                       $username = $_SERVER['REMOTE_USER'];
-
-                       if ( $wgAuthRemoteuserDomain ) {
-                               $username = str_replace( 
"$wgAuthRemoteuserDomain\\",
-                                       "", $username );
-                               $username = str_replace( 
"@$wgAuthRemoteuserDomain",
-                                       "", $username );
-                       }
-               } else {
-                       $username = "";
-               }
-
-               return $username;
-       }
-
-       /**
-        * Load the user from session
-        * @return mixed true if user is already logged in and no further 
action is needed.
-        *               User object if this user needs to be logged in
-        */
-       public function getUserFromSession( $username ) {
-               global $wgUser;
-               $this->setupSession();
-
-               $wgUser = User::newFromSession();
-               if ( !$wgUser->isAnon() ) {
-                       if ( $wgUser->getName() ==
-                               $this->getCanonicalName( $username ) ) {
-                               return true; // User is already logged in.
-                       } else {
-                               $wgUser->doLogout(); // Logout mismatched user.
-                       }
-               }
-               return $wgUser;
-       }
-
-       public function setupSession() {
-               if ( session_id() == '' ) {
-                       wfSetupSession();
-               }
-       }
-
-       public function handleLogin( User $user, $username ) {
-               // If the login form returns NEED_TOKEN try once more with the
-               // right token
-               $trycount = 0;
-               $token = '';
-               $errormessage = '';
-               do {
-                       $tryagain = false;
-                       // Submit a fake login form to authenticate the user.
-                       $params = new FauxRequest( array(
-                                       'wpName' => $username,
-                                       'wpPassword' => '',
-                                       'wpDomain' => '',
-                                       'wpLoginToken' => $token,
-                                       'wpRemember' => ''
-                               ) );
-
-                       // Authenticate user data will automatically create
-                       // new users.
-                       $loginForm = new LoginForm( $params );
-                       $result = $loginForm->authenticateUserData();
-                       switch ( $result ) {
-                               case LoginForm :: SUCCESS :
-                                       $user->setOption( 'rememberpassword', 1 
);
-                                       $user->setCookies();
-                                       break;
-                               case LoginForm :: NEED_TOKEN:
-                                       $token = $loginForm->getLoginToken();
-                                       $tryagain = ( $trycount == 0 );
-                                       break;
-                               case LoginForm :: WRONG_TOKEN:
-                                       $errormessage = 'WrongToken';
-                                       break;
-                               case LoginForm :: NO_NAME :
-                                       $errormessage = 'NoName';
-                                       break;
-                               case LoginForm :: ILLEGAL :
-                                       $errormessage = 'Illegal';
-                                       break;
-                               case LoginForm :: WRONG_PLUGIN_PASS :
-                                       $errormessage = 'WrongPluginPass';
-                                       break;
-                               case LoginForm :: NOT_EXISTS :
-                                       $errormessage = 'NotExists';
-                                       break;
-                               case LoginForm :: WRONG_PASS :
-                                       $errormessage = 'WrongPass';
-                                       break;
-                               case LoginForm :: EMPTY_PASS :
-                                       $errormessage = 'EmptyPass';
-                                       break;
-                               default:
-                                       $errormessage = 'Unknown';
-                                       break;
-                       }
-
-                       if ( $result != LoginForm::SUCCESS
-                               && $result != LoginForm::NEED_TOKEN ) {
-                               error_log( 'Unexpected REMOTE_USER 
authentication'.
-                                       ' failure. Login Error was:' .
-                                       $errormessage );
-                       }
-                       $trycount++;
-               } while ( $tryagain );
-       }
-}
diff --git a/Auth_remoteuser.php b/Auth_remoteuser.php
deleted file mode 100644
index da6547b..0000000
--- a/Auth_remoteuser.php
+++ /dev/null
@@ -1,136 +0,0 @@
-<?php
-// vim:sw=2:softtabstop=2:textwidth=80
-//
-// This program is free software: you can redistribute it and/or
-// modify it under the terms of the GNU General Public License as
-// published by the Free Software Foundation, either version 2 of the
-// License, or (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful, but
-// WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-// General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program.  If not, see
-// <http://www.gnu.org/licenses/>.
-//
-// Copyright 2006 Otheus Shelling
-// Copyright 2007 Rusty Burchfield
-// Copyright 2009 James Kinsman
-// Copyright 2010 Daniel Thomas
-// Copyright 2010 Ian Ward Comfort
-// Copyright 2014 Mark A. Hershberger
-//
-// In 2009, the copyright holders determined that the original
-// publishing of this code under GPLv3 was legally and logistically in
-// error, and re-licensed it under GPLv2.
-//
-// See http://www.mediawiki.org/wiki/Extension:Auth_remoteuser
-//
-// * Compatiblity with version 1.9 of MediaWiki. -- Rusty Burchfield
-// * Optional settings. -- Emmanuel Dreyfus
-// * Compatiblity with version 1.16 of MediaWiki. -- VibroAxe (James
-//   Kinsman)
-// * Allow domain substitution for Integrated Windows Authentication.
-//   -- VibroAxe (James Kinsman)
-// * Add optional $wgAuthRemoteuserMailDomain and remove hardcoding of
-//   permissions for anonymous users. -- drt24 (Daniel Thomas)
-// * Detect mismatches between the session user and REMOTE_USER.
-//   -- Ian Ward Comfort
-// * Refactored to allow easier extensibility. -- Mark A. Hershberger.
-// * Updated to match extension name in repo and newer methods on
-//   AuthPlugin. -- Mark A. Hershberger
-//
-// Add these lines to your LocalSettings.php
-//
-// // Don't let anonymous people do things...
-// $wgGroupPermissions['*']['createaccount']   = false;
-// $wgGroupPermissions['*']['read']            = false;
-// $wgGroupPermissions['*']['edit']            = false;
-//
-// /* This is required for Auth_remoteuser operation
-// require_once('extensions/Auth_remoteuser.php');
-// $wgAuth = new Auth_remoteuser();
-//
-// The constructor of Auth_remoteuser registers a hook to do the
-// automatic login.  Storing the Auth_remoteuser object in $wgAuth
-// tells mediawiki to use that object as the AuthPlugin.  This way the
-// login attempts by the hook will be handled by us.
-//
-// You probably want to edit the initUser function to set the users
-// real name and email address properly for your configuration.
-
-// Extension credits that show up on Special:Version
-$wgExtensionCredits['other'][] = array(
-       'path' => __FILE__,
-       'name' => 'Auth_remoteuser',
-       'version' => '1.1.4',
-       'author' => array( 'Otheus Shelling', 'Rusty Burchfield',
-               'James Kinsman', 'Daniel Thomas', 'Ian Ward Comfort',
-               '[[mw:User:MarkAHershberger|Mark A. Hershberger]]'
-       ),
-       'url' => 'https://www.mediawiki.org/wiki/Extension:Auth_remoteuser',
-       'descriptionmsg' => 'auth_remoteuser-desc',
-);
-
-$wgMessagesDirs['Auth_remoteuser'] = __DIR__ . '/i18n';
-
-// We must allow zero length passwords. This extension does not work
-// in MW 1.16 without this.
-$wgMinimalPasswordLength = 0;
-
-$wgAuthRemoteuserAuthz = true;
-
-/* User's name */
-$wgAuthRemoteuserName = isset( $_SERVER["AUTHENTICATE_CN"] )
-       ? $_SERVER["AUTHENTICATE_CN"]
-       : '';
-
-/* User's Mail */
-$wgAuthRemoteuserMail = isset( $_SERVER["AUTHENTICATE_MAIL"] )
-       ? $_SERVER["AUTHENTICATE_MAIL"]
-       : '';
-
-/* Do not send mail notifications */
-$wgAuthRemoteuserNotify = false;
-
-/* Remove DOMAIN\ from the beginning or @DOMAIN at the end of an IWA
- * username.  Set to your own netbios domain if you need this done. */
-$wgAuthRemoteuserDomain = "";
-
-/* User's mail domain to append to the user name to make their email
- * address */
-$wgAuthRemoteuserMailDomain = "example.com";
-
-/**
- * This hook is registered by the Auth_remoteuser constructor.  It
- * will be called on every page load.  It serves the function of
- * automatically logging in the user.  The Auth_remoteuser class is an
- * AuthPlugin and handles the actual authentication, user creation,
- * etc.
- *
- * Details:
- * 1. Check to see if the user has a session and is not anonymous.  If
- *    this is true, check whether REMOTE_USER matches the session
- *    user.  If so, we can just return; otherwise we must logout the
- *    session user and login as the REMOTE_USER.
- * 2. If the user doesn't have a session, we create a login form with
- *    our own fake request and ask the form to authenticate the user.
- *    If the user does not exist authenticateUserData will attempt to
- *    create one.  The login form uses our Auth_remoteuser class as an
- *    AuthPlugin.
- *
- * Note: If cookies are disabled, an infinite loop /might/ occur?
- */
-$wgExtensionFunctions[] = function () {
-       global $wgAuth;
-
-       if ( $wgAuth instanceof Auth_remoteuser ) {
-               $wgAuth->setupExtensionForRequest();
-       } else {
-               die( wfMessage( 'auth_remoteuser-wgautherror' ) );
-       }
-};
-
-$wgAutoloadClasses['Auth_remoteuser'] = __DIR__ . '/Auth_remoteuser.body.php';
\ No newline at end of file
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..bb4b513
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,92 @@
+GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share 
and change it. By contrast, the GNU General Public License is intended to 
guarantee your freedom to share and change free software--to make sure the 
software is free for all its users. This General Public License applies to most 
of the Free Software Foundation's software and to any other program whose 
authors commit to using it. (Some other Free Software Foundation software is 
covered by the GNU Library General Public License instead.) You can apply it to 
your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our 
General Public Licenses are designed to make sure that you have the freedom to 
distribute copies of free software (and charge for this service if you wish), 
that you receive source code or can get it if you want it, that you can change 
the software or use pieces of it in new free programs; and that you know you 
can do these things.
+
+To protect your rights, we need to make restrictions that forbid anyone to 
deny you these rights or to ask you to surrender the rights. These restrictions 
translate to certain responsibilities for you if you distribute copies of the 
software, or if you modify it.
+
+For example, if you distribute copies of such a program, whether gratis or for 
a fee, you must give the recipients all the rights that you have. You must make 
sure that they, too, receive or can get the source code. And you must show them 
these terms so they know their rights.
+
+We protect your rights with two steps: (1) copyright the software, and (2) 
offer you this license which gives you legal permission to copy, distribute 
and/or modify the software.
+
+Also, for each author's protection and ours, we want to make certain that 
everyone understands that there is no warranty for this free software. If the 
software is modified by someone else and passed on, we want its recipients to 
know that what they have is not the original, so that any problems introduced 
by others will not reflect on the original authors' reputations.
+
+Finally, any free program is threatened constantly by software patents. We 
wish to avoid the danger that redistributors of a free program will 
individually obtain patent licenses, in effect making the program proprietary. 
To prevent this, we have made it clear that any patent must be licensed for 
everyone's free use or not licensed at all.
+
+The precise terms and conditions for copying, distribution and modification 
follow.
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License applies to any program or other work which contains a notice 
placed by the copyright holder saying it may be distributed under the terms of 
this General Public License. The "Program", below, refers to any such program 
or work, and a "work based on the Program" means either the Program or any 
derivative work under copyright law: that is to say, a work containing the 
Program or a portion of it, either verbatim or with modifications and/or 
translated into another language. (Hereinafter, translation is included without 
limitation in the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not covered 
by this License; they are outside its scope. The act of running the Program is 
not restricted, and the output from the Program is covered only if its contents 
constitute a work based on the Program (independent of having been made by 
running the Program). Whether that is true depends on what the Program does.
+
+1. You may copy and distribute verbatim copies of the Program's source code as 
you receive it, in any medium, provided that you conspicuously and 
appropriately publish on each copy an appropriate copyright notice and 
disclaimer of warranty; keep intact all the notices that refer to this License 
and to the absence of any warranty; and give any other recipients of the 
Program a copy of this License along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and you may 
at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Program or any portion of it, 
thus forming a work based on the Program, and copy and distribute such 
modifications or work under the terms of Section 1 above, provided that you 
also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices stating 
that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in whole 
or in part contains or is derived from the Program or any part thereof, to be 
licensed as a whole at no charge to all third parties under the terms of this 
License.
+
+    c) If the modified program normally reads commands interactively when run, 
you must cause it, when started running for such interactive use in the most 
ordinary way, to print or display an announcement including an appropriate 
copyright notice and a notice that there is no warranty (or else, saying that 
you provide a warranty) and that users may redistribute the program under these 
conditions, and telling the user how to view a copy of this License. 
(Exception: if the Program itself is interactive but does not normally print 
such an announcement, your work based on the Program is not required to print 
an announcement.)
+
+These requirements apply to the modified work as a whole. If identifiable 
sections of that work are not derived from the Program, and can be reasonably 
considered independent and separate works in themselves, then this License, and 
its terms, do not apply to those sections when you distribute them as separate 
works. But when you distribute the same sections as part of a whole which is a 
work based on the Program, the distribution of the whole must be on the terms 
of this License, whose permissions for other licensees extend to the entire 
whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your 
rights to work written entirely by you; rather, the intent is to exercise the 
right to control the distribution of derivative or collective works based on 
the Program.
+
+In addition, mere aggregation of another work not based on the Program with 
the Program (or with a work based on the Program) on a volume of a storage or 
distribution medium does not bring the other work under the scope of this 
License.
+
+3. You may copy and distribute the Program (or a work based on it, under 
Section 2) in object code or executable form under the terms of Sections 1 and 
2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable source 
code, which must be distributed under the terms of Sections 1 and 2 above on a 
medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three years, to 
give any third party, for a charge no more than your cost of physically 
performing source distribution, a complete machine-readable copy of the 
corresponding source code, to be distributed under the terms of Sections 1 and 
2 above on a medium customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer to 
distribute corresponding source code. (This alternative is allowed only for 
noncommercial distribution and only if you received the program in object code 
or executable form with such an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for making 
modifications to it. For an executable work, complete source code means all the 
source code for all modules it contains, plus any associated interface 
definition files, plus the scripts used to control compilation and installation 
of the executable. However, as a special exception, the source code distributed 
need not include anything that is normally distributed (in either source or 
binary form) with the major components (compiler, kernel, and so on) of the 
operating system on which the executable runs, unless that component itself 
accompanies the executable.
+
+If distribution of executable or object code is made by offering access to 
copy from a designated place, then offering equivalent access to copy the 
source code from the same place counts as distribution of the source code, even 
though third parties are not compelled to copy the source along with the object 
code.
+
+4. You may not copy, modify, sublicense, or distribute the Program except as 
expressly provided under this License. Any attempt otherwise to copy, modify, 
sublicense or distribute the Program is void, and will automatically terminate 
your rights under this License. However, parties who have received copies, or 
rights, from you under this License will not have their licenses terminated so 
long as such parties remain in full compliance.
+
+5. You are not required to accept this License, since you have not signed it. 
However, nothing else grants you permission to modify or distribute the Program 
or its derivative works. These actions are prohibited by law if you do not 
accept this License. Therefore, by modifying or distributing the Program (or 
any work based on the Program), you indicate your acceptance of this License to 
do so, and all its terms and conditions for copying, distributing or modifying 
the Program or works based on it.
+
+6. Each time you redistribute the Program (or any work based on the Program), 
the recipient automatically receives a license from the original licensor to 
copy, distribute or modify the Program subject to these terms and conditions. 
You may not impose any further restrictions on the recipients' exercise of the 
rights granted herein. You are not responsible for enforcing compliance by 
third parties to this License.
+
+7. If, as a consequence of a court judgment or allegation of patent 
infringement or for any other reason (not limited to patent issues), conditions 
are imposed on you (whether by court order, agreement or otherwise) that 
contradict the conditions of this License, they do not excuse you from the 
conditions of this License. If you cannot distribute so as to satisfy 
simultaneously your obligations under this License and any other pertinent 
obligations, then as a consequence you may not distribute the Program at all. 
For example, if a patent license would not permit royalty-free redistribution 
of the Program by all those who receive copies directly or indirectly through 
you, then the only way you could satisfy both it and this License would be to 
refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under any 
particular circumstance, the balance of the section is intended to apply and 
the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or 
other property right claims or to contest validity of any such claims; this 
section has the sole purpose of protecting the integrity of the free software 
distribution system, which is implemented by public license practices. Many 
people have made generous contributions to the wide range of software 
distributed through that system in reliance on consistent application of that 
system; it is up to the author/donor to decide if he or she is willing to 
distribute software through any other system and a licensee cannot impose that 
choice.
+
+This section is intended to make thoroughly clear what is believed to be a 
consequence of the rest of this License.
+
+8. If the distribution and/or use of the Program is restricted in certain 
countries either by patents or by copyrighted interfaces, the original 
copyright holder who places the Program under this License may add an explicit 
geographical distribution limitation excluding those countries, so that 
distribution is permitted only in or among countries not thus excluded. In such 
case, this License incorporates the limitation as if written in the body of 
this License.
+
+9. The Free Software Foundation may publish revised and/or new versions of the 
General Public License from time to time. Such new versions will be similar in 
spirit to the present version, but may differ in detail to address new problems 
or concerns.
+
+Each version is given a distinguishing version number. If the Program 
specifies a version number of this License which applies to it and "any later 
version", you have the option of following the terms and conditions either of 
that version or of any later version published by the Free Software Foundation. 
If the Program does not specify a version number of this License, you may 
choose any version ever published by the Free Software Foundation.
+
+10. If you wish to incorporate parts of the Program into other free programs 
whose distribution conditions are different, write to the author to ask for 
permission. For software which is copyrighted by the Free Software Foundation, 
write to the Free Software Foundation; we sometimes make exceptions for this. 
Our decision will be guided by the two goals of preserving the free status of 
all derivatives of our free software and of promoting the sharing and reuse of 
software generally.
+
+NO WARRANTY
+
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR 
THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE 
STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE 
PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU 
ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL 
ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE 
PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR 
INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA 
BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 
FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER 
OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..52a0eef
--- /dev/null
+++ b/README.md
@@ -0,0 +1,318 @@
+Auth_remoteuser
+===============
+
+Auth_remoteuser is an extension for MediaWiki 1.27 and up which logs-in
+users into mediawiki automatically if they are already authenticated by
+a remote source. This can be anything ranging from webserver environment
+variables to request headers to arbitrary external sources if at least
+the remote user name maps to an existing user name in the local wiki
+database (or it can be created if the extension has the permissions to
+do so). The external source takes total responsibility in authenticating
+an authorized user.
+
+Because it is implemented as a SessionProvider in MediaWikis AuthManager
+stack, which was introduced with MediaWiki 1.27, you need a version of
+Auth_remoteuser below 2.0.0 to use this extension in MediaWiki 1.26 and
+below.
+
+
+Requirements
+------------
+
+* MediaWiki 1.27+
+
+
+Installation
+------------
+
+Copy this extension directory `Auth_remoteuser/` into your mediawiki
+extension folder `extensions/`. Then add the following line to your
+global configuration file `LocalSettings.php`:
+
+    wfLoadExtension( 'Auth_remoteuser' );
+
+Take account of MediaWikis global permissions for account creation
+inside your `LocalSettings.php`. At least one of them must be `true` for
+anonymous users to let this extension create accounts for users as of
+yet unknown to the wiki database. If you set this to `false`, then
+automatic login works only for users who have a wiki account already:
+
+    $wgGroupPermissions['*']['createaccount'] = true;
+
+    // If account creation by anonymous users is forbidden, then allow
+    // it to be created automatically.
+    $wgGroupPermissions['*']['createaccount'] = false;
+    $wgGroupPermissions['*']['autocreateaccount'] = true;
+
+    // Only login users automatically if known to the wiki already.
+    $wgGroupPermissions['*']['createaccount'] = false;
+    $wgGroupPermissions['*']['autocreateaccount'] = false;
+
+
+Configuration
+-------------
+
+You can adjust the behaviour of the extension to suit your needs by
+using a set of global configuration variables all starting with
+`$wgAuthRemoteuser`. Just add them to your `LocalSettings.php`. Default
+values, which you don't have to set explicitly are marked with the
+`// default` comment.
+
+* Set the name(s) to use for mapping into the local wiki user database.
+  This can either be a simple string, a closure or a mixed array of
+  strings and/or closures. If the value is `null`, the extension
+  defaults to using the environment variables `REMOTE_USER` and
+  `REDIRECT_REMOTE_USER`. The first name name in the given list, which
+  can be used as a valid MediaWiki user name, will be taken for login
+  (either by login to an existing wiki account or by creating first).
+  Examples:
+
+        $wgAuthRemoteuserUserName = null; // default
+
+        // Same behaviour as default `null`.
+        $wgAuthRemoteuserUserName = [
+            $_SERVER[ 'REMOTE_USER' ],
+            $_SERVER[ 'REDIRECT_REMOTE_USER' ]
+        ];
+
+        // Another remote source for user name(s).
+        $wgAuthRemoteuserUserName = $_SERVER[ 'LOGON_USER' ];
+
+        $wgAuthRemoteuserUserName = ""; // Will evaluate to nothing.
+        $wgAuthRemoteuserUserName = []; // Will evaluate to nothing.
+
+        // This is not advised, because it will evaluate every visitor
+        // to the same wiki user 'Everybody'.
+        $wgAuthRemoteuserUserName = "Everybody";
+
+        // Create a closure instead of providing strings directly.
+        $wgAuthRemoteuserUserName = function() {
+            $credentials = explode( ':',$_SERVER['HTTP_AUTHORIZATION']);
+            $username = $credentials[0];
+            $password = $credentials[1];
+            return MyOwnAuthorizer::authenticate( $username, $password )
+                ? $username : "";
+        };
+
+* When you need to process your remote user name before it can be used
+  as an identifier into the wiki user list, for example to strip a
+  Kerberos principal from the end, replacing invalid characters, or
+  blacklisting some names, use the hook `AuthRemoteuserFilterUserName`
+  provided by this extension. Just have a look at MediaWikis Hook
+  documentation on how to register additional functions to this hook. It
+  provides as first parameter the remote user name by reference to the
+  hook function. If the function returns false, the remote user name
+  will be ignored for automatic login.
+
+* This extension comes with predefined remote user name filters (which
+  are using the hook mentioned above). If you want to replace something,
+  set an array of search and replacement patterns to the following
+  configuration variable (Each pattern can be a regular expression in
+  PCRE syntax too):
+
+        $wgAuthRemoteuserUserNameReplaceFilter = null; // default
+
+        $wgAuthRemoteuserUserNameReplaceFilter = [
+            '_' => ' ',                  // replace underscores with
+                                         // spaces
+            '@INTRA.EXAMPLE.COM$' => '', // strip Kerberos principal
+                                         // from back
+            '^domain\\' => '',           // strip NTLM domain from front
+            'johndoe' => 'Admin',        // rewrite user johndoe
+            '/JaNeDoE/i' => 'Admin',     // rewrite all case-insensitive
+                                         // versions of janedoe
+            '^(.*)$' => 'auto_$1',       // prepend string 'auto_'
+            '^cn=(.*),dc=com$' => '$1',  // get nested user name
+            '^([^,]*),(.*)$' => '$2 $1'  // reorder names
+        ];
+
+* If you want to prevent some names from beeing logged in automatically,
+  blacklist them with the following filter. It accepts a list of names,
+  where each name can also be a regular expression in PCRE syntax:
+
+        $wgAuthRemoteuserUserNameBlacklistFilter = null; // default
+
+        $wgAuthRemoteuserUserNameBlacklistFilter = [
+            'johndoe',
+            'janedoe',
+            '/john/i', // matches all case-insensitive versions of john
+            '^f_'      // matches all users starting wit 'f_'
+        ];
+
+* The opposite of the `UserNameBlacklistFilter` can be achieved by using
+  the following filter, which permits the automatic login instead of
+  preventing it:
+
+        $wgAuthRemoteuserUserNameWhitelistFilter = null; // default
+
+        $wgAuthRemoteuserUserNameWhitelistFilter = [
+            'john',
+            'jane'
+        ];
+
+* When you have further user information available in your environment,
+  which can be tied to a created user, for example email address or real
+  name, then use one of the following configuration variables. Either
+  `UserPrefs` or `UserPrefsForced`, which applies them to new users only
+  or force them by applying them on each request. This can be useful if
+  you don't want the user to change this preference inside MediaWiki
+  (for example your company email address given by a remote source).
+  They are expecting an array of key value pairs of which 'realname' and
+  'email' corresponds to the new users real name and email address. Any
+  further key value pair specified gets mapped to a user preference of
+  the same name. But take note of MediaWikis `$wgDefaultUserOptions` and
+  `$wgHiddenPrefs`for declaring user preference options. In most cases
+  these globals are better suited for a definition of a default value
+  and disabling their modifiability:
+
+        $wgAuthRemoteuserUserPrefs = null;       // default
+        $wgAuthRemoteuserUserPrefsForced = null; // default
+
+        $wgAuthRemoteuserUserPrefs = [
+            'realname' => $_SERVER[ 'AUTHENTICATE_DISPLAYNAME' ],
+            'language' => 'en',
+            'disablemail' => 0
+        ];
+        // Users email address should not be changed inside MediaWiki.
+        $wgAuthRemoteuserUserPrefsForced = [
+            'email' => $_SERVER[ 'AUTHENTICATE_MAIL' ]
+        ];
+
+        // Instead use MediaWiki global for the preference option.
+        $wgDefaultUserOptions[ 'disablemail' ] = 0;
+        // And disable it from being changed by the user.
+        $wgHiddenPrefs[] = 'disablemail';
+        // But change it depending on type of remote user (uses the
+        // closure feature described below). For example if there are
+        // guest accounts identified by a leading 'g_' existing at your
+        // remote source, which have no valid email address, then
+        // disable the option specifically for these type of accounts.
+        $wgAuthRemoteuserUserPrefsForced = [
+            'disablemail' => function ( $metadata ) {
+                $name = $metadata[ 'remoteUserName' ];
+                return ( preg_match( '/^g_/', $name ) ) ? 1 : 0;
+            }
+        ];
+
+  You can specify an anonymous function for the values too. These
+  closures getting called when the actual value is needed, and not when
+  it is declared inside your `LocalSettings.php`. The first parameter
+  given to the function is an associative array with the following keys:
+  * `userId` - id of user in local wiki database or 0 if new/anonymous
+  * `remoteUserName` - value as given by the environment
+  * `filteredUserName` - after running hook for filtering user names
+  * `canonicalUserName` - representation in the local wiki database
+  * `canonicalUserNameUsed` - the user name used for the current session
+
+  Take the following as an example in which a cost-intensive function
+  (in a timely manner) is getting executed only once per user and not on
+  every request:
+
+        $wgAuthRemoteuserUserPrefs = [
+            'email' => function( $metadata ) use ( $rpc ) {
+                $name = $metadata[ 'remoteUserName' ];
+                // costly remote procedure call to get email address
+                return $rpc->query( 'email', $name );
+            }
+        ];
+
+* You can replace urls in MediaWiki, if your remote source is better
+  suited for handling specific behaviour. For example by default no
+  automatically logged-in user is allowed to logout (because he will be
+  logged-in automatically again with the next request). But maybe your
+  remote source should handle that logout (so that with the next request
+  there isn't a remote user name provided anymore to this extension).
+  Set an appropriate url to one of the following keys of the associative
+  array `wgAuthRemoteuserUserUrls`:
+  * `logout` - Provide a redirect url for the user logout. Depending on
+    your other extension configuration settings this will either replace
+    the link of the logout button in the user's personal url bar or
+    redirect after a call to the special page `Special:UserLogout`.
+    Accepts a string or a closure. If of type closure, then it should
+    return a string with a valid url (either external or internal). The
+    closure gets as first parameter the same array as closures for the
+    user preferences (see description there).
+
+  Examples:
+
+        $wgAuthRemoteuserUserUrls = null; // default
+
+        // Redirect to company domain controller host for logout.
+        $wgAuthRemoteuserUserUrls = [
+            'logout' => function( $metadata ) {
+                $user = $metadata[ 'remoteUserName' ];
+                return 'https://company.example.com/?logout=' . $user;
+            }
+        ];
+
+        // Redirect to user login page instead of default logout page.
+        // This is the default behaviour if user switching is allowed.
+        $wgAuthRemoteuserUserUrls = [
+            'logout' => function( $metadata ) {
+                return 'Special:UserLogin';
+            }
+        ];
+
+
+* By default this extension mimics the behaviour of Auth_remoteuser
+  versions prior 2.0.0, which prohibits using another local user then
+  the one identified by the remote source. You can change this behaviour
+  with the following configuration:
+
+        $wgAuthRemoteuserAllowUserSwitch = false; // default
+
+        $wgAuthRemoteuserAllowUserSwitch = true;
+
+* As an immutable SessionProvider (see `AllowUserSwitch` config above)
+  all special pages and login/logout links for authentication aren't
+  needed anymore by the identified user. If you still want them to be
+  shown, for example if you are using other session providers besides
+  this one, then set the following accordingly:
+
+        $wgAuthRemoteuserRemoveAuthPagesAndLinks = true; // default
+
+        $wgAuthRemoteuserRemoveAuthPagesAndLinks = false;
+
+* If you are using other SessionProvider extensions besides this one,
+  you have to specify their significance by using an ascending priority:
+
+        $wgAuthRemoteuserPriority = 50; // default
+
+        $wgAuthRemoteuserPriority = SessionInfo::MAX_PRIORITY;
+
+
+Upgrade
+-------
+
+This extension doesn't use any database entries, therefore you don't
+need that extension to be enabled while upgrading. Just disable it and
+after you have upgraded your wiki, reenable this extension.
+
+
+Upgrading from versions prior 2.0.0
+-----------------------------------
+
+All legacy configuration parameters are still fully supported. You don't
+have to rewrite your old `LocalSettings.php` settings. But to assist you
+in transitioning of old configuration parameters to new ones, the
+following list can guide you:
+
+* `$wgAuthRemoteuserAuthz` - This parameter has no equivalent new
+  parameter, because you can achive the same with not loading the
+  extension at all.
+* `$wgAuthRemoteuserName` - Superseded by `$wgRemoteuserUserPrefs`.
+* `$wgAuthRemoteuserMail` - Superseded by `$wgRemoteuserUserPrefs`.
+* `$wgAuthRemoteuserNotify` - Superseded by `$wgRemoteuserUserPrefs`.
+* `$wgAuthRemoteuserDomain` - Superseded by
+  `$wgRemoteuserUserNameReplaceFilter`.
+* `$wgAuthRemoteuserMailDomain` - Superseded by `$wgRemoteuserUserPrefs`.
+
+
+Additional notes
+----------------
+
+For a complete list of authors and any further documentation see the
+file `extension.json` or the `Special:Version` page on your wiki
+installation after you have enabled this extension.
+
+For the license see the file `COPYING`.
diff --git a/extension.json b/extension.json
new file mode 100644
index 0000000..f54b3f4
--- /dev/null
+++ b/extension.json
@@ -0,0 +1,48 @@
+{
+       "name": "Auth_remoteuser",
+       "version": "2.0.0",
+       "requires": {
+               "MediaWiki": ">= 1.27.0"
+       },
+       "config": {
+               "_prefix": "wgAuthRemoteuser",
+               "UserName": null,
+               "UserNameReplaceFilter": null,
+               "UserNameBlacklistFilter": null,
+               "UserNameWhitelistFilter": null,
+               "UserPrefs": null,
+               "UserPrefsForced": null,
+               "UserUrls": null,
+               "AllowUserSwitch": false,
+               "RemoveAuthPagesAndLinks": true,
+               "Priority": 50
+       },
+       "type": "other",
+       "author": [
+               "[[mw:User:Otheus|Otheus Shelling]]",
+               "[http://www.csh.rit.edu/~gicode Rusty Burchfield]",
+               "[[mw:User:VibroAxe|James Kinsman]]",
+               "Daniel Thomas",
+               "Ian Ward Comfort",
+               "[[mw:User:MarkAHershberger|Mark A. Hershberger]]",
+               "[https://wikitech.wikimedia.org/wiki/User:Enst80 Stefan 
Engelhardt]"
+       ],
+       "url": "https://www.mediawiki.org/wiki/Extension:Auth_remoteuser";,
+       "descriptionmsg": "auth_remoteuser-desc",
+       "MessagesDirs": {
+               "Auth_remoteuser": [
+                       "i18n"
+               ]
+       },
+       "license-name": "GPL-2.0+",
+       "SessionProviders": {
+               "Auth_remoteuser": {
+                       "class": 
"MediaWiki\\Extensions\\Auth_remoteuser\\AuthRemoteuserSessionProvider"
+               }
+       },
+       "AutoloadClasses": {
+               
"MediaWiki\\Extensions\\Auth_remoteuser\\UserNameSessionProvider": 
"src/UserNameSessionProvider.php",
+               
"MediaWiki\\Extensions\\Auth_remoteuser\\AuthRemoteuserSessionProvider": 
"src/AuthRemoteuserSessionProvider.php"
+       },
+       "manifest_version": 1
+}
diff --git a/i18n/en.json b/i18n/en.json
index 0ced9ed..008d30c 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -4,6 +4,5 @@
                        "Otheus Shelling"
                ]
        },
-       "auth_remoteuser-desc": "Automatically logs-in users using the 
<code>REMOTE_USER</code> environment variable",
-       "auth_remoteuser-wgautherror": "There is another extension using 
[https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:$wgAuth the 
<code>wgAuth</code> variable]. You can't use more than one extension using 
<code>$wgAuth</code> at the same time. If there isn't another extension, please 
make sure you set the following line in your <code>LocalSettings.php</code>:\n 
<code>$wgAuth = new Auth_remoteuser();</code>"
-}
\ No newline at end of file
+       "auth_remoteuser-desc": "Automatically logs-in users using the 
<code>REMOTE_USER</code> environment variable"
+}
diff --git a/i18n/qqq.json b/i18n/qqq.json
index d5dfd5d..35740eb 100644
--- a/i18n/qqq.json
+++ b/i18n/qqq.json
@@ -4,6 +4,5 @@
                        "Raimond Spekking"
                ]
        },
-       "auth_remoteuser-desc": "{{desc|name=Auth 
remoteuser|url=https://www.mediawiki.org/wiki/Extension:Auth_remoteuser}}";,
-       "auth_remoteuser-wgautherror": "Error message, if there is another 
Extension using $wgAuth or $wgAuth isn't set in LocalSettings.php correctly."
+       "auth_remoteuser-desc": "{{desc|name=Auth 
remoteuser|url=https://www.mediawiki.org/wiki/Extension:Auth_remoteuser}}";
 }
diff --git a/src/AuthRemoteuserSessionProvider.php 
b/src/AuthRemoteuserSessionProvider.php
new file mode 100644
index 0000000..6c55377
--- /dev/null
+++ b/src/AuthRemoteuserSessionProvider.php
@@ -0,0 +1,299 @@
+<?php
+/**
+ * This file is part of the MediaWiki extension Auth_remoteuser.
+ *
+ * Copyright (C) 2017 Stefan Engelhardt and others (for a complete list of
+ *                    authors see the file `extension.json`)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program (see the file `COPYING`); if not, write to the
+ *
+ *   Free Software Foundation, Inc.,
+ *   59 Temple Place, Suite 330,
+ *   Boston, MA 02111-1307
+ *   USA
+ *
+ * @file
+ */
+namespace MediaWiki\Extensions\Auth_remoteuser;
+
+use MediaWiki\Extensions\Auth_remoteuser\UserNameSessionProvider;
+use Hooks;
+use GlobalVarConfig;
+
+/**
+ * Session provider for the Auth_remoteuser extension.
+ *
+ * @version 2.0.0
+ * @since 2.0.0
+ */
+class AuthRemoteuserSessionProvider extends UserNameSessionProvider {
+
+       /**
+        * This extension provides the `AuthRemoteuserFilterUserName` hook.
+        *
+        * @since 2.0.0
+        */
+       const HOOKNAME = "AuthRemoteuserFilterUserName";
+
+       /**
+        * The constructor processes the extension configuration.
+        *
+        * Legacy extension parameters are still fully supported, but new 
parameters
+        * taking precedence over legacy ones. List of legacy parameters:
+        * * `$wgAuthRemoteuserAuthz`      equivalent to disabling the extension
+        * * `$wgAuthRemoteuserName`       superseded by 
`$wgRemoteuserUserPrefs`
+        * * `$wgAuthRemoteuserMail`       superseded by 
`$wgRemoteuserUserPrefs`
+        * * `$wgAuthRemoteuserNotify`     superseded by 
`$wgRemoteuserUserPrefs`
+        * * `$wgAuthRemoteuserDomain`     superseded by 
`$wgRemoteuserUserNameReplaceFilter`
+        * * `$wgAuthRemoteuserMailDomain` superseded by 
`$wgRemoteuserUserPrefs`
+        *
+        * List of global configuration parameters:
+        * * `$wgAuthRemoteuserUserName`
+        * * `$wgAuthRemoteuserUserNameReplaceFilter`
+        * * `$wgAuthRemoteuserUserNameBlacklistFilter`
+        * * `$wgAuthRemoteuserUserNameWhitelistFilter`
+        * * `$wgAuthRemoteuserUserPrefs`
+        * * `$wgAuthRemoteuserUserPrefsForced`
+        * * `$wgAuthRemoteuserUserUrls`
+        * * `$wgAuthRemoteuserAllowUserSwitch`
+        * * `$wgAuthRemoteuserRemoveAuthPagesAndLinks`
+        * * `$wgAuthRemoteuserPriority`
+        *
+        * @since 2.0.0
+        */
+       public function __construct( $params = [] ) {
+
+               # Process our extension specific configuration, but don't 
overwrite our
+               # parents `$this->config` property, because doing so will clash 
with the
+               # SessionManager setting of that property due to a different 
prefix used.
+               $conf = new GlobalVarConfig( 'wgAuthRemoteuser' );
+
+               $mapping = [
+                       'UserName' => 'remoteUserNames',
+                       'UserPrefs' => 'userPrefs',
+                       'UserPrefsForced' => 'userPrefsForced',
+                       'UserUrls' => 'userUrls',
+                       'AllowUserSwitch' => 'switchUser',
+                       'RemoveAuthPagesAndLinks' => 'removeAuthPagesAndLinks',
+                       'Priority' => 'priority'
+               ];
+
+               foreach ( $mapping as $confkey => $key ) {
+                       if ( $conf->has( $confkey ) ) {
+                               $params[ $key ] = $conf->get( $confkey );
+                       }
+               }
+
+               if ( $conf->has( 'UserNameReplaceFilter' ) &&
+                       null !== $conf->get( 'UserNameReplaceFilter' ) ) {
+                       $this->setUserNameReplaceFilter(
+                               $conf->get( 'UserNameReplaceFilter' )
+                       );
+               }
+
+               if ( $conf->has( 'UserNameBlacklistFilter' ) &&
+                       null !== $conf->get( 'UserNameBlacklistFilter' ) ) {
+                       $this->setUserNameMatchFilter(
+                               $conf->get( 'UserNameBlacklistFilter' ),
+                               false
+                       );
+               }
+
+               if ( $conf->has( 'UserNameWhitelistFilter' ) &&
+                       null !== $conf->get( 'UserNameWhitelistFilter' ) ) {
+                       $this->setUserNameMatchFilter(
+                               $conf->get( 'UserNameWhitelistFilter' ),
+                               true
+                       );
+               }
+
+               # Set default remote user name source if no other is specified.
+               if ( !isset( $params[ 'remoteUserNames' ] ) ) {
+                       $params[ 'remoteUserNames' ] = [
+                               getenv( 'REMOTE_USER' ),
+                               getenv( 'REDIRECT_REMOTE_USER' )
+                       ];
+               }
+
+               # Set default redirect url after logout if none given and user 
switching is
+               # allowed. Redirect to login page because with this extension 
in place there
+               # wouldn't be a real logout when the client gets logged-in 
again with the
+               # next request.
+               if ( !empty( $params[ 'switchUser' ] ) ) {
+                       if ( !isset( $params[ 'userUrls' ] ) || !is_array( 
$params[ 'userUrls' ] ) ) {
+                               $params[ 'userUrls' ] = [];
+                       }
+                       $params[ 'userUrls' ] += [ 'logout' => 
'Special:UserLogin' ]; 
+               }
+
+               # Prepare `userPrefs` configuration for legacy parameter 
evaluation.
+               if ( !isset( $params[ 'userPrefs' ] ) ||
+                       !is_array( $params[ 'userPrefs' ] ) ) {
+                       $params[ 'userPrefs' ] = [];
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserAuthz`.
+               #
+               # Turning all off (no autologin) will be attained by evaluating 
nothing.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'Authz' ) && !$conf->get( 'Authz' ) ) {
+                       $params[ 'remoteUserNames' ] = [];
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserName`.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'Name' ) && is_string( $conf->get( 'Name' ) ) 
&& $conf->get( 'Name' ) !== '' ) {
+                       $params[ 'userPrefs' ] += [ 'realname' => $conf->get( 
'Name' ) ];
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserMail`.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'Mail' ) && is_string( $conf->get( 'Mail' ) ) 
&& $conf->get( 'Mail' ) !== '' ) {
+                       $params[ 'userPrefs' ] += [ 'email' => $conf->get( 
'Mail' ) ];
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserNotify`.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'Notify' ) ) {
+                       $notify = $conf->get( 'Notify' ) ? 1 : 0;
+                       $params[ 'userPrefs' ] += [
+                               'enotifminoredits' => $notify,
+                               'enotifrevealaddr' => $notify,
+                               'enotifusertalkpages' => $notify,
+                               'enotifwatchlistpages' => $notify
+                       ];
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserDomain`.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'Domain' ) && is_string( $conf->get( 'Domain' 
) ) && $conf->get( 'Domain' ) !== '' ) {
+                       $this->setUserNameReplaceFilter( [
+                               '@' . $conf->get( 'Domain' ) . '$' => '',
+                               '^' . $conf->get( 'Domain' ) . '\\' => ''
+                       ] );
+               }
+
+               # Evaluation of legacy parameter `$wgAuthRemoteuserMailDomain`.
+               #
+               # Can't be used directly at this point of execution until we 
have our a valid
+               # user object with the according user name. Therefore we have 
to use the
+               # closure feature of the user preference values to defer the 
evaluation.
+               #
+               # @deprecated 2.0.0
+               if ( $conf->has( 'MailDomain' ) && is_string( $conf->get( 
'MailDomain' ) ) && $conf->get( 'MailDomain' ) !== '' ) {
+                       $domain = $conf->get( 'MailDomain' );
+                       $params[ 'userPrefs' ] += [
+                               'email' => function( $metadata ) use( $domain ) 
 {
+                                       return $metadata[ 'remoteUserName' ] . 
'@' . $domain;
+                               }
+                       ];
+               }
+
+               if ( count( $params[ 'userPrefs' ] ) < 1 ) {
+                       unset( $params[ 'userPrefs' ] );
+               }
+
+               parent::__construct( $params );
+       }
+
+       /**
+        * Helper method to apply replacement patterns to a remote user name 
before
+        * using it as an identifier into the local wiki user database.
+        *
+        * Method uses the provided hook and accepts regular expressions as 
search
+        * patterns.
+        *
+        * @param array $replacepatterns Array of search and replace patterns.
+        * @throws UnexpectedValueException Wrong parameter type given.
+        * @see preg_replace()
+        * @since 2.0.0
+        */
+       public function setUserNameReplaceFilter( $replacepatterns ) {
+
+               if ( !is_array( $replacepatterns ) ) {
+                       throw new UnexpectedValueException( __METHOD__ . ' 
expects an array as parameter.' );
+               }
+
+               Hooks::register(
+                       static::HOOKNAME,
+                       function ( &$username ) use ( $replacepatterns ) {
+                               foreach ( $replacepatterns as $pattern => 
$replacement ) {
+                                       # If $pattern is no regex, create one 
from it.
+                                       if ( @preg_match( $pattern, null ) === 
false ) {
+                                               $pattern = str_replace( '\\', 
'\\\\', $pattern );
+                                               $pattern = str_replace( '/', 
'\\/', $pattern );
+                                               $pattern = "/$pattern/";
+                                       }
+                                       $replaced = preg_replace( $pattern, 
$replacement, $username );
+                                       if ( null === $replaced ) {
+                                               return false;
+                                       }
+                                       $username = $replaced;
+                               }
+                               return true;
+                       }
+               );
+
+       }
+
+       /**
+        * Helper method to create a filter which matches the user name against 
a
+        * given list.
+        *
+        * Uses the provided hook. Each of the provided names can be a regular
+        * expression too.
+        *
+        * @param string[] $names List of names to match remote user name 
against.
+        * @param boolean $allow Either allow or disallow if name matches.
+        * @throws UnexpectedValueException Wrong parameter type given.
+        * @see preg_match()
+        * @since 2.0.0
+        */
+       public function setUserNameMatchFilter( $names, $allow ) {
+
+               if ( !is_array( $names ) ) {
+                       throw new UnexpectedValueException( __METHOD__ . ' 
expects an array as parameter.' );
+               }
+
+               $allow = (bool)$allow;
+
+               Hooks::register(
+                       static::HOOKNAME,
+                       function ( &$username ) use ( $names, $allow ) {
+                               if ( isset( $names[ $username ] ) ) {
+                                       return $allow;
+                               }
+                               foreach ( $names as $pattern ) {
+                                       # If $pattern is no regex, create one 
from it.
+                                       if ( @preg_match( $pattern, null ) === 
false ) {
+                                               $pattern = str_replace( '\\', 
'\\\\', $pattern );
+                                               $pattern = str_replace( '/', 
'\\/', $pattern );
+                                               $pattern = "/$pattern/";
+                                       }
+                                       if ( preg_match( $pattern, $username ) 
) {
+                                               return $allow;
+                                       }
+                               }
+                               return !$allow;
+                       }
+               );
+
+       }
+
+}
+
diff --git a/src/UserNameSessionProvider.php b/src/UserNameSessionProvider.php
new file mode 100644
index 0000000..c665644
--- /dev/null
+++ b/src/UserNameSessionProvider.php
@@ -0,0 +1,745 @@
+<?php
+/**
+ * This file is part of the MediaWiki extension Auth_remoteuser.
+ *
+ * Copyright (C) 2017 Stefan Engelhardt and others (for a complete list of
+ *                    authors see the file `extension.json`)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program (see the file `COPYING`); if not, write to the
+ *
+ *   Free Software Foundation, Inc.,
+ *   59 Temple Place, Suite 330,
+ *   Boston, MA 02111-1307
+ *   USA
+ *
+ * @file
+ */
+namespace MediaWiki\Extensions\Auth_remoteuser;
+
+use MediaWiki\Session\CookieSessionProvider;
+use MediaWiki\Session\SessionBackend;
+use MediaWiki\Session\SessionManager;
+use MediaWiki\Session\SessionInfo;
+use MediaWiki\Session\UserInfo;
+use WebRequest;
+use Hooks;
+use Sanitizer;
+use User;
+use Closure;
+use Title;
+
+/**
+ * MediaWiki session provider for arbitrary user name sources.
+ *
+ * A `UserNameSessionProvider` uses a given user name (the remote source takes
+ * total responsibility in authenticating that user) and tries to tie it to an
+ * according local MediaWiki user.
+ *
+ * This provider acts the same as the `CookieSessionProvider` but in contrast
+ * does not allow anonymous users per session as the `CookieSessionProvider`
+ * does. In this case a user will be set which is identified by the given
+ * user name. Additionally this provider will create a new session with the
+ * given user if no session exists for the current request. The default
+ * `CookieSessionProvider` creates new sessions on specific user activities
+ * only.
+ *
+ * @see CookieSessionProvider::provideSessionInfo()
+ * @version 2.0.0
+ * @since 2.0.0
+ */
+class UserNameSessionProvider extends CookieSessionProvider {
+
+       /**
+        * The hook identifier this class provides to filter user names.
+        *
+        * @var string
+        * @since 2.0.0
+        */
+       const HOOKNAME = "UserNameSessionProviderFilterUserName";
+
+       /**
+        * The remote user name(s) given as an array.
+        *
+        * @var string[]
+        * @since 2.0.0
+        */
+       protected $remoteUserNames;
+
+       /**
+        * User preferences applied in the moment of local account creation 
only.
+        *
+        * The preferences are given as an array of key value pairs. Each key 
relates
+        * to an according user preference option of the same name. Closures as 
values
+        * getting evaluated and should return the according value. The 
following keys
+        * are handled individually:
+        * * `realname` - Specifies the users real (display) name.
+        * * `email` - Specifies the users email address.
+        *
+        * @var array
+        * @since 2.0.0
+        */
+       protected $userPrefs;
+
+       /**
+        * User preferences applied to the user object on each request.
+        *
+        * @see self::$userPrefs
+        * @var array
+        * @since 2.0.0
+        */
+       protected $userPrefsForced;
+
+       /**
+        * Urls in links which differ from the default ones. The following keys 
are
+        * supported in this associative array:
+        * * 'logout' - Redirect to this url on logout.
+        *
+        * @var array
+        * @since 2.0.0
+        */
+       protected $userUrls;
+
+       /**
+        * Indicates if the automatically logged-in user can switch to another 
local
+        * MediaWiki account while still beeing identified by the remote user 
name.
+        *
+        * @var boolean
+        * @since 2.0.0
+        */
+       protected $switchUser;
+
+       /**
+        * Indicates if special pages related to authentication getting removed 
by us.
+        *
+        * @var boolean
+        * @since 2.0.0
+        */
+       protected $removeAuthPagesAndLinks;
+
+       /**
+        * A token unique to the remote source session.
+        *
+        * This must persist requests and if it changes, it indicates a change 
in the
+        * remote session.
+        *
+        * @var string
+        * @since 2.0.0
+        */
+       protected $remoteToken;
+
+       /**
+        * The constructor processes the class configuration.
+        *
+        * In addition to the keys of the parents constructor parameter 
`params` this
+        * constructor evaluates the following keys:
+        * * `remoteUserNames` - Either a string/closure or an array of
+        *   strings/closures listing the given remote user name(s). Each 
closure
+        *   should return a string.
+        * * `userPrefs` - @see self::$userPrefs
+        * * `userPrefsForced` - @see self::$userPrefsForced
+        * * `userUrls` - @see self::$userUrls
+        * * `switchUser` - @see self::$switchUser
+        * * `removeAuthPagesAndLinks` - @see self::$removeAuthPagesAndLinks
+        *
+        * @since 2.0.0
+        */
+       public function __construct( $params = [] ) {
+
+               # Setup configuration defaults.
+               $defaults = [
+                       'remoteUserNames' => [],
+                       'userPrefs' => null,
+                       'userPrefsForced' => null,
+                       'userUrls' => null,
+                       'switchUser' => false,
+                       'removeAuthPagesAndLinks' => true
+               ];
+
+               # Sanitize configuration and apply to own members.
+               foreach( $defaults as $key => $default) {
+                       $value = $default;
+                       if ( array_key_exists( $key, $params ) ) {
+                               switch( $key ) {
+                                       case 'remoteUserNames':
+                                               $final = [];
+                                               $names = $params[ $key ];
+                                               if ( !is_array( $names ) ) {
+                                                       $names = [ $names ];
+                                               }
+                                               foreach( $names as $name ) {
+                                                       if ( is_string( $name ) 
|| $name instanceof Closure ) {
+                                                               $final[] = 
$name;
+                                                       }
+                                               }
+                                               if ( count( $final ) ) {
+                                                       $value = $final;
+                                               }
+                                               break;
+                                       case 'userPrefs':
+                                       case 'userPrefsForced':
+                                       case 'userUrls':
+                                               if ( is_array( $params[ $key ] 
) ) {
+                                                       $value = $params[ $key 
];
+                                               }
+                                               break;
+                                       default:
+                                               $value = (bool)$params[ $key ];
+                                               break;
+                               }
+                       }
+                       $this->{ $key } = $value;
+               }
+
+               # The cookie prefix used by our parent will be the same as our 
class name to
+               # not interfere with cookies set by other instances of our 
parent.
+               $prefix = str_replace( '\\', '_', get_class( $this ) );
+               $params += [
+                       'sessionName' => $prefix . '_session',
+                       'cookieOptions' => []
+               ];
+               $params[ 'cookieOptions' ] += [ "prefix" => $prefix ];
+
+               # Let our parent sanitize the rest of the configuration.
+               parent::__construct( $params );
+       }
+
+       /**
+        * Method get's called by the SessionManager on every request for each
+        * SessionProvider installed to determine if this SessionProvider has
+        * identified a possible session.
+        *
+        * @since 2.0.0
+        */
+       public function provideSessionInfo( WebRequest $request ) {
+
+               # Loop through user names given by all remote sources. First 
hit, which
+               # matches a usable local user name, will be used for our 
SessionInfo then.
+               foreach ( $this->remoteUserNames as $remoteUserName ) {
+
+                       if ( $remoteUserName instanceof Closure ) {
+                               $remoteUserName = call_user_func( 
$remoteUserName );
+                       }
+
+                       # Keep info about remote-to-local user name processing 
for logging and
+                       # and later for provider metadata.
+                       $metadata = [ 'remoteUserName' => 
(string)$remoteUserName ];
+
+                       if ( !is_string( $remoteUserName ) || empty( 
$remoteUserName ) ) {
+                               $this->logger->warning(
+                                       "Can't login remote user 
'{remoteUserName}' automatically. " .
+                                       "Given remote user name is not of type 
string or empty.",
+                                       $metadata
+                               );
+                               continue;
+                       }
+
+                       # Process each given remote user name if needed, e.g. 
strip NTLM domain,
+                       # replace characters, rewrite to another username or 
even blacklist it by
+                       # returning false. This can be used by the wiki 
administrator to adjust
+                       # this SessionProvider to his specific needs.
+                       $filteredUserName = $remoteUserName;
+                       if ( !Hooks::run( static::HOOKNAME, [ 
&$filteredUserName ] ) ) {
+                               $metadata[ 'filteredUserName' ] = 
$filteredUserName;
+                               $this->logger->warning(
+                                       "Can't login remote user 
'{remoteUserName}' automatically. " .
+                                       "Blocked this user when applying filter 
to '{filteredUserName}'.",
+                                       $metadata
+                               );
+                               continue;
+                       }
+                       $metadata[ 'filteredUserName' ] = 
(string)$filteredUserName;
+
+                       if ( !is_string( $filteredUserName ) || empty( 
$filteredUserName ) ) {
+                               $this->logger->warning(
+                                       "Can't login remote user 
'{remoteUserName}' automatically. " .
+                                       "Filtered remote user name 
'{filteredUserName}' is not of " .
+                                       "type string or empty.",
+                                       $metadata
+                               );
+                               continue;
+                       }
+
+                       # Create a UserInfo (and User) object by given user 
name. The factory
+                       # method will take care of correct validation of user 
names. It will also
+                       # canonicalize it (e.g. transform the first letter to 
uppercase).
+                       #
+                       # An exception gets thrown when the given user name is 
not 'usable' as an
+                       # user name for the wiki, either blacklisted or 
contains invalid characters
+                       # or is an ip address.
+                       #
+                       # @see User::getCanonicalName()
+                       # @see User::isUsableName()
+                       # @see Title::newFromText()
+                       try {
+                               $userInfo = UserInfo::newFromName( 
$filteredUserName, true );
+                       } catch ( InvalidArgumentException $e ) {
+                               $metadata[ 'exception' ] = $e;
+                               $this->logger->warning(
+                                       "Can't login remote user 
'{remoteUserName}' automatically. " .
+                                       "Filtered name '{filteredUserName}' is 
not usable as an " .
+                                       "user name in MediaWiki.: {exception}",
+                                       $metadata
+                               );
+                               continue;
+                       }
+                       $metadata[ 'userId' ] = $userInfo->getId();
+                       $metadata[ 'canonicalUserName' ] = $userInfo->getName();
+
+                       # Let our parent class find a valid SessionInfo.
+                       $sessionInfo = parent::provideSessionInfo( $request );
+
+                       # Our parent class provided a session info, but the 
`$wgGroupPermission` for
+                       # creating user accounts was changed while using this 
extension. This leds
+                       # to a behaviour where a new user won't be created 
automatically even if the
+                       # wiki administrator enabled (auto) account creation by 
setting the specific
+                       # group permission `createaccount` or 
`autocreateaccount` to `true`.
+                       #
+                       # This happens in rare circurmstances only: The global 
permission forbids
+                       # account creation. A new user requests the wiki and a 
specific session is
+                       # getting created (by our parent). Then the 
`AuthManager` permits further
+                       # account creation attempts due to global permission by 
marking this session
+                       # as blacklistet. This blacklist info is stored inside 
the session itself.
+                       # Now when the wiki admin changes the global account 
creation permission to
+                       # `true` and the new user wants to access the wiki, 
then his account is not
+                       # created automatically due to this blacklist marking 
inside his current
+                       # session, identified by our parent class. Hence we 
throw this session away
+                       # in these rare cases (We could manipulate the session 
itself and delete that
+                       # `AuthManager::AutoCreateBlacklist` key instead, but 
that would look like
+                       # real hacked code inside this method).
+                       #
+                       # @see AuthManager::AutoCreateBlacklist
+                       # @see AuthManager::autoCreateUser()
+                       if ( $sessionInfo && !$userInfo->getId() ) {
+                               $anon = $userInfo->getUser();
+                               $permissions = $anon->getGroupPermissions( 
$anon->getEffectiveGroups() );
+                               if ( in_array( 'autocreateaccount', 
$permissions, true ) ||
+                                       in_array( 'createaccount', 
$permissions, true ) ) {
+                                       $this->logger->warning(
+                                               "Renew session due to global 
permission change " .
+                                               "in (auto) creating new users."
+                                       );
+                                       $sessionInfo = null;
+                               }
+                       }
+
+                       # If our parent provides a session info, it could be 
from an old request
+                       # where the old remote user name doesn't match the one 
used for the current
+                       # request. This happens when the client switched the 
user remotely (because
+                       # he has access to two different accounts at the remote 
source). Therefore
+                       # we have to mark the local authentication part (the 
cookie, because we
+                       # inherit from `CookieSessionProvider`) and compare it 
against the current
+                       # request. We use the `filteredUserName` instead of 
`remoteuserName` for the
+                       # comparison, because the wiki admin could have mapped 
two differing remote
+                       # user names to the same local username with an 
according filter. For the
+                       # marking itself we have to overwrite some inherited 
methods.
+                       #
+                       # @see self::getCookieDataToExport()
+                       # @see self::persistSession()
+                       if ( $sessionInfo ) {
+                               $prefix = $this->cookieOptions[ 'prefix' ];
+                               $old = $this->getCookie( $request, 
'RemoteToken', $prefix );
+                               if ( $old !== $filteredUserName ) {
+                                       $this->logger->warning(
+                                               "Renew local session due to 
remote session change."
+                                       );
+                                       $sessionInfo = null;
+                               }
+                       }
+
+                       # Our parent class couldn't provide any info. This 
means we can create a
+                       # new session with our identified user.
+                       if ( !$sessionInfo ) {
+                               $sessionInfo = new SessionInfo( 
$this->priority, [
+                                       'provider' => $this,
+                                       'id' => 
$this->manager->generateSessionId(),
+                                       'userInfo' => $userInfo
+                                       ]
+                               );
+                       }
+
+                       # The current session identifies an anonymous user, 
therefore we have to
+                       # use the forceUse flag to set our identified user. If 
we are configured
+                       # to forbid user switching, force the usage of our 
identified user too.
+                       if ( !$sessionInfo->getUserInfo() || 
!$sessionInfo->getUserInfo()->getId()
+                               || ( !$this->switchUser && 
$sessionInfo->getUserInfo()->getId() !== $userInfo->getId() ) ) {
+                               $sessionInfo = new SessionInfo( 
$sessionInfo->getPriority(), [
+                                       'copyFrom' => $sessionInfo,
+                                       'userInfo' => $userInfo,
+                                       'forceUse' => true
+                                       ]
+                               );
+                       }
+
+                       # Store info about user in the provider metadata.
+                       $metadata[ 'canonicalUserNameUsed' ] = 
$sessionInfo->getUserInfo()->getName();
+                       $sessionInfo = new SessionInfo( 
$sessionInfo->getPriority(), [
+                               'copyFrom' => $sessionInfo,
+                               'metadata' => $metadata
+                               ]
+                       );
+
+                       return $sessionInfo;
+               }
+
+               # We didn't identified anything, so let other SessionProviders 
do their work.
+               return null;
+       }
+
+       /**
+        * Never use the stored metadata and return the provided one in any 
case.
+        *
+        * But let our parents implementation of this method decide on his own 
for the
+        * other members.
+        *
+        * @since 2.0.0
+        */
+       public function mergeMetadata( array $savedMetadata, array 
$providedMetadata ) {
+               $keys = [
+                       'userId',
+                       'remoteUserName',
+                       'filteredUserName',
+                       'canonicalUserName',
+                       'canonicalUserNameUsed'
+               ];
+               foreach ( $keys as $key ) {
+                       $savedMetadata[ $key ] = $providedMetadata[ $key ];
+               }
+               return parent::mergeMetadata( $savedMetadata, $providedMetadata 
);
+       }
+
+       /**
+        * The SessionManager selected us as the SessionProvider for this 
request.
+        *
+        * Now we can add additional information to the requests user object and
+        * remove some special pages and personal urls from the clients 
frontend.
+        *
+        * @since 2.0.0
+        */
+       public function refreshSessionInfo( SessionInfo $info, WebRequest 
$request, &$metadata ) {
+
+               $this->logger->info( "Setting up auto login session for remote 
user name " .
+                       "'{remoteUserName}' (mapped to MediaWiki user 
'{canonicalUserName}', " .
+                       "currently active as MediaWiki user 
'{canonicalUserNameUsed}').",
+                       $metadata
+               );
+
+               $disableSpecialPages = [];
+               $disablePersonalUrls = [];
+               $preferences = ( $this->userPrefsForced ) ? 
$this->userPrefsForced : [];
+
+               # Disable any special pages related to user switching.
+               if ( !$this->switchUser ) {
+                       $disableSpecialPages += [
+                               'Userlogin',
+                               'Userlogout',
+                               'CreateAccount',
+                               'LinkAccounts',
+                               'UnlinkAccounts',
+                               'ChangeCredentials',
+                               'RemoveCredentials'
+                       ];
+               }
+
+               # This can only be true, if our `switchUser` member is set to 
true and the
+               # user identified by us uses another local wiki user for this 
session.
+               $switchedUser = ( $info->getUserInfo()->getId() !== $metadata[ 
'userId' ] ) ? true : false;
+
+               # Disable password related special pages and hide preference 
option.
+               if ( !$switchedUser ) {
+                       $disableSpecialPages += [ 'ChangePassword', 
'PasswordReset' ];
+                       global $wgHiddenPrefs;
+                       $wgHiddenPrefs[] = 'password';
+               }
+
+               # Redirect to given remote logout url. Either by redirect after 
a normal
+               # logout request to Special:UserLogout or by replacing the url 
in the logout
+               # button when user switching is not allowed and therefore the 
special page for
+               # logout is not accessible.
+               #
+               # When the special page UserLogout is accessible, then we have 
to distinguish
+               # between internal and external redirects. For internal 
redirects we have to
+               # use the `UserLogout` hook to redirect before the local 
session/cookie will
+               # be deleted. Because with this session provider in place we 
would login the
+               # user with the next request again anyway (so no need to 
destroy the session).
+               # For external redirects we must delete the local 
session/cookie first,
+               # therefore we use the `UserLogoutComplete` hook for these type 
of urls.
+               if ( $this->userUrls && isset( $this->userUrls[ 'logout' ] ) ) {
+                       $url = $this->userUrls[ 'logout' ];
+                       if ( $this->canChangeUser() ) {
+                               Hooks::register(
+                                       'UserLogout',
+                                       function() use ( $url, $metadata, 
$switchedUser ) {
+                                               if ( $url instanceof Closure ) {
+                                                       $url = call_user_func( 
$url, $metadata );
+                                               }
+                                               $internal = Title::newFromText( 
$url );
+                                               $known = $internal->isKnown();
+                                               if ( $known ) {
+                                                       $url = 
$internal->getFullURL();
+                                               }
+                                               if ( $known && !$switchedUser ) 
{
+                                                       # Inhibit redirect loop.
+                                                       if ( !preg_match( 
'#[/=]Special:UserLogout([/?&].*)?$#', $url ) ) {
+                                                               global $wgOut;
+                                                               
$wgOut->redirect( $url );
+                                                       }
+                                                       return false;
+                                               }
+                                               Hooks::register(
+                                                       'UserLogoutComplete',
+                                                       function() use ( $url ) 
{
+                                                               global $wgOut;
+                                                               
$wgOut->redirect( $url );
+                                                               return true;
+                                                       }
+                                               );
+                                               return true;
+                                       }
+                               );
+                       } else {
+                               Hooks::register(
+                                       'PersonalUrls',
+                                       function( &$personalurls ) use ( $url, 
$metadata ) {
+                                               if ( $url instanceof Closure ) {
+                                                       $url = call_user_func( 
$url, $metadata );
+                                               }
+                                               $internal = Title::newFromText( 
$url );
+                                               if ( $internal->isKnown() ) {
+                                                       $url = 
$internal->getLinkURL();
+                                               }
+                                               $personalurls[ 'logout' ][ 
'href' ] = $url;
+                                               return true;
+                                       }
+                               );
+                       }
+               } elseif ( !$switchedUser ) {
+                       $disablePersonalUrls[] = 'logout';
+               }
+
+               # Set user preferences on account creation only.
+               if ( !$info->getUserInfo()->getId() ) {
+                       $prefs = $preferences;
+                       if ( $this->userPrefs ) {
+                               $prefs += $this->userPrefs;
+                       }
+                       Hooks::register(
+                               'LocalUserCreated',
+                               function( $user, $autoCreated ) use ( $prefs, 
$metadata ) {
+                                       if ( $autoCreated ) {
+                                               $this->setUserPrefs(
+                                                       $user,
+                                                       $prefs,
+                                                       $metadata
+                                               );
+                                       }
+                               }
+                       );
+               }
+
+               # Set user preferences on each request.
+               #
+               # Forcing user preferences is useful if they are provided by an 
external
+               # source and must not be changed by the user himself.
+               #
+               # @see $wgGroupPermissions['user']['editmyoptions']
+               if ( !$switchedUser && count( $preferences ) ) {
+
+                       $this->setUserPrefs(
+                               $info->getUserInfo()->getUser(),
+                               $preferences,
+                               $metadata,
+                               true
+                       );
+
+                       # Disable special pages related to email preferences.
+                       if ( array_key_exists( 'email', $preferences ) ) {
+                               $disableSpecialPages += [
+                                       'ChangeEmail',
+                                       'Confirmemail',
+                                       'Invalidateemail'
+                               ];
+                       }
+
+                       # Do not hide forced preferences completely by using 
the global
+                       # `$wgHiddenPrefs`, because we still want them to be 
shown to the user.
+                       # Therefore use the according hook to disable their 
editing capabilities.
+                       $keys = array_keys( $preferences );
+                       Hooks::register(
+                               'GetPreferences',
+                               function( $user, &$prefs ) use ( $keys ) {
+                                       foreach( $keys as $key ) {
+
+                                               if ( 'email' === $key ) {
+                                                       $key = 'emailaddress';
+                                               }
+
+                                               if ( !array_key_exists( $key, 
$prefs ) ) {
+                                                       continue;
+                                               }
+
+                                               # Email preference needs 
special treatment, because it will display a
+                                               # link to change the address. 
We have to replace that with the address
+                                               # only.
+                                               if ( 'emailaddress' === $key ) {
+                                                       $prefs[ $key ][ 
'default' ] = $user->getEmail() ?
+                                                               
htmlspecialchars( $user->getEmail() ) : '';
+                                               }
+
+                                               $prefs[ $key ][ 'disabled' ] = 
'disabled';
+
+                                       }
+                               }
+                       );
+               }
+
+               # Don't remove anything.
+               if ( !$this->removeAuthPagesAndLinks ) {
+                       $disableSpecialPages = [];
+                       $disablePersonalUrls = [];
+               }
+
+               Hooks::register(
+                       'SpecialPage_initList',
+                       function ( &$specials ) use ( $disableSpecialPages ) {
+                               foreach ( $disableSpecialPages as $page ) {
+                                       unset( $specials[ $page ] );
+                               }
+                               return true;
+                       }
+               );
+
+               Hooks::register(
+                       'PersonalUrls',
+                       function ( &$personalurls ) use ( $disablePersonalUrls 
) {
+                               foreach ( $disablePersonalUrls as $url ) {
+                                       unset( $personalurls[ $url ] );
+                               }
+                               return true;
+                       }
+               );
+
+               return true;
+       }
+
+       /**
+        * We do support user switching (as inherited by our parent).
+        *
+        * This setting let us support the behaviour of Auth_remoteuser 
versions prior
+        * 2.0.0, where switching the logged-in local user (as denoted by the 
wiki
+        * database) wasn't possible.
+        *
+        * User switching is useful when your remote user is tied to a local 
wiki user,
+        * but needs access as another local user, e.g. a bot account, which in 
itself
+        * can never be identified as any remote user.
+        *
+        * @since 2.0.0
+        */
+       public function canChangeUser() {
+               return ( $this->switchUser ) ? parent::canChangeUser() : false;
+       }
+
+       /**
+        * Mark the cookie with current remote token.
+        *
+        * @since 2.0.0
+        */
+       protected function cookieDataToExport( $user, $remember ) {
+               return [ 'RemoteToken' => $this->remoteToken ] +
+                       parent::cookieDataToExport( $user, $remember );
+       }
+
+       /**
+        * Specify remote token.
+        *
+        * @since 2.0.0
+        */
+       public function persistSession( SessionBackend $session, WebRequest 
$request ) {
+               $metadata = $session->getProviderMetadata();
+               $this->remoteToken = $metadata[ 'filteredUserName' ];
+               return parent::persistSession( $session, $request );
+       }
+
+       /**
+        * Helper method to supplement (new local) users with additional 
information.
+        *
+        * The `$preferences` parameter contains an array of key => value 
pairs, where
+        * the keys `realname` and `email` are taken for the users real name 
and email
+        * address. All other keys in that array will be handled as an option 
into the
+        * users preference settings. Each value can also be of type Closure to 
get
+        * called when the value is evaluated. This type of late binding should 
then
+        * return the real value and could be useful, if you want to delegate 
the
+        * execution of code to a point where it is really needed and not inside
+        * `LocalSettings.php`. The first parameter given to such an anonymous 
function
+        * is an associative array with the following keys:
+        * * `userId` - id of user in local wiki database or 0 if new/anonymous
+        * * `remoteUserName` - value as given by the remote source
+        * * `filteredUserName` - after running hook for filtering of user names
+        * * `canonicalUserName` - representation in the local wiki database
+        * * `canonicalUserNameUsed` - the user name used for the current 
session
+        *
+        * @param User $user
+        * @param Array $preferences
+        * @param Array $metadata
+        * @param boolean $saveToDB Save changes to database with this funtion 
call.
+        * @see User::setRealName()
+        * @see User::setEmail()
+        * @see User::setOption()
+        * @since 2.0.0
+        */
+       public function setUserPrefs( $user, $preferences, $metadata, $saveToDB 
= false ) {
+
+               if ( $user instanceof User && is_array( $preferences ) && 
is_array( $metadata ) ) {
+
+                       # Mark changes to prevent superfluous database writings.
+                       $dirty = false;
+
+                       foreach ( $preferences as $option => $value ) {
+
+                               # If the given value is a closure, call it to 
get the value. All of our
+                               # provider metadata is exposed to this function 
as first parameter.
+                               if ( $value instanceof Closure ) {
+                                       $value = call_user_func( $value, 
$metadata );
+                               }
+
+                               switch ( $option ) {
+                                       case 'realname':
+                                               if ( is_string( $value ) && 
$value !== $user->getRealName() ) {
+                                                       $dirty = true;
+                                                       $user->setRealName( 
$value );
+                                               }
+                                               break;
+                                       case 'email':
+                                               if ( Sanitizer::validateEmail( 
$value ) && $value !== $user->getEmail() ) {
+                                                       $dirty = true;
+                                                       $user->setEmail( $value 
);
+                                                       $user->confirmEmail();
+                                               }
+                                               break;
+                                       default:
+                                               if ( $value != 
$user->getOption( $option ) ) {
+                                                       $dirty = true;
+                                                       $user->setOption( 
$option, $value );
+                                               }
+                               }
+                       }
+
+                       # Only update database if something has changed.
+                       if ( $saveToDB && $dirty ) {
+                               $user->saveSettings();
+                       }
+               }
+
+       }
+
+}
+

-- 
To view, visit https://gerrit.wikimedia.org/r/349273
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ia43098ea5b1b9b1138611c59181e34ed1a080586
Gerrit-PatchSet: 1
Gerrit-Project: mediawiki/extensions/Auth_remoteuser
Gerrit-Branch: REL1_28
Gerrit-Owner: Enst80 <stefan.engelha...@dlr.de>

_______________________________________________
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to