PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/package/app/html5/html5lib/v1.5.9a/tests/selenium_framework/includes/User.php

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

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