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

/includes/User.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 4114 lines | 2475 code | 337 blank | 1302 comment | 377 complexity | d5dd4076f198525eb956433ba19ecb64 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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. * Array of Strings List of member variables which are saved to the
  64. * shared cache (memcached). Any operation which changes the
  65. * corresponding database fields must call a cache-clearing function.
  66. * @showinitializer
  67. */
  68. static $mCacheVars = array(
  69. // user table
  70. 'mId',
  71. 'mName',
  72. 'mRealName',
  73. 'mPassword',
  74. 'mNewpassword',
  75. 'mNewpassTime',
  76. 'mEmail',
  77. 'mTouched',
  78. 'mToken',
  79. 'mEmailAuthenticated',
  80. 'mEmailToken',
  81. 'mEmailTokenExpires',
  82. 'mRegistration',
  83. 'mEditCount',
  84. // user_groups table
  85. 'mGroups',
  86. // user_properties table
  87. 'mOptionOverrides',
  88. );
  89. /**
  90. * Array of Strings Core rights.
  91. * Each of these should have a corresponding message of the form
  92. * "right-$right".
  93. * @showinitializer
  94. */
  95. static $mCoreRights = array(
  96. 'apihighlimits',
  97. 'autoconfirmed',
  98. 'autopatrol',
  99. 'bigdelete',
  100. 'block',
  101. 'blockemail',
  102. 'bot',
  103. 'browsearchive',
  104. 'createaccount',
  105. 'createpage',
  106. 'createtalk',
  107. 'delete',
  108. 'deletedhistory',
  109. 'deletedtext',
  110. 'deleterevision',
  111. 'edit',
  112. 'editinterface',
  113. 'editusercssjs', #deprecated
  114. 'editusercss',
  115. 'edituserjs',
  116. 'hideuser',
  117. 'import',
  118. 'importupload',
  119. 'ipblock-exempt',
  120. 'markbotedits',
  121. 'mergehistory',
  122. 'minoredit',
  123. 'move',
  124. 'movefile',
  125. 'move-rootuserpages',
  126. 'move-subpages',
  127. 'nominornewtalk',
  128. 'noratelimit',
  129. 'override-export-depth',
  130. 'patrol',
  131. 'protect',
  132. 'proxyunbannable',
  133. 'purge',
  134. 'read',
  135. 'reupload',
  136. 'reupload-shared',
  137. 'rollback',
  138. 'sendemail',
  139. 'siteadmin',
  140. 'suppressionlog',
  141. 'suppressredirect',
  142. 'suppressrevision',
  143. 'unblockself',
  144. 'undelete',
  145. 'unwatchedpages',
  146. 'upload',
  147. 'upload_by_url',
  148. 'userrights',
  149. 'userrights-interwiki',
  150. 'writeapi',
  151. );
  152. /**
  153. * String Cached results of getAllRights()
  154. */
  155. static $mAllRights = false;
  156. /** @name Cache variables */
  157. //@{
  158. var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
  159. $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
  160. $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides,
  161. $mCookiePassword, $mEditCount, $mAllowUsertalk;
  162. //@}
  163. /**
  164. * Bool Whether the cache variables have been loaded.
  165. */
  166. //@{
  167. var $mOptionsLoaded;
  168. /**
  169. * Array with already loaded items or true if all items have been loaded.
  170. */
  171. private $mLoadedItems = array();
  172. //@}
  173. /**
  174. * String Initialization data source if mLoadedItems!==true. May be one of:
  175. * - 'defaults' anonymous user initialised from class defaults
  176. * - 'name' initialise from mName
  177. * - 'id' initialise from mId
  178. * - 'session' log in from cookies or session if possible
  179. *
  180. * Use the User::newFrom*() family of functions to set this.
  181. */
  182. var $mFrom;
  183. /**
  184. * Lazy-initialized variables, invalidated with clearInstanceCache
  185. */
  186. var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
  187. $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
  188. $mLocked, $mHideName, $mOptions;
  189. /**
  190. * @var WebRequest
  191. */
  192. private $mRequest;
  193. /**
  194. * @var Block
  195. */
  196. var $mBlock;
  197. /**
  198. * @var Block
  199. */
  200. private $mBlockedFromCreateAccount = false;
  201. static $idCacheByName = array();
  202. /**
  203. * Lightweight constructor for an anonymous user.
  204. * Use the User::newFrom* factory functions for other kinds of users.
  205. *
  206. * @see newFromName()
  207. * @see newFromId()
  208. * @see newFromConfirmationCode()
  209. * @see newFromSession()
  210. * @see newFromRow()
  211. */
  212. function __construct() {
  213. $this->clearInstanceCache( 'defaults' );
  214. }
  215. /**
  216. * @return String
  217. */
  218. function __toString(){
  219. return $this->getName();
  220. }
  221. /**
  222. * Load the user table data for this object from the source given by mFrom.
  223. */
  224. public function load() {
  225. if ( $this->mLoadedItems === true ) {
  226. return;
  227. }
  228. wfProfileIn( __METHOD__ );
  229. # Set it now to avoid infinite recursion in accessors
  230. $this->mLoadedItems = true;
  231. switch ( $this->mFrom ) {
  232. case 'defaults':
  233. $this->loadDefaults();
  234. break;
  235. case 'name':
  236. $this->mId = self::idFromName( $this->mName );
  237. if ( !$this->mId ) {
  238. # Nonexistent user placeholder object
  239. $this->loadDefaults( $this->mName );
  240. } else {
  241. $this->loadFromId();
  242. }
  243. break;
  244. case 'id':
  245. $this->loadFromId();
  246. break;
  247. case 'session':
  248. $this->loadFromSession();
  249. wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
  250. break;
  251. default:
  252. throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
  253. }
  254. wfProfileOut( __METHOD__ );
  255. }
  256. /**
  257. * Load user table data, given mId has already been set.
  258. * @return Bool false if the ID does not exist, true otherwise
  259. */
  260. public function loadFromId() {
  261. global $wgMemc;
  262. if ( $this->mId == 0 ) {
  263. $this->loadDefaults();
  264. return false;
  265. }
  266. # Try cache
  267. $key = wfMemcKey( 'user', 'id', $this->mId );
  268. $data = $wgMemc->get( $key );
  269. if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
  270. # Object is expired, load from DB
  271. $data = false;
  272. }
  273. if ( !$data ) {
  274. wfDebug( "User: cache miss for user {$this->mId}\n" );
  275. # Load from DB
  276. if ( !$this->loadFromDatabase() ) {
  277. # Can't load from ID, user is anonymous
  278. return false;
  279. }
  280. $this->saveToCache();
  281. } else {
  282. wfDebug( "User: got user {$this->mId} from cache\n" );
  283. # Restore from cache
  284. foreach ( self::$mCacheVars as $name ) {
  285. $this->$name = $data[$name];
  286. }
  287. }
  288. return true;
  289. }
  290. /**
  291. * Save user data to the shared cache
  292. */
  293. public function saveToCache() {
  294. $this->load();
  295. $this->loadGroups();
  296. $this->loadOptions();
  297. if ( $this->isAnon() ) {
  298. // Anonymous users are uncached
  299. return;
  300. }
  301. $data = array();
  302. foreach ( self::$mCacheVars as $name ) {
  303. $data[$name] = $this->$name;
  304. }
  305. $data['mVersion'] = MW_USER_VERSION;
  306. $key = wfMemcKey( 'user', 'id', $this->mId );
  307. global $wgMemc;
  308. $wgMemc->set( $key, $data );
  309. }
  310. /** @name newFrom*() static factory methods */
  311. //@{
  312. /**
  313. * Static factory method for creation from username.
  314. *
  315. * This is slightly less efficient than newFromId(), so use newFromId() if
  316. * you have both an ID and a name handy.
  317. *
  318. * @param $name String Username, validated by Title::newFromText()
  319. * @param $validate String|Bool Validate username. Takes the same parameters as
  320. * User::getCanonicalName(), except that true is accepted as an alias
  321. * for 'valid', for BC.
  322. *
  323. * @return User object, or false if the username is invalid
  324. * (e.g. if it contains illegal characters or is an IP address). If the
  325. * username is not present in the database, the result will be a user object
  326. * with a name, zero user ID and default settings.
  327. */
  328. public static function newFromName( $name, $validate = 'valid' ) {
  329. if ( $validate === true ) {
  330. $validate = 'valid';
  331. }
  332. $name = self::getCanonicalName( $name, $validate );
  333. if ( $name === false ) {
  334. return false;
  335. } else {
  336. # Create unloaded user object
  337. $u = new User;
  338. $u->mName = $name;
  339. $u->mFrom = 'name';
  340. $u->setItemLoaded( 'name' );
  341. return $u;
  342. }
  343. }
  344. /**
  345. * Static factory method for creation from a given user ID.
  346. *
  347. * @param $id Int Valid user ID
  348. * @return User The corresponding User object
  349. */
  350. public static function newFromId( $id ) {
  351. $u = new User;
  352. $u->mId = $id;
  353. $u->mFrom = 'id';
  354. $u->setItemLoaded( 'id' );
  355. return $u;
  356. }
  357. /**
  358. * Factory method to fetch whichever user has a given email confirmation code.
  359. * This code is generated when an account is created or its e-mail address
  360. * has changed.
  361. *
  362. * If the code is invalid or has expired, returns NULL.
  363. *
  364. * @param $code String Confirmation code
  365. * @return User object, or null
  366. */
  367. public static function newFromConfirmationCode( $code ) {
  368. $dbr = wfGetDB( DB_SLAVE );
  369. $id = $dbr->selectField( 'user', 'user_id', array(
  370. 'user_email_token' => md5( $code ),
  371. 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
  372. ) );
  373. if( $id !== false ) {
  374. return User::newFromId( $id );
  375. } else {
  376. return null;
  377. }
  378. }
  379. /**
  380. * Create a new user object using data from session or cookies. If the
  381. * login credentials are invalid, the result is an anonymous user.
  382. *
  383. * @param $request WebRequest object to use; $wgRequest will be used if
  384. * ommited.
  385. * @return User object
  386. */
  387. public static function newFromSession( WebRequest $request = null ) {
  388. $user = new User;
  389. $user->mFrom = 'session';
  390. $user->mRequest = $request;
  391. return $user;
  392. }
  393. /**
  394. * Create a new user object from a user row.
  395. * The row should have the following fields from the user table in it:
  396. * - either user_name or user_id to load further data if needed (or both)
  397. * - user_real_name
  398. * - all other fields (email, password, etc.)
  399. * It is useless to provide the remaining fields if either user_id,
  400. * user_name and user_real_name are not provided because the whole row
  401. * will be loaded once more from the database when accessing them.
  402. *
  403. * @param $row Array A row from the user table
  404. * @return User
  405. */
  406. public static function newFromRow( $row ) {
  407. $user = new User;
  408. $user->loadFromRow( $row );
  409. return $user;
  410. }
  411. //@}
  412. /**
  413. * Get the username corresponding to a given user ID
  414. * @param $id Int User ID
  415. * @return String|false The corresponding username
  416. */
  417. public static function whoIs( $id ) {
  418. $dbr = wfGetDB( DB_SLAVE );
  419. return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
  420. }
  421. /**
  422. * Get the real name of a user given their user ID
  423. *
  424. * @param $id Int User ID
  425. * @return String|false The corresponding user's real name
  426. */
  427. public static function whoIsReal( $id ) {
  428. $dbr = wfGetDB( DB_SLAVE );
  429. return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
  430. }
  431. /**
  432. * Get database id given a user name
  433. * @param $name String Username
  434. * @return Int|Null The corresponding user's ID, or null if user is nonexistent
  435. */
  436. public static function idFromName( $name ) {
  437. $nt = Title::makeTitleSafe( NS_USER, $name );
  438. if( is_null( $nt ) ) {
  439. # Illegal name
  440. return null;
  441. }
  442. if ( isset( self::$idCacheByName[$name] ) ) {
  443. return self::$idCacheByName[$name];
  444. }
  445. $dbr = wfGetDB( DB_SLAVE );
  446. $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
  447. if ( $s === false ) {
  448. $result = null;
  449. } else {
  450. $result = $s->user_id;
  451. }
  452. self::$idCacheByName[$name] = $result;
  453. if ( count( self::$idCacheByName ) > 1000 ) {
  454. self::$idCacheByName = array();
  455. }
  456. return $result;
  457. }
  458. /**
  459. * Reset the cache used in idFromName(). For use in tests.
  460. */
  461. public static function resetIdByNameCache() {
  462. self::$idCacheByName = array();
  463. }
  464. /**
  465. * Does the string match an anonymous IPv4 address?
  466. *
  467. * This function exists for username validation, in order to reject
  468. * usernames which are similar in form to IP addresses. Strings such
  469. * as 300.300.300.300 will return true because it looks like an IP
  470. * address, despite not being strictly valid.
  471. *
  472. * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
  473. * address because the usemod software would "cloak" anonymous IP
  474. * addresses like this, if we allowed accounts like this to be created
  475. * new users could get the old edits of these anonymous users.
  476. *
  477. * @param $name String to match
  478. * @return Bool
  479. */
  480. public static function isIP( $name ) {
  481. return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
  482. }
  483. /**
  484. * Is the input a valid username?
  485. *
  486. * Checks if the input is a valid username, we don't want an empty string,
  487. * an IP address, anything that containins slashes (would mess up subpages),
  488. * is longer than the maximum allowed username size or doesn't begin with
  489. * a capital letter.
  490. *
  491. * @param $name String to match
  492. * @return Bool
  493. */
  494. public static function isValidUserName( $name ) {
  495. global $wgContLang, $wgMaxNameChars;
  496. if ( $name == ''
  497. || User::isIP( $name )
  498. || strpos( $name, '/' ) !== false
  499. || strlen( $name ) > $wgMaxNameChars
  500. || $name != $wgContLang->ucfirst( $name ) ) {
  501. wfDebugLog( 'username', __METHOD__ .
  502. ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
  503. return false;
  504. }
  505. // Ensure that the name can't be misresolved as a different title,
  506. // such as with extra namespace keys at the start.
  507. $parsed = Title::newFromText( $name );
  508. if( is_null( $parsed )
  509. || $parsed->getNamespace()
  510. || strcmp( $name, $parsed->getPrefixedText() ) ) {
  511. wfDebugLog( 'username', __METHOD__ .
  512. ": '$name' invalid due to ambiguous prefixes" );
  513. return false;
  514. }
  515. // Check an additional blacklist of troublemaker characters.
  516. // Should these be merged into the title char list?
  517. $unicodeBlacklist = '/[' .
  518. '\x{0080}-\x{009f}' . # iso-8859-1 control chars
  519. '\x{00a0}' . # non-breaking space
  520. '\x{2000}-\x{200f}' . # various whitespace
  521. '\x{2028}-\x{202f}' . # breaks and control chars
  522. '\x{3000}' . # ideographic space
  523. '\x{e000}-\x{f8ff}' . # private use
  524. ']/u';
  525. if( preg_match( $unicodeBlacklist, $name ) ) {
  526. wfDebugLog( 'username', __METHOD__ .
  527. ": '$name' invalid due to blacklisted characters" );
  528. return false;
  529. }
  530. return true;
  531. }
  532. /**
  533. * Usernames which fail to pass this function will be blocked
  534. * from user login and new account registrations, but may be used
  535. * internally by batch processes.
  536. *
  537. * If an account already exists in this form, login will be blocked
  538. * by a failure to pass this function.
  539. *
  540. * @param $name String to match
  541. * @return Bool
  542. */
  543. public static function isUsableName( $name ) {
  544. global $wgReservedUsernames;
  545. // Must be a valid username, obviously ;)
  546. if ( !self::isValidUserName( $name ) ) {
  547. return false;
  548. }
  549. static $reservedUsernames = false;
  550. if ( !$reservedUsernames ) {
  551. $reservedUsernames = $wgReservedUsernames;
  552. wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
  553. }
  554. // Certain names may be reserved for batch processes.
  555. foreach ( $reservedUsernames as $reserved ) {
  556. if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
  557. $reserved = wfMsgForContent( substr( $reserved, 4 ) );
  558. }
  559. if ( $reserved == $name ) {
  560. return false;
  561. }
  562. }
  563. return true;
  564. }
  565. /**
  566. * Usernames which fail to pass this function will be blocked
  567. * from new account registrations, but may be used internally
  568. * either by batch processes or by user accounts which have
  569. * already been created.
  570. *
  571. * Additional blacklisting may be added here rather than in
  572. * isValidUserName() to avoid disrupting existing accounts.
  573. *
  574. * @param $name String to match
  575. * @return Bool
  576. */
  577. public static function isCreatableName( $name ) {
  578. global $wgInvalidUsernameCharacters;
  579. // Ensure that the username isn't longer than 235 bytes, so that
  580. // (at least for the builtin skins) user javascript and css files
  581. // will work. (bug 23080)
  582. if( strlen( $name ) > 235 ) {
  583. wfDebugLog( 'username', __METHOD__ .
  584. ": '$name' invalid due to length" );
  585. return false;
  586. }
  587. // Preg yells if you try to give it an empty string
  588. if( $wgInvalidUsernameCharacters !== '' ) {
  589. if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
  590. wfDebugLog( 'username', __METHOD__ .
  591. ": '$name' invalid due to wgInvalidUsernameCharacters" );
  592. return false;
  593. }
  594. }
  595. return self::isUsableName( $name );
  596. }
  597. /**
  598. * Is the input a valid password for this user?
  599. *
  600. * @param $password String Desired password
  601. * @return Bool
  602. */
  603. public function isValidPassword( $password ) {
  604. //simple boolean wrapper for getPasswordValidity
  605. return $this->getPasswordValidity( $password ) === true;
  606. }
  607. /**
  608. * Given unvalidated password input, return error message on failure.
  609. *
  610. * @param $password String Desired password
  611. * @return mixed: true on success, string or array of error message on failure
  612. */
  613. public function getPasswordValidity( $password ) {
  614. global $wgMinimalPasswordLength, $wgContLang;
  615. static $blockedLogins = array(
  616. 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
  617. 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
  618. );
  619. $result = false; //init $result to false for the internal checks
  620. if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
  621. return $result;
  622. if ( $result === false ) {
  623. if( strlen( $password ) < $wgMinimalPasswordLength ) {
  624. return 'passwordtooshort';
  625. } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
  626. return 'password-name-match';
  627. } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
  628. return 'password-login-forbidden';
  629. } else {
  630. //it seems weird returning true here, but this is because of the
  631. //initialization of $result to false above. If the hook is never run or it
  632. //doesn't modify $result, then we will likely get down into this if with
  633. //a valid password.
  634. return true;
  635. }
  636. } elseif( $result === true ) {
  637. return true;
  638. } else {
  639. return $result; //the isValidPassword hook set a string $result and returned true
  640. }
  641. }
  642. /**
  643. * Does a string look like an e-mail address?
  644. *
  645. * This validates an email address using an HTML5 specification found at:
  646. * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
  647. * Which as of 2011-01-24 says:
  648. *
  649. * A valid e-mail address is a string that matches the ABNF production
  650. * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
  651. * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
  652. * 3.5.
  653. *
  654. * This function is an implementation of the specification as requested in
  655. * bug 22449.
  656. *
  657. * Client-side forms will use the same standard validation rules via JS or
  658. * HTML 5 validation; additional restrictions can be enforced server-side
  659. * by extensions via the 'isValidEmailAddr' hook.
  660. *
  661. * Note that this validation doesn't 100% match RFC 2822, but is believed
  662. * to be liberal enough for wide use. Some invalid addresses will still
  663. * pass validation here.
  664. *
  665. * @param $addr String E-mail address
  666. * @return Bool
  667. * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
  668. */
  669. public static function isValidEmailAddr( $addr ) {
  670. wfDeprecated( __METHOD__, '1.18' );
  671. return Sanitizer::validateEmail( $addr );
  672. }
  673. /**
  674. * Given unvalidated user input, return a canonical username, or false if
  675. * the username is invalid.
  676. * @param $name String User input
  677. * @param $validate String|Bool type of validation to use:
  678. * - false No validation
  679. * - 'valid' Valid for batch processes
  680. * - 'usable' Valid for batch processes and login
  681. * - 'creatable' Valid for batch processes, login and account creation
  682. *
  683. * @return bool|string
  684. */
  685. public static function getCanonicalName( $name, $validate = 'valid' ) {
  686. # Force usernames to capital
  687. global $wgContLang;
  688. $name = $wgContLang->ucfirst( $name );
  689. # Reject names containing '#'; these will be cleaned up
  690. # with title normalisation, but then it's too late to
  691. # check elsewhere
  692. if( strpos( $name, '#' ) !== false )
  693. return false;
  694. # Clean up name according to title rules
  695. $t = ( $validate === 'valid' ) ?
  696. Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
  697. # Check for invalid titles
  698. if( is_null( $t ) ) {
  699. return false;
  700. }
  701. # Reject various classes of invalid names
  702. global $wgAuth;
  703. $name = $wgAuth->getCanonicalName( $t->getText() );
  704. switch ( $validate ) {
  705. case false:
  706. break;
  707. case 'valid':
  708. if ( !User::isValidUserName( $name ) ) {
  709. $name = false;
  710. }
  711. break;
  712. case 'usable':
  713. if ( !User::isUsableName( $name ) ) {
  714. $name = false;
  715. }
  716. break;
  717. case 'creatable':
  718. if ( !User::isCreatableName( $name ) ) {
  719. $name = false;
  720. }
  721. break;
  722. default:
  723. throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
  724. }
  725. return $name;
  726. }
  727. /**
  728. * Count the number of edits of a user
  729. * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
  730. *
  731. * @param $uid Int User ID to check
  732. * @return Int the user's edit count
  733. */
  734. public static function edits( $uid ) {
  735. wfProfileIn( __METHOD__ );
  736. $dbr = wfGetDB( DB_SLAVE );
  737. // check if the user_editcount field has been initialized
  738. $field = $dbr->selectField(
  739. 'user', 'user_editcount',
  740. array( 'user_id' => $uid ),
  741. __METHOD__
  742. );
  743. if( $field === null ) { // it has not been initialized. do so.
  744. $dbw = wfGetDB( DB_MASTER );
  745. $count = $dbr->selectField(
  746. 'revision', 'count(*)',
  747. array( 'rev_user' => $uid ),
  748. __METHOD__
  749. );
  750. $dbw->update(
  751. 'user',
  752. array( 'user_editcount' => $count ),
  753. array( 'user_id' => $uid ),
  754. __METHOD__
  755. );
  756. } else {
  757. $count = $field;
  758. }
  759. wfProfileOut( __METHOD__ );
  760. return $count;
  761. }
  762. /**
  763. * Return a random password.
  764. *
  765. * @return String new random password
  766. */
  767. public static function randomPassword() {
  768. global $wgMinimalPasswordLength;
  769. // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
  770. $length = max( 10, $wgMinimalPasswordLength );
  771. // Multiply by 1.25 to get the number of hex characters we need
  772. $length = $length * 1.25;
  773. // Generate random hex chars
  774. $hex = MWCryptRand::generateHex( $length );
  775. // Convert from base 16 to base 32 to get a proper password like string
  776. return wfBaseConvert( $hex, 16, 32 );
  777. }
  778. /**
  779. * Set cached properties to default.
  780. *
  781. * @note This no longer clears uncached lazy-initialised properties;
  782. * the constructor does that instead.
  783. *
  784. * @param $name string
  785. */
  786. public function loadDefaults( $name = false ) {
  787. wfProfileIn( __METHOD__ );
  788. $this->mId = 0;
  789. $this->mName = $name;
  790. $this->mRealName = '';
  791. $this->mPassword = $this->mNewpassword = '';
  792. $this->mNewpassTime = null;
  793. $this->mEmail = '';
  794. $this->mOptionOverrides = null;
  795. $this->mOptionsLoaded = false;
  796. $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
  797. if( $loggedOut !== null ) {
  798. $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
  799. } else {
  800. $this->mTouched = '0'; # Allow any pages to be cached
  801. }
  802. $this->mToken = null; // Don't run cryptographic functions till we need a token
  803. $this->mEmailAuthenticated = null;
  804. $this->mEmailToken = '';
  805. $this->mEmailTokenExpires = null;
  806. $this->mRegistration = wfTimestamp( TS_MW );
  807. $this->mGroups = array();
  808. wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
  809. wfProfileOut( __METHOD__ );
  810. }
  811. /**
  812. * Return whether an item has been loaded.
  813. *
  814. * @param $item String: item to check. Current possibilities:
  815. * - id
  816. * - name
  817. * - realname
  818. * @param $all String: 'all' to check if the whole object has been loaded
  819. * or any other string to check if only the item is available (e.g.
  820. * for optimisation)
  821. * @return Boolean
  822. */
  823. public function isItemLoaded( $item, $all = 'all' ) {
  824. return ( $this->mLoadedItems === true && $all === 'all' ) ||
  825. ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
  826. }
  827. /**
  828. * Set that an item has been loaded
  829. *
  830. * @param $item String
  831. */
  832. private function setItemLoaded( $item ) {
  833. if ( is_array( $this->mLoadedItems ) ) {
  834. $this->mLoadedItems[$item] = true;
  835. }
  836. }
  837. /**
  838. * Load user data from the session or login cookie. If there are no valid
  839. * credentials, initialises the user as an anonymous user.
  840. * @return Bool True if the user is logged in, false otherwise.
  841. */
  842. private function loadFromSession() {
  843. global $wgExternalAuthType, $wgAutocreatePolicy;
  844. $result = null;
  845. wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
  846. if ( $result !== null ) {
  847. return $result;
  848. }
  849. if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
  850. $extUser = ExternalUser::newFromCookie();
  851. if ( $extUser ) {
  852. # TODO: Automatically create the user here (or probably a bit
  853. # lower down, in fact)
  854. }
  855. }
  856. $request = $this->getRequest();
  857. $cookieId = $request->getCookie( 'UserID' );
  858. $sessId = $request->getSessionData( 'wsUserID' );
  859. if ( $cookieId !== null ) {
  860. $sId = intval( $cookieId );
  861. if( $sessId !== null && $cookieId != $sessId ) {
  862. $this->loadDefaults(); // Possible collision!
  863. wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
  864. cookie user ID ($sId) don't match!" );
  865. return false;
  866. }
  867. $request->setSessionData( 'wsUserID', $sId );
  868. } elseif ( $sessId !== null && $sessId != 0 ) {
  869. $sId = $sessId;
  870. } else {
  871. $this->loadDefaults();
  872. return false;
  873. }
  874. if ( $request->getSessionData( 'wsUserName' ) !== null ) {
  875. $sName = $request->getSessionData( 'wsUserName' );
  876. } elseif ( $request->getCookie( 'UserName' ) !== null ) {
  877. $sName = $request->getCookie( 'UserName' );
  878. $request->setSessionData( 'wsUserName', $sName );
  879. } else {
  880. $this->loadDefaults();
  881. return false;
  882. }
  883. $proposedUser = User::newFromId( $sId );
  884. if ( !$proposedUser->isLoggedIn() ) {
  885. # Not a valid ID
  886. $this->loadDefaults();
  887. return false;
  888. }
  889. global $wgBlockDisablesLogin;
  890. if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
  891. # User blocked and we've disabled blocked user logins
  892. $this->loadDefaults();
  893. return false;
  894. }
  895. if ( $request->getSessionData( 'wsToken' ) ) {
  896. $passwordCorrect = $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' );
  897. $from = 'session';
  898. } elseif ( $request->getCookie( 'Token' ) ) {
  899. $passwordCorrect = $proposedUser->getToken( false ) === $request->getCookie( 'Token' );
  900. $from = 'cookie';
  901. } else {
  902. # No session or persistent login cookie
  903. $this->loadDefaults();
  904. return false;
  905. }
  906. if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
  907. $this->loadFromUserObject( $proposedUser );
  908. $request->setSessionData( 'wsToken', $this->mToken );
  909. wfDebug( "User: logged in from $from\n" );
  910. return true;
  911. } else {
  912. # Invalid credentials
  913. wfDebug( "User: can't log in from $from, invalid credentials\n" );
  914. $this->loadDefaults();
  915. return false;
  916. }
  917. }
  918. /**
  919. * Load user and user_group data from the database.
  920. * $this->mId must be set, this is how the user is identified.
  921. *
  922. * @return Bool True if the user exists, false if the user is anonymous
  923. */
  924. public function loadFromDatabase() {
  925. # Paranoia
  926. $this->mId = intval( $this->mId );
  927. /** Anonymous user */
  928. if( !$this->mId ) {
  929. $this->loadDefaults();
  930. return false;
  931. }
  932. $dbr = wfGetDB( DB_MASTER );
  933. $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
  934. wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
  935. if ( $s !== false ) {
  936. # Initialise user table data
  937. $this->loadFromRow( $s );
  938. $this->mGroups = null; // deferred
  939. $this->getEditCount(); // revalidation for nulls
  940. return true;
  941. } else {
  942. # Invalid user_id
  943. $this->mId = 0;
  944. $this->loadDefaults();
  945. return false;
  946. }
  947. }
  948. /**
  949. * Initialize this object from a row from the user table.
  950. *
  951. * @param $row Array Row from the user table to load.
  952. */
  953. public function loadFromRow( $row ) {
  954. $all = true;
  955. $this->mGroups = null; // deferred
  956. if ( isset( $row->user_name ) ) {
  957. $this->mName = $row->user_name;
  958. $this->mFrom = 'name';
  959. $this->setItemLoaded( 'name' );
  960. } else {
  961. $all = false;
  962. }
  963. if ( isset( $row->user_real_name ) ) {
  964. $this->mRealName = $row->user_real_name;
  965. $this->setItemLoaded( 'realname' );
  966. } else {
  967. $all = false;
  968. }
  969. if ( isset( $row->user_id ) ) {
  970. $this->mId = intval( $row->user_id );
  971. $this->mFrom = 'id';
  972. $this->setItemLoaded( 'id' );
  973. } else {
  974. $all = false;
  975. }
  976. if ( isset( $row->user_editcount ) ) {
  977. $this->mEditCount = $row->user_editcount;
  978. } else {
  979. $all = false;
  980. }
  981. if ( isset( $row->user_password ) ) {
  982. $this->mPassword = $row->user_password;
  983. $this->mNewpassword = $row->user_newpassword;
  984. $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
  985. $this->mEmail = $row->user_email;
  986. if ( isset( $row->user_options ) ) {
  987. $this->decodeOptions( $row->user_options );
  988. }
  989. $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
  990. $this->mToken = $row->user_token;
  991. if ( $this->mToken == '' ) {
  992. $this->mToken = null;
  993. }
  994. $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
  995. $this->mEmailToken = $row->user_email_token;
  996. $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
  997. $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
  998. } else {
  999. $all = false;
  1000. }
  1001. if ( $all ) {
  1002. $this->mLoadedItems = true;
  1003. }
  1004. }
  1005. /**
  1006. * Load the data for this user object from another user object.
  1007. *
  1008. * @param $user User
  1009. */
  1010. protected function loadFromUserObject( $user ) {
  1011. $user->load();
  1012. $user->loadGroups();
  1013. $user->loadOptions();
  1014. foreach ( self::$mCacheVars as $var ) {
  1015. $this->$var = $user->$var;
  1016. }
  1017. }
  1018. /**
  1019. * Load the groups from the database if they aren't already loaded.
  1020. */
  1021. private function loadGroups() {
  1022. if ( is_null( $this->mGroups ) ) {
  1023. $dbr = wfGetDB( DB_MASTER );
  1024. $res = $dbr->select( 'user_groups',
  1025. array( 'ug_group' ),
  1026. array( 'ug_user' => $this->mId ),
  1027. __METHOD__ );
  1028. $this->mGroups = array();
  1029. foreach ( $res as $row ) {
  1030. $this->mGroups[] = $row->ug_group;
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Add the user to the group if he/she meets given criteria.
  1036. *
  1037. * Contrary to autopromotion by \ref $wgAutopromote, the group will be
  1038. * possible to remove manually via Special:UserRights. In such case it
  1039. * will not be re-added automatically. The user will also not lose the
  1040. * group if they no longer meet the criteria.
  1041. *
  1042. * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
  1043. *
  1044. * @return array Array of groups the user has been promoted to.
  1045. *
  1046. * @see $wgAutopromoteOnce
  1047. */
  1048. public function addAutopromoteOnceGroups( $event ) {
  1049. global $wgAutopromoteOnceLogInRC;
  1050. $toPromote = array();
  1051. if ( $this->getId() ) {
  1052. $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
  1053. if ( count( $toPromote ) ) {
  1054. $oldGroups = $this->getGroups(); // previous groups
  1055. foreach ( $toPromote as $group ) {
  1056. $this->addGroup( $group );
  1057. }
  1058. $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
  1059. $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
  1060. $log->addEntry( 'autopromote',
  1061. $this->getUserPage(),
  1062. '', // no comment
  1063. // These group names are "list to texted"-ed in class LogPage.
  1064. array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
  1065. );
  1066. }
  1067. }
  1068. return $toPromote;
  1069. }
  1070. /**
  1071. * Clear various cached data stored in this object.
  1072. * @param $reloadFrom bool|String Reload user and user_groups table data from a
  1073. * given source. May be "name", "id", "defaults", "session", or false for
  1074. * no reload.
  1075. */
  1076. public function clearInstanceCache( $reloadFrom = false ) {
  1077. $this->mNewtalk = -1;
  1078. $this->mDatePreference = null;
  1079. $this->mBlockedby = -1; # Unset
  1080. $this->mHash = false;
  1081. $this->mRights = null;
  1082. $this->mEffectiveGroups = null;
  1083. $this->mImplicitGroups = null;
  1084. $this->mOptions = null;
  1085. if ( $reloadFrom ) {
  1086. $this->mLoadedItems = array();
  1087. $this->mFrom = $reloadFrom;
  1088. }
  1089. }
  1090. /**
  1091. * Combine the language default options with any site-specific options
  1092. * and add the default language variants.
  1093. *
  1094. * @return Array of String options
  1095. */
  1096. public static function getDefaultOptions() {
  1097. global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
  1098. $defOpt = $wgDefaultUserOptions;
  1099. # default language setting
  1100. $variant = $wgContLang->getDefaultVariant();
  1101. $defOpt['variant'] = $variant;
  1102. $defOpt['language'] = $variant;
  1103. foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
  1104. $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
  1105. }
  1106. $defOpt['skin'] = $wgDefaultSkin;
  1107. // FIXME: Ideally we'd cache the results of this function so the hook is only run once,
  1108. // but that breaks the parser tests because they rely on being able to change $wgContLang
  1109. // mid-request and see that change reflected in the return value of this function.
  1110. // Which is insane and would never happen during normal MW operation, but is also not
  1111. // likely to get fixed unless and until we context-ify everything.
  1112. // See also https://www.mediawiki.org/wiki/Special:Code/MediaWiki/101488#c25275
  1113. wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
  1114. return $defOpt;
  1115. }
  1116. /**
  1117. * Get a given default option value.
  1118. *
  1119. * @param $opt String Name of option to retrieve
  1120. * @return String Default option value
  1121. */
  1122. public static function getDefaultOption( $opt ) {
  1123. $defOpts = self::getDefaultOptions();
  1124. if( isset( $defOpts[$opt] ) ) {
  1125. return $defOpts[$opt];
  1126. } else {
  1127. return null;
  1128. }
  1129. }
  1130. /**
  1131. * Get blocking information
  1132. * @param $bFromSlave Bool Whether to check the slave database first. To
  1133. * improve performance, non-critical checks are done
  1134. * against slaves. Check when actually saving should be
  1135. * done against master.
  1136. */
  1137. private function getBlockedStatus( $bFromSlave = true ) {
  1138. global $wgProxyWhitelist, $wgUser;
  1139. if ( -1 != $this->mBlockedby ) {
  1140. return;
  1141. }
  1142. wfProfileIn( __METHOD__ );
  1143. wfDebug( __METHOD__.": checking...\n" );
  1144. // Initialize data...
  1145. // Otherwise something ends up stomping on $this->mBlockedby when
  1146. // things get lazy-loaded later, causing false positive block hits
  1147. // due to -1 !== 0. Probably session-related... Nothing should be
  1148. // overwriting mBlockedby, surely?
  1149. $this->load();
  1150. # We only need to worry about passing the IP address to the Block generator if the
  1151. # user is not immune to autoblocks/hardblocks, and they are the current user so we
  1152. # know which IP address they're actually coming from
  1153. if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
  1154. $ip = $this->getRequest()->getIP();
  1155. } else {
  1156. $ip = null;
  1157. }
  1158. # User/IP blocking
  1159. $block = Block::newFromTarget( $this->getName(), $ip, !$bFromSlave );
  1160. # Proxy blocking
  1161. if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
  1162. && !in_array( $ip, $wgProxyWhitelist ) )
  1163. {
  1164. # Local list
  1165. if ( self::isLocallyBlockedProxy( $ip ) ) {
  1166. $block = new Block;
  1167. $block->setBlocker( wfMsg( 'proxyblocker' ) );
  1168. $block->mReason = wfMsg( 'proxyblockreason' );
  1169. $block->setTarget( $ip );
  1170. } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
  1171. $block = new Block;
  1172. $block->setBlocker( wfMsg( 'sorbs' ) );
  1173. $block->mReason = wfMsg( 'sorbsreason' );
  1174. $block->setTarget( $ip );
  1175. }
  1176. }
  1177. if ( $block instanceof Block ) {
  1178. wfDebug( __METHOD__ . ": Found block.\n" );
  1179. $this->mBlock = $block;
  1180. $this->mBlockedby = $block->getByName();
  1181. $this->mBlockreason = $block->mReason;
  1182. $this->mHideName = $block->mHideName;
  1183. $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
  1184. } else {
  1185. $this->mBlockedby = '';
  1186. $this->mHideName = 0;
  1187. $this->mAllowUsertalk = false;
  1188. }
  1189. # Extensions
  1190. wfRunHooks( 'GetBlockedStatus', array( &$this ) );
  1191. wfProfileOut( __METHOD__ );
  1192. }
  1193. /**
  1194. * Whether the given IP is in a DNS blacklist.
  1195. *
  1196. * @param $ip String IP to check
  1197. * @param $checkWhitelist Bool: whether to check the whitelist first
  1198. * @return Bool True if blacklisted.
  1199. */
  1200. public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
  1201. global $wgEnableSorbs, $wgEnableDnsBlacklist,
  1202. $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
  1203. if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
  1204. return false;
  1205. if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
  1206. return false;
  1207. $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
  1208. return $this->inDnsBlacklist( $ip, $urls );
  1209. }
  1210. /**
  1211. * Whether the given IP is in a given DNS blacklist.
  1212. *
  1213. * @param $ip String IP to check
  1214. * @param $bases String|Array of Strings: URL of the DNS blacklist
  1215. * @return Bool True if blacklisted.
  1216. */
  1217. public function inDnsBlacklist( $ip, $bases ) {
  1218. wfProfileIn( __METHOD__ );
  1219. $found = false;
  1220. // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
  1221. if( IP::isIPv4( $ip ) ) {
  1222. # Reverse IP, bug 21255
  1223. $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
  1224. foreach( (array)$bases as $base ) {
  1225. # Make hostname
  1226. # If we have an access key, use that too (ProjectHoneypot, etc.)
  1227. if( is_array( $base ) ) {
  1228. if( count( $base ) >= 2 ) {
  1229. # Access key is 1, base URL is 0
  1230. $host = "{$base[1]}.$ipReversed.{$base[0]}";
  1231. } else {
  1232. $host = "$ipReversed.{$base[0]}";
  1233. }
  1234. } else {
  1235. $host = "$ipReversed.$base";
  1236. }
  1237. # Send query
  1238. $ipList = gethostbynamel( $host );
  1239. if( $ipList ) {
  1240. wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
  1241. $found = true;
  1242. break;
  1243. } else {
  1244. wfDebug( "Requested $host, not found in $base.\n" );
  1245. }
  1246. }
  1247. }
  1248. wfProfileOut( __METHOD__ );
  1249. return $found;
  1250. }
  1251. /**
  1252. * Check if an IP address is in the local proxy list
  1253. *
  1254. * @param $ip string
  1255. *
  1256. * @return bool
  1257. */
  1258. public static function isLocallyBlockedProxy( $ip ) {
  1259. global $wgProxyList;
  1260. if ( !$wgProxyList ) {
  1261. return false;
  1262. }
  1263. wfProfileIn( __METHOD__ );
  1264. if ( !is_array( $wgProxyList ) ) {
  1265. # Load from the specified file
  1266. $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
  1267. }
  1268. if ( !is_array( $wgProxyList ) ) {
  1269. $ret = false;
  1270. } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
  1271. $ret = true;
  1272. } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
  1273. # Old-style flipped proxy list
  1274. $ret = true;
  1275. } else {
  1276. $ret = false;
  1277. }
  1278. wfProfileOut( __METHOD__ );
  1279. return $ret;
  1280. }
  1281. /**
  1282. * Is this user subject to rate limiting?
  1283. *
  1284. * @return Bool True if rate limited
  1285. */
  1286. public function isPingLimitable() {
  1287. global $wgRateLimitsExcludedIPs;
  1288. if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
  1289. // No other good way currently to disable rate limits
  1290. // for specific IPs. :P
  1291. // But this is a crappy hack and should die.
  1292. return false;
  1293. }
  1294. return !$this->isAllowed('noratelimit');
  1295. }
  1296. /**
  1297. * Primitive rate limits: enforce maximum actions per time period
  1298. * to put a brake on flooding.
  1299. *
  1300. * @note When using a shared cache like memcached, IP-address
  1301. * last-hit counters will be shared across wikis.
  1302. *
  1303. * @param $action String Action to enforce; 'edit' if unspecified
  1304. * @return Bool True if a rate limiter was tripped
  1305. */
  1306. public function pingLimiter( $action = 'edit' ) {
  1307. # Call the 'PingLimiter' hook
  1308. $result = false;
  1309. if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
  1310. return $result;
  1311. }
  1312. global $wgRateLimits;
  1313. if( !isset( $wgRateLimits[$action] ) ) {
  1314. return false;
  1315. }
  1316. # Some groups shouldn't trigger the ping limiter, ever
  1317. if( !$this->isPingLimitable() )
  1318. return false;
  1319. global $wgMemc, $wgRateLimitLog;
  1320. wfProfileIn( __METHOD__ );
  1321. $limits = $wgRateLimits[$action];
  1322. $keys = array();
  1323. $id = $this->getId();
  1324. $ip = $this->getRequest()->getIP();
  1325. $userLimit = false;
  1326. if( isset( $limits['anon'] ) && $id == 0 ) {
  1327. $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
  1328. }
  1329. if( isset( $limits['user'] ) && $id != 0 ) {
  1330. $userLimit = $limits['user'];
  1331. }
  1332. if( $this->isNewbie() ) {
  1333. if( isset( $limits['newbie'] ) && $id != 0 ) {
  1334. $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
  1335. }
  1336. if( isset( $limits['ip'] ) ) {
  1337. $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
  1338. }
  1339. $matches = array();
  1340. if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
  1341. $subnet = $matches[1];
  1342. $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
  1343. }
  1344. }
  1345. // Check for group-specific permissions
  1346. // If more than one group applies, use the group with the highest limit
  1347. foreach ( $this->getGroups() as $group ) {
  1348. if ( isset( $limits[$group] ) ) {
  1349. if ( $userLimit === false || $limits[$group] > $userLimit ) {
  1350. $userLimit = $limits[$group];
  1351. }
  1352. }
  1353. }
  1354. // Set the user limit key
  1355. if ( $userLimit !== false ) {
  1356. wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
  1357. $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
  1358. }
  1359. $triggered = false;
  1360. foreach( $keys as $key => $limit ) {
  1361. list( $max, $period ) = $limit;
  1362. $summary = "(limit $max in {$period}s)";
  1363. $count = $wgMemc->get( $key );
  1364. // Already pinged?
  1365. if( $count ) {
  1366. if( $count > $max ) {
  1367. wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
  1368. if( $wgRateLimitLog ) {
  1369. wfSuppressWarnings();
  1370. file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
  1371. wfRestoreWarnings();
  1372. }
  1373. $triggered = true;
  1374. } else {
  1375. wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
  1376. }
  1377. } else {
  1378. wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
  1379. $wgMemc->add( $key, 0, intval( $period ) ); // first ping
  1380. }
  1381. $wgMemc->incr( $key );
  1382. }
  1383. wfProfileOut( __METHOD__ );
  1384. return $triggered;
  1385. }
  1386. /**
  1387. * Check if user is blocked
  1388. *
  1389. * @param $bFromSlave Bool Whether to check the slave database instead of the master
  1390. * @return Bool True if blocked, false otherwise
  1391. */
  1392. public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
  1393. return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
  1394. }
  1395. /**
  1396. * Get the block affecting the user, or null if the user is not blocked
  1397. *
  1398. * @param $bFromSlave Bool Whether to check the slave database instead of the master
  1399. * @return Block|null
  1400. */
  1401. public function getBlock( $bFromSlave = true ){
  1402. $this->getBlockedStatus( $bFromSlave );
  1403. return $this->mBlock instanceof Block ? $this->mBlock : null;
  1404. }
  1405. /**
  1406. * Check if user is blocked from editing a particular article
  1407. *
  1408. * @param $title Title to check
  1409. * @param $bFromSlave Bool whether to check the slave database instead of the master
  1410. * @return Bool
  1411. */
  1412. function isBlockedFrom( $title, $bFromSlave = false ) {
  1413. global $wgBlockAllowsUTEdit;
  1414. wfProfileIn( __METHOD__ );
  1415. $blocked = $this->isBlocked( $bFromSlave );
  1416. $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
  1417. # If a user's name is suppressed, they cannot make edits anywhere
  1418. if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
  1419. $title->getNamespace() == NS_USER_TALK ) {
  1420. $blocked = false;
  1421. wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
  1422. }
  1423. wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
  1424. wfProfileOut( __METHOD__ );
  1425. return $blocked;
  1426. }
  1427. /**
  1428. * If user is blocked, return the name of the user who placed the block
  1429. * @return String name of blocker
  1430. */
  1431. public function blockedBy() {
  1432. $this->getBlockedStatus();
  1433. return $this->mBlockedby;
  1434. }
  1435. /**
  1436. * If user is blocked, return the specified reason for the block
  1437. * @return String Blocking reason
  1438. */
  1439. public function blockedFor() {
  1440. $this->getBlockedStatus();
  1441. return $this->mBlockreason;
  1442. }
  1443. /**
  1444. * If user is blocked, return the ID for the block
  1445. * @return Int Block ID
  1446. */
  1447. public function getBlockId() {
  1448. $this->getBlockedStatus();
  1449. return ( $this->mBlock ? $this->mBlock->getId() : false );
  1450. }
  1451. /**
  1452. * Check if user is blocked on all wikis.
  1453. * Do not use for actual edit permission checks!
  1454. * This is intented for quick UI checks.
  1455. *
  1456. * @param $ip String IP address, uses current client if none given
  1457. * @return Bool True if blocked, false otherwise
  1458. */
  1459. public function isBlockedGlobally( $ip = '' ) {
  1460. if( $this->mBlockedGlobally !== null ) {
  1461. return $this->mBlockedGlobally;
  1462. }
  1463. // User is already an IP?
  1464. if( IP::isIPAddress( $this->getName() ) ) {
  1465. $ip = $this->getName();
  1466. } elseif( !$ip ) {
  1467. $ip = $this->getRequest()->getIP();
  1468. }
  1469. $blocked = false;
  1470. wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
  1471. $this->mBlockedGlobally = (bool)$blocked;
  1472. return $this->mBlockedGlobally;
  1473. }
  1474. /**
  1475. * Check if user account is locked
  1476. *
  1477. * @return Bool True if locked, false otherwise
  1478. */
  1479. public function isLocked() {
  1480. if( $this->mLocked !== null ) {
  1481. return $this->mLocked;
  1482. }
  1483. global $wgAuth;
  1484. $authUser = $wgAuth->getUserInstance( $this );
  1485. $this->mLocked = (bool)$authUser->isLocked();
  1486. return $this->mLocked;
  1487. }
  1488. /**
  1489. * Check if user account is hidden
  1490. *
  1491. * @return Bool True if hidden, false otherwise
  1492. */
  1493. public function isHidden() {
  1494. if( $this->mHideName !== null ) {
  1495. return $this->mHideName;
  1496. }
  1497. $this->getBlockedStatus();
  1498. if( !$this->mHideName ) {
  1499. global $wgAuth;
  1500. $authUser = $wgAuth->getUserInstance( $this );
  1501. $this->mHideName = (bool)$authUser->isHidden();
  1502. }
  1503. return $this->mHideName;
  1504. }
  1505. /**
  1506. * Get the user's ID.
  1507. * @return Int The user's ID; 0 if the user is anonymous or nonexistent
  1508. */
  1509. public function getId() {
  1510. if( $this->mId === null && $this->mName !== null
  1511. && User::isIP( $this->mName ) ) {
  1512. // Special case, we know the user is anonymous
  1513. return 0;
  1514. } elseif( !$this->isItemLoaded( 'id' ) ) {
  1515. // Don't load if this was initialized from an ID
  1516. $this->load();
  1517. }
  1518. return $this->mId;
  1519. }
  1520. /**
  1521. * Set the user and reload all fields according to a given ID
  1522. * @param $v Int User ID to reload
  1523. */
  1524. public function setId( $v ) {
  1525. $this->mId = $v;
  1526. $this->clearInstanceCache( 'id' );
  1527. }
  1528. /**
  1529. * Get the user name, or the IP of an anonymous user
  1530. * @return String User's name or IP address
  1531. */
  1532. public function getName() {
  1533. if ( $this->isItemLoaded( 'name', 'only' ) ) {
  1534. # Special case optimisation
  1535. return $this->mName;
  1536. } else {
  1537. $this->load();
  1538. if ( $this->mName === false ) {
  1539. # Clean up IPs
  1540. $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
  1541. }
  1542. return $this->mName;
  1543. }
  1544. }
  1545. /**
  1546. * Set the user name.
  1547. *
  1548. * This does not reload fields from the database according to the given
  1549. * name. Rather, it is used to create a temporary "nonexistent user" for
  1550. * later addition to the database. It can also be used to set the IP
  1551. * address for an anonymous user to something other than the current
  1552. * remote IP.
  1553. *
  1554. * @note User::newFromName() has rougly the same function, when the named user
  1555. * does not exist.
  1556. * @param $str String New user name to set
  1557. */
  1558. public function setName( $str ) {
  1559. $this->load();
  1560. $this->mName = $str;
  1561. }
  1562. /**
  1563. * Get the user's name escaped by underscores.
  1564. * @return String Username escaped by underscores.
  1565. */
  1566. public function getTitleKey() {
  1567. return str_replace( ' ', '_', $this->getName() );
  1568. }
  1569. /**
  1570. * Check if the user has new messages.
  1571. * @return Bool True if the user has new messages
  1572. */
  1573. public function getNewtalk() {
  1574. $this->load();
  1575. # Load the newtalk status if it is unloaded (mNewtalk=-1)
  1576. if( $this->mNewtalk === -1 ) {
  1577. $this->mNewtalk = false; # reset talk page status
  1578. # Check memcached separately for anons, who have no
  1579. # entire User object stored in there.
  1580. if( !$this->mId ) {
  1581. global $wgMemc;
  1582. $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
  1583. $newtalk = $wgMemc->get( $key );
  1584. if( strval( $newtalk ) !== '' ) {
  1585. $this->mNewtalk = (bool)$newtalk;
  1586. } else {
  1587. // Since we are caching this, make sure it is…

Large files files are truncated, but you can click here to view the full file