<?php
/**
* See user.txt
- *
+ * @file
*/
# Number of characters in user_token field
/**
* Thrown by User::setPassword() on error
- * @addtogroup Exception
+ * @ingroup Exception
*/
class PasswordError extends MWException {
// NOP
'minoredit',
'move',
'nominornewtalk',
+ 'noratelimit',
'patrol',
'protect',
'proxyunbannable',
* This is slightly less efficient than newFromId(), so use newFromId() if
* you have both an ID and a name handy.
*
- * @param string $name Username, validated by Title:newFromText()
- * @param mixed $validate Validate username. Takes the same parameters as
+ * @param $name String: username, validated by Title:newFromText()
+ * @param $validate Mixed: validate username. Takes the same parameters as
* User::getCanonicalName(), except that true is accepted as an alias
* for 'valid', for BC.
*
* @return User object, or null if the username is invalid. If the username
* is not present in the database, the result will be a user object with
* a name, zero user ID and default settings.
- * @static
*/
static function newFromName( $name, $validate = 'valid' ) {
if ( $validate === true ) {
*
* If the code is invalid or has expired, returns NULL.
*
- * @param string $code
+ * @param $code string
* @return User
- * @static
*/
static function newFromConfirmationCode( $code ) {
$dbr = wfGetDB( DB_SLAVE );
* login credentials are invalid, the result is an anonymous user.
*
* @return User
- * @static
*/
static function newFromSession() {
$user = new User;
/**
* Get username given an id.
- * @param integer $id Database user id
+ * @param $id Integer: database user id
* @return string Nickname of a user
- * @static
*/
static function whoIs( $id ) {
$dbr = wfGetDB( DB_SLAVE );
/**
* Get the real name of a user given their identifier
*
- * @param int $id Database user id
+ * @param $id Int: database user id
* @return string Real name of a user
*/
static function whoIsReal( $id ) {
/**
* Get database id given a user name
- * @param string $name Nickname of a user
+ * @param $name String: nickname of a user
* @return integer|null Database user id (null: if non existent
* @static
*/
* addresses like this, if we allowed accounts like this to be created
* new users could get the old edits of these anonymous users.
*
- * @static
- * @param string $name Nickname of a user
+ * @param $name String: nickname of a user
* @return bool
*/
static function isIP( $name ) {
- return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
- /*return preg_match("/^
- (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
- (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
- (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
- (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
- $/x", $name);*/
- }
-
- /**
- * Check if $name is an IPv6 IP.
- */
- static function isIPv6($name) {
- /*
- * if it has any non-valid characters, it can't be a valid IPv6
- * address.
- */
- if (preg_match("/[^:a-fA-F0-9]/", $name))
- return false;
-
- $parts = explode(":", $name);
- if (count($parts) < 3)
- return false;
- foreach ($parts as $part) {
- if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
- return false;
- }
- return true;
+ return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
}
/**
* is longer than the maximum allowed username size or doesn't begin with
* a capital letter.
*
- * @param string $name
+ * @param $name string
* @return bool
- * @static
*/
static function isValidUserName( $name ) {
global $wgContLang, $wgMaxNameChars;
* If an account already exists in this form, login will be blocked
* by a failure to pass this function.
*
- * @param string $name
+ * @param $name string
* @return bool
*/
static function isUsableName( $name ) {
global $wgReservedUsernames;
- return
- // Must be a valid username, obviously ;)
- self::isValidUserName( $name ) &&
+ // Must be a valid username, obviously ;)
+ if ( !self::isValidUserName( $name ) ) {
+ return false;
+ }
- // Certain names may be reserved for batch processes.
- !in_array( $name, $wgReservedUsernames );
+ // Certain names may be reserved for batch processes.
+ foreach ( $wgReservedUsernames as $reserved ) {
+ if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
+ $reserved = wfMsgForContent( substr( $reserved, 4 ) );
+ }
+ if ( $reserved == $name ) {
+ return false;
+ }
+ }
+ return true;
}
/**
* rather than in isValidUserName() to avoid disrupting
* existing accounts.
*
- * @param string $name
+ * @param $name string
* @return bool
*/
static function isCreatableName( $name ) {
/**
* Is the input a valid password for this user?
*
- * @param string $password Desired password
+ * @param $password String: desired password
* @return bool
*/
function isValidPassword( $password ) {
*
* @todo Check for RFC 2822 compilance (bug 959)
*
- * @param string $addr email address
+ * @param $addr String: email address
* @return bool
*/
public static function isValidEmailAddr( $addr ) {
/**
* 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
+ * @param $name string
+ * @param $validate Mixed: 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
*
* It should not be static and some day should be merged as proper member function / deprecated -- domas
*
- * @param int $uid The user ID to check
+ * @param $uid Int: the user ID to check
* @return int
- * @static
*/
static function edits( $uid ) {
wfProfileIn( __METHOD__ );
* @todo hash random numbers to improve security, like generateToken()
*
* @return string
- * @static
*/
static function randomPassword() {
global $wgMinimalPasswordLength;
$this->mRegistration = wfTimestamp( TS_MW );
$this->mGroups = array();
+ wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
+
wfProfileOut( __METHOD__ );
}
/**
* Clear various cached data stored in this object.
- * @param string $reloadFrom Reload user and user_groups table data from a
+ * @param $reloadFrom String: reload user and user_groups table data from a
* given source. May be "name", "id", "defaults", "session" or false for
* no reload.
*/
* and add the default language variants.
* Not really private cause it's called by Language class
* @return array
- * @static
* @private
*/
static function getDefaultOptions() {
/**
* Get a given default option value.
*
- * @param string $opt
+ * @param $opt string
* @return string
- * @static
- * @public
*/
- function getDefaultOption( $opt ) {
- $defOpts = User::getDefaultOptions();
+ public static function getDefaultOption( $opt ) {
+ $defOpts = self::getDefaultOptions();
if( isset( $defOpts[$opt] ) ) {
return $defOpts[$opt];
} else {
/**
* Get blocking information
* @private
- * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
- * non-critical checks are done against slaves. Check when actually saving should be done against
- * master.
+ * @param $bFromSlave Bool: specify whether to check slave or master. To
+ * improve performance, non-critical checks are done
+ * against slaves. Check when actually saving should be
+ * done against master.
*/
function getBlockedStatus( $bFromSlave = true ) {
global $wgEnableSorbs, $wgProxyWhitelist;
wfProfileIn( __METHOD__ );
wfDebug( __METHOD__.": checking...\n" );
+ // Initialize data...
+ // Otherwise something ends up stomping on $this->mBlockedby when
+ // things get lazy-loaded later, causing false positive block hits
+ // due to -1 !== 0. Probably session-related... Nothing should be
+ // overwriting mBlockedby, surely?
+ $this->load();
+
$this->mBlockedby = 0;
$this->mHideName = 0;
$ip = wfGetIP();
# Proxy blocking
if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
-
# Local list
if ( wfIsLocallyBlockedProxy( $ip ) ) {
$this->mBlockedby = wfMsg( 'proxyblocker' );
*/
public function isPingLimitable() {
global $wgRateLimitsExcludedGroups;
- return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
+ if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
+ // Deprecated, but kept for backwards-compatibility config
+ return false;
+ }
+ return !$this->isAllowed('noratelimit');
}
/**
* last-hit counters will be shared across wikis.
*
* @return bool true if a rate limiter was tripped
- * @public
*/
function pingLimiter( $action='edit' ) {
$keys = array();
$id = $this->getId();
$ip = wfGetIP();
+ $userLimit = false;
if( isset( $limits['anon'] ) && $id == 0 ) {
$keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
}
if( isset( $limits['user'] ) && $id != 0 ) {
- $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
+ $userLimit = $limits['user'];
}
if( $this->isNewbie() ) {
if( isset( $limits['newbie'] ) && $id != 0 ) {
$keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
}
}
+ // Check for group-specific permissions
+ // If more than one group applies, use the group with the highest limit
+ foreach ( $this->getGroups() as $group ) {
+ if ( isset( $limits[$group] ) ) {
+ if ( $userLimit === false || $limits[$group] > $userLimit ) {
+ $userLimit = $limits[$group];
+ }
+ }
+ }
+ // Set the user limit key
+ if ( $userLimit !== false ) {
+ wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
+ $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
+ }
$triggered = false;
foreach( $keys as $key => $limit ) {
/**
* Get the user ID. Returns 0 if the user is anonymous or nonexistent.
*/
- function getID() {
+ function getId() {
if( $this->mId === null and $this->mName !== null
and User::isIP( $this->mName ) ) {
// Special case, we know the user is anonymous
/**
* Set the user and reload all fields according to that ID
*/
- function setID( $v ) {
+ function setId( $v ) {
$this->mId = $v;
$this->clearInstanceCache( 'id' );
}
/**
* Return the title dbkey form of the name, for eg user pages.
* @return string
- * @public
*/
function getTitleKey() {
return str_replace( ' ', '_', $this->getName() );
* Perform a user_newtalk check, uncached.
* Use getNewtalk for a cached check.
*
- * @param string $field
- * @param mixed $id
- * @param bool $fromMaster True to fetch from the master, false for a slave
+ * @param $field string
+ * @param $id mixed
+ * @param $fromMaster Bool: true to fetch from the master, false for a slave
* @return bool
* @private
*/
/**
* Add or update the
- * @param string $field
- * @param mixed $id
+ * @param $field string
+ * @param $id mixed
* @private
*/
function updateNewtalk( $field, $id ) {
/**
* Clear the new messages flag for the given user
- * @param string $field
- * @param mixed $id
+ * @param $field string
+ * @param $id mixed
* @private
*/
function deleteNewtalk( $field, $id ) {
/**
* Update the 'You have new messages!' status.
- * @param bool $val
+ * @param $val bool
*/
function setNewtalk( $val ) {
if( wfReadOnly() ) {
return ($timestamp >= $this->mTouched);
}
- /**
- * Encrypt a password.
- * It can eventually salt a password.
- * @see User::addSalt()
- * @param string $p clear Password.
- * @return string Encrypted password.
- */
- function encryptPassword( $p ) {
- $this->load();
- return wfEncryptPassword( $this->mId, $p );
- }
-
/**
* Set the password and reset the random token
* Calls through to authentication plugin if necessary;
* wipes it, so the account cannot be logged in until
* a new password is set, for instance via e-mail.
*
- * @param string $str
+ * @param $str string
* @throws PasswordError on failure
*/
function setPassword( $str ) {
if( !$this->isValidPassword( $str ) ) {
global $wgMinimalPasswordLength;
- throw new PasswordError( wfMsg( 'passwordtooshort',
+ throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
$wgMinimalPasswordLength ) );
}
}
* Set the password and reset the random token no matter
* what.
*
- * @param string $str
+ * @param $str string
*/
function setInternalPassword( $str ) {
$this->load();
// Save an invalid hash...
$this->mPassword = '';
} else {
- $this->mPassword = $this->encryptPassword( $str );
+ $this->mPassword = self::crypt( $str );
}
$this->mNewpassword = '';
$this->mNewpassTime = null;
}
+
+ function getToken() {
+ $this->load();
+ return $this->mToken;
+ }
+
/**
* Set the random token (used for persistent authentication)
* Called from loadDefaults() among other places.
*/
function setNewpassword( $str, $throttle = true ) {
$this->load();
- $this->mNewpassword = $this->encryptPassword( $str );
+ $this->mNewpassword = self::crypt( $str );
if ( $throttle ) {
$this->mNewpassTime = wfTimestampNow();
}
}
/**
- * @param string $oname The option to check
- * @param string $defaultOverride A default value returned if the option does not exist
+ * @param $oname String: the option to check
+ * @param $defaultOverride String: A default value returned if the option does not exist
* @return string
*/
function getOption( $oname, $defaultOverride = '' ) {
}
/**
- * @param string $oname The option to check
+ * @param $oname String: the option to check
* @return bool False if the option is not selected, true if it is
*/
function getBoolOption( $oname ) {
/**
* Get an option as an integer value from the source string.
- * @param string $oname The option to check
- * @param int $default Optional value to return if option is unset/blank.
+ * @param $oname String: the option to check
+ * @param $default Int: optional value to return if option is unset/blank.
* @return int
*/
function getIntOption( $oname, $default=0 ) {
}
// Filter out any newlines that may have passed through input validation.
// Newlines are used to separate items in the options blob.
- $val = str_replace( "\r\n", "\n", $val );
- $val = str_replace( "\r", "\n", $val );
- $val = str_replace( "\n", " ", $val );
+ if( $val ) {
+ $val = str_replace( "\r\n", "\n", $val );
+ $val = str_replace( "\r", "\n", $val );
+ $val = str_replace( "\n", " ", $val );
+ }
+ // Explicitly NULL values should refer to defaults
+ global $wgDefaultUserOptions;
+ if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
+ $val = $wgDefaultUserOptions[$oname];
+ }
$this->mOptions[$oname] = $val;
}
if ( is_null( $this->mRights ) ) {
$this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
+ // Force reindexation of rights when a hook has unset one of them
+ $this->mRights = array_values( $this->mRights );
}
return $this->mRights;
}
* Get the list of implicit group memberships this user has.
* This includes all explicit groups, plus 'user' if logged in,
* '*' for all accounts and autopromoted groups
- * @param boolean $recache Don't use the cache
+ * @param $recache Boolean: don't use the cache
* @return array of strings
*/
function getEffectiveGroups( $recache = false ) {
/**
* Add the user to the given group.
* This takes immediate effect.
- * @param string $group
+ * @param $group string
*/
function addGroup( $group ) {
$dbw = wfGetDB( DB_MASTER );
/**
* Remove the user from the given group.
* This takes immediate effect.
- * @param string $group
+ * @param $group string
*/
function removeGroup( $group ) {
$this->load();
/**
* Check if user is allowed to access a feature / make an action
- * @param string $action Action to be checked
+ * @param $action String: action to be checked
* @return boolean True: action is allowed, False: action should not be allowed
*/
function isAllowed($action='') {
}
/**#@+
- * @param string $title Article title to look at
+ * @param $title Title: article title to look at
*/
/**
* the next change of the page if it's watched etc.
*/
function clearNotification( &$title ) {
- global $wgUser, $wgUseEnotif;
+ global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
# Do nothing if the database is locked to writes
if( wfReadOnly() ) {
$this->setNewtalk( false );
}
- if( !$wgUseEnotif ) {
+ if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
return;
}
$title->getText() == $wgUser->getName())
{
$watched = true;
- } elseif ( $this->getID() == $wgUser->getID() ) {
+ } elseif ( $this->getId() == $wgUser->getId() ) {
$watched = $title->userIsWatching();
} else {
$watched = true;
'wl_title' => $title->getDBkey(),
'wl_namespace' => $title->getNamespace(),
'wl_user' => $this->getID()
- ), 'User::clearLastVisited'
+ ), __METHOD__
);
}
}
* If e-notif e-mails are on, they will receive notification mails on
* the next change of any watched page.
*
- * @param int $currentUser user ID number
- * @public
+ * @param $currentUser Int: user ID number
*/
function clearAllNotifications( $currentUser ) {
- global $wgUseEnotif;
- if ( !$wgUseEnotif ) {
+ global $wgUseEnotif, $wgShowUpdatedMarker;
+ if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
$this->setNewtalk( false );
return;
}
if( $currentUser != 0 ) {
-
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'watchlist',
array( /* SET */
'wl_user' => $currentUser
), __METHOD__
);
-
- # we also need to clear here the "you have new message" notification for the own user_talk page
+ # We also need to clear here the "you have new message" notification for the own user_talk page
# This is cleared one page view later in Article::viewUpdates();
}
}
function setCookies() {
$this->load();
if ( 0 == $this->mId ) return;
-
- $_SESSION['wsUserID'] = $this->mId;
-
- $this->setCookie( 'UserID', $this->mId );
- $this->setCookie( 'UserName', $this->getName() );
-
- $_SESSION['wsUserName'] = $this->getName();
-
- $_SESSION['wsToken'] = $this->mToken;
+ $session = array(
+ 'wsUserID' => $this->mId,
+ 'wsToken' => $this->mToken,
+ 'wsUserName' => $this->getName()
+ );
+ $cookies = array(
+ 'UserID' => $this->mId,
+ 'UserName' => $this->getName(),
+ );
if ( 1 == $this->getOption( 'rememberpassword' ) ) {
- $this->setCookie( 'Token', $this->mToken );
+ $cookies['Token'] = $this->mToken;
} else {
- $this->clearCookie( 'Token' );
+ $cookies['Token'] = false;
+ }
+
+ wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
+ $_SESSION = $session + $_SESSION;
+ foreach ( $cookies as $name => $value ) {
+ if ( $value === false ) {
+ $this->clearCookie( $name );
+ } else {
+ $this->setCookie( $name, $value );
+ }
}
}
/**
* Add a user to the database, return the user object
*
- * @param string $name The user's name
- * @param array $params Associative array of non-default parameters to save to the database:
+ * @param $name String: the user's name
+ * @param $params Associative array of non-default parameters to save to the database:
* password The user's password. Password logins will be disabled if this is omitted.
* newpassword A temporary password mailed to the user
* email The user's email address
/**
* Determine if the user is blocked from using Special:Emailuser.
*
- * @public
* @return boolean
*/
function isBlockedFromEmailuser() {
* Get this user's personal page title.
*
* @return Title
- * @public
*/
function getUserPage() {
return Title::makeTitle( NS_USER, $this->getName() );
* Get this user's talk page title.
*
* @return Title
- * @public
*/
function getTalkPage() {
$title = $this->getUserPage();
function isNewbie() {
return !$this->isAllowed( 'autoconfirmed' );
}
+
+ /**
+ * Is the user active? We check to see if they've made at least
+ * X number of edits in the last Y days.
+ *
+ * @return bool true if the user is active, false if not
+ */
+ public function isActiveEditor() {
+ global $wgActiveUserEditCount, $wgActiveUserDays;
+ $dbr = wfGetDB( DB_SLAVE );
+
+ // Stolen without shame from RC
+ $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
+ $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
+ $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
+
+ $res = $dbr->select( 'revision', '1',
+ array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
+ __METHOD__,
+ array('LIMIT' => $wgActiveUserEditCount ) );
+
+ $count = $dbr->numRows($res);
+ $dbr->freeResult($res);
+
+ return $count == $wgActiveUserEditCount;
+ }
/**
* Check to see if the given clear-text password is one of the accepted passwords
- * @param string $password User password.
+ * @param $password String: user password.
* @return bool True if the given password is correct otherwise False.
*/
function checkPassword( $password ) {
/* Auth plugin doesn't allow local authentication for this user name */
return false;
}
- $ep = $this->encryptPassword( $password );
- if ( 0 == strcmp( $ep, $this->mPassword ) ) {
+ if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
return true;
} elseif ( function_exists( 'iconv' ) ) {
# Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
# Check for this with iconv
- $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
- if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
+ $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
+ if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
return true;
}
}
* @return bool
*/
function checkTemporaryPassword( $plaintext ) {
- $hash = $this->encryptPassword( $plaintext );
- return $hash === $this->mNewpassword;
+ return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
}
/**
* login credentials aren't being hijacked with a foreign form
* submission.
*
- * @param mixed $salt - Optional function-specific data for hash.
- * Use a string or an array of strings.
+ * @param $salt Mixed: optional function-specific data for hash.
+ * Use a string or an array of strings.
* @return string
- * @public
*/
function editToken( $salt = '' ) {
if ( $this->isAnon() ) {
* user's own login session, not a form submission from a third-party
* site.
*
- * @param string $val - the input value to compare
- * @param string $salt - Optional function-specific data for hash
+ * @param $val String: the input value to compare
+ * @param $salt String: optional function-specific data for hash
* @return bool
- * @public
*/
function matchEditToken( $val, $salt = '' ) {
$sessionToken = $this->editToken( $salt );
* Send an e-mail to this user's account. Does not check for
* confirmed status or validity.
*
- * @param string $subject
- * @param string $body
- * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
+ * @param $subject string
+ * @param $body string
+ * @param $from string: optional from address; default $wgPasswordSender will be used otherwise.
+ * @param $replyto string
* @return mixed True on success, a WikiError object on failure.
*/
function sendMail( $subject, $body, $from = null, $replyto = null ) {
/**
* Return a URL the user can use to confirm their email address.
- * @param $token: accepts the email confirmation token
+ * @param $token accepts the email confirmation token
* @return string
* @private
*/
function confirmationTokenUrl( $token ) {
- $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
- return $title->getFullUrl();
+ return $this->getTokenUrl( 'ConfirmEmail', $token );
}
/**
* Return a URL the user can use to invalidate their email address.
- * @param $token: accepts the email confirmation token
+ * @param $token accepts the email confirmation token
* @return string
* @private
*/
- function invalidationTokenUrl( $token ) {
- $title = SpecialPage::getTitleFor( 'Invalidateemail', $token );
- return $title->getFullUrl();
+ function invalidationTokenUrl( $token ) {
+ return $this->getTokenUrl( 'Invalidateemail', $token );
+ }
+
+ /**
+ * Internal function to format the e-mail validation/invalidation URLs.
+ * This uses $wgArticlePath directly as a quickie hack to use the
+ * hardcoded English names of the Special: pages, for ASCII safety.
+ *
+ * Since these URLs get dropped directly into emails, using the
+ * short English names avoids insanely long URL-encoded links, which
+ * also sometimes can get corrupted in some browsers/mailers
+ * (bug 6957 with Gmail and Internet Explorer).
+ */
+ protected function getTokenUrl( $page, $token ) {
+ global $wgArticlePath;
+ return wfExpandUrl(
+ str_replace(
+ '$1',
+ "Special:$page/$token",
+ $wgArticlePath ) );
}
/**
}
/**
- * @param array $groups list of groups
+ * @param $groups Array: list of groups
* @return array list of permission key names for given groups combined
*/
static function getGroupPermissions( $groups ) {
}
/**
- * @param string $group key name
+ * @param $group String: key name
* @return string localized descriptive name for group, if provided
*/
static function getGroupName( $group ) {
}
/**
- * @param string $group key name
+ * @param $group String: key name
* @return string localized descriptive name for member of a group, if provided
*/
static function getGroupMember( $group ) {
? $right
: $name;
}
+
+ /**
+ * Make an old-style password hash
+ *
+ * @param $password String: plain-text password
+ * @param $userId String: user ID
+ */
+ static function oldCrypt( $password, $userId ) {
+ global $wgPasswordSalt;
+ if ( $wgPasswordSalt ) {
+ return md5( $userId . '-' . md5( $password ) );
+ } else {
+ return md5( $password );
+ }
+ }
+
+ /**
+ * Make a new-style password hash
+ *
+ * @param $password String: plain-text password
+ * @param $salt String: salt, may be random or the user ID. False to generate a salt.
+ */
+ static function crypt( $password, $salt = false ) {
+ global $wgPasswordSalt;
+
+ if($wgPasswordSalt) {
+ if ( $salt === false ) {
+ $salt = substr( wfGenerateToken(), 0, 8 );
+ }
+ return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
+ } else {
+ return ':A:' . md5( $password);
+ }
+ }
+
+ /**
+ * Compare a password hash with a plain-text password. Requires the user
+ * ID if there's a chance that the hash is an old-style hash.
+ *
+ * @param $hash String: password hash
+ * @param $password String: plain-text password to compare
+ * @param $userId String: user ID for old-style password salt
+ */
+ static function comparePasswords( $hash, $password, $userId = false ) {
+ $m = false;
+ $type = substr( $hash, 0, 3 );
+ if ( $type == ':A:' ) {
+ # Unsalted
+ return md5( $password ) === substr( $hash, 3 );
+ } elseif ( $type == ':B:' ) {
+ # Salted
+ list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
+ return md5( $salt.'-'.md5( $password ) ) == $realHash;
+ } else {
+ # Old-style
+ return self::oldCrypt( $password, $userId ) === $hash;
+ }
+ }
}