/**
  * Check that we can perform the rename
  *
  * @param User $oldUser
  * @param User $newUser
  *
  * @return Status
  */
 public function validate(User $oldUser, User $newUser)
 {
     $status = new Status();
     if (!User::isCreatableName($newUser->getName())) {
         $status->fatal('centralauth-rename-badusername');
     }
     $caOldUser = CentralAuthUser::getInstance($oldUser);
     if (!$caOldUser->exists()) {
         $status->fatal('centralauth-rename-doesnotexist');
     }
     $caNewUser = CentralAuthUser::getInstance($newUser);
     if ($caNewUser->exists()) {
         $status->fatal('centralauth-rename-alreadyexists');
     }
     $unattached = $caNewUser->listUnattached();
     if ($unattached) {
         $status->fatal('centralauth-rename-unattached-intheway');
     }
     // Check we're not currently renaming the user
     $renameState = $caOldUser->renameInProgress();
     if ($renameState) {
         $status->fatal('centralauth-rename-alreadyinprogress', $renameState[1]);
     }
     return $status;
 }
Example #2
0
/**
 * Given a username, returns one of several codes to indicate whether it is valid to be a NEW username or not.
 *
 * Codes:
 * - OK: A user with this username may be created.
 * - INVALID: This is not a valid username.  This may mean that it is too long or has characters that aren't permitted, etc.
 * - EXISTS: A user with this name, so you cannot create one with this name.
 *
 * TODO: Is this a duplicate of user::isCreatableName()? It is important to note that wgWikiaMaxNameChars may be less than wgMaxNameChars which
 * is intentional because there are some long usernames that were created when only wgMaxNameChars limited to 255 characters and we still want
 * those usernames to be valid (so that they can still login), but we just don't want NEW accounts to be created above the length of wgWikiaMaxNameChars.
 *
 * @param string $uName The user name to check
 *
 * @return bool|string Return errors as an i18n key or true if the name is valid
 */
function wfValidateUserName($uName)
{
    if (!User::isNotMaxNameChars($uName)) {
        return 'userlogin-bad-username-length';
    }
    $userTitle = Title::newFromText($uName);
    if (is_null($userTitle)) {
        return 'userlogin-bad-username-character';
    }
    $uName = $userTitle->getText();
    if (!User::isCreatableName($uName)) {
        return 'userlogin-bad-username-character';
    }
    $dbr = wfGetDB(DB_SLAVE);
    $uName = $dbr->strencode($uName);
    if ($uName == '') {
        return 'userlogin-bad-username-character';
    }
    if (class_exists('SpoofUser')) {
        $spoof = new SpoofUser($uName);
        if ($spoof->isLegal()) {
            $conflicts = $spoof->getConflicts();
            if (!empty($conflicts)) {
                return 'userlogin-bad-username-taken';
            }
        }
    }
    if (in_array($uName, F::app()->wg->ReservedUsernames)) {
        // if we returned 'invalid', that would be confusing once a user
        // checked and found that the name already met the naming requirements.
        return 'userlogin-bad-username-taken';
    }
    // This username is valid
    return true;
}
Example #3
0
/**
 * Given a username, returns one of several codes to indicate whether it is valid to be a NEW username or not.
 *
 * Codes:
 * - OK: A user with this username may be created.
 * - INVALID: This is not a valid username.  This may mean that it is too long or has characters that aren't permitted, etc.
 * - EXISTS: A user with this name, so you cannot create one with this name.
 *
 * TODO: Is this a duplicate of user::isCreatableName()? It is important to note that wgWikiaMaxNameChars may be less than wgMaxNameChars which
 * is intentional because there are some long usernames that were created when only wgMaxNameChars limited to 255 characters and we still want
 * those usernames to be valid (so that they can still login), but we just don't want NEW accounts to be created above the length of wgWikiaMaxNameChars.
 */
function wfValidateUserName($uName)
{
    wfProfileIn(__METHOD__);
    $result = true;
    #wfMsg ('username-valid');
    $nt = Title::newFromText($uName);
    if (!User::isNotMaxNameChars($uName)) {
        $result = 'userlogin-bad-username-length';
    } elseif (is_null($nt)) {
        $result = 'userlogin-bad-username-character';
    } else {
        $uName = $nt->getText();
        if (!User::isCreatableName($uName)) {
            $result = 'userlogin-bad-username-character';
        } else {
            $dbr = wfGetDB(DB_SLAVE);
            $uName = $dbr->strencode($uName);
            if ($uName == '') {
                $result = 'userlogin-bad-username-character';
            } else {
                if (User::idFromName($uName) != 0) {
                    $result = 'userlogin-bad-username-taken';
                }
                global $wgReservedUsernames;
                if (in_array($uName, $wgReservedUsernames)) {
                    $result = 'userlogin-bad-username-taken';
                    // if we returned 'invalid', that would be confusing once a user checked and found that the name already met the naming requirements.
                }
            }
        }
    }
    wfProfileOut(__METHOD__);
    return $result;
}
 public static function onUserLoadFromSession($user, &$result)
 {
     $result = false;
     // don't attempt default auth process
     if (!isset($_SERVER['SSL_CLIENT_S_DN'])) {
         return true;
     }
     $parsed = self::parseDistinguishedName($_SERVER['SSL_CLIENT_S_DN']);
     if (!isset($parsed['CN'])) {
         return true;
     }
     $userName = $parsed['CN'];
     $localId = User::idFromName($userName);
     if ($localId === null) {
         // local user doesn't exists yet
         $user->loadDefaults($parsed['CN']);
         if (!User::isCreatableName($user->getName())) {
             wfDebug(__METHOD__ . ": Invalid username\n");
             return true;
         }
         $user->addToDatabase();
         if (isset($parsed['emailAddress'])) {
             $user->setEmail($parsed['emailAddress']);
         }
         $user->saveSettings();
         $user->addNewUserLogEntryAutoCreate();
         Hooks::run('AuthPluginAutoCreate', array($user));
         DeferredUpdates::addUpdate(new SiteStatsUpdate(0, 0, 0, 0, 1));
     } else {
         $user->setID($localId);
         $user->loadFromId();
     }
     global $wgUser;
     $wgUser =& $user;
     $result = true;
     // this also aborts default auth process
     return true;
 }
 public function checkUser($username, $output = false)
 {
     global $wgOut;
     $bits = explode('@', $username, 2);
     if (count($bits) == 1) {
         if ($output) {
             $this->showForm(wfMsgWikiHtml('crosswikiblock-local'));
         }
         return array('local');
     }
     list($name, $db) = $bits;
     if (!UserRightsProxy::validDatabase($db)) {
         if ($output) {
             $this->showForm(wfMsgWikiHtml('crosswikiblock-dbnotfound', htmlspecialchars($db)));
         }
         return array('dbnotfound', $db);
     }
     if (!User::isIP($name) && !User::isCreatableName($name)) {
         if ($output) {
             $this->showForm(wfMsgWikiHtml('crosswikiblock-noname', htmlspecialchars($name)));
         }
         return array('invalidname', $name);
     }
     if (!User::isIP($name)) {
         $userProxy = UserRightsProxy::newFromName($db, $name);
         $this->mUserProxy = $userProxy;
         if (!$userProxy) {
             if ($output) {
                 $this->showForm(wfMsgWikiHtml('crosswikiblock-nouser', htmlspecialchars($name), htmlspecialchars($db), htmlspecialchars($username)));
             }
             return array('usernotfound', $name, $db, $username);
         }
     }
     $this->mUsername = $name;
     $this->mDatabase = $db;
     return false;
 }
 /**
  * Validates username user enters on rename account form
  *
  * @author grunny
  */
 private function validateUserName($userName)
 {
     global $wgWikiaMaxNameChars;
     if ($userName == '') {
         $this->err[] = $this->msg('userlogin-error-noname')->escaped();
         $this->errInputs['wpUserNameNew'] = true;
         return false;
     }
     // check username length
     if (!User::isNotMaxNameChars($userName)) {
         $this->err[] = $this->msg('usersignup-error-username-length', $wgWikiaMaxNameChars)->escaped();
         $this->errInputs['wpUserNameNew'] = true;
         return false;
     }
     // check valid username
     if (!User::isCreatableName($userName)) {
         $this->err[] = $this->msg('usersignup-error-symbols-in-username')->escaped();
         $this->errInputs['wpUserNameNew'] = true;
         return false;
     }
     $result = wfValidateUserName($userName);
     if ($result === true) {
         $msgKey = '';
         if (!wfRunHooks('cxValidateUserName', array($userName, &$msgKey))) {
             $result = $msgKey;
         }
     }
     if ($result !== true) {
         $msg = '';
         if ($result === 'userlogin-bad-username-taken') {
             $msg = $this->msg('userlogin-error-userexists')->escaped();
         } else {
             if ($result === 'userlogin-bad-username-character') {
                 $msg = $this->msg('usersignup-error-symbols-in-username')->escaped();
             } else {
                 if ($result === 'userlogin-bad-username-length') {
                     $msg = $this->msg('usersignup-error-username-length', $wgWikiaMaxNameChars)->escaped();
                 }
             }
         }
         $this->err[] = empty($msg) ? $result : $msg;
         $this->errInputs['wpUserNameNew'] = true;
         return false;
     }
     return true;
 }
Example #7
0
 /**
  * Given unvalidated user input, return a canonical username, or false if 
  * the username is invalid.
  * @param string $name
  * @param mixed $validate Type of validation to use:
  *                         false        No validation
  *                         'valid'      Valid for batch processes
  *                         'usable'     Valid for batch processes and login
  *                         'creatable'  Valid for batch processes, login and account creation
  */
 static function getCanonicalName($name, $validate = 'valid')
 {
     # Force usernames to capital
     global $wgContLang;
     $name = $wgContLang->ucfirst($name);
     # Clean up name according to title rules
     $t = Title::newFromText($name);
     if (is_null($t)) {
         return false;
     }
     # Reject various classes of invalid names
     $name = $t->getText();
     global $wgAuth;
     $name = $wgAuth->getCanonicalName($t->getText());
     switch ($validate) {
         case false:
             break;
         case 'valid':
             if (!User::isValidUserName($name)) {
                 $name = false;
             }
             break;
         case 'usable':
             if (!User::isUsableName($name)) {
                 $name = false;
             }
             break;
         case 'creatable':
             if (!User::isCreatableName($name)) {
                 $name = false;
             }
             break;
         default:
             throw new MWException('Invalid parameter value for $validate in ' . __METHOD__);
     }
     return $name;
 }
 /**
  * Hook to add objectclasses and attributes for users being created.
  *
  * @static
  * @param  $auth
  * @param  $username
  * @param  $values
  * @param  $writeloc
  * @param  $userdn
  * @param  $result
  * @return bool
  */
 static function LDAPSetCreationValues($auth, $username, &$values, $writeloc, &$userdn, &$result)
 {
     global $wgOpenStackManagerLDAPDefaultGid;
     global $wgOpenStackManagerLDAPDefaultShell;
     global $wgOpenStackManagerLDAPUseUidAsNamingAttribute;
     global $wgRequest;
     $values['objectclass'][] = 'person';
     $values['objectclass'][] = 'ldappublickey';
     $values['objectclass'][] = 'posixaccount';
     $values['objectclass'][] = 'shadowaccount';
     $uidnumber = OpenStackNovaUser::getNextIdNumber($auth, 'uidnumber');
     if (!$uidnumber) {
         $auth->printDebug("Unable to allocate a UID", NONSENSITIVE);
         $result = false;
         return false;
     }
     $values['cn'] = $username;
     if ('' !== $auth->realname) {
         $values['displayname'] = $auth->realname;
     }
     $shellaccountname = $wgRequest->getText('shellaccountname');
     if (!preg_match("/^[a-z][a-z0-9\\-_]*\$/", $shellaccountname)) {
         $auth->printDebug("Invalid shell name {$shellaccountname}", NONSENSITIVE);
         $result = false;
         return false;
     }
     $check = ucfirst($shellaccountname);
     if (!User::isCreatableName($check)) {
         $auth->printDebug("{$shellaccountname} is not a creatable name.", NONSENSITIVE);
         $result = false;
         return false;
     }
     $values['uid'] = $shellaccountname;
     $base = $auth->getBaseDN(USERDN);
     # Though the LDAP plugin checks to see if the user account exists,
     # it does not check to see if the uid attribute is already used.
     $result = LdapAuthenticationPlugin::ldap_search($auth->ldapconn, $base, "(uid={$shellaccountname})");
     if ($result) {
         $entries = LdapAuthenticationPlugin::ldap_get_entries($auth->ldapconn, $result);
         if ((int) $entries['count'] > 0) {
             $auth->printDebug("User {$shellaccountname} already exists.", NONSENSITIVE);
             # uid attribute is already in use, fail.
             $result = false;
             return false;
         }
     }
     $values['uidnumber'] = $uidnumber;
     $values['gidnumber'] = $wgOpenStackManagerLDAPDefaultGid;
     $values['homedirectory'] = '/home/' . $shellaccountname;
     $values['loginshell'] = $wgOpenStackManagerLDAPDefaultShell;
     if ($wgOpenStackManagerLDAPUseUidAsNamingAttribute) {
         if ($writeloc === '') {
             $auth->printDebug("Trying to set the userdn, but write location isn't set.", NONSENSITIVE);
             return false;
         } else {
             $userdn = 'uid=' . $shellaccountname . ',' . $writeloc;
             $auth->printDebug("Using uid as the naming attribute, dn is: {$userdn}", NONSENSITIVE);
         }
     }
     $auth->printDebug("User account's objectclasses: ", NONSENSITIVE, $values['objectclass']);
     return true;
 }
 function validatePOSTParams()
 {
     global $wgUser, $wgAuth;
     $user = User::newFromId($this->userid);
     if (!$user->loadFromId()) {
         throw new InvalidPOSTParamException(wfMsg('uadm-failedtoloadfromidmsg', $this->userid));
     }
     $this->username = strtoupper(substr($this->username, 0, 1)) . substr($this->username, 1);
     // in case the user changes the case of the first character
     // Validate FORM
     if (empty($this->username)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->usernamefield));
     }
     // changing user name?
     if ($user->getName() != $this->username) {
         // check if its already being used
         if (User::idFromName($this->username) !== null) {
             throw new InvalidPOSTParamException(wfMsg('uadm-usernameinusemsg', $this->username));
         }
         if (!User::isCreatableName($this->username)) {
             throw new InvalidPOSTParamException(wfMsg('uadm-invalidusernamemsg', $this->usernamefield));
         }
         if ($this->domain != 'local' && $this->domain != '') {
             if (!$wgAuth->validDomain($this->domain)) {
                 throw new InvalidPOSTParamException(wfMsg('uadm-invaliddomainmsg'));
             }
             $wgAuth->setDomain($this->domain);
             if ($wgAuth->userExists($this->username)) {
                 throw new InvalidPOSTParamException(wfMsg('uadm-usernameinusemsg', $this->username));
             }
         }
     }
     //    if(!$wgUser->matchEditToken(stripslashes($this->edittoken), $this->userid))
     if (!$wgUser->matchEditToken($this->edittoken, $this->userid)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-formsubmissionerrormsg'));
     }
     if (empty($this->email)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->emailfield));
     }
     //if(!User::isValidEmailAddr($this->email))
     if (!Sanitizer::validateEmail($this->email)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-invalidemailmsg', $this->emailfield));
     }
     if (empty($this->reason)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->reasonfield));
     }
     if (empty($this->pwdaction)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-formsubmissionerrormsg'));
     }
     if ($this->action == 'saveuser' && $this->pwdaction == 'manual') {
         if (empty($this->password1) || empty($this->password2)) {
             throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->passwordfield));
         }
         if ($this->password1 != $this->password2) {
             throw new InvalidPOSTParamException(wfMsg('uadm-passwordsmustmatchmsg'));
         }
         //      $result = $user->checkPassword($this->password1);
         //      if($result !== true)
         //        throw new InvalidPOSTParamException(wfMsg('uadm-invalidpasswordmsg'));
     }
     return $user;
 }
Example #10
0
 /**
  * Given unvalidated user input, return a canonical username, or false if
  * the username is invalid.
  * @param $name String User input
  * @param $validate String|Bool type of validation to use:
  *                - false        No validation
  *                - 'valid'      Valid for batch processes
  *                - 'usable'     Valid for batch processes and login
  *                - 'creatable'  Valid for batch processes, login and account creation
  *
  * @return bool|string
  */
 public static function getCanonicalName($name, $validate = 'valid')
 {
     # Force usernames to capital
     global $wgContLang;
     $name = $wgContLang->ucfirst($name);
     # Reject names containing '#'; these will be cleaned up
     # with title normalisation, but then it's too late to
     # check elsewhere
     if (strpos($name, '#') !== false) {
         return false;
     }
     # Clean up name according to title rules
     $t = $validate === 'valid' ? Title::newFromText($name) : Title::makeTitle(NS_USER, $name);
     # Check for invalid titles
     if (is_null($t)) {
         return false;
     }
     # Reject various classes of invalid names
     global $wgAuth;
     $name = $wgAuth->getCanonicalName($t->getText());
     switch ($validate) {
         case false:
             break;
         case 'valid':
             if (!User::isValidUserName($name)) {
                 $name = false;
             }
             break;
         case 'usable':
             if (!User::isUsableName($name)) {
                 $name = false;
             }
             break;
         case 'creatable':
             if (!User::isCreatableName($name)) {
                 $name = false;
             }
             break;
         default:
             throw new MWException('Invalid parameter value for $validate in ' . __METHOD__);
     }
     return $name;
 }
 /**
  * Attempt to add a user to the database
  * Does the required authentication checks and updates for auto-creation
  * @param $user User
  * @throws Exception
  * @return bool Success
  */
 static function attemptAddUser($user)
 {
     global $wgAuth, $wgCentralAuthCreateOnView;
     $userName = $user->getName();
     // Denied by configuration?
     if (!$wgAuth->autoCreate()) {
         wfDebug(__METHOD__ . ": denied by configuration\n");
         return false;
     }
     if (!$wgCentralAuthCreateOnView) {
         // Only create local accounts when we perform an active login...
         // Don't freak people out on every page view
         wfDebug(__METHOD__ . ": denied by \$wgCentralAuthCreateOnView\n");
         return false;
     }
     // Is the user blacklisted by the session?
     // This is just a cache to avoid expensive DB queries in $user->isAllowedToCreateAccount().
     // The user can log in via Special:UserLogin to bypass the blacklist and get a proper
     // error message.
     $session = CentralAuthUser::getSession();
     if (isset($session['auto-create-blacklist']) && in_array(wfWikiID(), (array) $session['auto-create-blacklist'])) {
         wfDebug(__METHOD__ . ": blacklisted by session\n");
         return false;
     }
     // Is the user blocked?
     $anon = new User();
     if (!$anon->isAllowedAny('createaccount', 'centralauth-autoaccount') || $anon->isBlockedFromCreateAccount()) {
         // Blacklist the user to avoid repeated DB queries subsequently
         // First load the session again in case it changed while the above DB query was in progress
         wfDebug(__METHOD__ . ": user is blocked from this wiki, blacklisting\n");
         $session['auto-create-blacklist'][] = wfWikiID();
         CentralAuthUser::setSession($session);
         return false;
     }
     // Check for validity of username
     if (!User::isCreatableName($userName)) {
         wfDebug(__METHOD__ . ": Invalid username\n");
         $session['auto-create-blacklist'][] = wfWikiID();
         CentralAuthUser::setSession($session);
         return false;
     }
     // Give other extensions a chance to stop auto creation.
     $user->loadDefaults($userName);
     $abortMessage = '';
     if (!Hooks::run('AbortAutoAccount', array($user, &$abortMessage))) {
         // In this case we have no way to return the message to the user,
         // but we can log it.
         wfDebug(__METHOD__ . ": denied by other extension: {$abortMessage}\n");
         $session['auto-create-blacklist'][] = wfWikiID();
         CentralAuthUser::setSession($session);
         return false;
     }
     // Make sure the name has not been changed
     if ($user->getName() !== $userName) {
         throw new Exception("AbortAutoAccount hook tried to change the user name");
     }
     // Checks passed, create the user
     $from = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'CLI';
     wfDebugLog('CentralAuth-Bug39996', __METHOD__ . ": creating new user ({$userName}) - from: {$from}\n");
     try {
         $status = $user->addToDatabase();
     } catch (Exception $e) {
         wfDebugLog('CentralAuth-Bug39996', __METHOD__ . " User::addToDatabase for \"{$userName}\" threw an exception:" . " {$e->getMessage()}");
         throw $e;
     }
     if ($status === null) {
         // MW before 1.21 -- ok, continue
     } elseif (!$status->isOK()) {
         wfDebugLog('CentralAuth-Bug39996', __METHOD__ . ": failed with message " . $status->getWikiText() . "\n");
         return false;
     }
     $wgAuth->initUser($user, true);
     # Notify hooks (e.g. Newuserlog)
     Hooks::run('AuthPluginAutoCreate', array($user));
     # Update user count
     DeferredUpdates::addUpdate(new SiteStatsUpdate(0, 0, 0, 0, 1));
     return true;
 }
 /**
  * Adds an user to the database
  * @param String $uUser Json encoded new user
  * @return string json encoded response
  */
 public static function addUser($sUsername, $sPassword, $sRePassword, $sEmail, $sRealname, $aGroups = array())
 {
     $res = $resDelGroups = $resInsGroups = $resERealUser = false;
     if (wfReadOnly()) {
         global $wgReadOnly;
         return FormatJson::encode(array('success' => false, 'message' => array(wfMessage('bs-readonly', $wgReadOnly)->plain())));
     }
     if (BsCore::checkAccessAdmission('wikiadmin') === false) {
         return true;
     }
     //This is to overcome username case issues with custom AuthPlugin (i.e. LDAPAuth)
     //LDAPAuth woud otherwise turn the username to first-char-upper-rest-lower-case
     //At the end of this method we switch $_SESSION['wsDomain'] back again
     $tmpDomain = isset($_SESSION['wsDomain']) ? $_SESSION['wsDomain'] : '';
     $_SESSION['wsDomain'] = 'local';
     $aResponse = array('success' => false, 'errors' => array(), 'message' => array());
     $sUsername = ucfirst($sUsername);
     if (User::isCreatableName($sUsername) === false) {
         $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-invalid-uname')->plain());
     }
     if ($sEmail != '' && Sanitizer::validateEmail($sEmail) === false) {
         $aResponse['errors'][] = array('id' => 'email', 'message' => wfMessage('bs-usermanager-invalid-email-gen')->plain());
     }
     if ($sPassword == '') {
         $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('bs-usermanager-enter-pwd')->plain());
     }
     if (strpos($sRealname, '\\')) {
         $aResponse['errors'][] = array('id' => 'realname', 'message' => wfMessage('bs-usermanager-invalid-realname')->plain());
     }
     if ($sPassword != $sRePassword) {
         $aResponse['errors'][] = array('id' => 'repass', 'message' => wfMessage('badretype')->plain());
     }
     if (strtolower($sUsername) == strtolower($sPassword)) {
         $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('password-name-match')->plain());
     }
     $oNewUser = User::newFromName($sUsername);
     if ($oNewUser == null) {
         //Should not be neccessary as we check for username validity above
         $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-invalid-uname')->plain());
     }
     if ($oNewUser instanceof User) {
         if ($oNewUser->getId() != 0) {
             $aResponse['errors'][] = array('id' => 'username', 'message' => wfMessage('bs-usermanager-user-exists')->plain());
         }
         if ($oNewUser->isValidPassword($sPassword) == false) {
             //TODO: $oNewUser->getPasswordValidity() returns a message key in case of error. Maybe we sould return this message.
             $aResponse['errors'][] = array('id' => 'pass', 'message' => wfMessage('bs-usermanager-invalid-pwd')->plain());
         }
     }
     if (!empty($aResponse['errors'])) {
         //In case that any error occurred
         return FormatJson::encode($aResponse);
     }
     $oNewUser->addToDatabase();
     $oNewUser->setPassword($sPassword);
     $oNewUser->setEmail($sEmail);
     $oNewUser->setRealName($sRealname);
     $oNewUser->setToken();
     $oNewUser->saveSettings();
     $dbw = wfGetDB(DB_MASTER);
     $resDelGroups = $dbw->delete('user_groups', array('ug_user' => $oNewUser->getId()));
     $resInsGroups = true;
     if (is_array($aGroups)) {
         foreach ($aGroups as $sGroup) {
             if (in_array($sGroup, self::$excludegroups)) {
                 continue;
             }
             $resInsGroups = $dbw->insert('user_groups', array('ug_user' => $oNewUser->getId(), 'ug_group' => addslashes($sGroup)));
         }
     }
     if ($resDelGroups === false || $resInsGroups === false) {
         $aAnswer['success'] = false;
         $aAnswer['message'][] = wfMessage('bs-usermanager-db-error')->plain();
     }
     $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1);
     $ssUpdate->doUpdate();
     $aResponse['success'] = true;
     $aResponse['message'][] = wfMessage('bs-usermanager-user-added')->plain();
     $_SESSION['wsDomain'] = $tmpDomain;
     $oUserManager = BsExtensionManager::getExtension('UserManager');
     wfRunHooks('BSUserManagerAfterAddUser', array($oUserManager, $oNewUser, array('username' => $sUsername, 'email' => $sEmail, 'password' => $sPassword, 'realname' => $sRealname)));
     return FormatJson::encode($aResponse);
 }
 static function parseBlockAddress($addr)
 {
     $r = array();
     $bits = explode('@', $addr, 2);
     if (count($bits) < 2) {
         return array('error' => 'nowiki');
     }
     list($target, $wiki) = $bits;
     if (!UserRightsProxy::validDatabase($wiki)) {
         return array('error' => 'invalidwiki', 'wiki' => $wiki);
     }
     if (preg_match('/^#[0-9]+$/', $target)) {
         return array('blockid' => substr($target, 1), 'wiki' => $wiki);
     } elseif (User::isIP($target)) {
         return array('ip' => $target, 'wiki' => $wiki);
     } elseif (User::isCreatableName($target)) {
         return array('username' => $target, 'wiki' => $wiki);
     } else {
         return array('error' => 'invalidusername', 'username' => $target);
     }
 }
Example #14
0
 /**
  * Given unvalidated user input, return a canonical username, or false if
  * the username is invalid.
  * @param string $name User input
  * @param string|bool $validate Type of validation to use:
  *   - false        No validation
  *   - 'valid'      Valid for batch processes
  *   - 'usable'     Valid for batch processes and login
  *   - 'creatable'  Valid for batch processes, login and account creation
  *
  * @throws InvalidArgumentException
  * @return bool|string
  */
 public static function getCanonicalName($name, $validate = 'valid')
 {
     // Force usernames to capital
     global $wgContLang;
     $name = $wgContLang->ucfirst($name);
     # Reject names containing '#'; these will be cleaned up
     # with title normalisation, but then it's too late to
     # check elsewhere
     if (strpos($name, '#') !== false) {
         return false;
     }
     // Clean up name according to title rules,
     // but only when validation is requested (bug 12654)
     $t = $validate !== false ? Title::newFromText($name, NS_USER) : Title::makeTitle(NS_USER, $name);
     // Check for invalid titles
     if (is_null($t) || $t->getNamespace() !== NS_USER || $t->isExternal()) {
         return false;
     }
     // Reject various classes of invalid names
     $name = AuthManager::callLegacyAuthPlugin('getCanonicalName', [$t->getText()], $t->getText());
     switch ($validate) {
         case false:
             break;
         case 'valid':
             if (!User::isValidUserName($name)) {
                 $name = false;
             }
             break;
         case 'usable':
             if (!User::isUsableName($name)) {
                 $name = false;
             }
             break;
         case 'creatable':
             if (!User::isCreatableName($name)) {
                 $name = false;
             }
             break;
         default:
             throw new InvalidArgumentException('Invalid parameter value for $validate in ' . __METHOD__);
     }
     return $name;
 }
Example #15
0
 /**
  * Show the special page
  *
  * @param mixed $par Parameter passed to the page
  */
 public function execute($par)
 {
     global $wgOut, $wgUser, $wgRequest, $wgContLang;
     global $wgCapitalLinks;
     $this->setHeaders();
     $wgOut->addWikiMsg('renameuser-summary');
     if (!$wgUser->isAllowed('renameuser')) {
         $wgOut->permissionRequired('renameuser');
         return;
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage();
     }
     $showBlockLog = $wgRequest->getBool('submit-showBlockLog');
     $oldnamePar = trim(str_replace('_', ' ', $wgRequest->getText('oldusername', $par)));
     $oldusername = Title::makeTitle(NS_USER, $oldnamePar);
     // Force uppercase of newusername, otherwise wikis with wgCapitalLinks=false can create lc usernames
     $newusername = Title::makeTitleSafe(NS_USER, $wgContLang->ucfirst($wgRequest->getText('newusername')));
     $oun = is_object($oldusername) ? $oldusername->getText() : '';
     $nun = is_object($newusername) ? $newusername->getText() : '';
     $token = $wgUser->editToken();
     $reason = $wgRequest->getText('reason');
     $move_checked = $wgRequest->getBool('movepages', !$wgRequest->wasPosted());
     $suppress_checked = $wgRequest->getCheck('suppressredirect');
     $warnings = array();
     if ($oun && $nun && !$wgRequest->getCheck('confirmaction')) {
         wfRunHooks('RenameUserWarning', array($oun, $nun, &$warnings));
     }
     $wgOut->addHTML(Xml::openElement('form', array('method' => 'post', 'action' => $this->getTitle()->getLocalUrl(), 'id' => 'renameuser')) . Xml::openElement('fieldset') . Xml::element('legend', null, wfMsg('renameuser')) . Xml::openElement('table', array('id' => 'mw-renameuser-table')) . "<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameuserold'), 'oldusername') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('oldusername', 20, $oun, array('type' => 'text', 'tabindex' => '1')) . ' ' . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameusernew'), 'newusername') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('newusername', 20, $nun, array('type' => 'text', 'tabindex' => '2')) . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameuserreason'), 'reason') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('reason', 40, $reason, array('type' => 'text', 'tabindex' => '3', 'maxlength' => 255)) . "</td>\n\t\t\t</tr>");
     if ($wgUser->isAllowed('move')) {
         $wgOut->addHTML("\n\t\t\t\t<tr>\n\t\t\t\t\t<td>&#160;\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class='mw-input'>" . Xml::checkLabel(wfMsg('renameusermove'), 'movepages', 'movepages', $move_checked, array('tabindex' => '4')) . "</td>\n\t\t\t\t</tr>");
         if ($wgUser->isAllowed('suppressredirect')) {
             $wgOut->addHTML("\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>&#160;\n\t\t\t\t\t\t</td>\n\t\t\t\t\t\t<td class='mw-input'>" . Xml::checkLabel(wfMsg('renameusersuppress'), 'suppressredirect', 'suppressredirect', $suppress_checked, array('tabindex' => '5')) . "</td>\n\t\t\t\t\t</tr>");
         }
     }
     if ($warnings) {
         $warningsHtml = array();
         foreach ($warnings as $warning) {
             $warningsHtml[] = is_array($warning) ? call_user_func_array('wfMsgWikiHtml', $warning) : wfMsgHtml($warning);
         }
         $wgOut->addHTML("\n\t\t\t\t<tr>\n\t\t\t\t\t<td class='mw-label'>" . wfMsgWikiHtml('renameuserwarnings') . "\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class='mw-input'>" . '<ul style="color: red; font-weight: bold"><li>' . implode('</li><li>', $warningsHtml) . '</li></ul>' . "</td>\n\t\t\t\t</tr>");
         $wgOut->addHTML("\n\t\t\t\t<tr>\n\t\t\t\t\t<td>&#160;\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class='mw-input'>" . Xml::checkLabel(wfMsg('renameuserconfirm'), 'confirmaction', 'confirmaction', false, array('tabindex' => '6')) . "</td>\n\t\t\t\t</tr>");
     }
     $wgOut->addHTML("\n\t\t\t<tr>\n\t\t\t\t<td>&#160;\n\t\t\t\t</td>\n\t\t\t\t<td class='mw-submit'>" . Xml::submitButton(wfMsg('renameusersubmit'), array('name' => 'submit', 'tabindex' => '7', 'id' => 'submit')) . ' ' . Xml::submitButton(wfMsg('blocklogpage'), array('name' => 'submit-showBlockLog', 'id' => 'submit-showBlockLog', 'tabindex' => '8')) . "</td>\n\t\t\t</tr>" . Xml::closeElement('table') . Xml::closeElement('fieldset') . Html::hidden('token', $token) . Xml::closeElement('form') . "\n");
     // Show block log if requested
     if ($showBlockLog && is_object($oldusername)) {
         $this->showLogExtract($oldusername, 'block', $wgOut);
         return;
     }
     if ($wgRequest->getText('token') === '') {
         # They probably haven't even submitted the form, so don't go further.
         return;
     } elseif ($warnings) {
         # Let user read warnings
         return;
     } elseif (!$wgRequest->wasPosted() || !$wgUser->matchEditToken($wgRequest->getVal('token'))) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", 'renameuser-error-request');
         return;
     } elseif (!is_object($oldusername)) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrorinvalid', $wgRequest->getText('oldusername')));
         return;
     } elseif (!is_object($newusername)) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrorinvalid', $wgRequest->getText('newusername')));
         return;
     } elseif ($oldusername->getText() == $newusername->getText()) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", 'renameuser-error-same-user');
         return;
     }
     // Suppress username validation of old username
     $olduser = User::newFromName($oldusername->getText(), false);
     $newuser = User::newFromName($newusername->getText(), 'creatable');
     // It won't be an object if for instance "|" is supplied as a value
     if (!is_object($olduser)) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrorinvalid', $oldusername->getText()));
         return;
     }
     if (!is_object($newuser) || !User::isCreatableName($newuser->getName())) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrorinvalid', $newusername->getText()));
         return;
     }
     // Check for the existence of lowercase oldusername in database.
     // Until r19631 it was possible to rename a user to a name with first character as lowercase
     if ($oldusername->getText() !== $wgContLang->ucfirst($oldusername->getText())) {
         // oldusername was entered as lowercase -> check for existence in table 'user'
         $dbr = wfGetDB(DB_SLAVE);
         $uid = $dbr->selectField('user', 'user_id', array('user_name' => $oldusername->getText()), __METHOD__);
         if ($uid === false) {
             if (!$wgCapitalLinks) {
                 $uid = 0;
                 // We are on a lowercase wiki but lowercase username does not exists
             } else {
                 // We are on a standard uppercase wiki, use normal
                 $uid = $olduser->idForName();
                 $oldusername = Title::makeTitleSafe(NS_USER, $olduser->getName());
             }
         }
     } else {
         // oldusername was entered as upperase -> standard procedure
         $uid = $olduser->idForName();
     }
     if ($uid == 0) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrordoesnotexist', $oldusername->getText()));
         return;
     }
     if ($newuser->idForName() != 0) {
         $wgOut->wrapWikiMsg("<div class=\"errorbox\">\$1</div>", array('renameusererrorexists', $newusername->getText()));
         return;
     }
     // Always get the edits count, it will be used for the log message
     $contribs = User::edits($uid);
     // Give other affected extensions a chance to validate or abort
     if (!wfRunHooks('RenameUserAbort', array($uid, $oldusername->getText(), $newusername->getText()))) {
         return;
     }
     // Do the heavy lifting...
     $rename = new RenameuserSQL($oldusername->getText(), $newusername->getText(), $uid);
     if (!$rename->rename()) {
         return;
     }
     // If this user is renaming his/herself, make sure that Title::moveTo()
     // doesn't make a bunch of null move edits under the old name!
     if ($wgUser->getId() == $uid) {
         $wgUser->setName($newusername->getText());
     }
     // Log this rename
     $log = new LogPage('renameuser');
     $log->addEntry('renameuser', $oldusername, wfMsgExt('renameuser-log', array('parsemag', 'content'), $wgContLang->formatNum($contribs), $reason), $newusername->getText());
     // Move any user pages
     if ($wgRequest->getCheck('movepages') && $wgUser->isAllowed('move')) {
         $dbr = wfGetDB(DB_SLAVE);
         $pages = $dbr->select('page', array('page_namespace', 'page_title'), array('page_namespace IN (' . NS_USER . ',' . NS_USER_TALK . ')', '(page_title ' . $dbr->buildLike($oldusername->getDBkey() . '/', $dbr->anyString()) . ' OR page_title = ' . $dbr->addQuotes($oldusername->getDBkey()) . ')'), __METHOD__);
         $suppressRedirect = false;
         if ($wgRequest->getCheck('suppressredirect') && $wgUser->isAllowed('suppressredirect')) {
             $suppressRedirect = true;
         }
         $output = '';
         foreach ($pages as $row) {
             $oldPage = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             $newPage = Title::makeTitleSafe($row->page_namespace, preg_replace('!^[^/]+!', $newusername->getDBkey(), $row->page_title));
             # Do not autodelete or anything, title must not exist
             if ($newPage->exists() && !$oldPage->isValidMoveTarget($newPage)) {
                 $link = Linker::linkKnown($newPage);
                 $output .= Html::rawElement('li', array('class' => 'mw-renameuser-pe'), wfMessage('renameuser-page-exists')->rawParams($link)->escaped());
             } else {
                 $success = $oldPage->moveTo($newPage, false, wfMessage('renameuser-move-log', $oldusername->getText(), $newusername->getText())->inContentLanguage()->text(), !$suppressRedirect);
                 if ($success === true) {
                     # oldPage is not known in case of redirect suppression
                     $oldLink = Linker::link($oldPage, null, array(), array('redirect' => 'no'));
                     # newPage is always known because the move was successful
                     $newLink = Linker::linkKnown($newPage);
                     $output .= Html::rawElement('li', array('class' => 'mw-renameuser-pm'), wfMessage('renameuser-page-moved')->rawParams($oldLink, $newLink)->escaped());
                 } else {
                     $oldLink = Linker::linkKnown($oldPage);
                     $newLink = Linker::link($newPage);
                     $output .= Html::rawElement('li', array('class' => 'mw-renameuser-pu'), wfMessage('renameuser-page-unmoved')->rawParams($oldLink, $newLink)->escaped());
                 }
             }
         }
         if ($output) {
             $wgOut->addHTML(Html::rawElement('ul', array(), $output));
         }
     }
     // Output success message stuff :)
     $wgOut->wrapWikiMsg("<div class=\"successbox\">\$1</div><br style=\"clear:both\" />", array('renameusersuccess', $oldusername->getText(), $newusername->getText()));
 }
 /**
  * Checks if the request provided to the constructor is valid.
  *
  * @return bool True if all prerequisites are met
  */
 protected function setup()
 {
     wfProfileIn(__METHOD__);
     global $wgContLang, $wgCapitalLinks;
     //Sanitize input data
     $oldnamePar = trim(str_replace('_', ' ', $this->mRequestData->oldUsername));
     $oldTitle = Title::makeTitle(NS_USER, $oldnamePar);
     // Force uppercase of newusername, otherwise wikis with wgCapitalLinks=false can create lc usernames
     $newTitle = Title::makeTitleSafe(NS_USER, $wgContLang->ucfirst($this->mRequestData->newUsername));
     $oun = is_object($oldTitle) ? $oldTitle->getText() : '';
     $nun = is_object($newTitle) ? $newTitle->getText() : '';
     $this->addInternalLog("title: old={$oun} new={$nun}");
     //AntiSpoof test
     if (class_exists('SpoofUser')) {
         $oNewSpoofUser = new SpoofUser($nun);
         if (!$oNewSpoofUser->isLegal()) {
             $this->addWarning(wfMessage('userrenametool-error-antispoof-conflict', $nun));
         }
     } else {
         $this->addError(wfMessage('userrenametool-error-antispoof-notinstalled'));
     }
     //Phalanx test
     $warning = RenameUserHelper::testBlock($oun);
     if (!empty($warning)) {
         $this->addWarning($warning);
     }
     $warning = RenameUserHelper::testBlock($nun);
     if (!empty($warning)) {
         $this->addWarning($warning);
     }
     //Invalid old user name entered
     if (!$oun) {
         $this->addError(wfMessage('userrenametool-errorinvalid', $this->mRequestData->oldUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     //Invalid new user name entered
     if (!$nun) {
         $this->addError(wfMessage('userrenametool-errorinvalidnew', $this->mRequestData->newUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     //Old username is the same as new username
     if ($oldTitle->getText() === $newTitle->getText()) {
         $this->addError(wfMessage('userrenametool-error-same-user')->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     //validate new username and disable validation for old username
     $olduser = User::newFromName($oldTitle->getText(), false);
     $newuser = User::newFromName($newTitle->getText(), 'creatable');
     // It won't be an object if for instance "|" is supplied as a value
     if (!is_object($olduser)) {
         $this->addError(wfMessage('userrenametool-errorinvalid', $this->mRequestData->oldUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     if (!is_object($newuser) || !User::isCreatableName($newuser->getName())) {
         $this->addError(wfMessage('userrenametool-errorinvalid', $this->mRequestData->newUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     $this->addInternalLog("user: old={$olduser->getName()}:{$olduser->getId()} new={$newuser->getName()}:{$newuser->getId()}");
     // Check for the existence of lowercase oldusername in database.
     // Until r19631 it was possible to rename a user to a name with first character as lowercase
     if ($oldTitle->getText() !== $wgContLang->ucfirst($oldTitle->getText())) {
         // oldusername was entered as lowercase -> check for existence in table 'user'
         $dbr = WikiFactory::db(DB_SLAVE);
         $uid = $dbr->selectField('`user`', 'user_id', array('user_name' => $oldTitle->getText()), __METHOD__);
         $this->addLog('Running query: ' . $dbr->lastQuery() . " resulted in " . $dbr->affectedRows() . " row(s) being affected.");
         if ($uid === false) {
             if (!$wgCapitalLinks) {
                 $uid = 0;
                 // We are on a lowercase wiki but lowercase username does not exists
             } else {
                 // We are on a standard uppercase wiki, use normal
                 $uid = $olduser->idForName();
                 $oldTitle = Title::makeTitleSafe(NS_USER, $olduser->getName());
             }
         }
     } else {
         // oldusername was entered as upperase -> standard procedure
         $uid = $olduser->idForName();
     }
     $this->addInternalLog("id: uid={$uid} old={$olduser->getName()}:{$olduser->getId()} new={$newuser->getName()}:{$newuser->getId()}");
     //If old user name does not exist:
     if ($uid == 0) {
         $this->addError(wfMessage('userrenametool-errordoesnotexist', $this->mRequestData->oldUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     } elseif ($olduser->isLocked()) {
         $this->addError(wfMessage('userrenametool-errorlocked', $this->mRequestData->oldUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     } elseif ($olduser->isAllowed('bot')) {
         $this->addError(wfMessage('userrenametool-errorbot', $this->mRequestData->oldUsername)->inContentLanguage()->text());
         wfProfileOut(__METHOD__);
         return false;
     }
     $fakeuid = 0;
     //If new user name does exist (we have a special case - repeating rename process)
     if ($newuser->idForName() != 0) {
         $repeating = false;
         $processing = false;
         //invalidate properties cache and reload to get updated data
         //needed here, if the cache is wrong bad things happen
         $this->addInternalLog("pre-invalidate: titletext={$oldTitle->getText()} old={$olduser->getName()}");
         $olduser->invalidateCache();
         $olduser = User::newFromName($oldTitle->getText(), false);
         $renameData = $olduser->getGlobalAttribute('renameData', '');
         $this->addInternalLog("post-invalidate: titletext={$oldTitle->getText()} old={$olduser->getName()}:{$olduser->getId()}");
         $this->addLog("Scanning user option renameData for process data: {$renameData}");
         if (stripos($renameData, self::RENAME_TAG) !== false) {
             $tokens = explode(';', $renameData, 3);
             if (!empty($tokens[0])) {
                 $nameTokens = explode('=', $tokens[0], 2);
                 $repeating = count($nameTokens) == 2 && $nameTokens[0] === self::RENAME_TAG && $nameTokens[1] === $newuser->getName();
             }
             if (!empty($tokens[1])) {
                 $statusTokens = explode('=', $tokens[1], 2);
                 $processing = count($statusTokens) == 2 && $statusTokens[0] === self::PROCESS_TAG && (int) $statusTokens[1] === 1;
             }
             if (!empty($tokens[2])) {
                 $blockTokens = explode('=', $tokens[2], 2);
                 if (count($blockTokens) == 2 && $blockTokens[0] === self::PHALANX_BLOCK_TAG && is_numeric($blockTokens[1])) {
                     $this->mPhalanxBlockId = (int) $blockTokens[1];
                 }
             }
         }
         /**
         			 * Not needed, process must be resumable even in case of fatal errors, if 2 processes are run nothing bad happens
         			//if the process is already running throw an error
         			if($processing){
         				$this->addError( wfMessage( 'userrenametool-errorprocessing', $olduser->getName(), $newuser->getName())->inContentLanguage()->text() );
         				wfProfileOut(__METHOD__);
         				return false;
         			}*/
         if ($repeating) {
             $this->addWarning(wfMessage('userrenametool-warn-repeat', $this->mRequestData->oldUsername, $this->mRequestData->newUsername)->inContentLanguage()->text());
             //Swap the uids because the real user ID is the new user ID in this special case
             $fakeuid = $uid;
             $uid = $newuser->idForName();
         } else {
             //In the case other than repeating the process drop an error
             $this->addError(wfMessage('userrenametool-errorexists', $newuser->getName())->inContentLanguage()->text());
             wfProfileOut(__METHOD__);
             return false;
         }
     }
     //Execute Warning hook (arguments the same as in the original Renameuser extension)
     if (!$this->mActionConfirmed) {
         wfRunHooks('UserRename::Warning', array($this->mRequestData->oldUsername, $this->mRequestData->newUsername, &$this->mWarnings));
     }
     $this->mOldUsername = $olduser->getName();
     $this->mNewUsername = $newuser->getName();
     $this->mUserId = (int) $uid;
     $this->mFakeUserId = $fakeuid;
     $this->addInternalLog("setup: uid={$this->mUserId} fakeuid={$this->mFakeUserId} old={$this->mOldUsername} new={$this->mNewUsername}");
     //If there are only warnings and user confirmed that, do not show them again
     //on success page ;-)
     if ($this->mActionConfirmed) {
         $this->mWarnings = array();
     } elseif (count($this->mWarnings)) {
         //in case action is not confirmed and there are warnings display them and wait for confirmation before running the process
         wfProfileOut(__METHOD__);
         return false;
     }
     wfProfileOut(__METHOD__);
     return empty($this->mErrors);
 }
 function validatePOSTParams()
 {
     global $wgUser, $wgAuth;
     // Validate FORM
     if (empty($this->username)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->usernamefield));
     }
     $this->username = strtoupper(substr($this->username, 0, 1)) . substr($this->username, 1);
     // in case the user changes the case of the first character
     // check if its already being used
     if (User::idFromName($this->username) !== null) {
         throw new InvalidPOSTParamException(wfMsg('uadm-usernameinusemsg', $this->username));
     }
     if (!User::isCreatableName($this->username)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-invalidusernamemsg', $this->usernamefield));
     }
     if ($this->domain != 'local' && $this->domain != '') {
         if (!$wgAuth->validDomain($this->domain)) {
             throw new InvalidPOSTParamException(wfMsg('uadm-invaliddomainmsg'));
         }
         $wgAuth->setDomain($this->domain);
         if ($wgAuth->userExists($this->username)) {
             throw new InvalidPOSTParamException(wfMsg('uadm-usernameinusemsg', $this->username));
         }
     }
     //    if(!$wgUser->matchEditToken(stripslashes($this->edittoken), $this->userid))
     if (!$wgUser->matchEditToken($this->edittoken, 'adduser' . $wgUser->getName())) {
         throw new InvalidPOSTParamException(wfMsg('uadm-formsubmissionerrormsg'));
     }
     if (empty($this->email)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->emailfield));
     }
     //if(!User::isValidEmailAddr($this->email))
     if (!Sanitizer::validateEmail($this->email)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-invalidemailmsg', $this->emailfield));
     }
     if (empty($this->pwdaction)) {
         throw new InvalidPOSTParamException(wfMsg('uadm-formsubmissionerrormsg'));
     }
     if ($this->pwdaction == 'manual') {
         if (empty($this->password1) || empty($this->password2)) {
             throw new InvalidPOSTParamException(wfMsg('uadm-fieldisrequiredmsg', $this->passwordfield));
         }
         if ($this->password1 != $this->password2) {
             throw new InvalidPOSTParamException(wfMsg('uadm-passwordsmustmatchmsg'));
         }
     } elseif ($this->pwdaction != 'email' && $this->pwdaction != 'emailwelcome') {
         throw new InvalidPOSTParamException(wfMsg('uadm-formsubmissionerrormsg'));
     }
 }
Example #18
0
 /**
  * Show the special page
  *
  * @param mixed $par Parameter passed to the page
  */
 public function execute($par)
 {
     global $wgOut, $wgUser, $wgTitle, $wgRequest, $wgContLang, $wgLang;
     global $wgVersion, $wgMaxNameChars, $wgCapitalLinks;
     $this->setHeaders();
     if (!$wgUser->isAllowed('renameuser')) {
         $wgOut->permissionRequired('renameuser');
         return;
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     $showBlockLog = $wgRequest->getBool('submit-showBlockLog');
     $oldusername = Title::newFromText($wgRequest->getText('oldusername'), NS_USER);
     $newusername = Title::newFromText($wgContLang->ucfirst($wgRequest->getText('newusername')), NS_USER);
     // Force uppercase of newusername otherweise wikis with wgCapitalLinks=false can create lc usernames
     $oun = is_object($oldusername) ? $oldusername->getText() : '';
     $nun = is_object($newusername) ? $newusername->getText() : '';
     $token = $wgUser->editToken();
     $reason = $wgRequest->getText('reason');
     $is_checked = true;
     if ($wgRequest->wasPosted() && !$wgRequest->getCheck('movepages')) {
         $is_checked = false;
     }
     $wgOut->addHTML("\n\t\t\t<!-- Current contributions limit is " . RENAMEUSER_CONTRIBLIMIT . " -->" . Xml::openElement('form', array('method' => 'post', 'action' => $wgTitle->getLocalUrl(), 'id' => 'renameuser')) . Xml::openElement('fieldset') . Xml::element('legend', null, wfMsg('renameuser')) . Xml::openElement('table', array('id' => 'mw-renameuser-table')) . "<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameuserold'), 'oldusername') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('oldusername', 20, $oun, array('type' => 'text', 'tabindex' => '1')) . ' ' . Xml::submitButton(wfMsg('blocklogpage'), array('name' => 'submit-showBlockLog', 'id' => 'submit-showBlockLog', 'tabindex' => '2')) . ' ' . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameusernew'), 'newusername') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('newusername', 20, $nun, array('type' => 'text', 'tabindex' => '3')) . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('renameuserreason'), 'reason') . "</td>\n\t\t\t\t<td class='mw-input'>" . Xml::input('reason', 40, $reason, array('type' => 'text', 'tabindex' => '4', 'maxlength' => 255)) . "</td>\n\t\t\t</tr>");
     if ($wgUser->isAllowed('move') && version_compare($wgVersion, '1.9alpha', '>=')) {
         $wgOut->addHTML("\n\t\t\t\t<tr>\n\t\t\t\t\t<td>&nbsp;\n\t\t\t\t\t</td>\n\t\t\t\t\t<td class='mw-input'>" . Xml::checkLabel(wfMsg('renameusermove'), 'movepages', 'movepages', $is_checked, array('tabindex' => '5')) . "</td>\n\t\t\t\t</tr>");
     }
     $wgOut->addHTML("\n\t\t\t<tr>\n\t\t\t\t<td>&nbsp;\n\t\t\t\t</td>\n\t\t\t\t<td class='mw-submit'>" . Xml::submitButton(wfMsg('renameusersubmit'), array('name' => 'submit', 'tabindex' => '6', 'id' => 'submit')) . "</td>\n\t\t\t</tr>" . Xml::closeElement('table') . Xml::closeElement('fieldset') . Xml::hidden('token', $token) . Xml::closeElement('form') . "\n");
     // Show block log if requested
     if ($showBlockLog && is_object($oldusername)) {
         $this->showLogExtract($oldusername, 'block', $wgOut);
         return;
     }
     if ($wgRequest->getText('token') === '') {
         # They probably haven't even submitted the form, so don't go further.
         return;
     } elseif (!$wgRequest->wasPosted() || !$wgUser->matchEditToken($wgRequest->getVal('token'))) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameuser-error-request') . "</div>");
         return;
     } elseif (!is_object($oldusername)) {
         // FIXME: This is bogus.  Invalid titles need to be rename-able! (bug 12654)
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrorinvalid', $wgRequest->getText('oldusername')) . "</div>");
         return;
     } elseif (!is_object($newusername)) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrorinvalid', $wgRequest->getText('newusername')) . "</div>");
         return;
     } elseif ($oldusername->getText() == $newusername->getText()) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameuser-error-same-user') . "</div>");
         return;
     }
     // Suppress username validation of old username
     $olduser = User::newFromName($oldusername->getText(), false);
     $newuser = User::newFromName($newusername->getText());
     // It won't be an object if for instance "|" is supplied as a value
     if (!is_object($olduser)) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrorinvalid', $oldusername->getText()) . "</div>");
         return;
     }
     if (!is_object($newuser) || !User::isCreatableName($newuser->getName())) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrorinvalid', $newusername->getText()) . "</div>");
         return;
     }
     // Check for the existence of lowercase oldusername in database.
     // Until r19631 it was possible to rename a user to a name with first character as lowercase
     if ($wgRequest->getText('oldusername') !== $wgContLang->ucfirst($wgRequest->getText('oldusername'))) {
         // oldusername was entered as lowercase -> check for existence in table 'user'
         $dbr_lc = wfGetDB(DB_SLAVE);
         $s = trim($wgRequest->getText('oldusername'));
         $uid = $dbr_lc->selectField('user', 'user_id', array('BINARY user_name' => $s), __METHOD__);
         if ($uid === false) {
             $uid = 0;
             #	if ( !$wgCapitalLinks ) {
             #		$uid = 0; // We are on a lowercase wiki but lowercase username does not exists
             #	} else {
             #		$uid = $olduser->idForName(); // We are on a standard uppercase wiki, use normal
             #	}
         } else {
             // username with lowercase exists
             // Title::newFromText was nice, but forces uppercase
             // for older rename accidents on lowercase wikis we need the lowercase username as entered in the form
             $oldusername->mTextform = $wgRequest->getText('oldusername');
             $oldusername->mUrlform = $wgRequest->getText('oldusername');
             $oldusername->mDbkeyform = $wgRequest->getText('oldusername');
         }
     } else {
         // oldusername was entered as upperase -> standard procedure
         $uid = $olduser->idForName();
     }
     if ($uid == 0) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrordoesnotexist', $wgRequest->getText('oldusername')) . "</div>");
         return;
     }
     if ($newuser->idForName() != 0) {
         $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrorexists', $newusername->getText()) . "</div>");
         return;
     }
     // Always get the edits count, it will be used for the log message
     $contribs = User::edits($uid);
     // Check edit count
     if (!$wgUser->isAllowed('siteadmin')) {
         if (RENAMEUSER_CONTRIBLIMIT != 0 && $contribs > RENAMEUSER_CONTRIBLIMIT) {
             $wgOut->addWikiText("<div class=\"errorbox\">" . wfMsg('renameusererrortoomany', $oldusername->getText(), $wgLang->formatNum($contribs), $wgLang->formatNum(RENAMEUSER_CONTRIBLIMIT)) . "</div>");
             return;
         }
     }
     // Give other affected extensions a chance to validate or abort
     if (!wfRunHooks('RenameUserAbort', array($uid, $oldusername->getText(), $newusername->getText()))) {
         return;
     }
     $rename = new RenameuserSQL($oldusername->getText(), $newusername->getText(), $uid);
     $rename->rename();
     $log = new LogPage('renameuser');
     $log->addEntry('renameuser', $oldusername, wfMsgExt('renameuser-log', array('parsemag', 'content'), $wgContLang->formatNum($contribs), $reason), $newusername->getText());
     $wgOut->addWikiText("<div class=\"successbox\">" . wfMsg('renameusersuccess', $oldusername->getText(), $newusername->getText()) . "</div><br style=\"clear:both\" />");
     if ($wgRequest->getCheck('movepages') && $wgUser->isAllowed('move') && version_compare($wgVersion, '1.9alpha', '>=')) {
         $dbr =& wfGetDB(DB_SLAVE);
         $oldkey = $oldusername->getDBkey();
         $pages = $dbr->select('page', array('page_namespace', 'page_title'), array('page_namespace IN (' . NS_USER . ',' . NS_USER_TALK . ')', '(page_title LIKE ' . $dbr->addQuotes($dbr->escapeLike($oldusername->getDBkey()) . '/%') . ' OR page_title = ' . $dbr->addQuotes($oldusername->getDBkey()) . ')'), __METHOD__);
         $output = '';
         $skin =& $wgUser->getSkin();
         while ($row = $dbr->fetchObject($pages)) {
             $oldPage = Title::makeTitleSafe($row->page_namespace, $row->page_title);
             $newPage = Title::makeTitleSafe($row->page_namespace, preg_replace('!^[^/]+!', $newusername->getDBkey(), $row->page_title));
             if ($newPage->exists() && !$oldPage->isValidMoveTarget($newPage)) {
                 $link = $skin->makeKnownLinkObj($newPage);
                 $output .= '<li class="mw-renameuser-pe">' . wfMsgHtml('renameuser-page-exists', $link) . '</li>';
             } else {
                 $success = $oldPage->moveTo($newPage, false, wfMsgForContent('renameuser-move-log', $oldusername->getText(), $newusername->getText()));
                 if ($success === true) {
                     $oldLink = $skin->makeKnownLinkObj($oldPage, '', 'redirect=no');
                     $newLink = $skin->makeKnownLinkObj($newPage);
                     $output .= '<li class="mw-renameuser-pm">' . wfMsgHtml('renameuser-page-moved', $oldLink, $newLink) . '</li>';
                 } else {
                     $oldLink = $skin->makeKnownLinkObj($oldPage);
                     $newLink = $skin->makeLinkObj($newPage);
                     $output .= '<li class="mw-renameuser-pu">' . wfMsgHtml('renameuser-page-unmoved', $oldLink, $newLink) . '</li>';
                 }
             }
         }
         if ($output) {
             $wgOut->addHtml('<ul>' . $output . '</ul>');
         }
     }
 }
Example #19
0
 /**
  * @private
  */
 function addNewAccountInternal()
 {
     global $wgUser, $wgOut;
     global $wgEnableSorbs, $wgProxyWhitelist;
     global $wgMemc, $wgAccountCreationThrottle;
     global $wgAuth, $wgMinimalPasswordLength;
     // If the user passes an invalid domain, something is fishy
     if (!$wgAuth->validDomain($this->mDomain)) {
         $this->mainLoginForm(wfMsg('wrongpassword'));
         return false;
     }
     // If we are not allowing users to login locally, we should
     // be checking to see if the user is actually able to
     // authenticate to the authentication server before they
     // create an account (otherwise, they can create a local account
     // and login as any domain user). We only need to check this for
     // domains that aren't local.
     if ('local' != $this->mDomain && '' != $this->mDomain) {
         if (!$wgAuth->canCreateAccounts() && (!$wgAuth->userExists($this->mName) || !$wgAuth->authenticate($this->mName, $this->mPassword))) {
             $this->mainLoginForm(wfMsg('wrongpassword'));
             return false;
         }
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return false;
     }
     if (!$wgUser->isAllowedToCreateAccount()) {
         $this->userNotPrivilegedMessage();
         return false;
     }
     $ip = wfGetIP();
     if ($wgEnableSorbs && !in_array($ip, $wgProxyWhitelist) && $wgUser->inSorbsBlacklist($ip)) {
         $this->mainLoginForm(wfMsg('sorbs_create_account_reason') . ' (' . htmlspecialchars($ip) . ')');
         return;
     }
     $name = trim($this->mName);
     $u = User::newFromName($name);
     if (is_null($u) || !User::isCreatableName($u->getName())) {
         $this->mainLoginForm(wfMsg('noname'));
         return false;
     }
     if (0 != $u->idForName()) {
         $this->mainLoginForm(wfMsg('userexists'));
         return false;
     }
     if (0 != strcmp($this->mPassword, $this->mRetype)) {
         $this->mainLoginForm(wfMsg('badretype'));
         return false;
     }
     if (!$wgUser->isValidPassword($this->mPassword)) {
         $this->mainLoginForm(wfMsg('passwordtooshort', $wgMinimalPasswordLength));
         return false;
     }
     if ($wgAccountCreationThrottle) {
         $key = wfMemcKey('acctcreate', 'ip', $ip);
         $value = $wgMemc->incr($key);
         if (!$value) {
             $wgMemc->set($key, 1, 86400);
         }
         if ($value > $wgAccountCreationThrottle) {
             $this->throttleHit($wgAccountCreationThrottle);
             return false;
         }
     }
     $abortError = '';
     if (!wfRunHooks('AbortNewAccount', array($u, &$abortError))) {
         // Hook point to add extra creation throttles and blocks
         wfDebug("LoginForm::addNewAccountInternal: a hook blocked creation\n");
         $this->mainLoginForm($abortError);
         return false;
     }
     if (!$wgAuth->addUser($u, $this->mPassword)) {
         $this->mainLoginForm(wfMsg('externaldberror'));
         return false;
     }
     # Update user count
     $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1);
     $ssUpdate->doUpdate();
     return $this->initUser($u);
 }