private function checkEmail($addr, $expected = true, $msg = '') { if ($msg == '') { $msg = "Testing {$addr}"; } $this->assertEquals($expected, Sanitizer::validateEmail($addr), $msg); }
public static function receiverIsValid($receiver) { // Returns true if the parameter is a valid e-mail address, false if not $receiverIsValid = true; // There may be multiple e-mail addresses, divided by commas - which is valid // for us, but not for the validation functions we use below. So get the single // address into an array first, validate them one by one, and only if all are ok, // return true. $receiverArray = explode(',', str_replace(', ', ',', $receiver)); // To make sure some joker doesn't copy in a large number of e-mail addresses // and spams them all, lets set a (admittedly arbitrary) limit of 10. if (count($receiverArray) > 10) { return false; } if (method_exists('Sanitizer', 'validateEmail')) { // User::isValidEmailAddr() has been moved to Sanitizer::validateEmail as of // MediaWiki version 1.18 (I think). foreach ($receiverArray as $singleEmailAddress) { if (!Sanitizer::validateEmail($singleEmailAddress)) { $receiverIsValid = false; } } } else { foreach ($receiverArray as $singleEmailAddress) { if (!User::isValidEmailAddr($singleEmailAddress)) { $receiverIsValid = false; } } } return $receiverIsValid; }
/** * Show the special page * * @param $subpage Mixed: parameter passed to the page or null */ public function execute($subpage) { global $wgRequest, $wgUser, $wgOut; $this->setHeaders(); $hash_key = $wgRequest->getText('key', null); $email = $token = $timestamp = null; if (!empty($hash_key)) { #$hask_key = urldecode ( $hash_key ); $data = Wikia::verifyUserSecretKey($hash_key, 'sha256'); error_log("data = " . print_r($data, true)); if (!empty($data)) { $username = isset($data['user']) ? $data['user'] : null; $token = isset($data['token']) ? $data['token'] : null; $timestamp = isset($data['signature1']) ? $data['signature1'] : null; $oUser = User::newFromName($username); $email = $oUser->getEmail(); } } else { $email = $wgRequest->getText('email', null); $token = $wgRequest->getText('token', null); $timestamp = $wgRequest->getText('timestamp', null); } if ($email == null || $token == null || $timestamp == null) { #give up now, abandon all hope. $wgOut->addWikiMsg('unsubscribe-badaccess'); return; } #validate timestamp isnt spoiled (you only have 7 days) $timeCutoff = strtotime("7 days ago"); if ($timestamp <= $timeCutoff) { $wgOut->addWikiMsg('unsubscribe-badtime'); // $wgOut->addHTML("timestamp={$timestamp}\n"); #DEVL (remove before release) // $wgOut->addHTML("timeCutoff={$timeCutoff}\n"); #DEVL (remove before release) return; } #generate what the token SHOULD be $shouldToken = wfGenerateUnsubToken($email, $timestamp); if ($token != $shouldToken) { $wgOut->addWikiMsg('unsubscribe-badtoken'); // $wgOut->addHTML("shouldtoken={$shouldToken}\n"); #DEVL (remove before release) return; } #does the non-blank email they gave us look like an email? if (Sanitizer::validateEmail($email) == false) { #email wasnt blank, but didnt look like any email $wgOut->addWikiMsg('unsubscribe-bademail'); // $wgOut->addHTML("email={$email}\n"); #DEVL (remove before release) return; } #at this point, the 3 params check out. #is this their 2nd pass at this? $confirmed = $wgRequest->getBool('confirm', null); if ($wgRequest->wasPosted() && $confirmed) { #this is the 2nd round, they pushed the button, so do it $this->procUnsub($email); } else { #this is 1st pass, give them a button to push $this->showInfo($email, $token, $timestamp); } }
/** * Main execution point * * @param null|string $code Confirmation code passed to the page */ function execute( $code ) { $this->setHeaders(); $this->checkReadOnly(); $this->checkPermissions(); // This could also let someone check the current email address, so // require both permissions. if ( !$this->getUser()->isAllowed( 'viewmyprivateinfo' ) ) { throw new PermissionsError( 'viewmyprivateinfo' ); } if ( $code === null || $code === '' ) { if ( $this->getUser()->isLoggedIn() ) { if ( Sanitizer::validateEmail( $this->getUser()->getEmail() ) ) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg( 'confirmemail_noemail' ); } } else { $llink = Linker::linkKnown( SpecialPage::getTitleFor( 'Userlogin' ), $this->msg( 'loginreqlink' )->escaped(), array(), array( 'returnto' => $this->getTitle()->getPrefixedText() ) ); $this->getOutput()->addHTML( $this->msg( 'confirmemail_needlogin' )->rawParams( $llink )->parse() ); } } else { $this->attemptConfirm( $code ); } }
function execute() { global $wgLang, $wgRequest; global $wgOut, $wgExtensionsPath; global $wgUser, $wgCaptchaClass, $wgJsMimeType; $wgOut->addStyle(AssetsManager::getInstance()->getSassCommonURL('extensions/wikia/SpecialContact/SpecialContact.scss')); $this->mName = null; $this->mRealName = null; $this->mWhichWiki = null; $this->mProblem = $wgRequest->getText('wpContactSubject'); //subject $this->mProblemDesc = null; $this->mPosted = $wgRequest->wasPosted(); $this->mAction = $wgRequest->getVal('action'); $this->mEmail = $wgRequest->getText('wpEmail'); $this->mBrowser = $wgRequest->getText('wpBrowser'); $this->mAbTestInfo = $wgRequest->getText('wpAbTesting'); $this->mCCme = $wgRequest->getCheck('wgCC'); if ($this->mPosted && 'submit' == $this->mAction) { if (!$wgUser->isLoggedIn() && class_exists($wgCaptchaClass)) { $captchaObj = new $wgCaptchaClass(); $captchaObj->retrieveCaptcha(); $info = $captchaObj->retrieveCaptcha(); } #ubrfzy note: these were moved inside to (lazy) prevent some stupid bots $this->mName = $wgRequest->getText('wpName'); $this->mRealName = $wgRequest->getText('wpContactRealName'); $this->mWhichWiki = $wgRequest->getText('wpContactWikiName'); #sibject still handled outside of post check, because of existing hardcoded prefill links $this->mProblemDesc = $wgRequest->getText('wpContactDesc'); //body #malformed email? if (!Sanitizer::validateEmail($this->mEmail)) { $this->err[] .= wfMsg('invalidemailaddress'); $this->errInputs['wpEmail'] = true; } #empty message text? if (empty($this->mProblemDesc)) { $this->err[] .= wfMsg('specialcontact-nomessage'); $this->errInputs['wpContactDesc'] = true; } #captcha if (!$wgUser->isLoggedIn() && class_exists($wgCaptchaClass)) { // logged in users don't need the captcha (RT#139647) if (!(!empty($info) && $captchaObj->keyMatch($wgRequest->getVal('wpCaptchaWord'), $info))) { $this->err[] .= wfMsg('specialcontact-captchafail'); $this->errInputs['wpCaptchaWord'] = true; } } #no errors? if (empty($this->err)) { #send email $this->processCreation(); #stop here return; } #if there were any ->err s, they will be displayed in ContactForm } $this->mainContactForm(); }
public function execute() { $this->commit = $this->hasOption('commit'); $dbr = $this->getDB(DB_SLAVE); $dbw = $this->getDB(DB_MASTER); $lastId = 0; do { $rows = $dbr->select('user', array('user_id', 'user_email'), array('user_id > ' . $dbr->addQuotes($lastId), 'user_email != ""', 'user_email_authenticated IS NULL'), __METHOD__, array('LIMIT' => $this->mBatchSize)); $count = $rows->numRows(); $badIds = array(); foreach ($rows as $row) { if (!Sanitizer::validateEmail(trim($row->user_email))) { $this->output("Found bad email: {$row->user_email} for user #{$row->user_id}\n"); $badIds[] = $row->user_id; } if ($row->user_id > $lastId) { $lastId = $row->user_id; } } if ($badIds) { $badCount = count($badIds); if ($this->commit) { $this->output("Removing {$badCount} emails from the database.\n"); $dbw->update('user', array('user_email' => ''), array('user_id' => $badIds), __METHOD__); foreach ($badIds as $badId) { User::newFromId($badId)->invalidateCache(); } wfWaitForSlaves(); } else { $this->output("Would have removed {$badCount} emails from the database.\n"); } } } while ($count !== 0); $this->output("Done.\n"); }
/** * Handles group notification. * * @since 0.1 * * @param SWLGroup $group * @param array $userIDs * @param SMWChangeSet $changes * * @return true */ public static function onGroupNotify( SWLGroup $group, array $userIDs, SWLChangeSet $changes ) { global $egSWLMailPerChange, $egSWLMaxMails; foreach ( $userIDs as $userID ) { $user = User::newFromId( $userID ); if ( $user->getOption( 'swl_email', false ) ) { if ( !method_exists( 'Sanitizer', 'validateEmail' ) || Sanitizer::validateEmail( $user->getEmail() ) ) { $lastNotify = $user->getOption( 'swl_last_notify' ); $lastWatch = $user->getOption( 'swl_last_watch' ); if ( is_null( $lastNotify ) || is_null( $lastWatch ) || $lastNotify < $lastWatch ) { $mailCount = $user->getOption( 'swl_mail_count', 0 ); if ( $egSWLMailPerChange || $mailCount < $egSWLMaxMails ) { SWLEmailer::notifyUser( $group, $user, $changes, $egSWLMailPerChange ); $user->setOption( 'swl_last_notify', wfTimestampNow() ); $user->setOption( 'swl_mail_count', $mailCount + 1 ); $user->saveSettings(); } } } } } return true; }
/** * Main execution point * * @param null|string $code Confirmation code passed to the page * @throws PermissionsError * @throws ReadOnlyError * @throws UserNotLoggedIn */ function execute($code) { // Ignore things like master queries/connections on GET requests. // It's very convenient to just allow formless link usage. $trxProfiler = Profiler::instance()->getTransactionProfiler(); $this->setHeaders(); $this->checkReadOnly(); $this->checkPermissions(); // This could also let someone check the current email address, so // require both permissions. if (!$this->getUser()->isAllowed('viewmyprivateinfo')) { throw new PermissionsError('viewmyprivateinfo'); } if ($code === null || $code === '') { $this->requireLogin('confirmemail_needlogin'); if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } else { $old = $trxProfiler->setSilenced(true); $this->attemptConfirm($code); $trxProfiler->setSilenced($old); } }
protected function checkContactLink($name, $url, &$countOk) { global $wgVersion; $ok = false; if (Sanitizer::validateEmail($url)) { $ok = true; // assume OK } else { $bits = wfParseUrl($url); if ($bits && isset($bits['scheme'])) { if ($bits['scheme'] == 'mailto') { $ok = true; // assume OK } elseif (in_array($bits['scheme'], array('http', 'https'))) { $req = MWHttpRequest::factory($url, array('method' => 'GET', 'timeout' => 8, 'sslVerifyHost' => false, 'sslVerifyCert' => false)); $req->setUserAgent("MediaWiki {$wgVersion}, CheckCongressLinks Checker"); $ok = $req->execute()->isOK(); } } } if ($ok) { ++$countOk; } else { $this->output("Broken: [{$name}] [{$url}]\n"); } }
protected function doCreate() { $params = $this->extractRequestParams(); // Do validations foreach (explode('|', 'username|password|email') as $field) { if (!isset($params[$field])) { $this->dieUsage("Missing parameter {$field}", 'missingparam'); } } $username = $params['username']; if (User::getCanonicalName($username, 'creatable') === false) { $this->dieUsage("User name is not acceptable", 'invalidusername'); } $user = User::newFromName($username); if ($user->getID() !== 0) { $this->dieUsage("User name is in use", 'nonfreeusername'); } $password = $params['password']; if (!$user->isValidPassword($password)) { $this->dieUsage("Password is not acceptable", 'invalidpassword'); } $email = $params['email']; if (!Sanitizer::validateEmail($email)) { $this->dieUsage("Email is not acceptable", 'invalidemail'); } $user = TranslateSandbox::addUser($username, $email, $password); $output = array('user' => array('name' => $user->getName(), 'id' => $user->getId())); $user->setOption('language', $this->getContext()->getLanguage()->getCode()); $user->saveSettings(); $this->getResult()->addValue(null, $this->getModuleName(), $output); }
public static function onConfirmEmailShowRequestForm(EmailConfirmation &$pageObj, &$show) { $show = false; if (Sanitizer::validateEmail($pageObj->getUser()->getEmail())) { $userLoginHelper = new UserLoginHelper(); $userLoginHelper->showRequestFormConfirmEmail($pageObj); } else { $pageObj->getOutput()->addWikiMsg('usersignup-user-pref-confirmemail_noemail'); } return true; }
public function execute($par) { $this->checkPermissions(); $request = $this->getRequest(); $user = $this->getUser(); $out = $this->getOutput(); $this->setHeaders(); $store = $this->getStore(); $token = $request->getVal('token'); if ($request->wasPosted() && $user->matchEditToken($token, 'is')) { if ($request->getVal('do') === 'delete') { $store->deleteInvite($request->getVal('hash')); } if ($request->getVal('do') === 'add') { $email = $request->getVal('email'); $okay = Sanitizer::validateEmail($email); if (trim($email) === '') { // Silence } elseif (!$okay) { $out->wrapWikiMsg(Html::rawElement('div', array('class' => 'error'), "\$1"), array('is-invalidemail', $email)); } else { $groups = array(); foreach ($this->groups as $group) { if ($request->getCheck("group-{$group}")) { $groups[] = $group; } } $hash = $store->addInvite($user, $email, $groups); self::sendInviteEmail($user, $email, $hash); } } } $invites = $store->getInvites(); $lang = $this->getLanguage(); $out->addHtml(Html::openElement('table', array('class' => 'wikitable')) . Html::openElement('thead') . Html::openElement('tr') . Html::element('th', null, $this->msg('is-tableth-date')->text()) . Html::element('th', null, $this->msg('is-tableth-email')->text()) . Html::element('th', null, $this->msg('is-tableth-inviter')->text()) . Html::element('th', null, $this->msg('is-tableth-signup')->text()) . Html::element('th', null, $this->msg('is-tableth-groups')->text()) . Html::element('th', null, '') . $this->getAddRow() . Html::closeElement('thead')); foreach ($invites as $hash => $invite) { $whenSort = array('data-sort-value' => $invite['when']); $when = $lang->userTimeAndDate($invite['when'], $user); $email = $invite['email']; $groups = $invite['groups']; if (isset($invite['userid'])) { $inviteeUser = User::newFromId($invite['userid']); $name = $inviteeUser->getName(); $email = "{$name} <{$email}>"; } foreach ($groups as $i => $g) { $groups[$i] = User::getGroupMember($g); } $groups = $lang->commaList($groups); $out->addHtml(Html::openElement('tr') . Html::element('td', $whenSort, $when) . Html::element('td', null, $email) . Html::element('td', null, User::newFromId($invite['inviter'])->getName()) . Html::element('td', array('data-sort-value' => $invite['used']), $invite['used'] ? $lang->userTimeAndDate($invite['used'], $user) : '') . Html::element('td', null, $groups) . Html::rawElement('td', null, $invite['used'] ? '' : $this->getDeleteButton($invite['hash'])) . Html::closeElement('tr')); } $out->addhtml('</table>'); }
/** * Validate that the CUSTOM input of the ChooseName form is acceptable * and display an error page if it is not. */ function wikia_fbconnect_validateChooseNameForm(&$specialConnect) { wfProfileIn(__METHOD__); $allowDefault = true; global $wgRequest; $email = $wgRequest->getVal('wpEmail'); if ($email == "" || !Sanitizer::validateEmail($email)) { $specialConnect->sendPage('chooseNameForm', 'fbconnect-invalid-email'); $allowDefault = false; } wfProfileOut(__METHOD__); return $allowDefault; }
/** * Add data to the User object * @param User $user User being created (not added to the database yet). * This may become a "UserValue" in the future, or User may be refactored * into such. * @return StatusValue */ public function populateUser($user) { if ($this->email !== null && $this->email !== '') { if (!\Sanitizer::validateEmail($this->email)) { return StatusValue::newFatal('invalidemailaddress'); } $user->setEmail($this->email); } if ($this->realname !== null && $this->realname !== '') { $user->setRealName($this->realname); } return StatusValue::newGood(); }
public function execute() { global $wgUser, $wgAuth, $wgEnableEmail, $wgEmailAuthentication; if ($wgUser->isAnon()) { $this->dieUsage("You don't have permission to do that", 'permission-denied'); } $params = $this->extractRequestParams(); $error = false; switch ($params['mbaction']) { case 'setemail': if (!$wgAuth->allowPropChange('emailaddress')) { $error = wfMsgExt('cannotchangeemail', 'parseinline'); } else { //only set email if user does not have email on profile yet if (!$wgUser->getEmail()) { if (!isset($params['email']) || !Sanitizer::validateEmail($params['email'])) { $error = wfMsgExt('invalidemailaddress', 'parseinline'); } else { list($status, $info) = self::trySetUserEmail($wgUser, $params['email']); // Status Object if ($status !== true) { $error = $status->getWikiText($info); } else { $wgUser->saveSettings(); } } } } break; case 'resendverification': //only sends the email if the email has not been verified if ($wgEnableEmail && $wgEmailAuthentication && $wgUser->getEmail() && !$wgUser->isEmailConfirmed()) { $status = $wgUser->sendConfirmationMail('set'); if (!$status->isGood()) { $error = $status->getWikiText('mailerror'); } } break; default: throw new MWApiMoodBarSetUserEmailInvalidActionException("Action {$params['mbaction']} not implemented"); } if ($error === false) { $result = array('result' => 'success'); } else { $result = array('result' => 'error', 'error' => $error); } $this->getResult()->addValue(null, $this->getModuleName(), $result); }
/** * Main execution point * * @param $code Confirmation code passed to the page */ function execute($code) { $this->setHeaders(); $this->checkReadOnly(); if ($code === null || $code === '') { if ($this->getUser()->isLoggedIn()) { if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } else { $llink = Linker::linkKnown(SpecialPage::getTitleFor('Userlogin'), $this->msg('loginreqlink')->escaped(), array(), array('returnto' => $this->getTitle()->getPrefixedText())); $this->getOutput()->addHTML($this->msg('confirmemail_needlogin')->rawParams($llink)->parse()); } } else { $this->attemptConfirm($code); } }
/** * Main execution point * * @param $code Confirmation code passed to the page */ function execute($code) { $this->setHeaders(); if (wfReadOnly()) { throw new ReadOnlyError(); } if (empty($code)) { if ($this->getUser()->isLoggedIn()) { if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } else { $llink = Linker::linkKnown(SpecialPage::getTitleFor('Userlogin'), wfMsgHtml('loginreqlink'), array(), array('returnto' => $this->getTitle()->getPrefixedText())); $this->getOutput()->addHTML(wfMessage('confirmemail_needlogin')->rawParams($llink)->parse()); } } else { $this->attemptConfirm($code); } }
/** * Main execution point * * @param null|string $code Confirmation code passed to the page * @throws PermissionsError * @throws ReadOnlyError * @throws UserNotLoggedIn */ function execute($code) { $this->setHeaders(); $this->checkReadOnly(); $this->checkPermissions(); $this->requireLogin('confirmemail_needlogin'); // This could also let someone check the current email address, so // require both permissions. if (!$this->getUser()->isAllowed('viewmyprivateinfo')) { throw new PermissionsError('viewmyprivateinfo'); } if ($code === null || $code === '') { if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } else { $this->attemptConfirm($code); } }
/** * Main execution point * * @param $code Confirmation code passed to the page */ function execute($code) { $this->setHeaders(); $this->checkReadOnly(); /* Wikia change begin - @author: Uberfuzzy */ /* manual confirm code entry */ if (empty($code)) { #no code passed as execute param, #attempt to pull code from URL (as sent by manual form), and put where normal flow expects $code = $this->getRequest()->getText('code'); $code = trim($code); } else { #execute param not empty, try to catch new state here if ($code === 'manual') { $this->showManualForm(); return; } } /* wikia change end */ if ($code === null || $code === '') { if ($this->getUser()->isLoggedIn()) { /* Wikia change - begin */ $show = true; wfRunHooks('ConfirmEmailShowRequestForm', array(&$this, &$show)); if ($show) { if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } /* Wikia change - end */ } else { $llink = Linker::linkKnown(SpecialPage::getTitleFor('Userlogin'), $this->msg('loginreqlink')->escaped(), array(), array('returnto' => $this->getTitle()->getPrefixedText())); $this->getOutput()->addHTML($this->msg('confirmemail_needlogin')->rawParams($llink)->parse()); } } else { $this->attemptConfirm($code); } }
public function execute() { $userName = $this->getArg(0); if (preg_match('/^#\\d+$/', $userName)) { $user = User::newFromId(substr($userName, 1)); } else { $user = User::newFromName($userName); } if (!$user || !$user->getId() || !$user->loadFromId()) { $this->error("Error: user '{$userName}' does not exist\n", 1); } $email = $this->getArg(1); if (!Sanitizer::validateEmail($email)) { $this->error("Error: email '{$email}' is not valid\n", 1); } // Code from https://wikitech.wikimedia.org/wiki/Password_reset $user->setEmail($email); $user->setEmailAuthenticationTimestamp(wfTimestampNow()); $user->saveSettings(); // Kick whomever is currently controlling the account off $user->setPassword(PasswordFactory::generateRandomPasswordString(128)); }
/** * @param $user User * @param $pass string * @param $newaddr string * @return bool|string true or string on success, false on failure */ protected function attemptChange(User $user, $pass, $newaddr) { if ($newaddr != '' && !Sanitizer::validateEmail($newaddr)) { $this->error('invalidemailaddress'); return false; } $throttleCount = LoginForm::incLoginThrottle($user->getName()); if ($throttleCount === true) { $this->error('login-throttled'); return false; } global $wgRequirePasswordforEmailChange; if ($wgRequirePasswordforEmailChange && !$user->checkTemporaryPassword($pass) && !$user->checkPassword($pass)) { $this->error('wrongpassword'); return false; } if ($throttleCount) { LoginForm::clearLoginThrottle($user->getName()); } $oldaddr = $user->getEmail(); $status = $user->setEmailWithConfirmation($newaddr); if (!$status->isGood()) { $this->getOutput()->addHTML('<p class="error">' . $this->getOutput()->parseInline($status->getWikiText('mailerror')) . '</p>'); return false; } wfRunHooks('PrefsEmailAudit', array($user, $oldaddr, $newaddr)); $user->saveSettings(); return $status->value; }
protected function parseUserValue($value) { $value = trim($value); $this->m_wikitext = $value; if ($this->m_caption === false) { $this->m_caption = $this->m_wikitext; } $scheme = $hierpart = $query = $fragment = ''; if ($value === '') { // do not accept empty strings $this->addError(wfMessage('smw_emptystring')->inContentLanguage()->text()); return; } switch ($this->m_mode) { case SMW_URI_MODE_URI: case SMW_URI_MODE_ANNOURI: // Whether the the url value was externally encoded or not if (strpos($value, "%") === false) { $this->showUrlContextInRawFormat = false; } // If somehow the slash was encoded bring into one format $value = str_replace("%2F", "/", $value); $parts = explode(':', $value, 2); // try to split "schema:rest" if (count($parts) == 1) { // possibly add "http" as default $value = 'http://' . $value; $parts[1] = $parts[0]; $parts[0] = 'http'; } // check against blacklist $uri_blacklist = explode("\n", wfMessage('smw_uri_blacklist')->inContentLanguage()->text()); foreach ($uri_blacklist as $uri) { $uri = trim($uri); if ($uri !== '' && $uri == mb_substr($value, 0, mb_strlen($uri))) { // disallowed URI! $this->addError(wfMessage('smw_baduri', $value)->inContentLanguage()->text()); return; } } // decompose general URI components $scheme = $parts[0]; $parts = explode('?', $parts[1], 2); // try to split "hier-part?queryfrag" if (count($parts) == 2) { $hierpart = $parts[0]; $parts = explode('#', $parts[1], 2); // try to split "query#frag" $query = $parts[0]; $fragment = count($parts) == 2 ? $parts[1] : ''; } else { $query = ''; $parts = explode('#', $parts[0], 2); // try to split "hier-part#frag" $hierpart = $parts[0]; $fragment = count($parts) == 2 ? $parts[1] : ''; } // We do not validate the URI characters (the data item will do this) but we do some escaping: // encode most characters, but leave special symbols as given by user: $hierpart = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($hierpart)); $query = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($query)); $fragment = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($fragment)); /// NOTE: we do not support raw [ (%5D) and ] (%5E), although they are needed for ldap:// (but rarely in a wiki) /// NOTE: "+" gets encoded, as it is interpreted as space by most browsers when part of a URL; /// this prevents tel: from working directly, but we have a datatype for this anyway. if (substr($hierpart, 0, 2) === '//') { $hierpart = substr($hierpart, 2); } break; case SMW_URI_MODE_TEL: $scheme = 'tel'; if (substr($value, 0, 4) === 'tel:') { // accept optional "tel" $value = substr($value, 4); $this->m_wikitext = $value; } $hierpart = preg_replace('/(?<=[0-9]) (?=[0-9])/', '\\1-\\2', $value); $hierpart = str_replace(' ', '', $hierpart); if (substr($hierpart, 0, 2) == '00') { $hierpart = '+' . substr($hierpart, 2); } if (!$this->isUsedByQueryCondition && (strlen(preg_replace('/[^0-9]/', '', $hierpart)) < 6 || preg_match('<[-+./][-./]>', $hierpart) || !self::isValidTelURI('tel:' . $hierpart))) { /// TODO: introduce error-message for "bad" phone number $this->addError(wfMessage('smw_baduri', $this->m_wikitext)->inContentLanguage()->text()); return; } break; case SMW_URI_MODE_EMAIL: $scheme = 'mailto'; if (strpos($value, 'mailto:') === 0) { // accept optional "mailto" $value = substr($value, 7); $this->m_wikitext = $value; } if (!$this->isUsedByQueryCondition && !Sanitizer::validateEmail($value)) { /// TODO: introduce error-message for "bad" email $this->addError(wfMessage('smw_baduri', $value)->inContentLanguage()->text()); return; } $hierpart = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($value)); } // Now create the URI data item: try { $this->m_dataitem = new SMWDIUri($scheme, $hierpart, $query, $fragment, $this->m_typeid); } catch (SMWDataItemException $e) { $this->addError(wfMessage('smw_baduri', $this->m_wikitext)->inContentLanguage()->text()); } }
/** * Send confirmation email * * @param string $username * @return array The format of this array is: * [ * 'result' => result status[error/ok/invalidsession/confirmed], * 'msg' => result message * ] */ public function sendConfirmationEmail($username) { global $wgExternalSharedDB; if (empty($username)) { $result['result'] = 'error'; $result['msg'] = wfMessage('userlogin-error-noname')->escaped(); return $result; } // Check whether user already exists or is already confirmed wfWaitForSlaves(); // Wait for local DB - Wikis that keep user data in local DB (e.g. Uncyclopedia/Internal) wfWaitForSlaves($wgExternalSharedDB); // Wait for external shared DB $user = User::newFromName($username); if (!$user instanceof User || $user->getID() == 0) { // User doesn't exist $result['result'] = 'error'; $result['msg'] = wfMessage('userlogin-error-nosuchuser')->escaped(); return $result; } else { if (!$user->getGlobalFlag(UserLoginSpecialController::NOT_CONFIRMED_SIGNUP_OPTION_NAME) && $user->isEmailConfirmed()) { // User already confirmed on signup $result['result'] = 'confirmed'; $result['msg'] = wfMessage('usersignup-error-confirmed-user', $username, $user->getUserPage()->getFullURL())->parse(); return $result; } } // IF session is invalid, set invalidsession result and redirect to login page if (!(isset($_SESSION['notConfirmedUserId']) && $_SESSION['notConfirmedUserId'] == $user->getId())) { $result['result'] = 'invalidsession'; $result['msg'] = wfMessage('usersignup-error-invalid-user')->escaped(); return $result; } if (!$this->wg->EmailAuthentication || !Sanitizer::validateEmail($user->getEmail())) { // Why throw an invalid email error when wgEmailAuthentication is off? $result['result'] = 'error'; $result['msg'] = wfMessage('usersignup-error-invalid-email')->escaped(); return $result; } if ($user->isEmailConfirmed()) { $result['result'] = 'error'; $result['msg'] = wfMessage('usersignup-error-already-confirmed')->escaped(); return $result; } // Signup throttle check $memKey = $this->getMemKeyConfirmationEmailsSent($user->getId()); $emailSent = intval($this->wg->Memc->get($memKey)); if ($user->isEmailConfirmationPending() && strtotime($user->mEmailTokenExpires) - strtotime("+6 days") > 0 && $emailSent >= self::LIMIT_EMAILS_SENT) { $result['result'] = 'error'; $result['msg'] = wfMessage('usersignup-error-throttled-email')->escaped(); return $result; } $response = $user->sendConfirmationMail(false, 'ConfirmationMail'); if (!$response->isGood()) { $result['result'] = 'error'; $result['msg'] = wfMessage('userlogin-error-mail-error')->escaped(); } else { $result['result'] = 'ok'; $result['msg'] = wfMessage('usersignup-confirmation-email-sent', htmlspecialchars($user->getEmail()))->parse(); $this->incrMemc($memKey); } return $result; }
/** * Is this user's e-mail address valid-looking and confirmed within * limits of the current site configuration? * * @note If $wgEmailAuthentication is on, this may require the user to have * confirmed their address by returning a code or using a password * sent to the address from the wiki. * * @return Bool */ public function isEmailConfirmed() { global $wgEmailAuthentication; $this->load(); $confirmed = true; if (wfRunHooks('EmailConfirmed', array(&$this, &$confirmed))) { if ($this->isAnon()) { return false; } if (!Sanitizer::validateEmail($this->mEmail)) { return false; } if ($wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp()) { return false; } return true; } else { return $confirmed; } }
/** * As recCheckCondition, but *not* recursive. The only valid conditions * are those whose first element is APCOND_EMAILCONFIRMED/APCOND_EDITCOUNT/ * APCOND_AGE. Other types will throw an exception if no extension evalu- * ates them. * * @param $cond Array: A condition, which must not contain other conditions * @param $user User The user to check the condition against * @return bool Whether the condition is true for the user */ private static function checkCondition($cond, User $user) { global $wgEmailAuthentication, $wgEnableEditCountLocal; if (count($cond) < 1) { return false; } switch ($cond[0]) { case APCOND_EMAILCONFIRMED: if (Sanitizer::validateEmail($user->getEmail())) { if ($wgEmailAuthentication) { return (bool) $user->getEmailAuthenticationTimestamp(); } else { return true; } } return false; case APCOND_EDITCOUNT: if (!empty($wgEnableEditCountLocal)) { return $user->getEditCountLocal() >= $cond[1]; } else { return $user->getEditCount() >= $cond[1]; } case APCOND_AGE: $age = time() - wfTimestampOrNull(TS_UNIX, $user->getRegistration()); return $age >= $cond[1]; case APCOND_AGE_FROM_EDIT: $age = time() - wfTimestampOrNull(TS_UNIX, $user->getFirstEditTimestamp()); return $age >= $cond[1]; case APCOND_INGROUPS: $groups = array_slice($cond, 1); return count(array_intersect($groups, $user->getGroups())) == count($groups); case APCOND_ISIP: return $cond[1] == $user->getRequest()->getIP(); case APCOND_IPINRANGE: return IP::isInRange($user->getRequest()->getIP(), $cond[1]); case APCOND_BLOCKED: return $user->isBlocked(); case APCOND_ISBOT: return in_array('bot', User::getGroupPermissions($user->getGroups())); default: $result = null; wfRunHooks('AutopromoteCondition', array($cond[0], array_slice($cond, 1), $user, &$result)); if ($result === null) { throw new MWException("Unrecognized condition {$cond[0]} for autopromotion!"); } return (bool) $result; } }
/** * Create a HTMLForm descriptor for the core login fields. * @param FakeAuthTemplate $template B/C data (not used but needed by getBCFieldDefinitions) * @return array */ protected function getFieldDefinitions($template) { global $wgEmailConfirmToEdit; $isLoggedIn = $this->getUser()->isLoggedIn(); $continuePart = $this->isContinued() ? 'continue-' : ''; $anotherPart = $isLoggedIn ? 'another-' : ''; $expiration = $this->getRequest()->getSession()->getProvider()->getRememberUserDuration(); $expirationDays = ceil($expiration / (3600 * 24)); $secureLoginLink = ''; if ($this->mSecureLoginUrl) { $secureLoginLink = Html::element('a', ['href' => $this->mSecureLoginUrl, 'class' => 'mw-ui-flush-right mw-secure'], $this->msg('userlogin-signwithsecure')->text()); } if ($this->isSignup()) { $fieldDefinitions = ['username' => ['label-message' => 'userlogin-yourname', 'help-message' => 'createacct-helpusername', 'id' => 'wpName2', 'placeholder-message' => $isLoggedIn ? 'createacct-another-username-ph' : 'userlogin-yourname-ph'], 'mailpassword' => ['type' => 'check', 'label-message' => 'createaccountmail', 'name' => 'wpCreateaccountMail', 'id' => 'wpCreateaccountMail'], 'password' => ['id' => 'wpPassword2', 'placeholder-message' => 'createacct-yourpassword-ph', 'hide-if' => ['===', 'wpCreateaccountMail', '1']], 'domain' => [], 'retype' => ['baseField' => 'password', 'type' => 'password', 'label-message' => 'createacct-yourpasswordagain', 'id' => 'wpRetype', 'cssclass' => 'loginPassword', 'size' => 20, 'validation-callback' => function ($value, $alldata) { if (empty($alldata['mailpassword']) && !empty($alldata['password'])) { if (!$value) { return $this->msg('htmlform-required'); } elseif ($value !== $alldata['password']) { return $this->msg('badretype'); } } return true; }, 'hide-if' => ['===', 'wpCreateaccountMail', '1'], 'placeholder-message' => 'createacct-yourpasswordagain-ph'], 'email' => ['type' => 'email', 'label-message' => $wgEmailConfirmToEdit ? 'createacct-emailrequired' : 'createacct-emailoptional', 'id' => 'wpEmail', 'cssclass' => 'loginText', 'size' => '20', 'required' => $wgEmailConfirmToEdit, 'validation-callback' => function ($value, $alldata) { global $wgEmailConfirmToEdit; // AuthManager will check most of these, but that will make the auth // session fail and this won't, so nicer to do it this way if (!$value && $wgEmailConfirmToEdit) { // no point in allowing registration without email when email is // required to edit return $this->msg('noemailtitle'); } elseif (!$value && !empty($alldata['mailpassword'])) { // cannot send password via email when there is no email address return $this->msg('noemailcreate'); } elseif ($value && !Sanitizer::validateEmail($value)) { return $this->msg('invalidemailaddress'); } return true; }, 'placeholder-message' => 'createacct-' . $anotherPart . 'email-ph'], 'realname' => ['type' => 'text', 'help-message' => $isLoggedIn ? 'createacct-another-realname-tip' : 'prefs-help-realname', 'label-message' => 'createacct-realname', 'cssclass' => 'loginText', 'size' => 20, 'id' => 'wpRealName'], 'reason' => ['type' => 'text', 'label-message' => 'createacct-reason', 'cssclass' => 'loginText', 'id' => 'wpReason', 'size' => '20', 'placeholder-message' => 'createacct-reason-ph'], 'extrainput' => [], 'createaccount' => ['type' => 'submit', 'default' => $this->msg('createacct-' . $anotherPart . $continuePart . 'submit')->text(), 'name' => 'wpCreateaccount', 'id' => 'wpCreateaccount', 'weight' => 100]]; } else { $fieldDefinitions = ['username' => ['label-raw' => $this->msg('userlogin-yourname')->escaped() . $secureLoginLink, 'id' => 'wpName1', 'placeholder-message' => 'userlogin-yourname-ph'], 'password' => ['id' => 'wpPassword1', 'placeholder-message' => 'userlogin-yourpassword-ph'], 'domain' => [], 'extrainput' => [], 'rememberMe' => ['type' => 'check', 'label-message' => $this->msg('userlogin-remembermypassword')->numParams($expirationDays), 'id' => 'wpRemember'], 'loginattempt' => ['type' => 'submit', 'name' => 'wpRemember', 'default' => $this->msg('pt-login-' . $continuePart . 'button')->text(), 'id' => 'wpLoginAttempt', 'weight' => 100], 'linkcontainer' => ['type' => 'info', 'cssclass' => 'mw-form-related-link-container mw-userlogin-help', 'raw' => true, 'default' => Html::element('a', ['href' => Skin::makeInternalOrExternalUrl(wfMessage('helplogin-url')->inContentLanguage()->text())], $this->msg('userlogin-helplink2')->text()), 'weight' => 200]]; } $fieldDefinitions['username'] += ['type' => 'text', 'name' => 'wpName', 'cssclass' => 'loginText', 'size' => 20]; $fieldDefinitions['password'] += ['type' => 'password', 'name' => 'wpPassword', 'cssclass' => 'loginPassword', 'size' => 20]; if ($this->mEntryError) { $fieldDefinitions['entryError'] = ['type' => 'info', 'default' => Html::rawElement('div', ['class' => $this->mEntryErrorType . 'box'], $this->mEntryError), 'raw' => true, 'rawrow' => true, 'weight' => -100]; } if (!$this->showExtraInformation()) { unset($fieldDefinitions['linkcontainer']); } $fieldDefinitions = $this->getBCFieldDefinitions($fieldDefinitions, $template); $fieldDefinitions = array_filter($fieldDefinitions); return $fieldDefinitions; }
/** * Process the form. At this point we know that the user passes all the criteria in * userCanExecute(), and if the data array contains 'Username', etc, then Username * resets are allowed. * @param $data array * @return Bool|Array */ public function onSubmit(array $data) { global $wgAuth; if (isset($data['Domain'])) { if ($wgAuth->validDomain($data['Domain'])) { $wgAuth->setDomain($data['Domain']); } else { $wgAuth->setDomain('invaliddomain'); } } if (isset($data['Username']) && $data['Username'] !== '') { $method = 'username'; $users = array(User::newFromName($data['Username'])); } elseif (isset($data['Email']) && $data['Email'] !== '' && Sanitizer::validateEmail($data['Email'])) { $method = 'email'; $res = wfGetDB(DB_SLAVE)->select('user', '*', array('user_email' => $data['Email']), __METHOD__); if ($res) { $users = array(); foreach ($res as $row) { $users[] = User::newFromRow($row); } } else { // Some sort of database error, probably unreachable throw new MWException('Unknown database error in ' . __METHOD__); } } else { // The user didn't supply any data return false; } // Check for hooks (captcha etc), and allow them to modify the users list $error = array(); if (!wfRunHooks('SpecialPasswordResetOnSubmit', array(&$users, $data, &$error))) { return array($error); } if (count($users) == 0) { if ($method == 'email') { // Don't reveal whether or not an email address is in use return true; } else { return array('noname'); } } $firstUser = $users[0]; if (!$firstUser instanceof User || !$firstUser->getID()) { return array(array('nosuchuser', $data['Username'])); } // Check against the rate limiter if ($this->getUser()->pingLimiter('mailpassword')) { throw new ThrottledError(); } // Check against password throttle foreach ($users as $user) { if ($user->isPasswordReminderThrottled()) { global $wgPasswordReminderResendTime; # Round the time in hours to 3 d.p., in case someone is specifying # minutes or seconds. return array(array('throttled-mailpassword', round($wgPasswordReminderResendTime, 3))); } } global $wgNewPasswordExpiry; // All the users will have the same email address if ($firstUser->getEmail() == '') { // This won't be reachable from the email route, so safe to expose the username return array(array('noemail', $firstUser->getName())); } // We need to have a valid IP address for the hook, but per bug 18347, we should // send the user's name if they're logged in. $ip = wfGetIP(); if (!$ip) { return array('badipaddress'); } $caller = $this->getUser(); wfRunHooks('User::mailPasswordInternal', array(&$caller, &$ip, &$firstUser)); $username = $caller->getName(); $msg = IP::isValid($username) ? 'passwordreset-emailtext-ip' : 'passwordreset-emailtext-user'; // Send in the user's language; which should hopefully be the same $userLanguage = $firstUser->getOption('language'); $passwords = array(); foreach ($users as $user) { $password = $user->randomPassword(); $user->setNewpassword($password); $user->saveSettings(); $passwords[] = wfMessage('passwordreset-emailelement', $user->getName(), $password)->inLanguage($userLanguage)->plain(); // We'll escape the whole thing later } $passwordBlock = implode("\n\n", $passwords); $body = wfMessage($msg)->inLanguage($userLanguage); $body->params($username, $passwordBlock, count($passwords), Title::newMainPage()->getCanonicalUrl(), round($wgNewPasswordExpiry / 86400)); $title = wfMessage('passwordreset-emailtitle'); $result = $firstUser->sendMail($title->text(), $body->text()); if ($result->isGood()) { return true; } else { // @todo FIXME: The email didn't send, but we have already set the password throttle // timestamp, so they won't be able to try again until it expires... :( return array(array('mailerror', $result->getMessage())); } }
/** * HTMLForm field validation-callback for email field. * * @since 0.1 * * @param $value String * @param $alldata Array * * @return true|string */ public static function validateEmailField($value, $alldata = null) { if (!Sanitizer::validateEmail($value)) { return wfMsg('contest-signup-invalid-email'); } return true; }
/** * Make a new user account using the loaded data. * @private * @throws PermissionsError|ReadOnlyError * @return Status */ public function addNewAccountInternal() { global $wgAuth, $wgMemc, $wgAccountCreationThrottle, $wgEmailConfirmToEdit; // If the user passes an invalid domain, something is fishy if (!$wgAuth->validDomain($this->mDomain)) { return Status::newFatal('wrongpassword'); } // 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 authenti- // cation 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->mUsername) || !$wgAuth->authenticate($this->mUsername, $this->mPassword))) { return Status::newFatal('wrongpassword'); } } if (wfReadOnly()) { throw new ReadOnlyError(); } # Request forgery checks. if (!self::getCreateaccountToken()) { self::setCreateaccountToken(); return Status::newFatal('nocookiesfornew'); } # The user didn't pass a createaccount token if (!$this->mToken) { return Status::newFatal('sessionfailure'); } # Validate the createaccount token if ($this->mToken !== self::getCreateaccountToken()) { return Status::newFatal('sessionfailure'); } # Check permissions $currentUser = $this->getUser(); $creationBlock = $currentUser->isBlockedFromCreateAccount(); if (!$currentUser->isAllowed('createaccount')) { throw new PermissionsError('createaccount'); } elseif ($creationBlock instanceof Block) { // Throws an ErrorPageError. $this->userBlockedMessage($creationBlock); // This should never be reached. return false; } # Include checks that will include GlobalBlocking (Bug 38333) $permErrors = $this->getPageTitle()->getUserPermissionsErrors('createaccount', $currentUser, true); if (count($permErrors)) { throw new PermissionsError('createaccount', $permErrors); } $ip = $this->getRequest()->getIP(); if ($currentUser->isDnsBlacklisted($ip, true)) { return Status::newFatal('sorbs_create_account_reason'); } # Now create a dummy user ($u) and check if it is valid $u = User::newFromName($this->mUsername, 'creatable'); if (!$u) { return Status::newFatal('noname'); } # Make sure the user does not exist already $lock = $wgMemc->getScopedLock(wfGlobalCacheKey('account', md5($this->mUsername))); if (!$lock) { return Status::newFatal('usernameinprogress'); } elseif ($u->idForName(User::READ_LOCKING)) { return Status::newFatal('userexists'); } if ($this->mCreateaccountMail) { # do not force a password for account creation by email # set invalid password, it will be replaced later by a random generated password $this->mPassword = null; } else { if ($this->mPassword !== $this->mRetype) { return Status::newFatal('badretype'); } # check for password validity, return a fatal Status if invalid $validity = $u->checkPasswordValidity($this->mPassword, 'create'); if (!$validity->isGood()) { $validity->ok = false; // make sure this Status is fatal return $validity; } } # if you need a confirmed email address to edit, then obviously you # need an email address. if ($wgEmailConfirmToEdit && strval($this->mEmail) === '') { return Status::newFatal('noemailtitle'); } if (strval($this->mEmail) !== '' && !Sanitizer::validateEmail($this->mEmail)) { return Status::newFatal('invalidemailaddress'); } # Set some additional data so the AbortNewAccount hook can be used for # more than just username validation $u->setEmail($this->mEmail); $u->setRealName($this->mRealName); $abortError = ''; $abortStatus = null; if (!Hooks::run('AbortNewAccount', array($u, &$abortError, &$abortStatus))) { // Hook point to add extra creation throttles and blocks wfDebug("LoginForm::addNewAccountInternal: a hook blocked creation\n"); if ($abortStatus === null) { // Report back the old string as a raw message status. // This will report the error back as 'createaccount-hook-aborted' // with the given string as the message. // To return a different error code, return a Status object. $abortError = new Message('createaccount-hook-aborted', array($abortError)); $abortError->text(); return Status::newFatal($abortError); } else { // For MediaWiki 1.23+ and updated hooks, return the Status object // returned from the hook. return $abortStatus; } } // Hook point to check for exempt from account creation throttle if (!Hooks::run('ExemptFromAccountCreationThrottle', array($ip))) { wfDebug("LoginForm::exemptFromAccountCreationThrottle: a hook " . "allowed account creation w/o throttle\n"); } else { if ($wgAccountCreationThrottle && $currentUser->isPingLimitable()) { $key = wfMemcKey('acctcreate', 'ip', $ip); $value = $wgMemc->get($key); if (!$value) { $wgMemc->set($key, 0, 86400); } if ($value >= $wgAccountCreationThrottle) { return Status::newFatal('acct_creation_throttle_hit', $wgAccountCreationThrottle); } $wgMemc->incr($key); } } if (!$wgAuth->addUser($u, $this->mPassword, $this->mEmail, $this->mRealName)) { return Status::newFatal('externaldberror'); } self::clearCreateaccountToken(); return $this->initUser($u, false); }
/** * @return bool */ public function submit() { $retVal = true; $this->parent->setVarsFromRequest(array('wgSitename', '_NamespaceType', '_AdminName', '_AdminPassword', '_AdminPasswordConfirm', '_AdminEmail', '_Subscribe', '_SkipOptional', 'wgMetaNamespace')); // Validate site name if (strval($this->getVar('wgSitename')) === '') { $this->parent->showError('config-site-name-blank'); $retVal = false; } // Fetch namespace $nsType = $this->getVar('_NamespaceType'); if ($nsType == 'site-name') { $name = $this->getVar('wgSitename'); // Sanitize for namespace // This algorithm should match the JS one in WebInstallerOutput.php $name = preg_replace('/[\\[\\]\\{\\}|#<>%+? ]/', '_', $name); $name = str_replace('&', '&', $name); $name = preg_replace('/__+/', '_', $name); $name = ucfirst(trim($name, '_')); } elseif ($nsType == 'generic') { $name = wfMessage('config-ns-generic')->text(); } else { // other $name = $this->getVar('wgMetaNamespace'); } // Validate namespace if (strpos($name, ':') !== false) { $good = false; } else { // Title-style validation $title = Title::newFromText($name); if (!$title) { $good = $nsType == 'site-name'; } else { $name = $title->getDBkey(); $good = true; } } if (!$good) { $this->parent->showError('config-ns-invalid', $name); $retVal = false; } // Make sure it won't conflict with any existing namespaces global $wgContLang; $nsIndex = $wgContLang->getNsIndex($name); if ($nsIndex !== false && $nsIndex !== NS_PROJECT) { $this->parent->showError('config-ns-conflict', $name); $retVal = false; } $this->setVar('wgMetaNamespace', $name); // Validate username for creation $name = $this->getVar('_AdminName'); if (strval($name) === '') { $this->parent->showError('config-admin-name-blank'); $cname = $name; $retVal = false; } else { $cname = User::getCanonicalName($name, 'creatable'); if ($cname === false) { $this->parent->showError('config-admin-name-invalid', $name); $retVal = false; } else { $this->setVar('_AdminName', $cname); } } // Validate password $msg = false; $pwd = $this->getVar('_AdminPassword'); $user = User::newFromName($cname); if ($user) { $valid = $user->getPasswordValidity($pwd); } else { $valid = 'config-admin-name-invalid'; } if (strval($pwd) === '') { # $user->getPasswordValidity just checks for $wgMinimalPasswordLength. # This message is more specific and helpful. $msg = 'config-admin-password-blank'; } elseif ($pwd !== $this->getVar('_AdminPasswordConfirm')) { $msg = 'config-admin-password-mismatch'; } elseif ($valid !== true) { $msg = $valid; } if ($msg !== false) { call_user_func_array(array($this->parent, 'showError'), (array) $msg); $this->setVar('_AdminPassword', ''); $this->setVar('_AdminPasswordConfirm', ''); $retVal = false; } // Validate e-mail if provided $email = $this->getVar('_AdminEmail'); if ($email && !Sanitizer::validateEmail($email)) { $this->parent->showError('config-admin-error-bademail'); $retVal = false; } // If they asked to subscribe to mediawiki-announce but didn't give // an e-mail, show an error. Bug 29332 if (!$email && $this->getVar('_Subscribe')) { $this->parent->showError('config-subscribe-noemail'); $retVal = false; } return $retVal; }