PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 ) );
  1619. }
  1620. }
  1621. if( !$wgAuth->setPassword( $this, $str ) ) {
  1622. throw new PasswordError( wfMsg( 'externaldberror' ) );
  1623. }
  1624. $this->setInternalPassword( $str );
  1625. return true;
  1626. }
  1627. /**
  1628. * Set the password and reset the random token unconditionally.
  1629. *
  1630. * @param $str String New password to set
  1631. */
  1632. function setInternalPassword( $str ) {
  1633. $this->load();
  1634. $this->setToken();
  1635. if( $str === null ) {
  1636. // Save an invalid hash...
  1637. $this->mPassword = '';
  1638. } else {
  1639. $this->mPassword = self::crypt( $str );
  1640. }
  1641. $this->mNewpassword = '';
  1642. $this->mNewpassTime = null;
  1643. }
  1644. /**
  1645. * Get the user's current token.
  1646. * @return String Token
  1647. */
  1648. function getToken() {
  1649. $this->load();
  1650. return $this->mToken;
  1651. }
  1652. /**
  1653. * Set the random token (used for persistent authentication)
  1654. * Called from loadDefaults() among other places.
  1655. *
  1656. * @param $token String If specified, set the token to this value
  1657. * @private
  1658. */
  1659. function setToken( $token = false ) {
  1660. global $wgSecretKey, $wgProxyKey;
  1661. $this->load();
  1662. if ( !$token ) {
  1663. if ( $wgSecretKey ) {
  1664. $key = $wgSecretKey;
  1665. } elseif ( $wgProxyKey ) {
  1666. $key = $wgProxyKey;
  1667. } else {
  1668. $key = microtime();
  1669. }
  1670. $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
  1671. } else {
  1672. $this->mToken = $token;
  1673. }
  1674. }
  1675. /**
  1676. * Set the cookie password
  1677. *
  1678. * @param $str String New cookie password
  1679. * @private
  1680. */
  1681. function setCookiePassword( $str ) {
  1682. $this->load();
  1683. $this->mCookiePassword = md5( $str );
  1684. }
  1685. /**
  1686. * Set the password for a password reminder or new account email
  1687. *
  1688. * @param $str String New password to set
  1689. * @param $throttle Bool If true, reset the throttle timestamp to the present
  1690. */
  1691. function setNewpassword( $str, $throttle = true ) {
  1692. $this->load();
  1693. $this->mNewpassword = self::crypt( $str );
  1694. if ( $throttle ) {
  1695. $this->mNewpassTime = wfTimestampNow();
  1696. }
  1697. }
  1698. /**
  1699. * Has password reminder email been sent within the last
  1700. * $wgPasswordReminderResendTime hours?
  1701. * @return Bool
  1702. */
  1703. function isPasswordReminderThrottled() {
  1704. global $wgPasswordReminderResendTime;
  1705. $this->load();
  1706. if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
  1707. return false;
  1708. }
  1709. $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
  1710. return time() < $expiry;
  1711. }
  1712. /**
  1713. * Get the user's e-mail address
  1714. * @return String User's email address
  1715. */
  1716. function getEmail() {
  1717. $this->load();
  1718. wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
  1719. return $this->mEmail;
  1720. }
  1721. /**
  1722. * Get the timestamp of the user's e-mail authentication
  1723. * @return String TS_MW timestamp
  1724. */
  1725. function getEmailAuthenticationTimestamp() {
  1726. $this->load();
  1727. wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
  1728. return $this->mEmailAuthenticated;
  1729. }
  1730. /**
  1731. * Set the user's e-mail address
  1732. * @param $str String New e-mail address
  1733. */
  1734. function setEmail( $str ) {
  1735. $this->load();
  1736. $this->mEmail = $str;
  1737. wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
  1738. }
  1739. /**
  1740. * Get the user's real name
  1741. * @return String User's real name
  1742. */
  1743. function getRealName() {
  1744. $this->load();
  1745. return $this->mRealName;
  1746. }
  1747. /**
  1748. * Set the user's real name
  1749. * @param $str String New real name
  1750. */
  1751. function setRealName( $str ) {
  1752. $this->load();
  1753. $this->mRealName = $str;
  1754. }
  1755. /**
  1756. * Get the user's current setting for a given option.
  1757. *
  1758. * @param $oname String The option to check
  1759. * @param $defaultOverride String A default value returned if the option does not exist
  1760. * @return String User's current value for the option
  1761. * @see getBoolOption()
  1762. * @see getIntOption()
  1763. */
  1764. function getOption( $oname, $defaultOverride = null ) {
  1765. $this->loadOptions();
  1766. if ( is_null( $this->mOptions ) ) {
  1767. if($defaultOverride != '') {
  1768. return $defaultOverride;
  1769. }
  1770. $this->mOptions = User::getDefaultOptions();
  1771. }
  1772. if ( array_key_exists( $oname, $this->mOptions ) ) {
  1773. return $this->mOptions[$oname];
  1774. } else {
  1775. return $defaultOverride;
  1776. }
  1777. }
  1778. /**
  1779. * Get all user's options
  1780. *
  1781. * @return array
  1782. */
  1783. public function getOptions() {
  1784. $this->loadOptions();
  1785. return $this->mOptions;
  1786. }
  1787. /**
  1788. * Get the user's current setting for a given option, as a boolean value.
  1789. *
  1790. * @param $oname String The option to check
  1791. * @return Bool User's current value for the option
  1792. * @see getOption()
  1793. */
  1794. function getBoolOption( $oname ) {
  1795. return (bool)$this->getOption( $oname );
  1796. }
  1797. /**
  1798. * Get the user's current setting for a given option, as a boolean value.
  1799. *
  1800. * @param $oname String The option to check
  1801. * @param $defaultOverride Int A default value returned if the option does not exist
  1802. * @return Int User's current value for the option
  1803. * @see getOption()
  1804. */
  1805. function getIntOption( $oname, $defaultOverride=0 ) {
  1806. $val = $this->getOption( $oname );
  1807. if( $val == '' ) {
  1808. $val = $defaultOverride;
  1809. }
  1810. return intval( $val );
  1811. }
  1812. /**
  1813. * Set the given option for a user.
  1814. *
  1815. * @param $oname String The option to set
  1816. * @param $val mixed New value to set
  1817. */
  1818. function setOption( $oname, $val ) {
  1819. $this->load();
  1820. $this->loadOptions();
  1821. if ( $oname == 'skin' ) {
  1822. # Clear cached skin, so the new one displays immediately in Special:Preferences
  1823. $this->mSkin = null;
  1824. }
  1825. // Explicitly NULL values should refer to defaults
  1826. global $wgDefaultUserOptions;
  1827. if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
  1828. $val = $wgDefaultUserOptions[$oname];
  1829. }
  1830. $this->mOptions[$oname] = $val;
  1831. }
  1832. /**
  1833. * Reset all options to the site defaults
  1834. */
  1835. function resetOptions() {
  1836. $this->mOptions = User::getDefaultOptions();
  1837. }
  1838. /**
  1839. * Get the user's preferred date format.
  1840. * @return String User's preferred date format
  1841. */
  1842. function getDatePreference() {
  1843. // Important migration for old data rows
  1844. if ( is_null( $this->mDatePreference ) ) {
  1845. global $wgLang;
  1846. $value = $this->getOption( 'date' );
  1847. $map = $wgLang->getDatePreferenceMigrationMap();
  1848. if ( isset( $map[$value] ) ) {
  1849. $value = $map[$value];
  1850. }
  1851. $this->mDatePreference = $value;
  1852. }
  1853. return $this->mDatePreference;
  1854. }
  1855. /**
  1856. * Get the user preferred stub threshold
  1857. */
  1858. function getStubThreshold() {
  1859. global $wgMaxArticleSize; # Maximum article size, in Kb
  1860. $threshold = intval( $this->getOption( 'stubthreshold' ) );
  1861. if ( $threshold > $wgMaxArticleSize * 1024 ) {
  1862. # If they have set an impossible value, disable the preference
  1863. # so we can use the parser cache again.
  1864. $threshold = 0;
  1865. }
  1866. return $threshold;
  1867. }
  1868. /**
  1869. * Get the permissions this user has.
  1870. * @return Array of String permission names
  1871. */
  1872. function getRights() {
  1873. if ( is_null( $this->mRights ) ) {
  1874. $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
  1875. wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
  1876. // Force reindexation of rights when a hook has unset one of them
  1877. $this->mRights = array_values( $this->mRights );
  1878. }
  1879. return $this->mRights;
  1880. }
  1881. /**
  1882. * Get the list of explicit group memberships this user has.
  1883. * The implicit * and user groups are not included.
  1884. * @return Array of String internal group names
  1885. */
  1886. function getGroups() {
  1887. $this->load();
  1888. return $this->mGroups;
  1889. }
  1890. /**
  1891. * Get the list of implicit group memberships this user has.
  1892. * This includes all explicit groups, plus 'user' if logged in,
  1893. * '*' for all accounts, and autopromoted groups
  1894. * @param $recache Bool Whether to avoid the cache
  1895. * @return Array of String internal group names
  1896. */
  1897. function getEffectiveGroups( $recache = false ) {
  1898. if ( $recache || is_null( $this->mEffectiveGroups ) ) {
  1899. wfProfileIn( __METHOD__ );
  1900. $this->mEffectiveGroups = $this->getGroups();
  1901. $this->mEffectiveGroups[] = '*';
  1902. if( $this->getId() ) {
  1903. $this->mEffectiveGroups[] = 'user';
  1904. $this->mEffectiveGroups = array_unique( array_merge(
  1905. $this->mEffectiveGroups,
  1906. Autopromote::getAutopromoteGroups( $this )
  1907. ) );
  1908. # Hook for additional groups
  1909. wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
  1910. }
  1911. wfProfileOut( __METHOD__ );
  1912. }
  1913. return $this->mEffectiveGroups;
  1914. }
  1915. /**
  1916. * Get the user's edit count.
  1917. * @return Int
  1918. */
  1919. function getEditCount() {
  1920. if( $this->getId() ) {
  1921. if ( !isset( $this->mEditCount ) ) {
  1922. /* Populate the count, if it has not been populated yet */
  1923. $this->mEditCount = User::edits( $this->mId );
  1924. }
  1925. return $this->mEditCount;
  1926. } else {
  1927. /* nil */
  1928. return null;
  1929. }
  1930. }
  1931. /**
  1932. * Add the user to the given group.
  1933. * This takes immediate effect.
  1934. * @param $group String Name of the group to add
  1935. */
  1936. function addGroup( $group ) {
  1937. $dbw = wfGetDB( DB_MASTER );
  1938. if( $this->getId() ) {
  1939. $dbw->insert( 'user_groups',
  1940. array(
  1941. 'ug_user' => $this->getID(),
  1942. 'ug_group' => $group,
  1943. ),
  1944. __METHOD__,
  1945. array( 'IGNORE' ) );
  1946. }
  1947. $this->loadGroups();
  1948. $this->mGroups[] = $group;
  1949. $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
  1950. $this->invalidateCache();
  1951. }
  1952. /**
  1953. * Remove the user from the given group.
  1954. * This takes immediate effect.
  1955. * @param $group String Name of the group to remove
  1956. */
  1957. function removeGroup( $group ) {
  1958. $this->load();
  1959. $dbw = wfGetDB( DB_MASTER );
  1960. $dbw->delete( 'user_groups',
  1961. array(
  1962. 'ug_user' => $this->getID(),
  1963. 'ug_group' => $group,
  1964. ), __METHOD__ );
  1965. $this->loadGroups();
  1966. $this->mGroups = array_diff( $this->mGroups, array( $group ) );
  1967. $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
  1968. $this->invalidateCache();
  1969. }
  1970. /**
  1971. * Get whether the user is logged in
  1972. * @return Bool
  1973. */
  1974. function isLoggedIn() {
  1975. return $this->getID() != 0;
  1976. }
  1977. /**
  1978. * Get whether the user is anonymous
  1979. * @return Bool
  1980. */
  1981. function isAnon() {
  1982. return !$this->isLoggedIn();
  1983. }
  1984. /**
  1985. * Check if user is allowed to access a feature / make an action
  1986. * @param $action String action to be checked
  1987. * @return Boolean: True if action is allowed, else false
  1988. */
  1989. function isAllowed( $action = '' ) {
  1990. if ( $action === '' ) {
  1991. return true; // In the spirit of DWIM
  1992. }
  1993. # Patrolling may not be enabled
  1994. if( $action === 'patrol' || $action === 'autopatrol' ) {
  1995. global $wgUseRCPatrol, $wgUseNPPatrol;
  1996. if( !$wgUseRCPatrol && !$wgUseNPPatrol )
  1997. return false;
  1998. }
  1999. # Use strict parameter to avoid matching numeric 0 accidentally inserted
  2000. # by misconfiguration: 0 == 'foo'
  2001. return in_array( $action, $this->getRights(), true );
  2002. }
  2003. /**
  2004. * Check whether to enable recent changes patrol features for this user
  2005. * @return Boolean: True or false
  2006. */
  2007. public function useRCPatrol() {
  2008. global $wgUseRCPatrol;
  2009. return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
  2010. }
  2011. /**
  2012. * Check whether to enable new pages patrol features for this user
  2013. * @return Bool True or false
  2014. */
  2015. public function useNPPatrol() {
  2016. global $wgUseRCPatrol, $wgUseNPPatrol;
  2017. return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
  2018. }
  2019. /**
  2020. * Get the current skin, loading it if required, and setting a title
  2021. * @param $t Title: the title to use in the skin
  2022. * @return Skin The current skin
  2023. * @todo: FIXME : need to check the old failback system [AV]
  2024. */
  2025. function getSkin( $t = null ) {
  2026. if ( $t ) {
  2027. $skin = $this->createSkinObject();
  2028. $skin->setTitle( $t );
  2029. return $skin;
  2030. } else {
  2031. if ( !$this->mSkin ) {
  2032. $this->mSkin = $this->createSkinObject();
  2033. }
  2034. if ( !$this->mSkin->getTitle() ) {
  2035. global $wgOut;
  2036. $t = $wgOut->getTitle();
  2037. $this->mSkin->setTitle($t);
  2038. }
  2039. return $this->mSkin;
  2040. }
  2041. }
  2042. // Creates a Skin object, for getSkin()
  2043. private function createSkinObject() {
  2044. wfProfileIn( __METHOD__ );
  2045. global $wgHiddenPrefs;
  2046. if( !in_array( 'skin', $wgHiddenPrefs ) ) {
  2047. global $wgRequest;
  2048. # get the user skin
  2049. $userSkin = $this->getOption( 'skin' );
  2050. $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
  2051. } else {
  2052. # if we're not allowing users to override, then use the default
  2053. global $wgDefaultSkin;
  2054. $userSkin = $wgDefaultSkin;
  2055. }
  2056. $skin = Skin::newFromKey( $userSkin );
  2057. wfProfileOut( __METHOD__ );
  2058. return $skin;
  2059. }
  2060. /**
  2061. * Check the watched status of an article.
  2062. * @param $title Title of the article to look at
  2063. * @return Bool
  2064. */
  2065. function isWatched( $title ) {
  2066. $wl = WatchedItem::fromUserTitle( $this, $title );
  2067. return $wl->isWatched();
  2068. }
  2069. /**
  2070. * Watch an article.
  2071. * @param $title Title of the article to look at
  2072. */
  2073. function addWatch( $title ) {
  2074. $wl = WatchedItem::fromUserTitle( $this, $title );
  2075. $wl->addWatch();
  2076. $this->invalidateCache();
  2077. }
  2078. /**
  2079. * Stop watching an article.
  2080. * @param $title Title of the article to look at
  2081. */
  2082. function removeWatch( $title ) {
  2083. $wl = WatchedItem::fromUserTitle( $this, $title );
  2084. $wl->removeWatch();
  2085. $this->invalidateCache();
  2086. }
  2087. /**
  2088. * Clear the user's notification timestamp for the given title.
  2089. * If e-notif e-mails are on, they will receive notification mails on
  2090. * the next change of the page if it's watched etc.
  2091. * @param $title Title of the article to look at
  2092. */
  2093. function clearNotification( &$title ) {
  2094. global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
  2095. # Do nothing if the database is locked to writes
  2096. if( wfReadOnly() ) {
  2097. return;
  2098. }
  2099. if( $title->getNamespace() == NS_USER_TALK &&
  2100. $title->getText() == $this->getName() ) {
  2101. if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
  2102. return;
  2103. $this->setNewtalk( false );
  2104. }
  2105. if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
  2106. return;
  2107. }
  2108. if( $this->isAnon() ) {
  2109. // Nothing else to do...
  2110. return;
  2111. }
  2112. // Only update the timestamp if the page is being watched.
  2113. // The query to find out if it is watched is cached both in memcached and per-invocation,
  2114. // and when it does have to be executed, it can be on a slave
  2115. // If this is the user's newtalk page, we always update the timestamp
  2116. if( $title->getNamespace() == NS_USER_TALK &&
  2117. $title->getText() == $wgUser->getName() )
  2118. {
  2119. $watched = true;
  2120. } elseif ( $this->getId() == $wgUser->getId() ) {
  2121. $watched = $title->userIsWatching();
  2122. } else {
  2123. $watched = true;
  2124. }
  2125. // If the page is watched by the user (or may be watched), update the timestamp on any
  2126. // any matching rows
  2127. if ( $watched ) {
  2128. $dbw = wfGetDB( DB_MASTER );
  2129. $dbw->update( 'watchlist',
  2130. array( /* SET */
  2131. 'wl_notificationtimestamp' => null
  2132. ), array( /* WHERE */
  2133. 'wl_title' => $title->getDBkey(),
  2134. 'wl_namespace' => $title->getNamespace(),
  2135. 'wl_user' => $this->getID()
  2136. ), __METHOD__
  2137. );
  2138. }
  2139. }
  2140. /**
  2141. * Resets all of the given user's page-change notification timestamps.
  2142. * If e-notif e-mails are on, they will receive notification mails on
  2143. * the next change of any watched page.
  2144. *
  2145. * @param $currentUser Int User ID
  2146. */
  2147. function clearAllNotifications( $currentUser ) {
  2148. global $wgUseEnotif, $wgShowUpdatedMarker;
  2149. if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
  2150. $this->setNewtalk( false );
  2151. return;
  2152. }
  2153. if( $currentUser != 0 ) {
  2154. $dbw = wfGetDB( DB_MASTER );
  2155. $dbw->update( 'watchlist',
  2156. array( /* SET */
  2157. 'wl_notificationtimestamp' => null
  2158. ), array( /* WHERE */
  2159. 'wl_user' => $currentUser
  2160. ), __METHOD__
  2161. );
  2162. # We also need to clear here the "you have new message" notification for the own user_talk page
  2163. # This is cleared one page view later in Article::viewUpdates();
  2164. }
  2165. }
  2166. /**
  2167. * Set this user's options from an encoded string
  2168. * @param $str String Encoded options to import
  2169. * @private
  2170. */
  2171. function decodeOptions( $str ) {
  2172. if( !$str )
  2173. return;
  2174. $this->mOptionsLoaded = true;
  2175. $this->mOptionOverrides = array();
  2176. // If an option is not set in $str, use the default value
  2177. $this->mOptions = self::getDefaultOptions();
  2178. $a = explode( "\n", $str );
  2179. foreach ( $a as $s ) {
  2180. $m = array();
  2181. if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
  2182. $this->mOptions[$m[1]] = $m[2];
  2183. $this->mOptionOverrides[$m[1]] = $m[2];
  2184. }
  2185. }
  2186. }
  2187. /**
  2188. * Set a cookie on the user's client. Wrapper for
  2189. * WebResponse::setCookie
  2190. * @param $name String Name of the cookie to set
  2191. * @param $value String Value to set
  2192. * @param $exp Int Expiration time, as a UNIX time value;
  2193. * if 0 or not specified, use the default $wgCookieExpiration
  2194. */
  2195. protected function setCookie( $name, $value, $exp = 0 ) {
  2196. global $wgRequest;
  2197. $wgRequest->response()->setcookie( $name, $value, $exp );
  2198. }
  2199. /**
  2200. * Clear a cookie on the user's client
  2201. * @param $name String Name of the cookie to clear
  2202. */
  2203. protected function clearCookie( $name ) {
  2204. $this->setCookie( $name, '', time() - 86400 );
  2205. }
  2206. /**
  2207. * Set the default cookies for this session on the user's client.
  2208. */
  2209. function setCookies() {
  2210. $this->load();
  2211. if ( 0 == $this->mId ) return;
  2212. $session = array(
  2213. 'wsUserID' => $this->mId,
  2214. 'wsToken' => $this->mToken,
  2215. 'wsUserName' => $this->getName()
  2216. );
  2217. $cookies = array(
  2218. 'UserID' => $this->mId,
  2219. 'UserName' => $this->getName(),
  2220. );
  2221. if ( 1 == $this->getOption( 'rememberpassword' ) ) {
  2222. $cookies['Token'] = $this->mToken;
  2223. } else {
  2224. $cookies['Token'] = false;
  2225. }
  2226. wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
  2227. #check for null, since the hook could cause a null value
  2228. if ( !is_null( $session ) && isset( $_SESSION ) ){
  2229. $_SESSION = $session + $_SESSION;
  2230. }
  2231. foreach ( $cookies as $name => $value ) {
  2232. if ( $value === false ) {
  2233. $this->clearCookie( $name );
  2234. } else {
  2235. $this->setCookie( $name, $value );
  2236. }
  2237. }
  2238. }
  2239. /**
  2240. * Log this user out.
  2241. */
  2242. function logout() {
  2243. if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
  2244. $this->doLogout();
  2245. }
  2246. }
  2247. /**
  2248. * Clear the user's cookies and session, and reset the instance cache.
  2249. * @private
  2250. * @see logout()
  2251. */
  2252. function doLogout() {
  2253. $this->clearInstanceCache( 'defaults' );
  2254. $_SESSION['wsUserID'] = 0;
  2255. $this->clearCookie( 'UserID' );
  2256. $this->clearCookie( 'Token' );
  2257. # Remember when user logged out, to prevent seeing cached pages
  2258. $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
  2259. }
  2260. /**
  2261. * Save this user's settings into the database.
  2262. * @todo Only rarely do all these fields need to be set!
  2263. */
  2264. function saveSettings() {
  2265. $this->load();
  2266. if ( wfReadOnly() ) { return; }
  2267. if ( 0 == $this->mId ) { return; }
  2268. $this->mTouched = self::newTouchedTimestamp();
  2269. $dbw = wfGetDB( DB_MASTER );
  2270. $dbw->update( 'user',
  2271. array( /* SET */
  2272. 'user_name' => $this->mName,
  2273. 'user_password' => $this->mPassword,
  2274. 'user_newpassword' => $this->mNewpassword,
  2275. 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
  2276. 'user_real_name' => $this->mRealName,
  2277. 'user_email' => $this->mEmail,
  2278. 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
  2279. 'user_options' => '',
  2280. 'user_touched' => $dbw->timestamp( $this->mTouched ),
  2281. 'user_token' => $this->mToken,
  2282. 'user_email_token' => $this->mEmailToken,
  2283. 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
  2284. ), array( /* WHERE */
  2285. 'user_id' => $this->mId
  2286. ), __METHOD__
  2287. );
  2288. $this->saveOptions();
  2289. wfRunHooks( 'UserSaveSettings', array( $this ) );
  2290. $this->clearSharedCache();
  2291. $this->getUserPage()->invalidateCache();
  2292. }
  2293. /**
  2294. * If only this user's username is known, and it exists, return the user ID.
  2295. * @return Int
  2296. */
  2297. function idForName() {
  2298. $s = trim( $this->getName() );
  2299. if ( $s === '' ) return 0;
  2300. $dbr = wfGetDB( DB_SLAVE );
  2301. $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
  2302. if ( $id === false ) {
  2303. $id = 0;
  2304. }
  2305. return $id;
  2306. }
  2307. /**
  2308. * Add a user to the database, return the user object
  2309. *
  2310. * @param $name String Username to add
  2311. * @param $params Array of Strings Non-default parameters to save to the database:
  2312. * - password The user's password. Password logins will be disabled if this is omitted.
  2313. * - newpassword A temporary password mailed to the user
  2314. * - email The user's email address
  2315. * - email_authenticated The email authentication timestamp
  2316. * - real_name The user's real name
  2317. * - options An associative array of non-default options
  2318. * - token Random authentication token. Do not set.
  2319. * - registration Registration timestamp. Do not set.
  2320. *
  2321. * @return User object, or null if the username already exists
  2322. */
  2323. static function createNew( $name, $params = array() ) {
  2324. $user = new User;
  2325. $user->load();
  2326. if ( isset( $params['options'] ) ) {
  2327. $user->mOptions = $params['options'] + (array)$user->mOptions;
  2328. unset( $params['options'] );
  2329. }
  2330. $dbw = wfGetDB( DB_MASTER );
  2331. $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
  2332. $fields = array(
  2333. 'user_id' => $seqVal,
  2334. 'user_name' => $name,
  2335. 'user_password' => $user->mPassword,
  2336. 'user_newpassword' => $user->mNewpassword,
  2337. 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
  2338. 'user_email' => $user->mEmail,
  2339. 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
  2340. 'user_real_name' => $user->mRealName,
  2341. 'user_options' => '',
  2342. 'user_token' => $user->mToken,
  2343. 'user_registration' => $dbw->timestamp( $user->mRegistration ),
  2344. 'user_editcount' => 0,
  2345. );
  2346. foreach ( $params as $name => $value ) {
  2347. $fields["user_$name"] = $value;
  2348. }
  2349. $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
  2350. if ( $dbw->affectedRows() ) {
  2351. $newUser = User::newFromId( $dbw->insertId() );
  2352. } else {
  2353. $newUser = null;
  2354. }
  2355. return $newUser;
  2356. }
  2357. /**
  2358. * Add this existing user object to the database
  2359. */
  2360. function addToDatabase() {
  2361. $this->load();
  2362. $dbw = wfGetDB( DB_MASTER );
  2363. $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
  2364. $dbw->insert( 'user',
  2365. array(
  2366. 'user_id' => $seqVal,
  2367. 'user_name' => $this->mName,
  2368. 'user_password' => $this->mPassword,
  2369. 'user_newpassword' => $this->mNewpassword,
  2370. 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
  2371. 'user_email' => $this->mEmail,
  2372. 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
  2373. 'user_real_name' => $this->mRealName,
  2374. 'user_options' => '',
  2375. 'user_token' => $this->mToken,
  2376. 'user_registration' => $dbw->timestamp( $this->mRegistration ),
  2377. 'user_editcount' => 0,
  2378. ), __METHOD__
  2379. );
  2380. $this->mId = $dbw->insertId();
  2381. // Clear instance cache other than user table data, which is already accurate
  2382. $this->clearInstanceCache();
  2383. $this->saveOptions();
  2384. }
  2385. /**
  2386. * If this (non-anonymous) user is blocked, block any IP address
  2387. * they've successfully logged in from.
  2388. */
  2389. function spreadBlock() {
  2390. wfDebug( __METHOD__ . "()\n" );
  2391. $this->load();
  2392. if ( $this->mId == 0 ) {
  2393. return;
  2394. }
  2395. $userblock = Block::newFromDB( '', $this->mId );
  2396. if ( !$userblock ) {
  2397. return;
  2398. }
  2399. $userblock->doAutoblock( wfGetIP() );
  2400. }
  2401. /**
  2402. * Generate a string which will be different for any combination of
  2403. * user options which would produce different parser output.
  2404. * This will be used as part of the hash key for the parser cache,
  2405. * so users with the same options can share the same cached data
  2406. * safely.
  2407. *
  2408. * Extensions which require it should install 'PageRenderingHash' hook,
  2409. * which will give them a chance to modify this key based on their own
  2410. * settings.
  2411. *
  2412. * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
  2413. * @return String Page rendering hash
  2414. */
  2415. function getPageRenderingHash() {
  2416. global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
  2417. if( $this->mHash ){
  2418. return $this->mHash;
  2419. }
  2420. wfDeprecated( __METHOD__ );
  2421. // stubthreshold is only included below for completeness,
  2422. // since it disables the parser cache, its value will always
  2423. // be 0 when this function is called by parsercache.
  2424. $confstr = $this->getOption( 'math' );
  2425. $confstr .= '!' . $this->getStubThreshold();
  2426. if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
  2427. $confstr .= '!' . $this->getDatePreference();
  2428. }
  2429. $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
  2430. $confstr .= '!' . $wgLang->getCode();
  2431. $confstr .= '!' . $this->getOption( 'thumbsize' );
  2432. // add in language specific options, if any
  2433. $extra = $wgContLang->getExtraHashOptions();
  2434. $confstr .= $extra;
  2435. // Since the skin could be overloading link(), it should be
  2436. // included here but in practice, none of our skins do that.
  2437. $confstr .= $wgRenderHashAppend;
  2438. // Give a chance for extensions to modify the hash, if they have
  2439. // extra options or other effects on the parser cache.
  2440. wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
  2441. // Make it a valid memcached key fragment
  2442. $confstr = str_replace( ' ', '_', $confstr );
  2443. $this->mHash = $confstr;
  2444. return $confstr;
  2445. }
  2446. /**
  2447. * Get whether the user is explicitly blocked from account creation.
  2448. * @return Bool
  2449. */
  2450. function isBlockedFromCreateAccount() {
  2451. $this->getBlockedStatus();
  2452. return $this->mBlock && $this->mBlock->mCreateAccount;
  2453. }
  2454. /**
  2455. * Get whether the user is blocked from using Special:Emailuser.
  2456. * @return Bool
  2457. */
  2458. function isBlockedFromEmailuser() {
  2459. $this->getBlockedStatus();
  2460. return $this->mBlock && $this->mBlock->mBlockEmail;
  2461. }
  2462. /**
  2463. * Get whether the user is allowed to create an account.
  2464. * @return Bool
  2465. */
  2466. function isAllowedToCreateAccount() {
  2467. return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
  2468. }
  2469. /**
  2470. * Get this user's personal page title.
  2471. *
  2472. * @return Title: User's personal page title
  2473. */
  2474. function getUserPage() {
  2475. return Title::makeTitle( NS_USER, $this->getName() );
  2476. }
  2477. /**
  2478. * Get this user's talk page title.
  2479. *
  2480. * @return Title: User's talk page title
  2481. */
  2482. function getTalkPage() {
  2483. $title = $this->getUserPage();
  2484. return $title->getTalkPage();
  2485. }
  2486. /**
  2487. * Get the maximum valid user ID.
  2488. * @return Integer: User ID
  2489. * @static
  2490. */
  2491. function getMaxID() {
  2492. static $res; // cache
  2493. if ( isset( $res ) ) {
  2494. return $res;
  2495. } else {
  2496. $dbr = wfGetDB( DB_SLAVE );
  2497. return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
  2498. }
  2499. }
  2500. /**
  2501. * Determine whether the user is a newbie. Newbies are either
  2502. * anonymous IPs, or the most recently created accounts.
  2503. * @return Bool
  2504. */
  2505. function isNewbie() {
  2506. return !$this->isAllowed( 'autoconfirmed' );
  2507. }
  2508. /**
  2509. * Check to see if the given clear-text password is one of the accepted passwords
  2510. * @param $password String: user password.
  2511. * @return Boolean: True if the given password is correct, otherwise False.
  2512. */
  2513. function checkPassword( $password ) {
  2514. global $wgAuth;
  2515. $this->load();
  2516. // Even though we stop people from creating passwords that
  2517. // are shorter than this, doesn't mean people wont be able
  2518. // to. Certain authentication plugins do NOT want to save
  2519. // domain passwords in a mysql database, so we should
  2520. // check this (in case $wgAuth->strict() is false).
  2521. if( !$this->isValidPassword( $password ) ) {
  2522. return false;
  2523. }
  2524. if( $wgAuth->authenticate( $this->getName(), $password ) ) {
  2525. return true;
  2526. } elseif( $wgAuth->strict() ) {
  2527. /* Auth plugin doesn't allow local authentication */
  2528. return false;
  2529. } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
  2530. /* Auth plugin doesn't allow local authentication for this user name */
  2531. return false;
  2532. }
  2533. if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
  2534. return true;
  2535. } elseif ( function_exists( 'iconv' ) ) {
  2536. # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
  2537. # Check for this with iconv
  2538. $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
  2539. if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
  2540. return true;
  2541. }
  2542. }
  2543. return false;
  2544. }
  2545. /**
  2546. * Check if the given clear-text password matches the temporary password
  2547. * sent by e-mail for password reset operations.
  2548. * @return Boolean: True if matches, false otherwise
  2549. */
  2550. function checkTemporaryPassword( $plaintext ) {
  2551. global $wgNewPasswordExpiry;
  2552. if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
  2553. if ( is_null( $this->mNewpassTime ) ) {
  2554. return true;
  2555. }
  2556. $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
  2557. return ( time() < $expiry );
  2558. } else {
  2559. return false;
  2560. }
  2561. }
  2562. /**
  2563. * Initialize (if necessary) and return a session token value
  2564. * which can be used in edit forms to show that the user's
  2565. * login credentials aren't being hijacked with a foreign form
  2566. * submission.
  2567. *
  2568. * @param $salt String|Array of Strings Optional function-specific data for hashing
  2569. * @return String The new edit token
  2570. */
  2571. function editToken( $salt = '' ) {
  2572. if ( $this->isAnon() ) {
  2573. return EDIT_TOKEN_SUFFIX;
  2574. } else {
  2575. if( !isset( $_SESSION['wsEditToken'] ) ) {
  2576. $token = self::generateToken();
  2577. $_SESSION['wsEditToken'] = $token;
  2578. } else {
  2579. $token = $_SESSION['wsEditToken'];
  2580. }
  2581. if( is_array( $salt ) ) {
  2582. $salt = implode( '|', $salt );
  2583. }
  2584. return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
  2585. }
  2586. }
  2587. /**
  2588. * Generate a looking random token for various uses.
  2589. *
  2590. * @param $salt String Optional salt value
  2591. * @return String The new random token
  2592. */
  2593. public static function generateToken( $salt = '' ) {
  2594. $token = dechex( mt_rand() ) . dechex( mt_rand() );
  2595. return md5( $token . $salt );
  2596. }
  2597. /**
  2598. * Check given value against the token value stored in the session.
  2599. * A match should confirm that the form was submitted from the
  2600. * user's own login session, not a form submission from a third-party
  2601. * site.
  2602. *
  2603. * @param $val String Input value to compare
  2604. * @param $salt String Optional function-specific data for hashing
  2605. * @return Boolean: Whether the token matches
  2606. */
  2607. function matchEditToken( $val, $salt = '' ) {
  2608. $sessionToken = $this->editToken( $salt );
  2609. if ( $val != $sessionToken ) {
  2610. wfDebug( "User::matchEditToken: broken session data\n" );
  2611. }
  2612. return $val == $sessionToken;
  2613. }
  2614. /**
  2615. * Check given value against the token value stored in the session,
  2616. * ignoring the suffix.
  2617. *
  2618. * @param $val String Input value to compare
  2619. * @param $salt String Optional function-specific data for hashing
  2620. * @return Boolean: Whether the token matches
  2621. */
  2622. function matchEditTokenNoSuffix( $val, $salt = '' ) {
  2623. $sessionToken = $this->editToken( $salt );
  2624. return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
  2625. }
  2626. /**
  2627. * Generate a new e-mail confirmation token and send a confirmation/invalidation
  2628. * mail to the user's given address.
  2629. *
  2630. * @param $type String: message to send, either "created", "changed" or "set"
  2631. * @return Status object
  2632. */
  2633. function sendConfirmationMail( $type = 'created' ) {
  2634. global $wgLang;
  2635. $expiration = null; // gets passed-by-ref and defined in next line.
  2636. $token = $this->confirmationToken( $expiration );
  2637. $url = $this->confirmationTokenUrl( $token );
  2638. $invalidateURL = $this->invalidationTokenUrl( $token );
  2639. $this->saveSettings();
  2640. if ( $type == 'created' || $type === false ) {
  2641. $message = 'confirmemail_body';
  2642. } elseif ( $type === true ) {
  2643. $message = 'confirmemail_body_changed';
  2644. } else {
  2645. $message = 'confirmemail_body_' . $type;
  2646. }
  2647. return $this->sendMail( wfMsg( 'confirmemail_subject' ),
  2648. wfMsg( $message,
  2649. wfGetIP(),
  2650. $this->getName(),
  2651. $url,
  2652. $wgLang->timeanddate( $expiration, false ),
  2653. $invalidateURL,
  2654. $wgLang->date( $expiration, false ),
  2655. $wgLang->time( $expiration, false ) ) );
  2656. }
  2657. /**
  2658. * Send an e-mail to this user's account. Does not check for
  2659. * confirmed status or validity.
  2660. *
  2661. * @param $subject String Message subject
  2662. * @param $body String Message body
  2663. * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
  2664. * @param $replyto String Reply-To address
  2665. * @return Status
  2666. */
  2667. function sendMail( $subject, $body, $from = null, $replyto = null ) {
  2668. if( is_null( $from ) ) {
  2669. global $wgPasswordSender, $wgPasswordSenderName;
  2670. $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
  2671. } else {
  2672. $sender = new MailAddress( $from );
  2673. }
  2674. $to = new MailAddress( $this );
  2675. return UserMailer::send( $to, $sender, $subject, $body, $replyto );
  2676. }
  2677. /**
  2678. * Generate, store, and return a new e-mail confirmation code.
  2679. * A hash (unsalted, since it's used as a key) is stored.
  2680. *
  2681. * @note Call saveSettings() after calling this function to commit
  2682. * this change to the database.
  2683. *
  2684. * @param[out] &$expiration \mixed Accepts the expiration time
  2685. * @return String New token
  2686. * @private
  2687. */
  2688. function confirmationToken( &$expiration ) {
  2689. $now = time();
  2690. $expires = $now + 7 * 24 * 60 * 60;
  2691. $expiration = wfTimestamp( TS_MW, $expires );
  2692. $token = self::generateToken( $this->mId . $this->mEmail . $expires );
  2693. $hash = md5( $token );
  2694. $this->load();
  2695. $this->mEmailToken = $hash;
  2696. $this->mEmailTokenExpires = $expiration;
  2697. return $token;
  2698. }
  2699. /**
  2700. * Return a URL the user can use to confirm their email address.
  2701. * @param $token String Accepts the email confirmation token
  2702. * @return String New token URL
  2703. * @private
  2704. */
  2705. function confirmationTokenUrl( $token ) {
  2706. return $this->getTokenUrl( 'ConfirmEmail', $token );
  2707. }
  2708. /**
  2709. * Return a URL the user can use to invalidate their email address.
  2710. * @param $token String Accepts the email confirmation token
  2711. * @return String New token URL
  2712. * @private
  2713. */
  2714. function invalidationTokenUrl( $token ) {
  2715. return $this->getTokenUrl( 'Invalidateemail', $token );
  2716. }
  2717. /**
  2718. * Internal function to format the e-mail validation/invalidation URLs.
  2719. * This uses $wgArticlePath directly as a quickie hack to use the
  2720. * hardcoded English names of the Special: pages, for ASCII safety.
  2721. *
  2722. * @note Since these URLs get dropped directly into emails, using the
  2723. * short English names avoids insanely long URL-encoded links, which
  2724. * also sometimes can get corrupted in some browsers/mailers
  2725. * (bug 6957 with Gmail and Internet Explorer).
  2726. *
  2727. * @param $page String Special page
  2728. * @param $token String Token
  2729. * @return String Formatted URL
  2730. */
  2731. protected function getTokenUrl( $page, $token ) {
  2732. global $wgArticlePath;
  2733. return wfExpandUrl(
  2734. str_replace(
  2735. '$1',
  2736. "Special:$page/$token",
  2737. $wgArticlePath ) );
  2738. }
  2739. /**
  2740. * Mark the e-mail address confirmed.
  2741. *
  2742. * @note Call saveSettings() after calling this function to commit the change.
  2743. */
  2744. function confirmEmail() {
  2745. $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
  2746. wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
  2747. return true;
  2748. }
  2749. /**
  2750. * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
  2751. * address if it was already confirmed.
  2752. *
  2753. * @note Call saveSettings() after calling this function to commit the change.
  2754. */
  2755. function invalidateEmail() {
  2756. $this->load();
  2757. $this->mEmailToken = null;
  2758. $this->mEmailTokenExpires = null;
  2759. $this->setEmailAuthenticationTimestamp( null );
  2760. wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
  2761. return true;
  2762. }
  2763. /**
  2764. * Set the e-mail authentication timestamp.
  2765. * @param $timestamp String TS_MW timestamp
  2766. */
  2767. function setEmailAuthenticationTimestamp( $timestamp ) {
  2768. $this->load();
  2769. $this->mEmailAuthenticated = $timestamp;
  2770. wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
  2771. }
  2772. /**
  2773. * Is this user allowed to send e-mails within limits of current
  2774. * site configuration?
  2775. * @return Bool
  2776. */
  2777. function canSendEmail() {
  2778. global $wgEnableEmail, $wgEnableUserEmail;
  2779. if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
  2780. return false;
  2781. }
  2782. $canSend = $this->isEmailConfirmed();
  2783. wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
  2784. return $canSend;
  2785. }
  2786. /**
  2787. * Is this user allowed to receive e-mails within limits of current
  2788. * site configuration?
  2789. * @return Bool
  2790. */
  2791. function canReceiveEmail() {
  2792. return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
  2793. }
  2794. /**
  2795. * Is this user's e-mail address valid-looking and confirmed within
  2796. * limits of the current site configuration?
  2797. *
  2798. * @note If $wgEmailAuthentication is on, this may require the user to have
  2799. * confirmed their address by returning a code or using a password
  2800. * sent to the address from the wiki.
  2801. *
  2802. * @return Bool
  2803. */
  2804. function isEmailConfirmed() {
  2805. global $wgEmailAuthentication;
  2806. $this->load();
  2807. $confirmed = true;
  2808. if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
  2809. if( $this->isAnon() )
  2810. return false;
  2811. if( !self::isValidEmailAddr( $this->mEmail ) )
  2812. return false;
  2813. if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
  2814. return false;
  2815. return true;
  2816. } else {
  2817. return $confirmed;
  2818. }
  2819. }
  2820. /**
  2821. * Check whether there is an outstanding request for e-mail confirmation.
  2822. * @return Bool
  2823. */
  2824. function isEmailConfirmationPending() {
  2825. global $wgEmailAuthentication;
  2826. return $wgEmailAuthentication &&
  2827. !$this->isEmailConfirmed() &&
  2828. $this->mEmailToken &&
  2829. $this->mEmailTokenExpires > wfTimestamp();
  2830. }
  2831. /**
  2832. * Get the timestamp of account creation.
  2833. *
  2834. * @return String|Bool Timestamp of account creation, or false for
  2835. * non-existent/anonymous user accounts.
  2836. */
  2837. public function getRegistration() {
  2838. return $this->getId() > 0
  2839. ? $this->mRegistration
  2840. : false;
  2841. }
  2842. /**
  2843. * Get the timestamp of the first edit
  2844. *
  2845. * @return String|Bool Timestamp of first edit, or false for
  2846. * non-existent/anonymous user accounts.
  2847. */
  2848. public function getFirstEditTimestamp() {
  2849. if( $this->getId() == 0 ) {
  2850. return false; // anons
  2851. }
  2852. $dbr = wfGetDB( DB_SLAVE );
  2853. $time = $dbr->selectField( 'revision', 'rev_timestamp',
  2854. array( 'rev_user' => $this->getId() ),
  2855. __METHOD__,
  2856. array( 'ORDER BY' => 'rev_timestamp ASC' )
  2857. );
  2858. if( !$time ) {
  2859. return false; // no edits
  2860. }
  2861. return wfTimestamp( TS_MW, $time );
  2862. }
  2863. /**
  2864. * Get the permissions associated with a given list of groups
  2865. *
  2866. * @param $groups Array of Strings List of internal group names
  2867. * @return Array of Strings List of permission key names for given groups combined
  2868. */
  2869. static function getGroupPermissions( $groups ) {
  2870. global $wgGroupPermissions, $wgRevokePermissions;
  2871. $rights = array();
  2872. // grant every granted permission first
  2873. foreach( $groups as $group ) {
  2874. if( isset( $wgGroupPermissions[$group] ) ) {
  2875. $rights = array_merge( $rights,
  2876. // array_filter removes empty items
  2877. array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
  2878. }
  2879. }
  2880. // now revoke the revoked permissions
  2881. foreach( $groups as $group ) {
  2882. if( isset( $wgRevokePermissions[$group] ) ) {
  2883. $rights = array_diff( $rights,
  2884. array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
  2885. }
  2886. }
  2887. return array_unique( $rights );
  2888. }
  2889. /**
  2890. * Get all the groups who have a given permission
  2891. *
  2892. * @param $role String Role to check
  2893. * @return Array of Strings List of internal group names with the given permission
  2894. */
  2895. static function getGroupsWithPermission( $role ) {
  2896. global $wgGroupPermissions;
  2897. $allowedGroups = array();
  2898. foreach ( $wgGroupPermissions as $group => $rights ) {
  2899. if ( isset( $rights[$role] ) && $rights[$role] ) {
  2900. $allowedGroups[] = $group;
  2901. }
  2902. }
  2903. return $allowedGroups;
  2904. }
  2905. /**
  2906. * Get the localized descriptive name for a group, if it exists
  2907. *
  2908. * @param $group String Internal group name
  2909. * @return String Localized descriptive group name
  2910. */
  2911. static function getGroupName( $group ) {
  2912. $msg = wfMessage( "group-$group" );
  2913. return $msg->isBlank() ? $group : $msg->text();
  2914. }
  2915. /**
  2916. * Get the localized descriptive name for a member of a group, if it exists
  2917. *
  2918. * @param $group String Internal group name
  2919. * @return String Localized name for group member
  2920. */
  2921. static function getGroupMember( $group ) {
  2922. $msg = wfMessage( "group-$group-member" );
  2923. return $msg->isBlank() ? $group : $msg->text();
  2924. }
  2925. /**
  2926. * Return the set of defined explicit groups.
  2927. * The implicit groups (by default *, 'user' and 'autoconfirmed')
  2928. * are not included, as they are defined automatically, not in the database.
  2929. * @return Array of internal group names
  2930. */
  2931. static function getAllGroups() {
  2932. global $wgGroupPermissions, $wgRevokePermissions;
  2933. return array_diff(
  2934. array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
  2935. self::getImplicitGroups()
  2936. );
  2937. }
  2938. /**
  2939. * Get a list of all available permissions.
  2940. * @return Array of permission names
  2941. */
  2942. static function getAllRights() {
  2943. if ( self::$mAllRights === false ) {
  2944. global $wgAvailableRights;
  2945. if ( count( $wgAvailableRights ) ) {
  2946. self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
  2947. } else {
  2948. self::$mAllRights = self::$mCoreRights;
  2949. }
  2950. wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
  2951. }
  2952. return self::$mAllRights;
  2953. }
  2954. /**
  2955. * Get a list of implicit groups
  2956. * @return Array of Strings Array of internal group names
  2957. */
  2958. public static function getImplicitGroups() {
  2959. global $wgImplicitGroups;
  2960. $groups = $wgImplicitGroups;
  2961. wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
  2962. return $groups;
  2963. }
  2964. /**
  2965. * Get the title of a page describing a particular group
  2966. *
  2967. * @param $group String Internal group name
  2968. * @return Title|Bool Title of the page if it exists, false otherwise
  2969. */
  2970. static function getGroupPage( $group ) {
  2971. $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
  2972. if( $msg->exists() ) {
  2973. $title = Title::newFromText( $msg->text() );
  2974. if( is_object( $title ) )
  2975. return $title;
  2976. }
  2977. return false;
  2978. }
  2979. /**
  2980. * Create a link to the group in HTML, if available;
  2981. * else return the group name.
  2982. *
  2983. * @param $group String Internal name of the group
  2984. * @param $text String The text of the link
  2985. * @return String HTML link to the group
  2986. */
  2987. static function makeGroupLinkHTML( $group, $text = '' ) {
  2988. if( $text == '' ) {
  2989. $text = self::getGroupName( $group );
  2990. }
  2991. $title = self::getGroupPage( $group );
  2992. if( $title ) {
  2993. global $wgUser;
  2994. $sk = $wgUser->getSkin();
  2995. return $sk->link( $title, htmlspecialchars( $text ) );
  2996. } else {
  2997. return $text;
  2998. }
  2999. }
  3000. /**
  3001. * Create a link to the group in Wikitext, if available;
  3002. * else return the group name.
  3003. *
  3004. * @param $group String Internal name of the group
  3005. * @param $text String The text of the link
  3006. * @return String Wikilink to the group
  3007. */
  3008. static function makeGroupLinkWiki( $group, $text = '' ) {
  3009. if( $text == '' ) {
  3010. $text = self::getGroupName( $group );
  3011. }
  3012. $title = self::getGroupPage( $group );
  3013. if( $title ) {
  3014. $page = $title->getPrefixedText();
  3015. return "[[$page|$text]]";
  3016. } else {
  3017. return $text;
  3018. }
  3019. }
  3020. /**
  3021. * Returns an array of the groups that a particular group can add/remove.
  3022. *
  3023. * @param $group String: the group to check for whether it can add/remove
  3024. * @return Array array( 'add' => array( addablegroups ),
  3025. * 'remove' => array( removablegroups ),
  3026. * 'add-self' => array( addablegroups to self),
  3027. * 'remove-self' => array( removable groups from self) )
  3028. */
  3029. static function changeableByGroup( $group ) {
  3030. global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
  3031. $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
  3032. if( empty( $wgAddGroups[$group] ) ) {
  3033. // Don't add anything to $groups
  3034. } elseif( $wgAddGroups[$group] === true ) {
  3035. // You get everything
  3036. $groups['add'] = self::getAllGroups();
  3037. } elseif( is_array( $wgAddGroups[$group] ) ) {
  3038. $groups['add'] = $wgAddGroups[$group];
  3039. }
  3040. // Same thing for remove
  3041. if( empty( $wgRemoveGroups[$group] ) ) {
  3042. } elseif( $wgRemoveGroups[$group] === true ) {
  3043. $groups['remove'] = self::getAllGroups();
  3044. } elseif( is_array( $wgRemoveGroups[$group] ) ) {
  3045. $groups['remove'] = $wgRemoveGroups[$group];
  3046. }
  3047. // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
  3048. if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
  3049. foreach( $wgGroupsAddToSelf as $key => $value ) {
  3050. if( is_int( $key ) ) {
  3051. $wgGroupsAddToSelf['user'][] = $value;
  3052. }
  3053. }
  3054. }
  3055. if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
  3056. foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
  3057. if( is_int( $key ) ) {
  3058. $wgGroupsRemoveFromSelf['user'][] = $value;
  3059. }
  3060. }
  3061. }
  3062. // Now figure out what groups the user can add to him/herself
  3063. if( empty( $wgGroupsAddToSelf[$group] ) ) {
  3064. } elseif( $wgGroupsAddToSelf[$group] === true ) {
  3065. // No idea WHY this would be used, but it's there
  3066. $groups['add-self'] = User::getAllGroups();
  3067. } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
  3068. $groups['add-self'] = $wgGroupsAddToSelf[$group];
  3069. }
  3070. if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
  3071. } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
  3072. $groups['remove-self'] = User::getAllGroups();
  3073. } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
  3074. $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
  3075. }
  3076. return $groups;
  3077. }
  3078. /**
  3079. * Returns an array of groups that this user can add and remove
  3080. * @return Array array( 'add' => array( addablegroups ),
  3081. * 'remove' => array( removablegroups ),
  3082. * 'add-self' => array( addablegroups to self),
  3083. * 'remove-self' => array( removable groups from self) )
  3084. */
  3085. function changeableGroups() {
  3086. if( $this->isAllowed( 'userrights' ) ) {
  3087. // This group gives the right to modify everything (reverse-
  3088. // compatibility with old "userrights lets you change
  3089. // everything")
  3090. // Using array_merge to make the groups reindexed
  3091. $all = array_merge( User::getAllGroups() );
  3092. return array(
  3093. 'add' => $all,
  3094. 'remove' => $all,
  3095. 'add-self' => array(),
  3096. 'remove-self' => array()
  3097. );
  3098. }
  3099. // Okay, it's not so simple, we will have to go through the arrays
  3100. $groups = array(
  3101. 'add' => array(),
  3102. 'remove' => array(),
  3103. 'add-self' => array(),
  3104. 'remove-self' => array()
  3105. );
  3106. $addergroups = $this->getEffectiveGroups();
  3107. foreach( $addergroups as $addergroup ) {
  3108. $groups = array_merge_recursive(
  3109. $groups, $this->changeableByGroup( $addergroup )
  3110. );
  3111. $groups['add'] = array_unique( $groups['add'] );
  3112. $groups['remove'] = array_unique( $groups['remove'] );
  3113. $groups['add-self'] = array_unique( $groups['add-self'] );
  3114. $groups['remove-self'] = array_unique( $groups['remove-self'] );
  3115. }
  3116. return $groups;
  3117. }
  3118. /**
  3119. * Increment the user's edit-count field.
  3120. * Will have no effect for anonymous users.
  3121. */
  3122. function incEditCount() {
  3123. if( !$this->isAnon() ) {
  3124. $dbw = wfGetDB( DB_MASTER );
  3125. $dbw->update( 'user',
  3126. array( 'user_editcount=user_editcount+1' ),
  3127. array( 'user_id' => $this->getId() ),
  3128. __METHOD__ );
  3129. // Lazy initialization check...
  3130. if( $dbw->affectedRows() == 0 ) {
  3131. // Pull from a slave to be less cruel to servers
  3132. // Accuracy isn't the point anyway here
  3133. $dbr = wfGetDB( DB_SLAVE );
  3134. $count = $dbr->selectField( 'revision',
  3135. 'COUNT(rev_user)',
  3136. array( 'rev_user' => $this->getId() ),
  3137. __METHOD__ );
  3138. // Now here's a goddamn hack...
  3139. if( $dbr !== $dbw ) {
  3140. // If we actually have a slave server, the count is
  3141. // at least one behind because the current transaction
  3142. // has not been committed and replicated.
  3143. $count++;
  3144. } else {
  3145. // But if DB_SLAVE is selecting the master, then the
  3146. // count we just read includes the revision that was
  3147. // just added in the working transaction.
  3148. }
  3149. $dbw->update( 'user',
  3150. array( 'user_editcount' => $count ),
  3151. array( 'user_id' => $this->getId() ),
  3152. __METHOD__ );
  3153. }
  3154. }
  3155. // edit count in user cache too
  3156. $this->invalidateCache();
  3157. }
  3158. /**
  3159. * Get the description of a given right
  3160. *
  3161. * @param $right String Right to query
  3162. * @return String Localized description of the right
  3163. */
  3164. static function getRightDescription( $right ) {
  3165. $key = "right-$right";
  3166. $name = wfMsg( $key );
  3167. return $name == '' || wfEmptyMsg( $key, $name )
  3168. ? $right
  3169. : $name;
  3170. }
  3171. /**
  3172. * Make an old-style password hash
  3173. *
  3174. * @param $password String Plain-text password
  3175. * @param $userId String User ID
  3176. * @return String Password hash
  3177. */
  3178. static function oldCrypt( $password, $userId ) {
  3179. global $wgPasswordSalt;
  3180. if ( $wgPasswordSalt ) {
  3181. return md5( $userId . '-' . md5( $password ) );
  3182. } else {
  3183. return md5( $password );
  3184. }
  3185. }
  3186. /**
  3187. * Make a new-style password hash
  3188. *
  3189. * @param $password String Plain-text password
  3190. * @param $salt String Optional salt, may be random or the user ID.
  3191. * If unspecified or false, will generate one automatically
  3192. * @return String Password hash
  3193. */
  3194. static function crypt( $password, $salt = false ) {
  3195. global $wgPasswordSalt;
  3196. $hash = '';
  3197. if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
  3198. return $hash;
  3199. }
  3200. if( $wgPasswordSalt ) {
  3201. if ( $salt === false ) {
  3202. $salt = substr( wfGenerateToken(), 0, 8 );
  3203. }
  3204. return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
  3205. } else {
  3206. return ':A:' . md5( $password );
  3207. }
  3208. }
  3209. /**
  3210. * Compare a password hash with a plain-text password. Requires the user
  3211. * ID if there's a chance that the hash is an old-style hash.
  3212. *
  3213. * @param $hash String Password hash
  3214. * @param $password String Plain-text password to compare
  3215. * @param $userId String User ID for old-style password salt
  3216. * @return Boolean:
  3217. */
  3218. static function comparePasswords( $hash, $password, $userId = false ) {
  3219. $type = substr( $hash, 0, 3 );
  3220. $result = false;
  3221. if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
  3222. return $result;
  3223. }
  3224. if ( $type == ':A:' ) {
  3225. # Unsalted
  3226. return md5( $password ) === substr( $hash, 3 );
  3227. } elseif ( $type == ':B:' ) {
  3228. # Salted
  3229. list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
  3230. return md5( $salt.'-'.md5( $password ) ) == $realHash;
  3231. } else {
  3232. # Old-style
  3233. return self::oldCrypt( $password, $userId ) === $hash;
  3234. }
  3235. }
  3236. /**
  3237. * Add a newuser log entry for this user
  3238. *
  3239. * @param $byEmail Boolean: account made by email?
  3240. * @param $reason String: user supplied reason
  3241. */
  3242. public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
  3243. global $wgUser, $wgContLang, $wgNewUserLog;
  3244. if( empty( $wgNewUserLog ) ) {
  3245. return true; // disabled
  3246. }
  3247. if( $this->getName() == $wgUser->getName() ) {
  3248. $action = 'create';
  3249. } else {
  3250. $action = 'create2';
  3251. if ( $byEmail ) {
  3252. if ( $reason === '' ) {
  3253. $reason = wfMsgForContent( 'newuserlog-byemail' );
  3254. } else {
  3255. $reason = $wgContLang->commaList( array(
  3256. $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
  3257. }
  3258. }
  3259. }
  3260. $log = new LogPage( 'newusers' );
  3261. $log->addEntry(
  3262. $action,
  3263. $this->getUserPage(),
  3264. $reason,
  3265. array( $this->getId() )
  3266. );
  3267. return true;
  3268. }
  3269. /**
  3270. * Add an autocreate newuser log entry for this user
  3271. * Used by things like CentralAuth and perhaps other authplugins.
  3272. */
  3273. public function addNewUserLogEntryAutoCreate() {
  3274. global $wgNewUserLog, $wgLogAutocreatedAccounts;
  3275. if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
  3276. return true; // disabled
  3277. }
  3278. $log = new LogPage( 'newusers', false );
  3279. $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
  3280. return true;
  3281. }
  3282. protected function loadOptions() {
  3283. $this->load();
  3284. if ( $this->mOptionsLoaded || !$this->getId() )
  3285. return;
  3286. $this->mOptions = self::getDefaultOptions();
  3287. // Maybe load from the object
  3288. if ( !is_null( $this->mOptionOverrides ) ) {
  3289. wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
  3290. foreach( $this->mOptionOverrides as $key => $value ) {
  3291. $this->mOptions[$key] = $value;
  3292. }
  3293. } else {
  3294. wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
  3295. // Load from database
  3296. $dbr = wfGetDB( DB_SLAVE );
  3297. $res = $dbr->select(
  3298. 'user_properties',
  3299. '*',
  3300. array( 'up_user' => $this->getId() ),
  3301. __METHOD__
  3302. );
  3303. foreach ( $res as $row ) {
  3304. $this->mOptionOverrides[$row->up_property] = $row->up_value;
  3305. $this->mOptions[$row->up_property] = $row->up_value;
  3306. }
  3307. }
  3308. $this->mOptionsLoaded = true;
  3309. wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
  3310. }
  3311. protected function saveOptions() {
  3312. global $wgAllowPrefChange;
  3313. $extuser = ExternalUser::newFromUser( $this );
  3314. $this->loadOptions();
  3315. $dbw = wfGetDB( DB_MASTER );
  3316. $insert_rows = array();
  3317. $saveOptions = $this->mOptions;
  3318. // Allow hooks to abort, for instance to save to a global profile.
  3319. // Reset options to default state before saving.
  3320. if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
  3321. return;
  3322. foreach( $saveOptions as $key => $value ) {
  3323. # Don't bother storing default values
  3324. if ( ( is_null( self::getDefaultOption( $key ) ) &&
  3325. !( $value === false || is_null($value) ) ) ||
  3326. $value != self::getDefaultOption( $key ) ) {
  3327. $insert_rows[] = array(
  3328. 'up_user' => $this->getId(),
  3329. 'up_property' => $key,
  3330. 'up_value' => $value,
  3331. );
  3332. }
  3333. if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
  3334. switch ( $wgAllowPrefChange[$key] ) {
  3335. case 'local':
  3336. case 'message':
  3337. break;
  3338. case 'semiglobal':
  3339. case 'global':
  3340. $extuser->setPref( $key, $value );
  3341. }
  3342. }
  3343. }
  3344. $dbw->begin();
  3345. $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
  3346. $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
  3347. $dbw->commit();
  3348. }
  3349. /**
  3350. * Provide an array of HTML5 attributes to put on an input element
  3351. * intended for the user to enter a new password. This may include
  3352. * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
  3353. *
  3354. * Do *not* use this when asking the user to enter his current password!
  3355. * Regardless of configuration, users may have invalid passwords for whatever
  3356. * reason (e.g., they were set before requirements were tightened up).
  3357. * Only use it when asking for a new password, like on account creation or
  3358. * ResetPass.
  3359. *
  3360. * Obviously, you still need to do server-side checking.
  3361. *
  3362. * NOTE: A combination of bugs in various browsers means that this function
  3363. * actually just returns array() unconditionally at the moment. May as
  3364. * well keep it around for when the browser bugs get fixed, though.
  3365. *
  3366. * FIXME : This does not belong here; put it in Html or Linker or somewhere
  3367. *
  3368. * @return array Array of HTML attributes suitable for feeding to
  3369. * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
  3370. * That will potentially output invalid XHTML 1.0 Transitional, and will
  3371. * get confused by the boolean attribute syntax used.)
  3372. */
  3373. public static function passwordChangeInputAttribs() {
  3374. global $wgMinimalPasswordLength;
  3375. if ( $wgMinimalPasswordLength == 0 ) {
  3376. return array();
  3377. }
  3378. # Note that the pattern requirement will always be satisfied if the
  3379. # input is empty, so we need required in all cases.
  3380. #
  3381. # FIXME (bug 23769): This needs to not claim the password is required
  3382. # if e-mail confirmation is being used. Since HTML5 input validation
  3383. # is b0rked anyway in some browsers, just return nothing. When it's
  3384. # re-enabled, fix this code to not output required for e-mail
  3385. # registration.
  3386. #$ret = array( 'required' );
  3387. $ret = array();
  3388. # We can't actually do this right now, because Opera 9.6 will print out
  3389. # the entered password visibly in its error message! When other
  3390. # browsers add support for this attribute, or Opera fixes its support,
  3391. # we can add support with a version check to avoid doing this on Opera
  3392. # versions where it will be a problem. Reported to Opera as
  3393. # DSK-262266, but they don't have a public bug tracker for us to follow.
  3394. /*
  3395. if ( $wgMinimalPasswordLength > 1 ) {
  3396. $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
  3397. $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
  3398. $wgMinimalPasswordLength );
  3399. }
  3400. */
  3401. return $ret;
  3402. }
  3403. /**
  3404. * Format the user message using a hook, a template, or, failing these, a static format.
  3405. * @param $subject String the subject of the message
  3406. * @param $text String the content of the message
  3407. * @param $signature String the signature, if provided.
  3408. */
  3409. static protected function formatUserMessage( $subject, $text, $signature ) {
  3410. if ( wfRunHooks( 'FormatUserMessage',
  3411. array( $subject, &$text, $signature ) ) ) {
  3412. $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
  3413. $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
  3414. if ( !$template
  3415. || $template->getNamespace() !== NS_TEMPLATE
  3416. || !$template->exists() ) {
  3417. $text = "\n== $subject ==\n\n$text\n\n-- $signature";
  3418. } else {
  3419. $text = '{{'. $template->getText()
  3420. . " | subject=$subject | body=$text | signature=$signature }}";
  3421. }
  3422. }
  3423. return $text;
  3424. }
  3425. /**
  3426. * Leave a user a message
  3427. * @param $subject String the subject of the message
  3428. * @param $text String the message to leave
  3429. * @param $signature String Text to leave in the signature
  3430. * @param $summary String the summary for this change, defaults to
  3431. * "Leave system message."
  3432. * @param $editor User The user leaving the message, defaults to
  3433. * "{{MediaWiki:usermessage-editor}}"
  3434. * @param $flags Int default edit flags
  3435. *
  3436. * @return boolean true if it was successful
  3437. */
  3438. public function leaveUserMessage( $subject, $text, $signature = "",
  3439. $summary = null, $editor = null, $flags = 0 ) {
  3440. if ( !isset( $summary ) ) {
  3441. $summary = wfMsgForContent( 'usermessage-summary' );
  3442. }
  3443. if ( !isset( $editor ) ) {
  3444. $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
  3445. if ( !$editor->isLoggedIn() ) {
  3446. $editor->addToDatabase();
  3447. }
  3448. }
  3449. $article = new Article( $this->getTalkPage() );
  3450. wfRunHooks( 'SetupUserMessageArticle',
  3451. array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
  3452. $text = self::formatUserMessage( $subject, $text, $signature );
  3453. $flags = $article->checkFlags( $flags );
  3454. if ( $flags & EDIT_UPDATE ) {
  3455. $text = $article->getContent() . $text;
  3456. }
  3457. $dbw = wfGetDB( DB_MASTER );
  3458. $dbw->begin();
  3459. try {
  3460. $status = $article->doEdit( $text, $summary, $flags, false, $editor );
  3461. } catch ( DBQueryError $e ) {
  3462. $status = Status::newFatal("DB Error");
  3463. }
  3464. if ( $status->isGood() ) {
  3465. // Set newtalk with the right user ID
  3466. $this->setNewtalk( true );
  3467. wfRunHooks( 'AfterUserMessage',
  3468. array( $this, $article, $subject, $text, $signature, $summary, $editor ) );
  3469. $dbw->commit();
  3470. } else {
  3471. // The article was concurrently created
  3472. wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
  3473. $dbw->rollback();
  3474. }
  3475. return $status->isGood();
  3476. }
  3477. }