PageRenderTime 67ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/User.php

https://bitbucket.org/ghostfreeman/freeside-wiki
PHP | 4224 lines | 2552 code | 348 blank | 1324 comment | 386 complexity | 047c26b9c0b2fb034bde9e14b2271929 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Implements the User class for the %MediaWiki software.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. /**
  23. * Int Number of characters in user_token field.
  24. * @ingroup Constants
  25. */
  26. define( 'USER_TOKEN_LENGTH', 32 );
  27. /**
  28. * Int Serialized record version.
  29. * @ingroup Constants
  30. */
  31. define( 'MW_USER_VERSION', 8 );
  32. /**
  33. * String Some punctuation to prevent editing from broken text-mangling proxies.
  34. * @ingroup Constants
  35. */
  36. define( 'EDIT_TOKEN_SUFFIX', '+\\' );
  37. /**
  38. * Thrown by User::setPassword() on error.
  39. * @ingroup Exception
  40. */
  41. class PasswordError extends MWException {
  42. // NOP
  43. }
  44. /**
  45. * The User object encapsulates all of the user-specific settings (user_id,
  46. * name, rights, password, email address, options, last login time). Client
  47. * classes use the getXXX() functions to access these fields. These functions
  48. * do all the work of determining whether the user is logged in,
  49. * whether the requested option can be satisfied from cookies or
  50. * whether a database query is needed. Most of the settings needed
  51. * for rendering normal pages are set in the cookie to minimize use
  52. * of the database.
  53. */
  54. class User {
  55. /**
  56. * Global constants made accessible as class constants so that autoloader
  57. * magic can be used.
  58. */
  59. const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
  60. const MW_USER_VERSION = MW_USER_VERSION;
  61. const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
  62. /**
  63. * Maximum items in $mWatchedItems
  64. */
  65. const MAX_WATCHED_ITEMS_CACHE = 100;
  66. /**
  67. * Array of Strings List of member variables which are saved to the
  68. * shared cache (memcached). Any operation which changes the
  69. * corresponding database fields must call a cache-clearing function.
  70. * @showinitializer
  71. */
  72. static $mCacheVars = array(
  73. // user table
  74. 'mId',
  75. 'mName',
  76. 'mRealName',
  77. 'mPassword',
  78. 'mNewpassword',
  79. 'mNewpassTime',
  80. 'mEmail',
  81. 'mTouched',
  82. 'mToken',
  83. 'mEmailAuthenticated',
  84. 'mEmailToken',
  85. 'mEmailTokenExpires',
  86. 'mRegistration',
  87. 'mEditCount',
  88. // user_groups table
  89. 'mGroups',
  90. // user_properties table
  91. 'mOptionOverrides',
  92. );
  93. /**
  94. * Array of Strings Core rights.
  95. * Each of these should have a corresponding message of the form
  96. * "right-$right".
  97. * @showinitializer
  98. */
  99. static $mCoreRights = array(
  100. 'apihighlimits',
  101. 'autoconfirmed',
  102. 'autopatrol',
  103. 'bigdelete',
  104. 'block',
  105. 'blockemail',
  106. 'bot',
  107. 'browsearchive',
  108. 'createaccount',
  109. 'createpage',
  110. 'createtalk',
  111. 'delete',
  112. 'deletedhistory',
  113. 'deletedtext',
  114. 'deletelogentry',
  115. 'deleterevision',
  116. 'edit',
  117. 'editinterface',
  118. 'editprotected',
  119. 'editusercssjs', #deprecated
  120. 'editusercss',
  121. 'edituserjs',
  122. 'hideuser',
  123. 'import',
  124. 'importupload',
  125. 'ipblock-exempt',
  126. 'markbotedits',
  127. 'mergehistory',
  128. 'minoredit',
  129. 'move',
  130. 'movefile',
  131. 'move-rootuserpages',
  132. 'move-subpages',
  133. 'nominornewtalk',
  134. 'noratelimit',
  135. 'override-export-depth',
  136. 'passwordreset',
  137. 'patrol',
  138. 'patrolmarks',
  139. 'protect',
  140. 'proxyunbannable',
  141. 'purge',
  142. 'read',
  143. 'reupload',
  144. 'reupload-own',
  145. 'reupload-shared',
  146. 'rollback',
  147. 'sendemail',
  148. 'siteadmin',
  149. 'suppressionlog',
  150. 'suppressredirect',
  151. 'suppressrevision',
  152. 'unblockself',
  153. 'undelete',
  154. 'unwatchedpages',
  155. 'upload',
  156. 'upload_by_url',
  157. 'userrights',
  158. 'userrights-interwiki',
  159. 'writeapi',
  160. );
  161. /**
  162. * String Cached results of getAllRights()
  163. */
  164. static $mAllRights = false;
  165. /** @name Cache variables */
  166. //@{
  167. var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
  168. $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
  169. $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
  170. $mGroups, $mOptionOverrides;
  171. //@}
  172. /**
  173. * Bool Whether the cache variables have been loaded.
  174. */
  175. //@{
  176. var $mOptionsLoaded;
  177. /**
  178. * Array with already loaded items or true if all items have been loaded.
  179. */
  180. private $mLoadedItems = array();
  181. //@}
  182. /**
  183. * String Initialization data source if mLoadedItems!==true. May be one of:
  184. * - 'defaults' anonymous user initialised from class defaults
  185. * - 'name' initialise from mName
  186. * - 'id' initialise from mId
  187. * - 'session' log in from cookies or session if possible
  188. *
  189. * Use the User::newFrom*() family of functions to set this.
  190. */
  191. var $mFrom;
  192. /**
  193. * Lazy-initialized variables, invalidated with clearInstanceCache
  194. */
  195. var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
  196. $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
  197. $mLocked, $mHideName, $mOptions;
  198. /**
  199. * @var WebRequest
  200. */
  201. private $mRequest;
  202. /**
  203. * @var Block
  204. */
  205. var $mBlock;
  206. /**
  207. * @var bool
  208. */
  209. var $mAllowUsertalk;
  210. /**
  211. * @var Block
  212. */
  213. private $mBlockedFromCreateAccount = false;
  214. /**
  215. * @var Array
  216. */
  217. private $mWatchedItems = array();
  218. static $idCacheByName = array();
  219. /**
  220. * Lightweight constructor for an anonymous user.
  221. * Use the User::newFrom* factory functions for other kinds of users.
  222. *
  223. * @see newFromName()
  224. * @see newFromId()
  225. * @see newFromConfirmationCode()
  226. * @see newFromSession()
  227. * @see newFromRow()
  228. */
  229. function __construct() {
  230. $this->clearInstanceCache( 'defaults' );
  231. }
  232. /**
  233. * @return String
  234. */
  235. function __toString(){
  236. return $this->getName();
  237. }
  238. /**
  239. * Load the user table data for this object from the source given by mFrom.
  240. */
  241. public function load() {
  242. if ( $this->mLoadedItems === true ) {
  243. return;
  244. }
  245. wfProfileIn( __METHOD__ );
  246. # Set it now to avoid infinite recursion in accessors
  247. $this->mLoadedItems = true;
  248. switch ( $this->mFrom ) {
  249. case 'defaults':
  250. $this->loadDefaults();
  251. break;
  252. case 'name':
  253. $this->mId = self::idFromName( $this->mName );
  254. if ( !$this->mId ) {
  255. # Nonexistent user placeholder object
  256. $this->loadDefaults( $this->mName );
  257. } else {
  258. $this->loadFromId();
  259. }
  260. break;
  261. case 'id':
  262. $this->loadFromId();
  263. break;
  264. case 'session':
  265. $this->loadFromSession();
  266. wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
  267. break;
  268. default:
  269. throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
  270. }
  271. wfProfileOut( __METHOD__ );
  272. }
  273. /**
  274. * Load user table data, given mId has already been set.
  275. * @return Bool false if the ID does not exist, true otherwise
  276. */
  277. public function loadFromId() {
  278. global $wgMemc;
  279. if ( $this->mId == 0 ) {
  280. $this->loadDefaults();
  281. return false;
  282. }
  283. # Try cache
  284. $key = wfMemcKey( 'user', 'id', $this->mId );
  285. $data = $wgMemc->get( $key );
  286. if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
  287. # Object is expired, load from DB
  288. $data = false;
  289. }
  290. if ( !$data ) {
  291. wfDebug( "User: cache miss for user {$this->mId}\n" );
  292. # Load from DB
  293. if ( !$this->loadFromDatabase() ) {
  294. # Can't load from ID, user is anonymous
  295. return false;
  296. }
  297. $this->saveToCache();
  298. } else {
  299. wfDebug( "User: got user {$this->mId} from cache\n" );
  300. # Restore from cache
  301. foreach ( self::$mCacheVars as $name ) {
  302. $this->$name = $data[$name];
  303. }
  304. }
  305. return true;
  306. }
  307. /**
  308. * Save user data to the shared cache
  309. */
  310. public function saveToCache() {
  311. $this->load();
  312. $this->loadGroups();
  313. $this->loadOptions();
  314. if ( $this->isAnon() ) {
  315. // Anonymous users are uncached
  316. return;
  317. }
  318. $data = array();
  319. foreach ( self::$mCacheVars as $name ) {
  320. $data[$name] = $this->$name;
  321. }
  322. $data['mVersion'] = MW_USER_VERSION;
  323. $key = wfMemcKey( 'user', 'id', $this->mId );
  324. global $wgMemc;
  325. $wgMemc->set( $key, $data );
  326. }
  327. /** @name newFrom*() static factory methods */
  328. //@{
  329. /**
  330. * Static factory method for creation from username.
  331. *
  332. * This is slightly less efficient than newFromId(), so use newFromId() if
  333. * you have both an ID and a name handy.
  334. *
  335. * @param $name String Username, validated by Title::newFromText()
  336. * @param $validate String|Bool Validate username. Takes the same parameters as
  337. * User::getCanonicalName(), except that true is accepted as an alias
  338. * for 'valid', for BC.
  339. *
  340. * @return User object, or false if the username is invalid
  341. * (e.g. if it contains illegal characters or is an IP address). If the
  342. * username is not present in the database, the result will be a user object
  343. * with a name, zero user ID and default settings.
  344. */
  345. public static function newFromName( $name, $validate = 'valid' ) {
  346. if ( $validate === true ) {
  347. $validate = 'valid';
  348. }
  349. $name = self::getCanonicalName( $name, $validate );
  350. if ( $name === false ) {
  351. return false;
  352. } else {
  353. # Create unloaded user object
  354. $u = new User;
  355. $u->mName = $name;
  356. $u->mFrom = 'name';
  357. $u->setItemLoaded( 'name' );
  358. return $u;
  359. }
  360. }
  361. /**
  362. * Static factory method for creation from a given user ID.
  363. *
  364. * @param $id Int Valid user ID
  365. * @return User The corresponding User object
  366. */
  367. public static function newFromId( $id ) {
  368. $u = new User;
  369. $u->mId = $id;
  370. $u->mFrom = 'id';
  371. $u->setItemLoaded( 'id' );
  372. return $u;
  373. }
  374. /**
  375. * Factory method to fetch whichever user has a given email confirmation code.
  376. * This code is generated when an account is created or its e-mail address
  377. * has changed.
  378. *
  379. * If the code is invalid or has expired, returns NULL.
  380. *
  381. * @param $code String Confirmation code
  382. * @return User object, or null
  383. */
  384. public static function newFromConfirmationCode( $code ) {
  385. $dbr = wfGetDB( DB_SLAVE );
  386. $id = $dbr->selectField( 'user', 'user_id', array(
  387. 'user_email_token' => md5( $code ),
  388. 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
  389. ) );
  390. if( $id !== false ) {
  391. return User::newFromId( $id );
  392. } else {
  393. return null;
  394. }
  395. }
  396. /**
  397. * Create a new user object using data from session or cookies. If the
  398. * login credentials are invalid, the result is an anonymous user.
  399. *
  400. * @param $request WebRequest object to use; $wgRequest will be used if
  401. * ommited.
  402. * @return User object
  403. */
  404. public static function newFromSession( WebRequest $request = null ) {
  405. $user = new User;
  406. $user->mFrom = 'session';
  407. $user->mRequest = $request;
  408. return $user;
  409. }
  410. /**
  411. * Create a new user object from a user row.
  412. * The row should have the following fields from the user table in it:
  413. * - either user_name or user_id to load further data if needed (or both)
  414. * - user_real_name
  415. * - all other fields (email, password, etc.)
  416. * It is useless to provide the remaining fields if either user_id,
  417. * user_name and user_real_name are not provided because the whole row
  418. * will be loaded once more from the database when accessing them.
  419. *
  420. * @param $row Array A row from the user table
  421. * @return User
  422. */
  423. public static function newFromRow( $row ) {
  424. $user = new User;
  425. $user->loadFromRow( $row );
  426. return $user;
  427. }
  428. //@}
  429. /**
  430. * Get the username corresponding to a given user ID
  431. * @param $id Int User ID
  432. * @return String|bool The corresponding username
  433. */
  434. public static function whoIs( $id ) {
  435. return UserCache::singleton()->getProp( $id, 'name' );
  436. }
  437. /**
  438. * Get the real name of a user given their user ID
  439. *
  440. * @param $id Int User ID
  441. * @return String|bool The corresponding user's real name
  442. */
  443. public static function whoIsReal( $id ) {
  444. return UserCache::singleton()->getProp( $id, 'real_name' );
  445. }
  446. /**
  447. * Get database id given a user name
  448. * @param $name String Username
  449. * @return Int|Null The corresponding user's ID, or null if user is nonexistent
  450. */
  451. public static function idFromName( $name ) {
  452. $nt = Title::makeTitleSafe( NS_USER, $name );
  453. if( is_null( $nt ) ) {
  454. # Illegal name
  455. return null;
  456. }
  457. if ( isset( self::$idCacheByName[$name] ) ) {
  458. return self::$idCacheByName[$name];
  459. }
  460. $dbr = wfGetDB( DB_SLAVE );
  461. $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
  462. if ( $s === false ) {
  463. $result = null;
  464. } else {
  465. $result = $s->user_id;
  466. }
  467. self::$idCacheByName[$name] = $result;
  468. if ( count( self::$idCacheByName ) > 1000 ) {
  469. self::$idCacheByName = array();
  470. }
  471. return $result;
  472. }
  473. /**
  474. * Reset the cache used in idFromName(). For use in tests.
  475. */
  476. public static function resetIdByNameCache() {
  477. self::$idCacheByName = array();
  478. }
  479. /**
  480. * Does the string match an anonymous IPv4 address?
  481. *
  482. * This function exists for username validation, in order to reject
  483. * usernames which are similar in form to IP addresses. Strings such
  484. * as 300.300.300.300 will return true because it looks like an IP
  485. * address, despite not being strictly valid.
  486. *
  487. * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
  488. * address because the usemod software would "cloak" anonymous IP
  489. * addresses like this, if we allowed accounts like this to be created
  490. * new users could get the old edits of these anonymous users.
  491. *
  492. * @param $name String to match
  493. * @return Bool
  494. */
  495. public static function isIP( $name ) {
  496. return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
  497. }
  498. /**
  499. * Is the input a valid username?
  500. *
  501. * Checks if the input is a valid username, we don't want an empty string,
  502. * an IP address, anything that containins slashes (would mess up subpages),
  503. * is longer than the maximum allowed username size or doesn't begin with
  504. * a capital letter.
  505. *
  506. * @param $name String to match
  507. * @return Bool
  508. */
  509. public static function isValidUserName( $name ) {
  510. global $wgContLang, $wgMaxNameChars;
  511. if ( $name == ''
  512. || User::isIP( $name )
  513. || strpos( $name, '/' ) !== false
  514. || strlen( $name ) > $wgMaxNameChars
  515. || $name != $wgContLang->ucfirst( $name ) ) {
  516. wfDebugLog( 'username', __METHOD__ .
  517. ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
  518. return false;
  519. }
  520. // Ensure that the name can't be misresolved as a different title,
  521. // such as with extra namespace keys at the start.
  522. $parsed = Title::newFromText( $name );
  523. if( is_null( $parsed )
  524. || $parsed->getNamespace()
  525. || strcmp( $name, $parsed->getPrefixedText() ) ) {
  526. wfDebugLog( 'username', __METHOD__ .
  527. ": '$name' invalid due to ambiguous prefixes" );
  528. return false;
  529. }
  530. // Check an additional blacklist of troublemaker characters.
  531. // Should these be merged into the title char list?
  532. $unicodeBlacklist = '/[' .
  533. '\x{0080}-\x{009f}' . # iso-8859-1 control chars
  534. '\x{00a0}' . # non-breaking space
  535. '\x{2000}-\x{200f}' . # various whitespace
  536. '\x{2028}-\x{202f}' . # breaks and control chars
  537. '\x{3000}' . # ideographic space
  538. '\x{e000}-\x{f8ff}' . # private use
  539. ']/u';
  540. if( preg_match( $unicodeBlacklist, $name ) ) {
  541. wfDebugLog( 'username', __METHOD__ .
  542. ": '$name' invalid due to blacklisted characters" );
  543. return false;
  544. }
  545. return true;
  546. }
  547. /**
  548. * Usernames which fail to pass this function will be blocked
  549. * from user login and new account registrations, but may be used
  550. * internally by batch processes.
  551. *
  552. * If an account already exists in this form, login will be blocked
  553. * by a failure to pass this function.
  554. *
  555. * @param $name String to match
  556. * @return Bool
  557. */
  558. public static function isUsableName( $name ) {
  559. global $wgReservedUsernames;
  560. // Must be a valid username, obviously ;)
  561. if ( !self::isValidUserName( $name ) ) {
  562. return false;
  563. }
  564. static $reservedUsernames = false;
  565. if ( !$reservedUsernames ) {
  566. $reservedUsernames = $wgReservedUsernames;
  567. wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
  568. }
  569. // Certain names may be reserved for batch processes.
  570. foreach ( $reservedUsernames as $reserved ) {
  571. if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
  572. $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
  573. }
  574. if ( $reserved == $name ) {
  575. return false;
  576. }
  577. }
  578. return true;
  579. }
  580. /**
  581. * Usernames which fail to pass this function will be blocked
  582. * from new account registrations, but may be used internally
  583. * either by batch processes or by user accounts which have
  584. * already been created.
  585. *
  586. * Additional blacklisting may be added here rather than in
  587. * isValidUserName() to avoid disrupting existing accounts.
  588. *
  589. * @param $name String to match
  590. * @return Bool
  591. */
  592. public static function isCreatableName( $name ) {
  593. global $wgInvalidUsernameCharacters;
  594. // Ensure that the username isn't longer than 235 bytes, so that
  595. // (at least for the builtin skins) user javascript and css files
  596. // will work. (bug 23080)
  597. if( strlen( $name ) > 235 ) {
  598. wfDebugLog( 'username', __METHOD__ .
  599. ": '$name' invalid due to length" );
  600. return false;
  601. }
  602. // Preg yells if you try to give it an empty string
  603. if( $wgInvalidUsernameCharacters !== '' ) {
  604. if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
  605. wfDebugLog( 'username', __METHOD__ .
  606. ": '$name' invalid due to wgInvalidUsernameCharacters" );
  607. return false;
  608. }
  609. }
  610. return self::isUsableName( $name );
  611. }
  612. /**
  613. * Is the input a valid password for this user?
  614. *
  615. * @param $password String Desired password
  616. * @return Bool
  617. */
  618. public function isValidPassword( $password ) {
  619. //simple boolean wrapper for getPasswordValidity
  620. return $this->getPasswordValidity( $password ) === true;
  621. }
  622. /**
  623. * Given unvalidated password input, return error message on failure.
  624. *
  625. * @param $password String Desired password
  626. * @return mixed: true on success, string or array of error message on failure
  627. */
  628. public function getPasswordValidity( $password ) {
  629. global $wgMinimalPasswordLength, $wgContLang;
  630. static $blockedLogins = array(
  631. 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
  632. 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
  633. );
  634. $result = false; //init $result to false for the internal checks
  635. if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
  636. return $result;
  637. if ( $result === false ) {
  638. if( strlen( $password ) < $wgMinimalPasswordLength ) {
  639. return 'passwordtooshort';
  640. } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
  641. return 'password-name-match';
  642. } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
  643. return 'password-login-forbidden';
  644. } else {
  645. //it seems weird returning true here, but this is because of the
  646. //initialization of $result to false above. If the hook is never run or it
  647. //doesn't modify $result, then we will likely get down into this if with
  648. //a valid password.
  649. return true;
  650. }
  651. } elseif( $result === true ) {
  652. return true;
  653. } else {
  654. return $result; //the isValidPassword hook set a string $result and returned true
  655. }
  656. }
  657. /**
  658. * Does a string look like an e-mail address?
  659. *
  660. * This validates an email address using an HTML5 specification found at:
  661. * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
  662. * Which as of 2011-01-24 says:
  663. *
  664. * A valid e-mail address is a string that matches the ABNF production
  665. * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
  666. * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
  667. * 3.5.
  668. *
  669. * This function is an implementation of the specification as requested in
  670. * bug 22449.
  671. *
  672. * Client-side forms will use the same standard validation rules via JS or
  673. * HTML 5 validation; additional restrictions can be enforced server-side
  674. * by extensions via the 'isValidEmailAddr' hook.
  675. *
  676. * Note that this validation doesn't 100% match RFC 2822, but is believed
  677. * to be liberal enough for wide use. Some invalid addresses will still
  678. * pass validation here.
  679. *
  680. * @param $addr String E-mail address
  681. * @return Bool
  682. * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
  683. */
  684. public static function isValidEmailAddr( $addr ) {
  685. wfDeprecated( __METHOD__, '1.18' );
  686. return Sanitizer::validateEmail( $addr );
  687. }
  688. /**
  689. * Given unvalidated user input, return a canonical username, or false if
  690. * the username is invalid.
  691. * @param $name String User input
  692. * @param $validate String|Bool type of validation to use:
  693. * - false No validation
  694. * - 'valid' Valid for batch processes
  695. * - 'usable' Valid for batch processes and login
  696. * - 'creatable' Valid for batch processes, login and account creation
  697. *
  698. * @return bool|string
  699. */
  700. public static function getCanonicalName( $name, $validate = 'valid' ) {
  701. # Force usernames to capital
  702. global $wgContLang;
  703. $name = $wgContLang->ucfirst( $name );
  704. # Reject names containing '#'; these will be cleaned up
  705. # with title normalisation, but then it's too late to
  706. # check elsewhere
  707. if( strpos( $name, '#' ) !== false )
  708. return false;
  709. # Clean up name according to title rules
  710. $t = ( $validate === 'valid' ) ?
  711. Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
  712. # Check for invalid titles
  713. if( is_null( $t ) ) {
  714. return false;
  715. }
  716. # Reject various classes of invalid names
  717. global $wgAuth;
  718. $name = $wgAuth->getCanonicalName( $t->getText() );
  719. switch ( $validate ) {
  720. case false:
  721. break;
  722. case 'valid':
  723. if ( !User::isValidUserName( $name ) ) {
  724. $name = false;
  725. }
  726. break;
  727. case 'usable':
  728. if ( !User::isUsableName( $name ) ) {
  729. $name = false;
  730. }
  731. break;
  732. case 'creatable':
  733. if ( !User::isCreatableName( $name ) ) {
  734. $name = false;
  735. }
  736. break;
  737. default:
  738. throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
  739. }
  740. return $name;
  741. }
  742. /**
  743. * Count the number of edits of a user
  744. * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
  745. *
  746. * @param $uid Int User ID to check
  747. * @return Int the user's edit count
  748. */
  749. public static function edits( $uid ) {
  750. wfProfileIn( __METHOD__ );
  751. $dbr = wfGetDB( DB_SLAVE );
  752. // check if the user_editcount field has been initialized
  753. $field = $dbr->selectField(
  754. 'user', 'user_editcount',
  755. array( 'user_id' => $uid ),
  756. __METHOD__
  757. );
  758. if( $field === null ) { // it has not been initialized. do so.
  759. $dbw = wfGetDB( DB_MASTER );
  760. $count = $dbr->selectField(
  761. 'revision', 'count(*)',
  762. array( 'rev_user' => $uid ),
  763. __METHOD__
  764. );
  765. $dbw->update(
  766. 'user',
  767. array( 'user_editcount' => $count ),
  768. array( 'user_id' => $uid ),
  769. __METHOD__
  770. );
  771. } else {
  772. $count = $field;
  773. }
  774. wfProfileOut( __METHOD__ );
  775. return $count;
  776. }
  777. /**
  778. * Return a random password.
  779. *
  780. * @return String new random password
  781. */
  782. public static function randomPassword() {
  783. global $wgMinimalPasswordLength;
  784. // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
  785. $length = max( 10, $wgMinimalPasswordLength );
  786. // Multiply by 1.25 to get the number of hex characters we need
  787. $length = $length * 1.25;
  788. // Generate random hex chars
  789. $hex = MWCryptRand::generateHex( $length );
  790. // Convert from base 16 to base 32 to get a proper password like string
  791. return wfBaseConvert( $hex, 16, 32 );
  792. }
  793. /**
  794. * Set cached properties to default.
  795. *
  796. * @note This no longer clears uncached lazy-initialised properties;
  797. * the constructor does that instead.
  798. *
  799. * @param $name string
  800. */
  801. public function loadDefaults( $name = false ) {
  802. wfProfileIn( __METHOD__ );
  803. $this->mId = 0;
  804. $this->mName = $name;
  805. $this->mRealName = '';
  806. $this->mPassword = $this->mNewpassword = '';
  807. $this->mNewpassTime = null;
  808. $this->mEmail = '';
  809. $this->mOptionOverrides = null;
  810. $this->mOptionsLoaded = false;
  811. $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
  812. if( $loggedOut !== null ) {
  813. $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
  814. } else {
  815. $this->mTouched = '0'; # Allow any pages to be cached
  816. }
  817. $this->mToken = null; // Don't run cryptographic functions till we need a token
  818. $this->mEmailAuthenticated = null;
  819. $this->mEmailToken = '';
  820. $this->mEmailTokenExpires = null;
  821. $this->mRegistration = wfTimestamp( TS_MW );
  822. $this->mGroups = array();
  823. wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
  824. wfProfileOut( __METHOD__ );
  825. }
  826. /**
  827. * Return whether an item has been loaded.
  828. *
  829. * @param $item String: item to check. Current possibilities:
  830. * - id
  831. * - name
  832. * - realname
  833. * @param $all String: 'all' to check if the whole object has been loaded
  834. * or any other string to check if only the item is available (e.g.
  835. * for optimisation)
  836. * @return Boolean
  837. */
  838. public function isItemLoaded( $item, $all = 'all' ) {
  839. return ( $this->mLoadedItems === true && $all === 'all' ) ||
  840. ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
  841. }
  842. /**
  843. * Set that an item has been loaded
  844. *
  845. * @param $item String
  846. */
  847. private function setItemLoaded( $item ) {
  848. if ( is_array( $this->mLoadedItems ) ) {
  849. $this->mLoadedItems[$item] = true;
  850. }
  851. }
  852. /**
  853. * Load user data from the session or login cookie. If there are no valid
  854. * credentials, initialises the user as an anonymous user.
  855. * @return Bool True if the user is logged in, false otherwise.
  856. */
  857. private function loadFromSession() {
  858. global $wgExternalAuthType, $wgAutocreatePolicy;
  859. $result = null;
  860. wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
  861. if ( $result !== null ) {
  862. return $result;
  863. }
  864. if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
  865. $extUser = ExternalUser::newFromCookie();
  866. if ( $extUser ) {
  867. # TODO: Automatically create the user here (or probably a bit
  868. # lower down, in fact)
  869. }
  870. }
  871. $request = $this->getRequest();
  872. $cookieId = $request->getCookie( 'UserID' );
  873. $sessId = $request->getSessionData( 'wsUserID' );
  874. if ( $cookieId !== null ) {
  875. $sId = intval( $cookieId );
  876. if( $sessId !== null && $cookieId != $sessId ) {
  877. $this->loadDefaults(); // Possible collision!
  878. wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
  879. cookie user ID ($sId) don't match!" );
  880. return false;
  881. }
  882. $request->setSessionData( 'wsUserID', $sId );
  883. } elseif ( $sessId !== null && $sessId != 0 ) {
  884. $sId = $sessId;
  885. } else {
  886. $this->loadDefaults();
  887. return false;
  888. }
  889. if ( $request->getSessionData( 'wsUserName' ) !== null ) {
  890. $sName = $request->getSessionData( 'wsUserName' );
  891. } elseif ( $request->getCookie( 'UserName' ) !== null ) {
  892. $sName = $request->getCookie( 'UserName' );
  893. $request->setSessionData( 'wsUserName', $sName );
  894. } else {
  895. $this->loadDefaults();
  896. return false;
  897. }
  898. $proposedUser = User::newFromId( $sId );
  899. if ( !$proposedUser->isLoggedIn() ) {
  900. # Not a valid ID
  901. $this->loadDefaults();
  902. return false;
  903. }
  904. global $wgBlockDisablesLogin;
  905. if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
  906. # User blocked and we've disabled blocked user logins
  907. $this->loadDefaults();
  908. return false;
  909. }
  910. if ( $request->getSessionData( 'wsToken' ) ) {
  911. $passwordCorrect = $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' );
  912. $from = 'session';
  913. } elseif ( $request->getCookie( 'Token' ) ) {
  914. $passwordCorrect = $proposedUser->getToken( false ) === $request->getCookie( 'Token' );
  915. $from = 'cookie';
  916. } else {
  917. # No session or persistent login cookie
  918. $this->loadDefaults();
  919. return false;
  920. }
  921. if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
  922. $this->loadFromUserObject( $proposedUser );
  923. $request->setSessionData( 'wsToken', $this->mToken );
  924. wfDebug( "User: logged in from $from\n" );
  925. return true;
  926. } else {
  927. # Invalid credentials
  928. wfDebug( "User: can't log in from $from, invalid credentials\n" );
  929. $this->loadDefaults();
  930. return false;
  931. }
  932. }
  933. /**
  934. * Load user and user_group data from the database.
  935. * $this->mId must be set, this is how the user is identified.
  936. *
  937. * @return Bool True if the user exists, false if the user is anonymous
  938. */
  939. public function loadFromDatabase() {
  940. # Paranoia
  941. $this->mId = intval( $this->mId );
  942. /** Anonymous user */
  943. if( !$this->mId ) {
  944. $this->loadDefaults();
  945. return false;
  946. }
  947. $dbr = wfGetDB( DB_MASTER );
  948. $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
  949. wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
  950. if ( $s !== false ) {
  951. # Initialise user table data
  952. $this->loadFromRow( $s );
  953. $this->mGroups = null; // deferred
  954. $this->getEditCount(); // revalidation for nulls
  955. return true;
  956. } else {
  957. # Invalid user_id
  958. $this->mId = 0;
  959. $this->loadDefaults();
  960. return false;
  961. }
  962. }
  963. /**
  964. * Initialize this object from a row from the user table.
  965. *
  966. * @param $row Array Row from the user table to load.
  967. */
  968. public function loadFromRow( $row ) {
  969. $all = true;
  970. $this->mGroups = null; // deferred
  971. if ( isset( $row->user_name ) ) {
  972. $this->mName = $row->user_name;
  973. $this->mFrom = 'name';
  974. $this->setItemLoaded( 'name' );
  975. } else {
  976. $all = false;
  977. }
  978. if ( isset( $row->user_real_name ) ) {
  979. $this->mRealName = $row->user_real_name;
  980. $this->setItemLoaded( 'realname' );
  981. } else {
  982. $all = false;
  983. }
  984. if ( isset( $row->user_id ) ) {
  985. $this->mId = intval( $row->user_id );
  986. $this->mFrom = 'id';
  987. $this->setItemLoaded( 'id' );
  988. } else {
  989. $all = false;
  990. }
  991. if ( isset( $row->user_editcount ) ) {
  992. $this->mEditCount = $row->user_editcount;
  993. } else {
  994. $all = false;
  995. }
  996. if ( isset( $row->user_password ) ) {
  997. $this->mPassword = $row->user_password;
  998. $this->mNewpassword = $row->user_newpassword;
  999. $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
  1000. $this->mEmail = $row->user_email;
  1001. if ( isset( $row->user_options ) ) {
  1002. $this->decodeOptions( $row->user_options );
  1003. }
  1004. $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
  1005. $this->mToken = $row->user_token;
  1006. if ( $this->mToken == '' ) {
  1007. $this->mToken = null;
  1008. }
  1009. $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
  1010. $this->mEmailToken = $row->user_email_token;
  1011. $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
  1012. $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
  1013. } else {
  1014. $all = false;
  1015. }
  1016. if ( $all ) {
  1017. $this->mLoadedItems = true;
  1018. }
  1019. }
  1020. /**
  1021. * Load the data for this user object from another user object.
  1022. *
  1023. * @param $user User
  1024. */
  1025. protected function loadFromUserObject( $user ) {
  1026. $user->load();
  1027. $user->loadGroups();
  1028. $user->loadOptions();
  1029. foreach ( self::$mCacheVars as $var ) {
  1030. $this->$var = $user->$var;
  1031. }
  1032. }
  1033. /**
  1034. * Load the groups from the database if they aren't already loaded.
  1035. */
  1036. private function loadGroups() {
  1037. if ( is_null( $this->mGroups ) ) {
  1038. $dbr = wfGetDB( DB_MASTER );
  1039. $res = $dbr->select( 'user_groups',
  1040. array( 'ug_group' ),
  1041. array( 'ug_user' => $this->mId ),
  1042. __METHOD__ );
  1043. $this->mGroups = array();
  1044. foreach ( $res as $row ) {
  1045. $this->mGroups[] = $row->ug_group;
  1046. }
  1047. }
  1048. }
  1049. /**
  1050. * Add the user to the group if he/she meets given criteria.
  1051. *
  1052. * Contrary to autopromotion by \ref $wgAutopromote, the group will be
  1053. * possible to remove manually via Special:UserRights. In such case it
  1054. * will not be re-added automatically. The user will also not lose the
  1055. * group if they no longer meet the criteria.
  1056. *
  1057. * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
  1058. *
  1059. * @return array Array of groups the user has been promoted to.
  1060. *
  1061. * @see $wgAutopromoteOnce
  1062. */
  1063. public function addAutopromoteOnceGroups( $event ) {
  1064. global $wgAutopromoteOnceLogInRC;
  1065. $toPromote = array();
  1066. if ( $this->getId() ) {
  1067. $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
  1068. if ( count( $toPromote ) ) {
  1069. $oldGroups = $this->getGroups(); // previous groups
  1070. foreach ( $toPromote as $group ) {
  1071. $this->addGroup( $group );
  1072. }
  1073. $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
  1074. $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
  1075. $log->addEntry( 'autopromote',
  1076. $this->getUserPage(),
  1077. '', // no comment
  1078. // These group names are "list to texted"-ed in class LogPage.
  1079. array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
  1080. );
  1081. }
  1082. }
  1083. return $toPromote;
  1084. }
  1085. /**
  1086. * Clear various cached data stored in this object.
  1087. * @param $reloadFrom bool|String Reload user and user_groups table data from a
  1088. * given source. May be "name", "id", "defaults", "session", or false for
  1089. * no reload.
  1090. */
  1091. public function clearInstanceCache( $reloadFrom = false ) {
  1092. $this->mNewtalk = -1;
  1093. $this->mDatePreference = null;
  1094. $this->mBlockedby = -1; # Unset
  1095. $this->mHash = false;
  1096. $this->mRights = null;
  1097. $this->mEffectiveGroups = null;
  1098. $this->mImplicitGroups = null;
  1099. $this->mOptions = null;
  1100. if ( $reloadFrom ) {
  1101. $this->mLoadedItems = array();
  1102. $this->mFrom = $reloadFrom;
  1103. }
  1104. }
  1105. /**
  1106. * Combine the language default options with any site-specific options
  1107. * and add the default language variants.
  1108. *
  1109. * @return Array of String options
  1110. */
  1111. public static function getDefaultOptions() {
  1112. global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
  1113. $defOpt = $wgDefaultUserOptions;
  1114. # default language setting
  1115. $variant = $wgContLang->getDefaultVariant();
  1116. $defOpt['variant'] = $variant;
  1117. $defOpt['language'] = $variant;
  1118. foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
  1119. $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
  1120. }
  1121. $defOpt['skin'] = $wgDefaultSkin;
  1122. // FIXME: Ideally we'd cache the results of this function so the hook is only run once,
  1123. // but that breaks the parser tests because they rely on being able to change $wgContLang
  1124. // mid-request and see that change reflected in the return value of this function.
  1125. // Which is insane and would never happen during normal MW operation, but is also not
  1126. // likely to get fixed unless and until we context-ify everything.
  1127. // See also https://www.mediawiki.org/wiki/Special:Code/MediaWiki/101488#c25275
  1128. wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
  1129. return $defOpt;
  1130. }
  1131. /**
  1132. * Get a given default option value.
  1133. *
  1134. * @param $opt String Name of option to retrieve
  1135. * @return String Default option value
  1136. */
  1137. public static function getDefaultOption( $opt ) {
  1138. $defOpts = self::getDefaultOptions();
  1139. if( isset( $defOpts[$opt] ) ) {
  1140. return $defOpts[$opt];
  1141. } else {
  1142. return null;
  1143. }
  1144. }
  1145. /**
  1146. * Get blocking information
  1147. * @param $bFromSlave Bool Whether to check the slave database first. To
  1148. * improve performance, non-critical checks are done
  1149. * against slaves. Check when actually saving should be
  1150. * done against master.
  1151. */
  1152. private function getBlockedStatus( $bFromSlave = true ) {
  1153. global $wgProxyWhitelist, $wgUser;
  1154. if ( -1 != $this->mBlockedby ) {
  1155. return;
  1156. }
  1157. wfProfileIn( __METHOD__ );
  1158. wfDebug( __METHOD__.": checking...\n" );
  1159. // Initialize data...
  1160. // Otherwise something ends up stomping on $this->mBlockedby when
  1161. // things get lazy-loaded later, causing false positive block hits
  1162. // due to -1 !== 0. Probably session-related... Nothing should be
  1163. // overwriting mBlockedby, surely?
  1164. $this->load();
  1165. # We only need to worry about passing the IP address to the Block generator if the
  1166. # user is not immune to autoblocks/hardblocks, and they are the current user so we
  1167. # know which IP address they're actually coming from
  1168. if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
  1169. $ip = $this->getRequest()->getIP();
  1170. } else {
  1171. $ip = null;
  1172. }
  1173. # User/IP blocking
  1174. $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
  1175. # Proxy blocking
  1176. if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
  1177. && !in_array( $ip, $wgProxyWhitelist ) )
  1178. {
  1179. # Local list
  1180. if ( self::isLocallyBlockedProxy( $ip ) ) {
  1181. $block = new Block;
  1182. $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
  1183. $block->mReason = wfMessage( 'proxyblockreason' )->text();
  1184. $block->setTarget( $ip );
  1185. } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
  1186. $block = new Block;
  1187. $block->setBlocker( wfMessage( 'sorbs' )->text() );
  1188. $block->mReason = wfMessage( 'sorbsreason' )->text();
  1189. $block->setTarget( $ip );
  1190. }
  1191. }
  1192. if ( $block instanceof Block ) {
  1193. wfDebug( __METHOD__ . ": Found block.\n" );
  1194. $this->mBlock = $block;
  1195. $this->mBlockedby = $block->getByName();
  1196. $this->mBlockreason = $block->mReason;
  1197. $this->mHideName = $block->mHideName;
  1198. $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
  1199. } else {
  1200. $this->mBlockedby = '';
  1201. $this->mHideName = 0;
  1202. $this->mAllowUsertalk = false;
  1203. }
  1204. # Extensions
  1205. wfRunHooks( 'GetBlockedStatus', array( &$this ) );
  1206. wfProfileOut( __METHOD__ );
  1207. }
  1208. /**
  1209. * Whether the given IP is in a DNS blacklist.
  1210. *
  1211. * @param $ip String IP to check
  1212. * @param $checkWhitelist Bool: whether to check the whitelist first
  1213. * @return Bool True if blacklisted.
  1214. */
  1215. public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
  1216. global $wgEnableSorbs, $wgEnableDnsBlacklist,
  1217. $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
  1218. if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
  1219. return false;
  1220. if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
  1221. return false;
  1222. $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
  1223. return $this->inDnsBlacklist( $ip, $urls );
  1224. }
  1225. /**
  1226. * Whether the given IP is in a given DNS blacklist.
  1227. *
  1228. * @param $ip String IP to check
  1229. * @param $bases String|Array of Strings: URL of the DNS blacklist
  1230. * @return Bool True if blacklisted.
  1231. */
  1232. public function inDnsBlacklist( $ip, $bases ) {
  1233. wfProfileIn( __METHOD__ );
  1234. $found = false;
  1235. // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
  1236. if( IP::isIPv4( $ip ) ) {
  1237. # Reverse IP, bug 21255
  1238. $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
  1239. foreach( (array)$bases as $base ) {
  1240. # Make hostname
  1241. # If we have an access key, use that too (ProjectHoneypot, etc.)
  1242. if( is_array( $base ) ) {
  1243. if( count( $base ) >= 2 ) {
  1244. # Access key is 1, base URL is 0
  1245. $host = "{$base[1]}.$ipReversed.{$base[0]}";
  1246. } else {
  1247. $host = "$ipReversed.{$base[0]}";
  1248. }
  1249. } else {
  1250. $host = "$ipReversed.$base";
  1251. }
  1252. # Send query
  1253. $ipList = gethostbynamel( $host );
  1254. if( $ipList ) {
  1255. wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
  1256. $found = true;
  1257. break;
  1258. } else {
  1259. wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
  1260. }
  1261. }
  1262. }
  1263. wfProfileOut( __METHOD__ );
  1264. return $found;
  1265. }
  1266. /**
  1267. * Check if an IP address is in the local proxy list
  1268. *
  1269. * @param $ip string
  1270. *
  1271. * @return bool
  1272. */
  1273. public static function isLocallyBlockedProxy( $ip ) {
  1274. global $wgProxyList;
  1275. if ( !$wgProxyList ) {
  1276. return false;
  1277. }
  1278. wfProfileIn( __METHOD__ );
  1279. if ( !is_array( $wgProxyList ) ) {
  1280. # Load from the specified file
  1281. $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
  1282. }
  1283. if ( !is_array( $wgProxyList ) ) {
  1284. $ret = false;
  1285. } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
  1286. $ret = true;
  1287. } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
  1288. # Old-style flipped proxy list
  1289. $ret = true;
  1290. } else {
  1291. $ret = false;
  1292. }
  1293. wfProfileOut( __METHOD__ );
  1294. return $ret;
  1295. }
  1296. /**
  1297. * Is this user subject to rate limiting?
  1298. *
  1299. * @return Bool True if rate limited
  1300. */
  1301. public function isPingLimitable() {
  1302. global $wgRateLimitsExcludedIPs;
  1303. if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
  1304. // No other good way currently to disable rate limits
  1305. // for specific IPs. :P
  1306. // But this is a crappy hack and should die.
  1307. return false;
  1308. }
  1309. return !$this->isAllowed('noratelimit');
  1310. }
  1311. /**
  1312. * Primitive rate limits: enforce maximum actions per time period
  1313. * to put a brake on flooding.
  1314. *
  1315. * @note When using a shared cache like memcached, IP-address
  1316. * last-hit counters will be shared across wikis.
  1317. *
  1318. * @param $action String Action to enforce; 'edit' if unspecified
  1319. * @return Bool True if a rate limiter was tripped
  1320. */
  1321. public function pingLimiter( $action = 'edit' ) {
  1322. # Call the 'PingLimiter' hook
  1323. $result = false;
  1324. if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
  1325. return $result;
  1326. }
  1327. global $wgRateLimits;
  1328. if( !isset( $wgRateLimits[$action] ) ) {
  1329. return false;
  1330. }
  1331. # Some groups shouldn't trigger the ping limiter, ever
  1332. if( !$this->isPingLimitable() )
  1333. return false;
  1334. global $wgMemc, $wgRateLimitLog;
  1335. wfProfileIn( __METHOD__ );
  1336. $limits = $wgRateLimits[$action];
  1337. $keys = array();
  1338. $id = $this->getId();
  1339. $ip = $this->getRequest()->getIP();
  1340. $userLimit = false;
  1341. if( isset( $limits['anon'] ) && $id == 0 ) {
  1342. $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
  1343. }
  1344. if( isset( $limits['user'] ) && $id != 0 ) {
  1345. $userLimit = $limits['user'];
  1346. }
  1347. if( $this->isNewbie() ) {
  1348. if( isset( $limits['newbie'] ) && $id != 0 ) {
  1349. $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
  1350. }
  1351. if( isset( $limits['ip'] ) ) {
  1352. $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
  1353. }
  1354. $matches = array();
  1355. if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
  1356. $subnet = $matches[1];
  1357. $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
  1358. }
  1359. }
  1360. // Check for group-specific permissions
  1361. // If more than one group applies, use the group with the highest limit
  1362. foreach ( $this->getGroups() as $group ) {
  1363. if ( isset( $limits[$group] ) ) {
  1364. if ( $userLimit === false || $limits[$group] > $userLimit ) {
  1365. $userLimit = $limits[$group];
  1366. }
  1367. }
  1368. }
  1369. // Set the user limit key
  1370. if ( $userLimit !== false ) {
  1371. wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
  1372. $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
  1373. }
  1374. $triggered = false;
  1375. foreach( $keys as $key => $limit ) {
  1376. list( $max, $period ) = $limit;
  1377. $summary = "(limit $max in {$period}s)";
  1378. $count = $wgMemc->get( $key );
  1379. // Already pinged?
  1380. if( $count ) {
  1381. if( $count >= $max ) {
  1382. wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
  1383. if( $wgRateLimitLog ) {
  1384. wfSuppressWarnings();
  1385. file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
  1386. wfRestoreWarnings();
  1387. }
  1388. $triggered = true;
  1389. } else {
  1390. wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
  1391. }
  1392. } else {
  1393. wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
  1394. $wgMemc->add( $key, 0, intval( $period ) ); // first ping
  1395. }
  1396. $wgMemc->incr( $key );
  1397. }
  1398. wfProfileOut( __METHOD__ );
  1399. return $triggered;
  1400. }
  1401. /**
  1402. * Check if user is blocked
  1403. *
  1404. * @param $bFromSlave Bool Whether to check the slave database instead of the master
  1405. * @return Bool True if blocked, false otherwise
  1406. */
  1407. public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
  1408. return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
  1409. }
  1410. /**
  1411. * Get the block affecting the user, or null if the user is not blocked
  1412. *
  1413. * @param $bFromSlave Bool Whether to check the slave database instead of the master
  1414. * @return Block|null
  1415. */
  1416. public function getBlock( $bFromSlave = true ){
  1417. $this->getBlockedStatus( $bFromSlave );
  1418. return $this->mBlock instanceof Block ? $this->mBlock : null;
  1419. }
  1420. /**
  1421. * Check if user is blocked from editing a particular article
  1422. *
  1423. * @param $title Title to check
  1424. * @param $bFromSlave Bool whether to check the slave database instead of the master
  1425. * @return Bool
  1426. */
  1427. function isBlockedFrom( $title, $bFromSlave = false ) {
  1428. global $wgBlockAllowsUTEdit;
  1429. wfProfileIn( __METHOD__ );
  1430. $blocked = $this->isBlocked( $bFromSlave );
  1431. $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
  1432. # If a user's name is suppressed, they cannot make edits anywhere
  1433. if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
  1434. $title->getNamespace() == NS_USER_TALK ) {
  1435. $blocked = false;
  1436. wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
  1437. }
  1438. wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
  1439. wfProfileOut( __METHOD__ );
  1440. return $blocked;
  1441. }
  1442. /**
  1443. * If user is blocked, return the name of the user who placed the block
  1444. * @return String name of blocker
  1445. */
  1446. public function blockedBy() {
  1447. $this->getBlockedStatus();
  1448. return $this->mBlockedby;
  1449. }
  1450. /**
  1451. * If user is blocked, return the specified reason for the block
  1452. * @return String Blocking reason
  1453. */
  1454. public function blockedFor() {
  1455. $this->getBlockedStatus();
  1456. return $this->mBlockreason;
  1457. }
  1458. /**
  1459. * If user is blocked, return the ID for the block
  1460. * @return Int Block ID
  1461. */
  1462. public function getBlockId() {
  1463. $this->getBlockedStatus();
  1464. return ( $this->mBlock ? $this->mBlock->getId() : false );
  1465. }
  1466. /**
  1467. * Check if user is blocked on all wikis.
  1468. * Do not use for actual edit permission checks!
  1469. * This is intented for quick UI checks.
  1470. *
  1471. * @param $ip String IP address, uses current client if none given
  1472. * @return Bool True if blocked, false otherwise
  1473. */
  1474. public function isBlockedGlobally( $ip = '' ) {
  1475. if( $this->mBlockedGlobally !== null ) {
  1476. return $this->mBlockedGlobally;
  1477. }
  1478. // User is already an IP?
  1479. if( IP::isIPAddress( $this->getName() ) ) {
  1480. $ip = $this->getName();
  1481. } elseif( !$ip ) {
  1482. $ip = $this->getRequest()->getIP();
  1483. }
  1484. $blocked = false;
  1485. wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
  1486. $this->mBlockedGlobally = (bool)$blocked;
  1487. return $this->mBlockedGlobally;
  1488. }
  1489. /**
  1490. * Check if user account is locked
  1491. *
  1492. * @return Bool True if locked, false otherwise
  1493. */
  1494. public function isLocked() {
  1495. if( $this->mLocked !== null ) {
  1496. return $this->mLocked;
  1497. }
  1498. global $wgAuth;
  1499. $authUser = $wgAuth->getUserInstance( $this );
  1500. $this->mLocked = (bool)$authUser->isLocked();
  1501. return $this->mLocked;
  1502. }
  1503. /**
  1504. * Check if user account is hidden
  1505. *
  1506. * @return Bool True if hidden, false otherwise
  1507. */
  1508. public function isHidden() {
  1509. if( $this->mHideName !== null ) {
  1510. return $this->mHideName;
  1511. }
  1512. $this->getBlockedStatus();
  1513. if( !$this->mHideName ) {
  1514. global $wgAuth;
  1515. $authUser = $wgAuth->getUserInstance( $this );
  1516. $this->mHideName = (bool)$authUser->isHidden();
  1517. }
  1518. return $this->mHideName;
  1519. }
  1520. /**
  1521. * Get the user's ID.
  1522. * @return Int The user's ID; 0 if the user is anonymous or nonexistent
  1523. */
  1524. public function getId() {
  1525. if( $this->mId === null && $this->mName !== null
  1526. && User::isIP( $this->mName ) ) {
  1527. // Special case, we know the user is anonymous
  1528. return 0;
  1529. } elseif( !$this->isItemLoaded( 'id' ) ) {
  1530. // Don't load if this was initialized from an ID
  1531. $this->load();
  1532. }
  1533. return $this->mId;
  1534. }
  1535. /**
  1536. * Set the user and reload all fields according to a given ID
  1537. * @param $v Int User ID to reload
  1538. */
  1539. public function setId( $v ) {
  1540. $this->mId = $v;
  1541. $this->clearInstanceCache( 'id' );
  1542. }
  1543. /**
  1544. * Get the user name, or the IP of an anonymous user
  1545. * @return String User's name or IP address
  1546. */
  1547. public function getName() {
  1548. if ( $this->isItemLoaded( 'name', 'only' ) ) {
  1549. # Special case optimisation
  1550. return $this->mName;
  1551. } else {
  1552. $this->load();
  1553. if ( $this->mName === false ) {
  1554. # Clean up IPs
  1555. $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
  1556. }
  1557. return $this->mName;
  1558. }
  1559. }
  1560. /**
  1561. * Set the user name.
  1562. *
  1563. * This does not reload fields from the database according to the given
  1564. * name. Rather, it is used to create a temporary "nonexistent user" for
  1565. * later addition to the database. It can also be used to set the IP
  1566. * address for an anonymous user to something other than the current
  1567. * remote IP.
  1568. *
  1569. * @note User::newFromName() has rougly the same function, when the named user
  1570. * does not exist.
  1571. * @param $str String New user name to set
  1572. */
  1573. public function setName( $str ) {
  1574. $this->load();
  1575. $this->mName = $str;
  1576. }
  1577. /**
  1578. * Get the user's name escaped by underscores.
  1579. * @return String Username escaped by underscores.
  1580. */
  1581. public function getTitleKey() {
  1582. return str_replace( ' ', '_', $this->getName() );
  1583. }
  1584. /**
  1585. * Check if the user has new messages.
  1586. * @return Bool True if the user has new messages
  1587. */
  1588. public function getNewtalk() {
  1589. $this->load();
  1590. # Load the newtalk status if it is unloaded (mNewtalk=-1)
  1591. if( $this->mNewtalk === -1 ) {
  1592. $this->mNewtalk = false; # reset talk page status
  1593. # Check memcached separately for anons, who have no
  1594. # entire User object stored in there.
  1595. if( !$this->mId ) {
  1596. global $wgDisableAnonTalk;
  1597. if( $wgDisableAnonTalk ) {
  1598. // Anon newtalk disabled by configuration.
  1599. $this->mNewtalk = false;
  1600. } else {
  1601. global $wgMemc;
  1602. $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
  1603. $newtalk = $wgMemc->get( $key );
  1604. if( strval( $newtalk ) !== '' ) {
  1605. $this->mNewtalk = (bool)$newtalk;
  1606. } else {
  1607. // Since we are caching this, make sure it is up to date by getting it
  1608. // from the master
  1609. $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
  1610. $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
  1611. }
  1612. }
  1613. } else {
  1614. $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
  1615. }
  1616. }
  1617. return (bool)$this->mNewtalk;
  1618. }
  1619. /**
  1620. * Return the talk page(s) this user has new messages on.
  1621. * @return Array of String page URLs
  1622. */
  1623. public function getNewMessageLinks() {
  1624. $talks = array();
  1625. if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
  1626. return $talks;
  1627. } elseif( !$this->getNewtalk() ) {
  1628. return array();
  1629. }
  1630. $utp = $this->getTalkPage();
  1631. $dbr = wfGetDB( DB_SLAVE );
  1632. // Get the "last viewed rev" timestamp from the oldest message notification
  1633. $timestamp = $dbr->selectField( 'user_newtalk',
  1634. 'MIN(user_last_timestamp)',
  1635. $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
  1636. __METHOD__ );
  1637. $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
  1638. return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
  1639. }
  1640. /**
  1641. * Internal uncached check for new messages
  1642. *
  1643. * @see getNewtalk()
  1644. * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
  1645. * @param $id String|Int User's IP address for anonymous users, User ID otherwise
  1646. * @param $fromMaster Bool true to fetch from the master, false for a slave
  1647. * @return Bool True if the user has new messages
  1648. */
  1649. protected function checkNewtalk( $field, $id, $fromMaster = false ) {
  1650. if ( $fromMaster ) {
  1651. $db = wfGetDB( DB_MASTER );
  1652. } else {
  1653. $db = wfGetDB( DB_SLAVE );
  1654. }
  1655. $ok = $db->selectField( 'user_newtalk', $field,
  1656. array( $field => $id ), __METHOD__ );
  1657. return $ok !== false;
  1658. }
  1659. /**
  1660. * Add or update the new messages flag
  1661. * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
  1662. * @param $id String|Int User's IP address for anonymous users, User ID otherwise
  1663. * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
  1664. * @return Bool True if successful, false otherwise
  1665. */
  1666. protected function updateNewtalk( $field, $id, $curRev = null ) {
  1667. // Get timestamp of the talk page revision prior to the current one
  1668. $prevRev = $curRev ? $curRev->getPrevious() : false;
  1669. $ts = $prevRev ? $prevRev->getTimestamp() : null;
  1670. // Mark the user as having new messages since this revision
  1671. $dbw = wfGetDB( DB_MASTER );
  1672. $dbw->insert( 'user_newtalk',
  1673. array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
  1674. __METHOD__,
  1675. 'IGNORE' );
  1676. if ( $dbw->affectedRows() ) {
  1677. wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
  1678. return true;
  1679. } else {
  1680. wfDebug( __METHOD__ . " already set ($field, $id)\n" );
  1681. return false;
  1682. }
  1683. }
  1684. /**
  1685. * Clear the new messages flag for the given user
  1686. * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
  1687. * @param $id String|Int User's IP address for anonymous users, User ID otherwise
  1688. * @return Bool True if successful, false otherwise
  1689. */
  1690. protected function deleteNewtalk( $field, $id ) {
  1691. $dbw = wfGetDB( DB_MASTER );
  1692. $dbw->delete( 'user_newtalk',
  1693. array( $field => $id ),
  1694. __METHOD__ );
  1695. if ( $dbw->affectedRows() ) {
  1696. wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
  1697. return true;
  1698. } else {
  1699. wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
  1700. return false;
  1701. }
  1702. }
  1703. /**
  1704. * Update the 'You have new messages!' status.
  1705. * @param $val Bool Whether the user has new messages
  1706. * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
  1707. */
  1708. public function setNewtalk( $val, $curRev = null ) {
  1709. if( wfReadOnly() ) {
  1710. return;
  1711. }
  1712. $this->load();
  1713. $this->mNewtalk = $val;
  1714. if( $this->isAnon() ) {
  1715. $field = 'user_ip';
  1716. $id = $this->getName();
  1717. } else {
  1718. $field = 'user_id';
  1719. $id = $this->getId();
  1720. }
  1721. global $wgMemc;
  1722. if( $val ) {
  1723. $changed = $this->updateNewtalk( $field, $id, $curRev );
  1724. } else {
  1725. $changed = $this->deleteNewtalk( $field, $id );
  1726. }
  1727. if( $this->isAnon() ) {
  1728. // Anons have a separate memcached space, since
  1729. // user records aren't kept for them.
  1730. $key = wfMemcKey( 'newtalk', 'ip', $id );
  1731. $wgMemc->set( $key, $val ? 1 : 0, 1800 );
  1732. }
  1733. if ( $changed ) {
  1734. $this->invalidateCache();
  1735. }
  1736. }
  1737. /**
  1738. * Generate a current or new-future timestamp to be stored in the
  1739. * user_touched field when we update things.
  1740. * @return String Timestamp in TS_MW format
  1741. */
  1742. private static function newTouchedTimestamp() {
  1743. global $wgClockSkewFudge;
  1744. return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
  1745. }
  1746. /**
  1747. * Clear user data from memcached.
  1748. * Use after applying fun updates to the database; caller's
  1749. * responsibility to update user_touched if appropriate.
  1750. *
  1751. * Called implicitly from invalidateCache() and saveSettings().
  1752. */
  1753. private function clearSharedCache() {
  1754. $this->load();
  1755. if( $this->mId ) {
  1756. global $wgMemc;
  1757. $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
  1758. }
  1759. }
  1760. /**
  1761. * Immediately touch the user data cache for this account.
  1762. * Updates user_touched field, and removes account data from memcached
  1763. * for reload on the next hit.
  1764. */
  1765. public function invalidateCache() {
  1766. if( wfReadOnly() ) {
  1767. return;
  1768. }
  1769. $this->load();
  1770. if( $this->mId ) {
  1771. $this->mTouched = self::newTouchedTimestamp();
  1772. $dbw = wfGetDB( DB_MASTER );
  1773. // Prevent contention slams by checking user_touched first
  1774. $now = $dbw->timestamp( $this->mTouched );
  1775. $needsPurge = $dbw->selectField( 'user', '1',
  1776. array( 'user_id' => $this->mId, 'user_touched < ' . $dbw->addQuotes( $now ) )
  1777. );
  1778. if ( $needsPurge ) {
  1779. $dbw->update( 'user',
  1780. array( 'user_touched' => $now ),
  1781. array( 'user_id' => $this->mId, 'user_touched < ' . $dbw->addQuotes( $now ) ),
  1782. __METHOD__
  1783. );
  1784. }
  1785. $this->clearSharedCache();
  1786. }
  1787. }
  1788. /**
  1789. * Validate the cache for this account.
  1790. * @param $timestamp String A timestamp in TS_MW format
  1791. *
  1792. * @return bool
  1793. */
  1794. public function validateCache( $timestamp ) {
  1795. $this->load();
  1796. return ( $timestamp >= $this->mTouched );
  1797. }
  1798. /**
  1799. * Get the user touched timestamp
  1800. * @return String timestamp
  1801. */
  1802. public function getTouched() {
  1803. $this->load();
  1804. return $this->mTouched;
  1805. }
  1806. /**
  1807. * Set the password and reset the random token.
  1808. * Calls through to authentication plugin if necessary;
  1809. * will have no effect if the auth plugin refuses to
  1810. * pass the change through or if the legal password
  1811. * checks fail.
  1812. *
  1813. * As a special case, setting the password to null
  1814. * wipes it, so the account cannot be logged in until
  1815. * a new password is set, for instance via e-mail.
  1816. *
  1817. * @param $str String New password to set
  1818. * @throws PasswordError on failure
  1819. *
  1820. * @return bool
  1821. */
  1822. public function setPassword( $str ) {
  1823. global $wgAuth;
  1824. if( $str !== null ) {
  1825. if( !$wgAuth->allowPasswordChange() ) {
  1826. throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
  1827. }
  1828. if( !$this->isValidPassword( $str ) ) {
  1829. global $wgMinimalPasswordLength;
  1830. $valid = $this->getPasswordValidity( $str );
  1831. if ( is_array( $valid ) ) {
  1832. $message = array_shift( $valid );
  1833. $params = $valid;
  1834. } else {
  1835. $message = $valid;
  1836. $params = array( $wgMinimalPasswordLength );
  1837. }
  1838. throw new PasswordError( wfMessage( $message, $params )->text() );
  1839. }
  1840. }
  1841. if( !$wgAuth->setPassword( $this, $str ) ) {
  1842. throw new PasswordError( wfMessage( 'externaldberror' )->text() );
  1843. }
  1844. $this->setInternalPassword( $str );
  1845. return true;
  1846. }
  1847. /**
  1848. * Set the password and reset the random token unconditionally.
  1849. *
  1850. * @param $str String New password to set
  1851. */
  1852. public function setInternalPassword( $str ) {
  1853. $this->load();
  1854. $this->setToken();
  1855. if( $str === null ) {
  1856. // Save an invalid hash...
  1857. $this->mPassword = '';
  1858. } else {
  1859. $this->mPassword = self::crypt( $str );
  1860. }
  1861. $this->mNewpassword = '';
  1862. $this->mNewpassTime = null;
  1863. }
  1864. /**
  1865. * Get the user's current token.
  1866. * @param $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
  1867. * @return String Token
  1868. */
  1869. public function getToken( $forceCreation = true ) {
  1870. $this->load();
  1871. if ( !$this->mToken && $forceCreation ) {
  1872. $this->setToken();
  1873. }
  1874. return $this->mToken;
  1875. }
  1876. /**
  1877. * Set the random token (used for persistent authentication)
  1878. * Called from loadDefaults() among other places.
  1879. *
  1880. * @param $token String|bool If specified, set the token to this value
  1881. */
  1882. public function setToken( $token = false ) {
  1883. $this->load();
  1884. if ( !$token ) {
  1885. $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
  1886. } else {
  1887. $this->mToken = $token;
  1888. }
  1889. }
  1890. /**
  1891. * Set the password for a password reminder or new account email
  1892. *
  1893. * @param $str String New password to set
  1894. * @param $throttle Bool If true, reset the throttle timestamp to the present
  1895. */
  1896. public function setNewpassword( $str, $throttle = true ) {
  1897. $this->load();
  1898. $this->mNewpassword = self::crypt( $str );
  1899. if ( $throttle ) {
  1900. $this->mNewpassTime = wfTimestampNow();
  1901. }
  1902. }
  1903. /**
  1904. * Has password reminder email been sent within the last
  1905. * $wgPasswordReminderResendTime hours?
  1906. * @return Bool
  1907. */
  1908. public function isPasswordReminderThrottled() {
  1909. global $wgPasswordReminderResendTime;
  1910. $this->load();
  1911. if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
  1912. return false;
  1913. }
  1914. $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
  1915. return time() < $expiry;
  1916. }
  1917. /**
  1918. * Get the user's e-mail address
  1919. * @return String User's email address
  1920. */
  1921. public function getEmail() {
  1922. $this->load();
  1923. wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
  1924. return $this->mEmail;
  1925. }
  1926. /**
  1927. * Get the timestamp of the user's e-mail authentication
  1928. * @return String TS_MW timestamp
  1929. */
  1930. public function getEmailAuthenticationTimestamp() {
  1931. $this->load();
  1932. wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
  1933. return $this->mEmailAuthenticated;
  1934. }
  1935. /**
  1936. * Set the user's e-mail address
  1937. * @param $str String New e-mail address
  1938. */
  1939. public function setEmail( $str ) {
  1940. $this->load();
  1941. if( $str == $this->mEmail ) {
  1942. return;
  1943. }
  1944. $this->mEmail = $str;
  1945. $this->invalidateEmail();
  1946. wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
  1947. }
  1948. /**
  1949. * Set the user's e-mail address and a confirmation mail if needed.
  1950. *
  1951. * @since 1.20
  1952. * @param $str String New e-mail address
  1953. * @return Status
  1954. */
  1955. public function setEmailWithConfirmation( $str ) {
  1956. global $wgEnableEmail, $wgEmailAuthentication;
  1957. if ( !$wgEnableEmail ) {
  1958. return Status::newFatal( 'emaildisabled' );
  1959. }
  1960. $oldaddr = $this->getEmail();
  1961. if ( $str === $oldaddr ) {
  1962. return Status::newGood( true );
  1963. }
  1964. $this->setEmail( $str );
  1965. if ( $str !== '' && $wgEmailAuthentication ) {
  1966. # Send a confirmation request to the new address if needed
  1967. $type = $oldaddr != '' ? 'changed' : 'set';
  1968. $result = $this->sendConfirmationMail( $type );
  1969. if ( $result->isGood() ) {
  1970. # Say the the caller that a confirmation mail has been sent
  1971. $result->value = 'eauth';
  1972. }
  1973. } else {
  1974. $result = Status::newGood( true );
  1975. }
  1976. return $result;
  1977. }
  1978. /**
  1979. * Get the user's real name
  1980. * @return String User's real name
  1981. */
  1982. public function getRealName() {
  1983. if ( !$this->isItemLoaded( 'realname' ) ) {
  1984. $this->load();
  1985. }
  1986. return $this->mRealName;
  1987. }
  1988. /**
  1989. * Set the user's real name
  1990. * @param $str String New real name
  1991. */
  1992. public function setRealName( $str ) {
  1993. $this->load();
  1994. $this->mRealName = $str;
  1995. }
  1996. /**
  1997. * Get the user's current setting for a given option.
  1998. *
  1999. * @param $oname String The option to check
  2000. * @param $defaultOverride String A default value returned if the option does not exist
  2001. * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
  2002. * @return String User's current value for the option
  2003. * @see getBoolOption()
  2004. * @see getIntOption()
  2005. */
  2006. public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
  2007. global $wgHiddenPrefs;
  2008. $this->loadOptions();
  2009. if ( is_null( $this->mOptions ) ) {
  2010. if($defaultOverride != '') {
  2011. return $defaultOverride;
  2012. }
  2013. $this->mOptions = User::getDefaultOptions();
  2014. }
  2015. # We want 'disabled' preferences to always behave as the default value for
  2016. # users, even if they have set the option explicitly in their settings (ie they
  2017. # set it, and then it was disabled removing their ability to change it). But
  2018. # we don't want to erase the preferences in the database in case the preference
  2019. # is re-enabled again. So don't touch $mOptions, just override the returned value
  2020. if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ){
  2021. return self::getDefaultOption( $oname );
  2022. }
  2023. if ( array_key_exists( $oname, $this->mOptions ) ) {
  2024. return $this->mOptions[$oname];
  2025. } else {
  2026. return $defaultOverride;
  2027. }
  2028. }
  2029. /**
  2030. * Get all user's options
  2031. *
  2032. * @return array
  2033. */
  2034. public function getOptions() {
  2035. global $wgHiddenPrefs;
  2036. $this->loadOptions();
  2037. $options = $this->mOptions;
  2038. # We want 'disabled' preferences to always behave as the default value for
  2039. # users, even if they have set the option explicitly in their settings (ie they
  2040. # set it, and then it was disabled removing their ability to change it). But
  2041. # we don't want to erase the preferences in the database in case the preference
  2042. # is re-enabled again. So don't touch $mOptions, just override the returned value
  2043. foreach( $wgHiddenPrefs as $pref ){
  2044. $default = self::getDefaultOption( $pref );
  2045. if( $default !== null ){
  2046. $options[$pref] = $default;
  2047. }
  2048. }
  2049. return $options;
  2050. }
  2051. /**
  2052. * Get the user's current setting for a given option, as a boolean value.
  2053. *
  2054. * @param $oname String The option to check
  2055. * @return Bool User's current value for the option
  2056. * @see getOption()
  2057. */
  2058. public function getBoolOption( $oname ) {
  2059. return (bool)$this->getOption( $oname );
  2060. }
  2061. /**
  2062. * Get the user's current setting for a given option, as a boolean value.
  2063. *
  2064. * @param $oname String The option to check
  2065. * @param $defaultOverride Int A default value returned if the option does not exist
  2066. * @return Int User's current value for the option
  2067. * @see getOption()
  2068. */
  2069. public function getIntOption( $oname, $defaultOverride=0 ) {
  2070. $val = $this->getOption( $oname );
  2071. if( $val == '' ) {
  2072. $val = $defaultOverride;
  2073. }
  2074. return intval( $val );
  2075. }
  2076. /**
  2077. * Set the given option for a user.
  2078. *
  2079. * @param $oname String The option to set
  2080. * @param $val mixed New value to set
  2081. */
  2082. public function setOption( $oname, $val ) {
  2083. $this->load();
  2084. $this->loadOptions();
  2085. // Explicitly NULL values should refer to defaults
  2086. if( is_null( $val ) ) {
  2087. $defaultOption = self::getDefaultOption( $oname );
  2088. if( !is_null( $defaultOption ) ) {
  2089. $val = $defaultOption;
  2090. }
  2091. }
  2092. $this->mOptions[$oname] = $val;
  2093. }
  2094. /**
  2095. * Reset all options to the site defaults
  2096. */
  2097. public function resetOptions() {
  2098. $this->load();
  2099. $this->mOptions = self::getDefaultOptions();
  2100. $this->mOptionsLoaded = true;
  2101. }
  2102. /**
  2103. * Get the user's preferred date format.
  2104. * @return String User's preferred date format
  2105. */
  2106. public function getDatePreference() {
  2107. // Important migration for old data rows
  2108. if ( is_null( $this->mDatePreference ) ) {
  2109. global $wgLang;
  2110. $value = $this->getOption( 'date' );
  2111. $map = $wgLang->getDatePreferenceMigrationMap();
  2112. if ( isset( $map[$value] ) ) {
  2113. $value = $map[$value];
  2114. }
  2115. $this->mDatePreference = $value;
  2116. }
  2117. return $this->mDatePreference;
  2118. }
  2119. /**
  2120. * Get the user preferred stub threshold
  2121. *
  2122. * @return int
  2123. */
  2124. public function getStubThreshold() {
  2125. global $wgMaxArticleSize; # Maximum article size, in Kb
  2126. $threshold = intval( $this->getOption( 'stubthreshold' ) );
  2127. if ( $threshold > $wgMaxArticleSize * 1024 ) {
  2128. # If they have set an impossible value, disable the preference
  2129. # so we can use the parser cache again.
  2130. $threshold = 0;
  2131. }
  2132. return $threshold;
  2133. }
  2134. /**
  2135. * Get the permissions this user has.
  2136. * @return Array of String permission names
  2137. */
  2138. public function getRights() {
  2139. if ( is_null( $this->mRights ) ) {
  2140. $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
  2141. wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
  2142. // Force reindexation of rights when a hook has unset one of them
  2143. $this->mRights = array_values( $this->mRights );
  2144. }
  2145. return $this->mRights;
  2146. }
  2147. /**
  2148. * Get the list of explicit group memberships this user has.
  2149. * The implicit * and user groups are not included.
  2150. * @return Array of String internal group names
  2151. */
  2152. public function getGroups() {
  2153. $this->load();
  2154. $this->loadGroups();
  2155. return $this->mGroups;
  2156. }
  2157. /**
  2158. * Get the list of implicit group memberships this user has.
  2159. * This includes all explicit groups, plus 'user' if logged in,
  2160. * '*' for all accounts, and autopromoted groups
  2161. * @param $recache Bool Whether to avoid the cache
  2162. * @return Array of String internal group names
  2163. */
  2164. public function getEffectiveGroups( $recache = false ) {
  2165. if ( $recache || is_null( $this->mEffectiveGroups ) ) {
  2166. wfProfileIn( __METHOD__ );
  2167. $this->mEffectiveGroups = array_unique( array_merge(
  2168. $this->getGroups(), // explicit groups
  2169. $this->getAutomaticGroups( $recache ) // implicit groups
  2170. ) );
  2171. # Hook for additional groups
  2172. wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
  2173. wfProfileOut( __METHOD__ );
  2174. }
  2175. return $this->mEffectiveGroups;
  2176. }
  2177. /**
  2178. * Get the list of implicit group memberships this user has.
  2179. * This includes 'user' if logged in, '*' for all accounts,
  2180. * and autopromoted groups
  2181. * @param $recache Bool Whether to avoid the cache
  2182. * @return Array of String internal group names
  2183. */
  2184. public function getAutomaticGroups( $recache = false ) {
  2185. if ( $recache || is_null( $this->mImplicitGroups ) ) {
  2186. wfProfileIn( __METHOD__ );
  2187. $this->mImplicitGroups = array( '*' );
  2188. if ( $this->getId() ) {
  2189. $this->mImplicitGroups[] = 'user';
  2190. $this->mImplicitGroups = array_unique( array_merge(
  2191. $this->mImplicitGroups,
  2192. Autopromote::getAutopromoteGroups( $this )
  2193. ) );
  2194. }
  2195. if ( $recache ) {
  2196. # Assure data consistency with rights/groups,
  2197. # as getEffectiveGroups() depends on this function
  2198. $this->mEffectiveGroups = null;
  2199. }
  2200. wfProfileOut( __METHOD__ );
  2201. }
  2202. return $this->mImplicitGroups;
  2203. }
  2204. /**
  2205. * Returns the groups the user has belonged to.
  2206. *
  2207. * The user may still belong to the returned groups. Compare with getGroups().
  2208. *
  2209. * The function will not return groups the user had belonged to before MW 1.17
  2210. *
  2211. * @return array Names of the groups the user has belonged to.
  2212. */
  2213. public function getFormerGroups() {
  2214. if( is_null( $this->mFormerGroups ) ) {
  2215. $dbr = wfGetDB( DB_MASTER );
  2216. $res = $dbr->select( 'user_former_groups',
  2217. array( 'ufg_group' ),
  2218. array( 'ufg_user' => $this->mId ),
  2219. __METHOD__ );
  2220. $this->mFormerGroups = array();
  2221. foreach( $res as $row ) {
  2222. $this->mFormerGroups[] = $row->ufg_group;
  2223. }
  2224. }
  2225. return $this->mFormerGroups;
  2226. }
  2227. /**
  2228. * Get the user's edit count.
  2229. * @return Int
  2230. */
  2231. public function getEditCount() {
  2232. if( $this->getId() ) {
  2233. if ( !isset( $this->mEditCount ) ) {
  2234. /* Populate the count, if it has not been populated yet */
  2235. $this->mEditCount = User::edits( $this->mId );
  2236. }
  2237. return $this->mEditCount;
  2238. } else {
  2239. /* nil */
  2240. return null;
  2241. }
  2242. }
  2243. /**
  2244. * Add the user to the given group.
  2245. * This takes immediate effect.
  2246. * @param $group String Name of the group to add
  2247. */
  2248. public function addGroup( $group ) {
  2249. if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
  2250. $dbw = wfGetDB( DB_MASTER );
  2251. if( $this->getId() ) {
  2252. $dbw->insert( 'user_groups',
  2253. array(
  2254. 'ug_user' => $this->getID(),
  2255. 'ug_group' => $group,
  2256. ),
  2257. __METHOD__,
  2258. array( 'IGNORE' ) );
  2259. }
  2260. }
  2261. $this->loadGroups();
  2262. $this->mGroups[] = $group;
  2263. $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
  2264. $this->invalidateCache();
  2265. }
  2266. /**
  2267. * Remove the user from the given group.
  2268. * This takes immediate effect.
  2269. * @param $group String Name of the group to remove
  2270. */
  2271. public function removeGroup( $group ) {
  2272. $this->load();
  2273. if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
  2274. $dbw = wfGetDB( DB_MASTER );
  2275. $dbw->delete( 'user_groups',
  2276. array(
  2277. 'ug_user' => $this->getID(),
  2278. 'ug_group' => $group,
  2279. ), __METHOD__ );
  2280. // Remember that the user was in this group
  2281. $dbw->insert( 'user_former_groups',
  2282. array(
  2283. 'ufg_user' => $this->getID(),
  2284. 'ufg_group' => $group,
  2285. ),
  2286. __METHOD__,
  2287. array( 'IGNORE' ) );
  2288. }
  2289. $this->loadGroups();
  2290. $this->mGroups = array_diff( $this->mGroups, array( $group ) );
  2291. $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
  2292. $this->invalidateCache();
  2293. }
  2294. /**
  2295. * Get whether the user is logged in
  2296. * @return Bool
  2297. */
  2298. public function isLoggedIn() {
  2299. return $this->getID() != 0;
  2300. }
  2301. /**
  2302. * Get whether the user is anonymous
  2303. * @return Bool
  2304. */
  2305. public function isAnon() {
  2306. return !$this->isLoggedIn();
  2307. }
  2308. /**
  2309. * Check if user is allowed to access a feature / make an action
  2310. *
  2311. * @internal param \String $varargs permissions to test
  2312. * @return Boolean: True if user is allowed to perform *any* of the given actions
  2313. *
  2314. * @return bool
  2315. */
  2316. public function isAllowedAny( /*...*/ ){
  2317. $permissions = func_get_args();
  2318. foreach( $permissions as $permission ){
  2319. if( $this->isAllowed( $permission ) ){
  2320. return true;
  2321. }
  2322. }
  2323. return false;
  2324. }
  2325. /**
  2326. *
  2327. * @internal param $varargs string
  2328. * @return bool True if the user is allowed to perform *all* of the given actions
  2329. */
  2330. public function isAllowedAll( /*...*/ ){
  2331. $permissions = func_get_args();
  2332. foreach( $permissions as $permission ){
  2333. if( !$this->isAllowed( $permission ) ){
  2334. return false;
  2335. }
  2336. }
  2337. return true;
  2338. }
  2339. /**
  2340. * Internal mechanics of testing a permission
  2341. * @param $action String
  2342. * @return bool
  2343. */
  2344. public function isAllowed( $action = '' ) {
  2345. if ( $action === '' ) {
  2346. return true; // In the spirit of DWIM
  2347. }
  2348. # Patrolling may not be enabled
  2349. if( $action === 'patrol' || $action === 'autopatrol' ) {
  2350. global $wgUseRCPatrol, $wgUseNPPatrol;
  2351. if( !$wgUseRCPatrol && !$wgUseNPPatrol )
  2352. return false;
  2353. }
  2354. # Use strict parameter to avoid matching numeric 0 accidentally inserted
  2355. # by misconfiguration: 0 == 'foo'
  2356. return in_array( $action, $this->getRights(), true );
  2357. }
  2358. /**
  2359. * Check whether to enable recent changes patrol features for this user
  2360. * @return Boolean: True or false
  2361. */
  2362. public function useRCPatrol() {
  2363. global $wgUseRCPatrol;
  2364. return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
  2365. }
  2366. /**
  2367. * Check whether to enable new pages patrol features for this user
  2368. * @return Bool True or false
  2369. */
  2370. public function useNPPatrol() {
  2371. global $wgUseRCPatrol, $wgUseNPPatrol;
  2372. return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
  2373. }
  2374. /**
  2375. * Get the WebRequest object to use with this object
  2376. *
  2377. * @return WebRequest
  2378. */
  2379. public function getRequest() {
  2380. if ( $this->mRequest ) {
  2381. return $this->mRequest;
  2382. } else {
  2383. global $wgRequest;
  2384. return $wgRequest;
  2385. }
  2386. }
  2387. /**
  2388. * Get the current skin, loading it if required
  2389. * @return Skin The current skin
  2390. * @todo FIXME: Need to check the old failback system [AV]
  2391. * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
  2392. */
  2393. public function getSkin() {
  2394. wfDeprecated( __METHOD__, '1.18' );
  2395. return RequestContext::getMain()->getSkin();
  2396. }
  2397. /**
  2398. * Get a WatchedItem for this user and $title.
  2399. *
  2400. * @param $title Title
  2401. * @return WatchedItem
  2402. */
  2403. public function getWatchedItem( $title ) {
  2404. $key = $title->getNamespace() . ':' . $title->getDBkey();
  2405. if ( isset( $this->mWatchedItems[$key] ) ) {
  2406. return $this->mWatchedItems[$key];
  2407. }
  2408. if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
  2409. $this->mWatchedItems = array();
  2410. }
  2411. $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title );
  2412. return $this->mWatchedItems[$key];
  2413. }
  2414. /**
  2415. * Check the watched status of an article.
  2416. * @param $title Title of the article to look at
  2417. * @return Bool
  2418. */
  2419. public function isWatched( $title ) {
  2420. return $this->getWatchedItem( $title )->isWatched();
  2421. }
  2422. /**
  2423. * Watch an article.
  2424. * @param $title Title of the article to look at
  2425. */
  2426. public function addWatch( $title ) {
  2427. $this->getWatchedItem( $title )->addWatch();
  2428. $this->invalidateCache();
  2429. }
  2430. /**
  2431. * Stop watching an article.
  2432. * @param $title Title of the article to look at
  2433. */
  2434. public function removeWatch( $title ) {
  2435. $this->getWatchedItem( $title )->removeWatch();
  2436. $this->invalidateCache();
  2437. }
  2438. /**
  2439. * Clear the user's notification timestamp for the given title.
  2440. * If e-notif e-mails are on, they will receive notification mails on
  2441. * the next change of the page if it's watched etc.
  2442. * @param $title Title of the article to look at
  2443. */
  2444. public function clearNotification( &$title ) {
  2445. global $wgUseEnotif, $wgShowUpdatedMarker;
  2446. # Do nothing if the database is locked to writes
  2447. if( wfReadOnly() ) {
  2448. return;
  2449. }
  2450. if( $title->getNamespace() == NS_USER_TALK &&
  2451. $title->getText() == $this->getName() ) {
  2452. if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
  2453. return;
  2454. $this->setNewtalk( false );
  2455. }
  2456. if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
  2457. return;
  2458. }
  2459. if( $this->isAnon() ) {
  2460. // Nothing else to do...
  2461. return;
  2462. }
  2463. // Only update the timestamp if the page is being watched.
  2464. // The query to find out if it is watched is cached both in memcached and per-invocation,
  2465. // and when it does have to be executed, it can be on a slave
  2466. // If this is the user's newtalk page, we always update the timestamp
  2467. $force = '';
  2468. if ( $title->getNamespace() == NS_USER_TALK &&
  2469. $title->getText() == $this->getName() )
  2470. {
  2471. $force = 'force';
  2472. }
  2473. $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
  2474. }
  2475. /**
  2476. * Resets all of the given user's page-change notification timestamps.
  2477. * If e-notif e-mails are on, they will receive notification mails on
  2478. * the next change of any watched page.
  2479. */
  2480. public function clearAllNotifications() {
  2481. global $wgUseEnotif, $wgShowUpdatedMarker;
  2482. if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
  2483. $this->setNewtalk( false );
  2484. return;
  2485. }
  2486. $id = $this->getId();
  2487. if( $id != 0 ) {
  2488. $dbw = wfGetDB( DB_MASTER );
  2489. $dbw->update( 'watchlist',
  2490. array( /* SET */
  2491. 'wl_notificationtimestamp' => null
  2492. ), array( /* WHERE */
  2493. 'wl_user' => $id
  2494. ), __METHOD__
  2495. );
  2496. # We also need to clear here the "you have new message" notification for the own user_talk page
  2497. # This is cleared one page view later in Article::viewUpdates();
  2498. }
  2499. }
  2500. /**
  2501. * Set this user's options from an encoded string
  2502. * @param $str String Encoded options to import
  2503. *
  2504. * @deprecated in 1.19 due to removal of user_options from the user table
  2505. */
  2506. private function decodeOptions( $str ) {
  2507. wfDeprecated( __METHOD__, '1.19' );
  2508. if( !$str )
  2509. return;
  2510. $this->mOptionsLoaded = true;
  2511. $this->mOptionOverrides = array();
  2512. // If an option is not set in $str, use the default value
  2513. $this->mOptions = self::getDefaultOptions();
  2514. $a = explode( "\n", $str );
  2515. foreach ( $a as $s ) {
  2516. $m = array();
  2517. if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
  2518. $this->mOptions[$m[1]] = $m[2];
  2519. $this->mOptionOverrides[$m[1]] = $m[2];
  2520. }
  2521. }
  2522. }
  2523. /**
  2524. * Set a cookie on the user's client. Wrapper for
  2525. * WebResponse::setCookie
  2526. * @param $name String Name of the cookie to set
  2527. * @param $value String Value to set
  2528. * @param $exp Int Expiration time, as a UNIX time value;
  2529. * if 0 or not specified, use the default $wgCookieExpiration
  2530. */
  2531. protected function setCookie( $name, $value, $exp = 0 ) {
  2532. $this->getRequest()->response()->setcookie( $name, $value, $exp );
  2533. }
  2534. /**
  2535. * Clear a cookie on the user's client
  2536. * @param $name String Name of the cookie to clear
  2537. */
  2538. protected function clearCookie( $name ) {
  2539. $this->setCookie( $name, '', time() - 86400 );
  2540. }
  2541. /**
  2542. * Set the default cookies for this session on the user's client.
  2543. *
  2544. * @param $request WebRequest object to use; $wgRequest will be used if null
  2545. * is passed.
  2546. */
  2547. public function setCookies( $request = null ) {
  2548. if ( $request === null ) {
  2549. $request = $this->getRequest();
  2550. }
  2551. $this->load();
  2552. if ( 0 == $this->mId ) return;
  2553. if ( !$this->mToken ) {
  2554. // When token is empty or NULL generate a new one and then save it to the database
  2555. // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
  2556. // Simply by setting every cell in the user_token column to NULL and letting them be
  2557. // regenerated as users log back into the wiki.
  2558. $this->setToken();
  2559. $this->saveSettings();
  2560. }
  2561. $session = array(
  2562. 'wsUserID' => $this->mId,
  2563. 'wsToken' => $this->mToken,
  2564. 'wsUserName' => $this->getName()
  2565. );
  2566. $cookies = array(
  2567. 'UserID' => $this->mId,
  2568. 'UserName' => $this->getName(),
  2569. );
  2570. if ( 1 == $this->getOption( 'rememberpassword' ) ) {
  2571. $cookies['Token'] = $this->mToken;
  2572. } else {
  2573. $cookies['Token'] = false;
  2574. }
  2575. wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
  2576. foreach ( $session as $name => $value ) {
  2577. $request->setSessionData( $name, $value );
  2578. }
  2579. foreach ( $cookies as $name => $value ) {
  2580. if ( $value === false ) {
  2581. $this->clearCookie( $name );
  2582. } else {
  2583. $this->setCookie( $name, $value );
  2584. }
  2585. }
  2586. }
  2587. /**
  2588. * Log this user out.
  2589. */
  2590. public function logout() {
  2591. if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
  2592. $this->doLogout();
  2593. }
  2594. }
  2595. /**
  2596. * Clear the user's cookies and session, and reset the instance cache.
  2597. * @see logout()
  2598. */
  2599. public function doLogout() {
  2600. $this->clearInstanceCache( 'defaults' );
  2601. $this->getRequest()->setSessionData( 'wsUserID', 0 );
  2602. $this->clearCookie( 'UserID' );
  2603. $this->clearCookie( 'Token' );
  2604. # Remember when user logged out, to prevent seeing cached pages
  2605. $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
  2606. }
  2607. /**
  2608. * Save this user's settings into the database.
  2609. * @todo Only rarely do all these fields need to be set!
  2610. */
  2611. public function saveSettings() {
  2612. global $wgAuth;
  2613. $this->load();
  2614. if ( wfReadOnly() ) { return; }
  2615. if ( 0 == $this->mId ) { return; }
  2616. $this->mTouched = self::newTouchedTimestamp();
  2617. if ( !$wgAuth->allowSetLocalPassword() ) {
  2618. $this->mPassword = '';
  2619. }
  2620. $dbw = wfGetDB( DB_MASTER );
  2621. $dbw->update( 'user',
  2622. array( /* SET */
  2623. 'user_name' => $this->mName,
  2624. 'user_password' => $this->mPassword,
  2625. 'user_newpassword' => $this->mNewpassword,
  2626. 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
  2627. 'user_real_name' => $this->mRealName,
  2628. 'user_email' => $this->mEmail,
  2629. 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
  2630. 'user_touched' => $dbw->timestamp( $this->mTouched ),
  2631. 'user_token' => strval( $this->mToken ),
  2632. 'user_email_token' => $this->mEmailToken,
  2633. 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
  2634. ), array( /* WHERE */
  2635. 'user_id' => $this->mId
  2636. ), __METHOD__
  2637. );
  2638. $this->saveOptions();
  2639. wfRunHooks( 'UserSaveSettings', array( $this ) );
  2640. $this->clearSharedCache();
  2641. $this->getUserPage()->invalidateCache();
  2642. }
  2643. /**
  2644. * If only this user's username is known, and it exists, return the user ID.
  2645. * @return Int
  2646. */
  2647. public function idForName() {
  2648. $s = trim( $this->getName() );
  2649. if ( $s === '' ) return 0;
  2650. $dbr = wfGetDB( DB_SLAVE );
  2651. $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
  2652. if ( $id === false ) {
  2653. $id = 0;
  2654. }
  2655. return $id;
  2656. }
  2657. /**
  2658. * Add a user to the database, return the user object
  2659. *
  2660. * @param $name String Username to add
  2661. * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
  2662. * - password The user's password hash. Password logins will be disabled if this is omitted.
  2663. * - newpassword Hash for a temporary password that has been mailed to the user
  2664. * - email The user's email address
  2665. * - email_authenticated The email authentication timestamp
  2666. * - real_name The user's real name
  2667. * - options An associative array of non-default options
  2668. * - token Random authentication token. Do not set.
  2669. * - registration Registration timestamp. Do not set.
  2670. *
  2671. * @return User object, or null if the username already exists
  2672. */
  2673. public static function createNew( $name, $params = array() ) {
  2674. $user = new User;
  2675. $user->load();
  2676. if ( isset( $params['options'] ) ) {
  2677. $user->mOptions = $params['options'] + (array)$user->mOptions;
  2678. unset( $params['options'] );
  2679. }
  2680. $dbw = wfGetDB( DB_MASTER );
  2681. $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
  2682. $fields = array(
  2683. 'user_id' => $seqVal,
  2684. 'user_name' => $name,
  2685. 'user_password' => $user->mPassword,
  2686. 'user_newpassword' => $user->mNewpassword,
  2687. 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
  2688. 'user_email' => $user->mEmail,
  2689. 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
  2690. 'user_real_name' => $user->mRealName,
  2691. 'user_token' => strval( $user->mToken ),
  2692. 'user_registration' => $dbw->timestamp( $user->mRegistration ),
  2693. 'user_editcount' => 0,
  2694. 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
  2695. );
  2696. foreach ( $params as $name => $value ) {
  2697. $fields["user_$name"] = $value;
  2698. }
  2699. $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
  2700. if ( $dbw->affectedRows() ) {
  2701. $newUser = User::newFromId( $dbw->insertId() );
  2702. } else {
  2703. $newUser = null;
  2704. }
  2705. return $newUser;
  2706. }
  2707. /**
  2708. * Add this existing user object to the database
  2709. */
  2710. public function addToDatabase() {
  2711. $this->load();
  2712. $this->mTouched = self::newTouchedTimestamp();
  2713. $dbw = wfGetDB( DB_MASTER );
  2714. $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
  2715. $dbw->insert( 'user',
  2716. array(
  2717. 'user_id' => $seqVal,
  2718. 'user_name' => $this->mName,
  2719. 'user_password' => $this->mPassword,
  2720. 'user_newpassword' => $this->mNewpassword,
  2721. 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
  2722. 'user_email' => $this->mEmail,
  2723. 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
  2724. 'user_real_name' => $this->mRealName,
  2725. 'user_token' => strval( $this->mToken ),
  2726. 'user_registration' => $dbw->timestamp( $this->mRegistration ),
  2727. 'user_editcount' => 0,
  2728. 'user_touched' => $dbw->timestamp( $this->mTouched ),
  2729. ), __METHOD__
  2730. );
  2731. $this->mId = $dbw->insertId();
  2732. // Clear instance cache other than user table data, which is already accurate
  2733. $this->clearInstanceCache();
  2734. $this->saveOptions();
  2735. }
  2736. /**
  2737. * If this user is logged-in and blocked,
  2738. * block any IP address they've successfully logged in from.
  2739. * @return bool A block was spread
  2740. */
  2741. public function spreadAnyEditBlock() {
  2742. if ( $this->isLoggedIn() && $this->isBlocked() ) {
  2743. return $this->spreadBlock();
  2744. }
  2745. return false;
  2746. }
  2747. /**
  2748. * If this (non-anonymous) user is blocked,
  2749. * block the IP address they've successfully logged in from.
  2750. * @return bool A block was spread
  2751. */
  2752. protected function spreadBlock() {
  2753. wfDebug( __METHOD__ . "()\n" );
  2754. $this->load();
  2755. if ( $this->mId == 0 ) {
  2756. return false;
  2757. }
  2758. $userblock = Block::newFromTarget( $this->getName() );
  2759. if ( !$userblock ) {
  2760. return false;
  2761. }
  2762. return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
  2763. }
  2764. /**
  2765. * Generate a string which will be different for any combination of
  2766. * user options which would produce different parser output.
  2767. * This will be used as part of the hash key for the parser cache,
  2768. * so users with the same options can share the same cached data
  2769. * safely.
  2770. *
  2771. * Extensions which require it should install 'PageRenderingHash' hook,
  2772. * which will give them a chance to modify this key based on their own
  2773. * settings.
  2774. *
  2775. * @deprecated since 1.17 use the ParserOptions object to get the relevant options
  2776. * @return String Page rendering hash
  2777. */
  2778. public function getPageRenderingHash() {
  2779. wfDeprecated( __METHOD__, '1.17' );
  2780. global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
  2781. if( $this->mHash ){
  2782. return $this->mHash;
  2783. }
  2784. // stubthreshold is only included below for completeness,
  2785. // since it disables the parser cache, its value will always
  2786. // be 0 when this function is called by parsercache.
  2787. $confstr = $this->getOption( 'math' );
  2788. $confstr .= '!' . $this->getStubThreshold();
  2789. if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
  2790. $confstr .= '!' . $this->getDatePreference();
  2791. }
  2792. $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
  2793. $confstr .= '!' . $wgLang->getCode();
  2794. $confstr .= '!' . $this->getOption( 'thumbsize' );
  2795. // add in language specific options, if any
  2796. $extra = $wgContLang->getExtraHashOptions();
  2797. $confstr .= $extra;
  2798. // Since the skin could be overloading link(), it should be
  2799. // included here but in practice, none of our skins do that.
  2800. $confstr .= $wgRenderHashAppend;
  2801. // Give a chance for extensions to modify the hash, if they have
  2802. // extra options or other effects on the parser cache.
  2803. wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
  2804. // Make it a valid memcached key fragment
  2805. $confstr = str_replace( ' ', '_', $confstr );
  2806. $this->mHash = $confstr;
  2807. return $confstr;
  2808. }
  2809. /**
  2810. * Get whether the user is explicitly blocked from account creation.
  2811. * @return Bool|Block
  2812. */
  2813. public function isBlockedFromCreateAccount() {
  2814. $this->getBlockedStatus();
  2815. if( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ){
  2816. return $this->mBlock;
  2817. }
  2818. # bug 13611: if the IP address the user is trying to create an account from is
  2819. # blocked with createaccount disabled, prevent new account creation there even
  2820. # when the user is logged in
  2821. if( $this->mBlockedFromCreateAccount === false ){
  2822. $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
  2823. }
  2824. return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
  2825. ? $this->mBlockedFromCreateAccount
  2826. : false;
  2827. }
  2828. /**
  2829. * Get whether the user is blocked from using Special:Emailuser.
  2830. * @return Bool
  2831. */
  2832. public function isBlockedFromEmailuser() {
  2833. $this->getBlockedStatus();
  2834. return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
  2835. }
  2836. /**
  2837. * Get whether the user is allowed to create an account.
  2838. * @return Bool
  2839. */
  2840. function isAllowedToCreateAccount() {
  2841. return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
  2842. }
  2843. /**
  2844. * Get this user's personal page title.
  2845. *
  2846. * @return Title: User's personal page title
  2847. */
  2848. public function getUserPage() {
  2849. return Title::makeTitle( NS_USER, $this->getName() );
  2850. }
  2851. /**
  2852. * Get this user's talk page title.
  2853. *
  2854. * @return Title: User's talk page title
  2855. */
  2856. public function getTalkPage() {
  2857. $title = $this->getUserPage();
  2858. return $title->getTalkPage();
  2859. }
  2860. /**
  2861. * Determine whether the user is a newbie. Newbies are either
  2862. * anonymous IPs, or the most recently created accounts.
  2863. * @return Bool
  2864. */
  2865. public function isNewbie() {
  2866. return !$this->isAllowed( 'autoconfirmed' );
  2867. }
  2868. /**
  2869. * Check to see if the given clear-text password is one of the accepted passwords
  2870. * @param $password String: user password.
  2871. * @return Boolean: True if the given password is correct, otherwise False.
  2872. */
  2873. public function checkPassword( $password ) {
  2874. global $wgAuth, $wgLegacyEncoding;
  2875. $this->load();
  2876. // Even though we stop people from creating passwords that
  2877. // are shorter than this, doesn't mean people wont be able
  2878. // to. Certain authentication plugins do NOT want to save
  2879. // domain passwords in a mysql database, so we should
  2880. // check this (in case $wgAuth->strict() is false).
  2881. if( !$this->isValidPassword( $password ) ) {
  2882. return false;
  2883. }
  2884. if( $wgAuth->authenticate( $this->getName(), $password ) ) {
  2885. return true;
  2886. } elseif( $wgAuth->strict() ) {
  2887. /* Auth plugin doesn't allow local authentication */
  2888. return false;
  2889. } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
  2890. /* Auth plugin doesn't allow local authentication for this user name */
  2891. return false;
  2892. }
  2893. if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
  2894. return true;
  2895. } elseif ( $wgLegacyEncoding ) {
  2896. # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
  2897. # Check for this with iconv
  2898. $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
  2899. if ( $cp1252Password != $password &&
  2900. self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
  2901. {
  2902. return true;
  2903. }
  2904. }
  2905. return false;
  2906. }
  2907. /**
  2908. * Check if the given clear-text password matches the temporary password
  2909. * sent by e-mail for password reset operations.
  2910. *
  2911. * @param $plaintext string
  2912. *
  2913. * @return Boolean: True if matches, false otherwise
  2914. */
  2915. public function checkTemporaryPassword( $plaintext ) {
  2916. global $wgNewPasswordExpiry;
  2917. $this->load();
  2918. if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
  2919. if ( is_null( $this->mNewpassTime ) ) {
  2920. return true;
  2921. }
  2922. $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
  2923. return ( time() < $expiry );
  2924. } else {
  2925. return false;
  2926. }
  2927. }
  2928. /**
  2929. * Alias for getEditToken.
  2930. * @deprecated since 1.19, use getEditToken instead.
  2931. *
  2932. * @param $salt String|Array of Strings Optional function-specific data for hashing
  2933. * @param $request WebRequest object to use or null to use $wgRequest
  2934. * @return String The new edit token
  2935. */
  2936. public function editToken( $salt = '', $request = null ) {
  2937. wfDeprecated( __METHOD__, '1.19' );
  2938. return $this->getEditToken( $salt, $request );
  2939. }
  2940. /**
  2941. * Initialize (if necessary) and return a session token value
  2942. * which can be used in edit forms to show that the user's
  2943. * login credentials aren't being hijacked with a foreign form
  2944. * submission.
  2945. *
  2946. * @since 1.19
  2947. *
  2948. * @param $salt String|Array of Strings Optional function-specific data for hashing
  2949. * @param $request WebRequest object to use or null to use $wgRequest
  2950. * @return String The new edit token
  2951. */
  2952. public function getEditToken( $salt = '', $request = null ) {
  2953. if ( $request == null ) {
  2954. $request = $this->getRequest();
  2955. }
  2956. if ( $this->isAnon() ) {
  2957. return EDIT_TOKEN_SUFFIX;
  2958. } else {
  2959. $token = $request->getSessionData( 'wsEditToken' );
  2960. if ( $token === null ) {
  2961. $token = MWCryptRand::generateHex( 32 );
  2962. $request->setSessionData( 'wsEditToken', $token );
  2963. }
  2964. if( is_array( $salt ) ) {
  2965. $salt = implode( '|', $salt );
  2966. }
  2967. return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
  2968. }
  2969. }
  2970. /**
  2971. * Generate a looking random token for various uses.
  2972. *
  2973. * @param $salt String Optional salt value
  2974. * @return String The new random token
  2975. * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pesudo-randomness
  2976. */
  2977. public static function generateToken( $salt = '' ) {
  2978. return MWCryptRand::generateHex( 32 );
  2979. }
  2980. /**
  2981. * Check given value against the token value stored in the session.
  2982. * A match should confirm that the form was submitted from the
  2983. * user's own login session, not a form submission from a third-party
  2984. * site.
  2985. *
  2986. * @param $val String Input value to compare
  2987. * @param $salt String Optional function-specific data for hashing
  2988. * @param $request WebRequest object to use or null to use $wgRequest
  2989. * @return Boolean: Whether the token matches
  2990. */
  2991. public function matchEditToken( $val, $salt = '', $request = null ) {
  2992. $sessionToken = $this->getEditToken( $salt, $request );
  2993. if ( $val != $sessionToken ) {
  2994. wfDebug( "User::matchEditToken: broken session data\n" );
  2995. }
  2996. return $val == $sessionToken;
  2997. }
  2998. /**
  2999. * Check given value against the token value stored in the session,
  3000. * ignoring the suffix.
  3001. *
  3002. * @param $val String Input value to compare
  3003. * @param $salt String Optional function-specific data for hashing
  3004. * @param $request WebRequest object to use or null to use $wgRequest
  3005. * @return Boolean: Whether the token matches
  3006. */
  3007. public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
  3008. $sessionToken = $this->getEditToken( $salt, $request );
  3009. return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
  3010. }
  3011. /**
  3012. * Generate a new e-mail confirmation token and send a confirmation/invalidation
  3013. * mail to the user's given address.
  3014. *
  3015. * @param $type String: message to send, either "created", "changed" or "set"
  3016. * @return Status object
  3017. */
  3018. public function sendConfirmationMail( $type = 'created' ) {
  3019. global $wgLang;
  3020. $expiration = null; // gets passed-by-ref and defined in next line.
  3021. $token = $this->confirmationToken( $expiration );
  3022. $url = $this->confirmationTokenUrl( $token );
  3023. $invalidateURL = $this->invalidationTokenUrl( $token );
  3024. $this->saveSettings();
  3025. if ( $type == 'created' || $type === false ) {
  3026. $message = 'confirmemail_body';
  3027. } elseif ( $type === true ) {
  3028. $message = 'confirmemail_body_changed';
  3029. } else {
  3030. $message = 'confirmemail_body_' . $type;
  3031. }
  3032. return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
  3033. wfMessage( $message,
  3034. $this->getRequest()->getIP(),
  3035. $this->getName(),
  3036. $url,
  3037. $wgLang->timeanddate( $expiration, false ),
  3038. $invalidateURL,
  3039. $wgLang->date( $expiration, false ),
  3040. $wgLang->time( $expiration, false ) )->text() );
  3041. }
  3042. /**
  3043. * Send an e-mail to this user's account. Does not check for
  3044. * confirmed status or validity.
  3045. *
  3046. * @param $subject String Message subject
  3047. * @param $body String Message body
  3048. * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
  3049. * @param $replyto String Reply-To address
  3050. * @return Status
  3051. */
  3052. public function sendMail( $subject, $body, $from = null, $replyto = null ) {
  3053. if( is_null( $from ) ) {
  3054. global $wgPasswordSender, $wgPasswordSenderName;
  3055. $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
  3056. } else {
  3057. $sender = new MailAddress( $from );
  3058. }
  3059. $to = new MailAddress( $this );
  3060. return UserMailer::send( $to, $sender, $subject, $body, $replyto );
  3061. }
  3062. /**
  3063. * Generate, store, and return a new e-mail confirmation code.
  3064. * A hash (unsalted, since it's used as a key) is stored.
  3065. *
  3066. * @note Call saveSettings() after calling this function to commit
  3067. * this change to the database.
  3068. *
  3069. * @param &$expiration \mixed Accepts the expiration time
  3070. * @return String New token
  3071. */
  3072. private function confirmationToken( &$expiration ) {
  3073. global $wgUserEmailConfirmationTokenExpiry;
  3074. $now = time();
  3075. $expires = $now + $wgUserEmailConfirmationTokenExpiry;
  3076. $expiration = wfTimestamp( TS_MW, $expires );
  3077. $this->load();
  3078. $token = MWCryptRand::generateHex( 32 );
  3079. $hash = md5( $token );
  3080. $this->mEmailToken = $hash;
  3081. $this->mEmailTokenExpires = $expiration;
  3082. return $token;
  3083. }
  3084. /**
  3085. * Return a URL the user can use to confirm their email address.
  3086. * @param $token String Accepts the email confirmation token
  3087. * @return String New token URL
  3088. */
  3089. private function confirmationTokenUrl( $token ) {
  3090. return $this->getTokenUrl( 'ConfirmEmail', $token );
  3091. }
  3092. /**
  3093. * Return a URL the user can use to invalidate their email address.
  3094. * @param $token String Accepts the email confirmation token
  3095. * @return String New token URL
  3096. */
  3097. private function invalidationTokenUrl( $token ) {
  3098. return $this->getTokenUrl( 'InvalidateEmail', $token );
  3099. }
  3100. /**
  3101. * Internal function to format the e-mail validation/invalidation URLs.
  3102. * This uses a quickie hack to use the
  3103. * hardcoded English names of the Special: pages, for ASCII safety.
  3104. *
  3105. * @note Since these URLs get dropped directly into emails, using the
  3106. * short English names avoids insanely long URL-encoded links, which
  3107. * also sometimes can get corrupted in some browsers/mailers
  3108. * (bug 6957 with Gmail and Internet Explorer).
  3109. *
  3110. * @param $page String Special page
  3111. * @param $token String Token
  3112. * @return String Formatted URL
  3113. */
  3114. protected function getTokenUrl( $page, $token ) {
  3115. // Hack to bypass localization of 'Special:'
  3116. $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
  3117. return $title->getCanonicalUrl();
  3118. }
  3119. /**
  3120. * Mark the e-mail address confirmed.
  3121. *
  3122. * @note Call saveSettings() after calling this function to commit the change.
  3123. *
  3124. * @return bool
  3125. */
  3126. public function confirmEmail() {
  3127. $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
  3128. wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
  3129. return true;
  3130. }
  3131. /**
  3132. * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
  3133. * address if it was already confirmed.
  3134. *
  3135. * @note Call saveSettings() after calling this function to commit the change.
  3136. * @return bool Returns true
  3137. */
  3138. function invalidateEmail() {
  3139. $this->load();
  3140. $this->mEmailToken = null;
  3141. $this->mEmailTokenExpires = null;
  3142. $this->setEmailAuthenticationTimestamp( null );
  3143. wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
  3144. return true;
  3145. }
  3146. /**
  3147. * Set the e-mail authentication timestamp.
  3148. * @param $timestamp String TS_MW timestamp
  3149. */
  3150. function setEmailAuthenticationTimestamp( $timestamp ) {
  3151. $this->load();
  3152. $this->mEmailAuthenticated = $timestamp;
  3153. wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
  3154. }
  3155. /**
  3156. * Is this user allowed to send e-mails within limits of current
  3157. * site configuration?
  3158. * @return Bool
  3159. */
  3160. public function canSendEmail() {
  3161. global $wgEnableEmail, $wgEnableUserEmail;
  3162. if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
  3163. return false;
  3164. }
  3165. $canSend = $this->isEmailConfirmed();
  3166. wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
  3167. return $canSend;
  3168. }
  3169. /**
  3170. * Is this user allowed to receive e-mails within limits of current
  3171. * site configuration?
  3172. * @return Bool
  3173. */
  3174. public function canReceiveEmail() {
  3175. return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
  3176. }
  3177. /**
  3178. * Is this user's e-mail address valid-looking and confirmed within
  3179. * limits of the current site configuration?
  3180. *
  3181. * @note If $wgEmailAuthentication is on, this may require the user to have
  3182. * confirmed their address by returning a code or using a password
  3183. * sent to the address from the wiki.
  3184. *
  3185. * @return Bool
  3186. */
  3187. public function isEmailConfirmed() {
  3188. global $wgEmailAuthentication;
  3189. $this->load();
  3190. $confirmed = true;
  3191. if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
  3192. if( $this->isAnon() ) {
  3193. return false;
  3194. }
  3195. if( !Sanitizer::validateEmail( $this->mEmail ) ) {
  3196. return false;
  3197. }
  3198. if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
  3199. return false;
  3200. }
  3201. return true;
  3202. } else {
  3203. return $confirmed;
  3204. }
  3205. }
  3206. /**
  3207. * Check whether there is an outstanding request for e-mail confirmation.
  3208. * @return Bool
  3209. */
  3210. public function isEmailConfirmationPending() {
  3211. global $wgEmailAuthentication;
  3212. return $wgEmailAuthentication &&
  3213. !$this->isEmailConfirmed() &&
  3214. $this->mEmailToken &&
  3215. $this->mEmailTokenExpires > wfTimestamp();
  3216. }
  3217. /**
  3218. * Get the timestamp of account creation.
  3219. *
  3220. * @return String|Bool Timestamp of account creation, or false for
  3221. * non-existent/anonymous user accounts.
  3222. */
  3223. public function getRegistration() {
  3224. if ( $this->isAnon() ) {
  3225. return false;
  3226. }
  3227. $this->load();
  3228. return $this->mRegistration;
  3229. }
  3230. /**
  3231. * Get the timestamp of the first edit
  3232. *
  3233. * @return String|Bool Timestamp of first edit, or false for
  3234. * non-existent/anonymous user accounts.
  3235. */
  3236. public function getFirstEditTimestamp() {
  3237. if( $this->getId() == 0 ) {
  3238. return false; // anons
  3239. }
  3240. $dbr = wfGetDB( DB_SLAVE );
  3241. $time = $dbr->selectField( 'revision', 'rev_timestamp',
  3242. array( 'rev_user' => $this->getId() ),
  3243. __METHOD__,
  3244. array( 'ORDER BY' => 'rev_timestamp ASC' )
  3245. );
  3246. if( !$time ) {
  3247. return false; // no edits
  3248. }
  3249. return wfTimestamp( TS_MW, $time );
  3250. }
  3251. /**
  3252. * Get the permissions associated with a given list of groups
  3253. *
  3254. * @param $groups Array of Strings List of internal group names
  3255. * @return Array of Strings List of permission key names for given groups combined
  3256. */
  3257. public static function getGroupPermissions( $groups ) {
  3258. global $wgGroupPermissions, $wgRevokePermissions;
  3259. $rights = array();
  3260. // grant every granted permission first
  3261. foreach( $groups as $group ) {
  3262. if( isset( $wgGroupPermissions[$group] ) ) {
  3263. $rights = array_merge( $rights,
  3264. // array_filter removes empty items
  3265. array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
  3266. }
  3267. }
  3268. // now revoke the revoked permissions
  3269. foreach( $groups as $group ) {
  3270. if( isset( $wgRevokePermissions[$group] ) ) {
  3271. $rights = array_diff( $rights,
  3272. array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
  3273. }
  3274. }
  3275. return array_unique( $rights );
  3276. }
  3277. /**
  3278. * Get all the groups who have a given permission
  3279. *
  3280. * @param $role String Role to check
  3281. * @return Array of Strings List of internal group names with the given permission
  3282. */
  3283. public static function getGroupsWithPermission( $role ) {
  3284. global $wgGroupPermissions;
  3285. $allowedGroups = array();
  3286. foreach ( $wgGroupPermissions as $group => $rights ) {
  3287. if ( isset( $rights[$role] ) && $rights[$role] ) {
  3288. $allowedGroups[] = $group;
  3289. }
  3290. }
  3291. return $allowedGroups;
  3292. }
  3293. /**
  3294. * Get the localized descriptive name for a group, if it exists
  3295. *
  3296. * @param $group String Internal group name
  3297. * @return String Localized descriptive group name
  3298. */
  3299. public static function getGroupName( $group ) {
  3300. $msg = wfMessage( "group-$group" );
  3301. return $msg->isBlank() ? $group : $msg->text();
  3302. }
  3303. /**
  3304. * Get the localized descriptive name for a member of a group, if it exists
  3305. *
  3306. * @param $group String Internal group name
  3307. * @param $username String Username for gender (since 1.19)
  3308. * @return String Localized name for group member
  3309. */
  3310. public static function getGroupMember( $group, $username = '#' ) {
  3311. $msg = wfMessage( "group-$group-member", $username );
  3312. return $msg->isBlank() ? $group : $msg->text();
  3313. }
  3314. /**
  3315. * Return the set of defined explicit groups.
  3316. * The implicit groups (by default *, 'user' and 'autoconfirmed')
  3317. * are not included, as they are defined automatically, not in the database.
  3318. * @return Array of internal group names
  3319. */
  3320. public static function getAllGroups() {
  3321. global $wgGroupPermissions, $wgRevokePermissions;
  3322. return array_diff(
  3323. array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
  3324. self::getImplicitGroups()
  3325. );
  3326. }
  3327. /**
  3328. * Get a list of all available permissions.
  3329. * @return Array of permission names
  3330. */
  3331. public static function getAllRights() {
  3332. if ( self::$mAllRights === false ) {
  3333. global $wgAvailableRights;
  3334. if ( count( $wgAvailableRights ) ) {
  3335. self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
  3336. } else {
  3337. self::$mAllRights = self::$mCoreRights;
  3338. }
  3339. wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
  3340. }
  3341. return self::$mAllRights;
  3342. }
  3343. /**
  3344. * Get a list of implicit groups
  3345. * @return Array of Strings Array of internal group names
  3346. */
  3347. public static function getImplicitGroups() {
  3348. global $wgImplicitGroups;
  3349. $groups = $wgImplicitGroups;
  3350. wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
  3351. return $groups;
  3352. }
  3353. /**
  3354. * Get the title of a page describing a particular group
  3355. *
  3356. * @param $group String Internal group name
  3357. * @return Title|Bool Title of the page if it exists, false otherwise
  3358. */
  3359. public static function getGroupPage( $group ) {
  3360. $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
  3361. if( $msg->exists() ) {
  3362. $title = Title::newFromText( $msg->text() );
  3363. if( is_object( $title ) )
  3364. return $title;
  3365. }
  3366. return false;
  3367. }
  3368. /**
  3369. * Create a link to the group in HTML, if available;
  3370. * else return the group name.
  3371. *
  3372. * @param $group String Internal name of the group
  3373. * @param $text String The text of the link
  3374. * @return String HTML link to the group
  3375. */
  3376. public static function makeGroupLinkHTML( $group, $text = '' ) {
  3377. if( $text == '' ) {
  3378. $text = self::getGroupName( $group );
  3379. }
  3380. $title = self::getGroupPage( $group );
  3381. if( $title ) {
  3382. return Linker::link( $title, htmlspecialchars( $text ) );
  3383. } else {
  3384. return $text;
  3385. }
  3386. }
  3387. /**
  3388. * Create a link to the group in Wikitext, if available;
  3389. * else return the group name.
  3390. *
  3391. * @param $group String Internal name of the group
  3392. * @param $text String The text of the link
  3393. * @return String Wikilink to the group
  3394. */
  3395. public static function makeGroupLinkWiki( $group, $text = '' ) {
  3396. if( $text == '' ) {
  3397. $text = self::getGroupName( $group );
  3398. }
  3399. $title = self::getGroupPage( $group );
  3400. if( $title ) {
  3401. $page = $title->getPrefixedText();
  3402. return "[[$page|$text]]";
  3403. } else {
  3404. return $text;
  3405. }
  3406. }
  3407. /**
  3408. * Returns an array of the groups that a particular group can add/remove.
  3409. *
  3410. * @param $group String: the group to check for whether it can add/remove
  3411. * @return Array array( 'add' => array( addablegroups ),
  3412. * 'remove' => array( removablegroups ),
  3413. * 'add-self' => array( addablegroups to self),
  3414. * 'remove-self' => array( removable groups from self) )
  3415. */
  3416. public static function changeableByGroup( $group ) {
  3417. global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
  3418. $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
  3419. if( empty( $wgAddGroups[$group] ) ) {
  3420. // Don't add anything to $groups
  3421. } elseif( $wgAddGroups[$group] === true ) {
  3422. // You get everything
  3423. $groups['add'] = self::getAllGroups();
  3424. } elseif( is_array( $wgAddGroups[$group] ) ) {
  3425. $groups['add'] = $wgAddGroups[$group];
  3426. }
  3427. // Same thing for remove
  3428. if( empty( $wgRemoveGroups[$group] ) ) {
  3429. } elseif( $wgRemoveGroups[$group] === true ) {
  3430. $groups['remove'] = self::getAllGroups();
  3431. } elseif( is_array( $wgRemoveGroups[$group] ) ) {
  3432. $groups['remove'] = $wgRemoveGroups[$group];
  3433. }
  3434. // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
  3435. if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
  3436. foreach( $wgGroupsAddToSelf as $key => $value ) {
  3437. if( is_int( $key ) ) {
  3438. $wgGroupsAddToSelf['user'][] = $value;
  3439. }
  3440. }
  3441. }
  3442. if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
  3443. foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
  3444. if( is_int( $key ) ) {
  3445. $wgGroupsRemoveFromSelf['user'][] = $value;
  3446. }
  3447. }
  3448. }
  3449. // Now figure out what groups the user can add to him/herself
  3450. if( empty( $wgGroupsAddToSelf[$group] ) ) {
  3451. } elseif( $wgGroupsAddToSelf[$group] === true ) {
  3452. // No idea WHY this would be used, but it's there
  3453. $groups['add-self'] = User::getAllGroups();
  3454. } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
  3455. $groups['add-self'] = $wgGroupsAddToSelf[$group];
  3456. }
  3457. if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
  3458. } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
  3459. $groups['remove-self'] = User::getAllGroups();
  3460. } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
  3461. $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
  3462. }
  3463. return $groups;
  3464. }
  3465. /**
  3466. * Returns an array of groups that this user can add and remove
  3467. * @return Array array( 'add' => array( addablegroups ),
  3468. * 'remove' => array( removablegroups ),
  3469. * 'add-self' => array( addablegroups to self),
  3470. * 'remove-self' => array( removable groups from self) )
  3471. */
  3472. public function changeableGroups() {
  3473. if( $this->isAllowed( 'userrights' ) ) {
  3474. // This group gives the right to modify everything (reverse-
  3475. // compatibility with old "userrights lets you change
  3476. // everything")
  3477. // Using array_merge to make the groups reindexed
  3478. $all = array_merge( User::getAllGroups() );
  3479. return array(
  3480. 'add' => $all,
  3481. 'remove' => $all,
  3482. 'add-self' => array(),
  3483. 'remove-self' => array()
  3484. );
  3485. }
  3486. // Okay, it's not so simple, we will have to go through the arrays
  3487. $groups = array(
  3488. 'add' => array(),
  3489. 'remove' => array(),
  3490. 'add-self' => array(),
  3491. 'remove-self' => array()
  3492. );
  3493. $addergroups = $this->getEffectiveGroups();
  3494. foreach( $addergroups as $addergroup ) {
  3495. $groups = array_merge_recursive(
  3496. $groups, $this->changeableByGroup( $addergroup )
  3497. );
  3498. $groups['add'] = array_unique( $groups['add'] );
  3499. $groups['remove'] = array_unique( $groups['remove'] );
  3500. $groups['add-self'] = array_unique( $groups['add-self'] );
  3501. $groups['remove-self'] = array_unique( $groups['remove-self'] );
  3502. }
  3503. return $groups;
  3504. }
  3505. /**
  3506. * Increment the user's edit-count field.
  3507. * Will have no effect for anonymous users.
  3508. */
  3509. public function incEditCount() {
  3510. if( !$this->isAnon() ) {
  3511. $dbw = wfGetDB( DB_MASTER );
  3512. $dbw->update( 'user',
  3513. array( 'user_editcount=user_editcount+1' ),
  3514. array( 'user_id' => $this->getId() ),
  3515. __METHOD__ );
  3516. // Lazy initialization check...
  3517. if( $dbw->affectedRows() == 0 ) {
  3518. // Pull from a slave to be less cruel to servers
  3519. // Accuracy isn't the point anyway here
  3520. $dbr = wfGetDB( DB_SLAVE );
  3521. $count = $dbr->selectField( 'revision',
  3522. 'COUNT(rev_user)',
  3523. array( 'rev_user' => $this->getId() ),
  3524. __METHOD__ );
  3525. // Now here's a goddamn hack...
  3526. if( $dbr !== $dbw ) {
  3527. // If we actually have a slave server, the count is
  3528. // at least one behind because the current transaction
  3529. // has not been committed and replicated.
  3530. $count++;
  3531. } else {
  3532. // But if DB_SLAVE is selecting the master, then the
  3533. // count we just read includes the revision that was
  3534. // just added in the working transaction.
  3535. }
  3536. $dbw->update( 'user',
  3537. array( 'user_editcount' => $count ),
  3538. array( 'user_id' => $this->getId() ),
  3539. __METHOD__ );
  3540. }
  3541. }
  3542. // edit count in user cache too
  3543. $this->invalidateCache();
  3544. }
  3545. /**
  3546. * Get the description of a given right
  3547. *
  3548. * @param $right String Right to query
  3549. * @return String Localized description of the right
  3550. */
  3551. public static function getRightDescription( $right ) {
  3552. $key = "right-$right";
  3553. $msg = wfMessage( $key );
  3554. return $msg->isBlank() ? $right : $msg->text();
  3555. }
  3556. /**
  3557. * Make an old-style password hash
  3558. *
  3559. * @param $password String Plain-text password
  3560. * @param $userId String User ID
  3561. * @return String Password hash
  3562. */
  3563. public static function oldCrypt( $password, $userId ) {
  3564. global $wgPasswordSalt;
  3565. if ( $wgPasswordSalt ) {
  3566. return md5( $userId . '-' . md5( $password ) );
  3567. } else {
  3568. return md5( $password );
  3569. }
  3570. }
  3571. /**
  3572. * Make a new-style password hash
  3573. *
  3574. * @param $password String Plain-text password
  3575. * @param bool|string $salt Optional salt, may be random or the user ID.
  3576. * If unspecified or false, will generate one automatically
  3577. * @return String Password hash
  3578. */
  3579. public static function crypt( $password, $salt = false ) {
  3580. global $wgPasswordSalt;
  3581. $hash = '';
  3582. if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
  3583. return $hash;
  3584. }
  3585. if( $wgPasswordSalt ) {
  3586. if ( $salt === false ) {
  3587. $salt = MWCryptRand::generateHex( 8 );
  3588. }
  3589. return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
  3590. } else {
  3591. return ':A:' . md5( $password );
  3592. }
  3593. }
  3594. /**
  3595. * Compare a password hash with a plain-text password. Requires the user
  3596. * ID if there's a chance that the hash is an old-style hash.
  3597. *
  3598. * @param $hash String Password hash
  3599. * @param $password String Plain-text password to compare
  3600. * @param $userId String|bool User ID for old-style password salt
  3601. *
  3602. * @return Boolean
  3603. */
  3604. public static function comparePasswords( $hash, $password, $userId = false ) {
  3605. $type = substr( $hash, 0, 3 );
  3606. $result = false;
  3607. if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
  3608. return $result;
  3609. }
  3610. if ( $type == ':A:' ) {
  3611. # Unsalted
  3612. return md5( $password ) === substr( $hash, 3 );
  3613. } elseif ( $type == ':B:' ) {
  3614. # Salted
  3615. list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
  3616. return md5( $salt.'-'.md5( $password ) ) === $realHash;
  3617. } else {
  3618. # Old-style
  3619. return self::oldCrypt( $password, $userId ) === $hash;
  3620. }
  3621. }
  3622. /**
  3623. * Add a newuser log entry for this user. Before 1.19 the return value was always true.
  3624. *
  3625. * @param $byEmail Boolean: account made by email?
  3626. * @param $reason String: user supplied reason
  3627. *
  3628. * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
  3629. */
  3630. public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
  3631. global $wgUser, $wgContLang, $wgNewUserLog;
  3632. if( empty( $wgNewUserLog ) ) {
  3633. return true; // disabled
  3634. }
  3635. if( $this->getName() == $wgUser->getName() ) {
  3636. $action = 'create';
  3637. } else {
  3638. $action = 'create2';
  3639. if ( $byEmail ) {
  3640. if ( $reason === '' ) {
  3641. $reason = wfMessage( 'newuserlog-byemail' )->inContentLanguage()->text();
  3642. } else {
  3643. $reason = $wgContLang->commaList( array(
  3644. $reason, wfMessage( 'newuserlog-byemail' )->inContentLanguage()->text() ) );
  3645. }
  3646. }
  3647. }
  3648. $log = new LogPage( 'newusers' );
  3649. return (int)$log->addEntry(
  3650. $action,
  3651. $this->getUserPage(),
  3652. $reason,
  3653. array( $this->getId() )
  3654. );
  3655. }
  3656. /**
  3657. * Add an autocreate newuser log entry for this user
  3658. * Used by things like CentralAuth and perhaps other authplugins.
  3659. *
  3660. * @return bool
  3661. */
  3662. public function addNewUserLogEntryAutoCreate() {
  3663. global $wgNewUserLog;
  3664. if( !$wgNewUserLog ) {
  3665. return true; // disabled
  3666. }
  3667. $log = new LogPage( 'newusers', false );
  3668. $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ), $this );
  3669. return true;
  3670. }
  3671. /**
  3672. * @todo document
  3673. */
  3674. protected function loadOptions() {
  3675. $this->load();
  3676. if ( $this->mOptionsLoaded || !$this->getId() )
  3677. return;
  3678. $this->mOptions = self::getDefaultOptions();
  3679. // Maybe load from the object
  3680. if ( !is_null( $this->mOptionOverrides ) ) {
  3681. wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
  3682. foreach( $this->mOptionOverrides as $key => $value ) {
  3683. $this->mOptions[$key] = $value;
  3684. }
  3685. } else {
  3686. wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
  3687. // Load from database
  3688. $dbr = wfGetDB( DB_SLAVE );
  3689. $res = $dbr->select(
  3690. 'user_properties',
  3691. array( 'up_property', 'up_value' ),
  3692. array( 'up_user' => $this->getId() ),
  3693. __METHOD__
  3694. );
  3695. $this->mOptionOverrides = array();
  3696. foreach ( $res as $row ) {
  3697. $this->mOptionOverrides[$row->up_property] = $row->up_value;
  3698. $this->mOptions[$row->up_property] = $row->up_value;
  3699. }
  3700. }
  3701. $this->mOptionsLoaded = true;
  3702. wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
  3703. }
  3704. /**
  3705. * @todo document
  3706. */
  3707. protected function saveOptions() {
  3708. global $wgAllowPrefChange;
  3709. $this->loadOptions();
  3710. // Not using getOptions(), to keep hidden preferences in database
  3711. $saveOptions = $this->mOptions;
  3712. // Allow hooks to abort, for instance to save to a global profile.
  3713. // Reset options to default state before saving.
  3714. if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
  3715. return;
  3716. }
  3717. $extuser = ExternalUser::newFromUser( $this );
  3718. $userId = $this->getId();
  3719. $insert_rows = array();
  3720. foreach( $saveOptions as $key => $value ) {
  3721. # Don't bother storing default values
  3722. $defaultOption = self::getDefaultOption( $key );
  3723. if ( ( is_null( $defaultOption ) &&
  3724. !( $value === false || is_null( $value ) ) ) ||
  3725. $value != $defaultOption ) {
  3726. $insert_rows[] = array(
  3727. 'up_user' => $userId,
  3728. 'up_property' => $key,
  3729. 'up_value' => $value,
  3730. );
  3731. }
  3732. if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
  3733. switch ( $wgAllowPrefChange[$key] ) {
  3734. case 'local':
  3735. case 'message':
  3736. break;
  3737. case 'semiglobal':
  3738. case 'global':
  3739. $extuser->setPref( $key, $value );
  3740. }
  3741. }
  3742. }
  3743. $dbw = wfGetDB( DB_MASTER );
  3744. $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
  3745. $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
  3746. }
  3747. /**
  3748. * Provide an array of HTML5 attributes to put on an input element
  3749. * intended for the user to enter a new password. This may include
  3750. * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
  3751. *
  3752. * Do *not* use this when asking the user to enter his current password!
  3753. * Regardless of configuration, users may have invalid passwords for whatever
  3754. * reason (e.g., they were set before requirements were tightened up).
  3755. * Only use it when asking for a new password, like on account creation or
  3756. * ResetPass.
  3757. *
  3758. * Obviously, you still need to do server-side checking.
  3759. *
  3760. * NOTE: A combination of bugs in various browsers means that this function
  3761. * actually just returns array() unconditionally at the moment. May as
  3762. * well keep it around for when the browser bugs get fixed, though.
  3763. *
  3764. * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
  3765. *
  3766. * @return array Array of HTML attributes suitable for feeding to
  3767. * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
  3768. * That will potentially output invalid XHTML 1.0 Transitional, and will
  3769. * get confused by the boolean attribute syntax used.)
  3770. */
  3771. public static function passwordChangeInputAttribs() {
  3772. global $wgMinimalPasswordLength;
  3773. if ( $wgMinimalPasswordLength == 0 ) {
  3774. return array();
  3775. }
  3776. # Note that the pattern requirement will always be satisfied if the
  3777. # input is empty, so we need required in all cases.
  3778. #
  3779. # @todo FIXME: Bug 23769: This needs to not claim the password is required
  3780. # if e-mail confirmation is being used. Since HTML5 input validation
  3781. # is b0rked anyway in some browsers, just return nothing. When it's
  3782. # re-enabled, fix this code to not output required for e-mail
  3783. # registration.
  3784. #$ret = array( 'required' );
  3785. $ret = array();
  3786. # We can't actually do this right now, because Opera 9.6 will print out
  3787. # the entered password visibly in its error message! When other
  3788. # browsers add support for this attribute, or Opera fixes its support,
  3789. # we can add support with a version check to avoid doing this on Opera
  3790. # versions where it will be a problem. Reported to Opera as
  3791. # DSK-262266, but they don't have a public bug tracker for us to follow.
  3792. /*
  3793. if ( $wgMinimalPasswordLength > 1 ) {
  3794. $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
  3795. $ret['title'] = wfMessage( 'passwordtooshort' )
  3796. ->numParams( $wgMinimalPasswordLength )->text();
  3797. }
  3798. */
  3799. return $ret;
  3800. }
  3801. /**
  3802. * Return the list of user fields that should be selected to create
  3803. * a new user object.
  3804. * @return array
  3805. */
  3806. public static function selectFields() {
  3807. return array(
  3808. 'user_id',
  3809. 'user_name',
  3810. 'user_real_name',
  3811. 'user_password',
  3812. 'user_newpassword',
  3813. 'user_newpass_time',
  3814. 'user_email',
  3815. 'user_touched',
  3816. 'user_token',
  3817. 'user_email_authenticated',
  3818. 'user_email_token',
  3819. 'user_email_token_expires',
  3820. 'user_registration',
  3821. 'user_editcount',
  3822. );
  3823. }
  3824. }