PageRenderTime 71ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/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

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. * 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 $wgDi

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