PageRenderTime 35ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/User.php

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