-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
User.php
4893 lines (4446 loc) · 143 KB
/
User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Implements the User class for the %MediaWiki software.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
/**
* Int Number of characters in user_token field.
* @ingroup Constants
*/
define( 'USER_TOKEN_LENGTH', 32 );
/**
* Int Serialized record version.
* @ingroup Constants
*/
define( 'MW_USER_VERSION', 9 );
/**
* String Some punctuation to prevent editing from broken text-mangling proxies.
* @ingroup Constants
*/
define( 'EDIT_TOKEN_SUFFIX', '+\\' );
/**
* Thrown by User::setPassword() on error.
* @ingroup Exception
*/
class PasswordError extends MWException {
// NOP
}
/**
* The User object encapsulates all of the user-specific settings (user_id,
* name, rights, password, email address, options, last login time). Client
* classes use the getXXX() functions to access these fields. These functions
* do all the work of determining whether the user is logged in,
* whether the requested option can be satisfied from cookies or
* whether a database query is needed. Most of the settings needed
* for rendering normal pages are set in the cookie to minimize use
* of the database.
*/
class User {
/**
* Global constants made accessible as class constants so that autoloader
* magic can be used.
*/
const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
const MW_USER_VERSION = MW_USER_VERSION;
const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
/**
* Maximum items in $mWatchedItems
*/
const MAX_WATCHED_ITEMS_CACHE = 100;
/**
* Array of Strings List of member variables which are saved to the
* shared cache (memcached). Any operation which changes the
* corresponding database fields must call a cache-clearing function.
* @showinitializer
*/
static $mCacheVars = array(
// user table
'mId',
'mName',
'mRealName',
'mPassword',
'mNewpassword',
'mNewpassTime',
'mEmail',
'mTouched',
'mToken',
'mEmailAuthenticated',
'mEmailToken',
'mEmailTokenExpires',
'mPasswordExpires',
'mRegistration',
'mEditCount',
// user_groups table
'mGroups',
// user_properties table
'mOptionOverrides',
);
/**
* Array of Strings Core rights.
* Each of these should have a corresponding message of the form
* "right-$right".
* @showinitializer
*/
static $mCoreRights = array(
'apihighlimits',
'autoconfirmed',
'autopatrol',
'bigdelete',
'block',
'blockemail',
'bot',
'browsearchive',
'createaccount',
'createpage',
'createtalk',
'delete',
'deletedhistory',
'deletedtext',
'deletelogentry',
'deleterevision',
'edit',
'editcontentmodel',
'editinterface',
'editprotected',
'editmyoptions',
'editmyprivateinfo',
'editmyusercss',
'editmyuserjs',
'editmywatchlist',
'editsemiprotected',
'editusercssjs', #deprecated
'editusercss',
'edituserjs',
'hideuser',
'import',
'importupload',
'ipblock-exempt',
'markbotedits',
'mergehistory',
'minoredit',
'move',
'movefile',
'move-rootuserpages',
'move-subpages',
'nominornewtalk',
'noratelimit',
'override-export-depth',
'passwordreset',
'patrol',
'patrolmarks',
'protect',
'proxyunbannable',
'purge',
'read',
'reupload',
'reupload-own',
'reupload-shared',
'rollback',
'sendemail',
'siteadmin',
'suppressionlog',
'suppressredirect',
'suppressrevision',
'unblockself',
'undelete',
'unwatchedpages',
'upload',
'upload_by_url',
'userrights',
'userrights-interwiki',
'viewmyprivateinfo',
'viewmywatchlist',
'writeapi',
);
/**
* String Cached results of getAllRights()
*/
static $mAllRights = false;
/** @name Cache variables */
//@{
var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
$mEmail, $mTouched, $mToken, $mEmailAuthenticated,
$mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
$mGroups, $mOptionOverrides;
protected $mPasswordExpires;
//@}
/**
* Bool Whether the cache variables have been loaded.
*/
//@{
var $mOptionsLoaded;
/**
* Array with already loaded items or true if all items have been loaded.
*/
private $mLoadedItems = array();
//@}
/**
* String Initialization data source if mLoadedItems!==true. May be one of:
* - 'defaults' anonymous user initialised from class defaults
* - 'name' initialise from mName
* - 'id' initialise from mId
* - 'session' log in from cookies or session if possible
*
* Use the User::newFrom*() family of functions to set this.
*/
var $mFrom;
/**
* Lazy-initialized variables, invalidated with clearInstanceCache
*/
var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
$mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
$mLocked, $mHideName, $mOptions;
/**
* @var WebRequest
*/
private $mRequest;
/**
* @var Block
*/
var $mBlock;
/**
* @var bool
*/
var $mAllowUsertalk;
/**
* @var Block
*/
private $mBlockedFromCreateAccount = false;
/**
* @var Array
*/
private $mWatchedItems = array();
static $idCacheByName = array();
/**
* Lightweight constructor for an anonymous user.
* Use the User::newFrom* factory functions for other kinds of users.
*
* @see newFromName()
* @see newFromId()
* @see newFromConfirmationCode()
* @see newFromSession()
* @see newFromRow()
*/
public function __construct() {
$this->clearInstanceCache( 'defaults' );
}
/**
* @return string
*/
public function __toString() {
return $this->getName();
}
/**
* Load the user table data for this object from the source given by mFrom.
*/
public function load() {
if ( $this->mLoadedItems === true ) {
return;
}
wfProfileIn( __METHOD__ );
// Set it now to avoid infinite recursion in accessors
$this->mLoadedItems = true;
switch ( $this->mFrom ) {
case 'defaults':
$this->loadDefaults();
break;
case 'name':
$this->mId = self::idFromName( $this->mName );
if ( !$this->mId ) {
// Nonexistent user placeholder object
$this->loadDefaults( $this->mName );
} else {
$this->loadFromId();
}
break;
case 'id':
$this->loadFromId();
break;
case 'session':
if ( !$this->loadFromSession() ) {
// Loading from session failed. Load defaults.
$this->loadDefaults();
}
wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
break;
default:
wfProfileOut( __METHOD__ );
throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
}
wfProfileOut( __METHOD__ );
}
/**
* Load user table data, given mId has already been set.
* @return bool false if the ID does not exist, true otherwise
*/
public function loadFromId() {
global $wgMemc;
if ( $this->mId == 0 ) {
$this->loadDefaults();
return false;
}
// Try cache
$key = wfMemcKey( 'user', 'id', $this->mId );
$data = $wgMemc->get( $key );
if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
// Object is expired, load from DB
$data = false;
}
if ( !$data ) {
wfDebug( "User: cache miss for user {$this->mId}\n" );
// Load from DB
if ( !$this->loadFromDatabase() ) {
// Can't load from ID, user is anonymous
return false;
}
$this->saveToCache();
} else {
wfDebug( "User: got user {$this->mId} from cache\n" );
// Restore from cache
foreach ( self::$mCacheVars as $name ) {
$this->$name = $data[$name];
}
}
$this->mLoadedItems = true;
return true;
}
/**
* Save user data to the shared cache
*/
public function saveToCache() {
$this->load();
$this->loadGroups();
$this->loadOptions();
if ( $this->isAnon() ) {
// Anonymous users are uncached
return;
}
$data = array();
foreach ( self::$mCacheVars as $name ) {
$data[$name] = $this->$name;
}
$data['mVersion'] = MW_USER_VERSION;
$key = wfMemcKey( 'user', 'id', $this->mId );
global $wgMemc;
$wgMemc->set( $key, $data );
}
/** @name newFrom*() static factory methods */
//@{
/**
* Static factory method for creation from username.
*
* This is slightly less efficient than newFromId(), so use newFromId() if
* you have both an ID and a name handy.
*
* @param string $name Username, validated by Title::newFromText()
* @param string|bool $validate Validate username. Takes the same parameters as
* User::getCanonicalName(), except that true is accepted as an alias
* for 'valid', for BC.
*
* @return User|bool User object, or false if the username is invalid
* (e.g. if it contains illegal characters or is an IP address). If the
* username is not present in the database, the result will be a user object
* with a name, zero user ID and default settings.
*/
public static function newFromName( $name, $validate = 'valid' ) {
if ( $validate === true ) {
$validate = 'valid';
}
$name = self::getCanonicalName( $name, $validate );
if ( $name === false ) {
return false;
} else {
// Create unloaded user object
$u = new User;
$u->mName = $name;
$u->mFrom = 'name';
$u->setItemLoaded( 'name' );
return $u;
}
}
/**
* Static factory method for creation from a given user ID.
*
* @param int $id Valid user ID
* @return User The corresponding User object
*/
public static function newFromId( $id ) {
$u = new User;
$u->mId = $id;
$u->mFrom = 'id';
$u->setItemLoaded( 'id' );
return $u;
}
/**
* Factory method to fetch whichever user has a given email confirmation code.
* This code is generated when an account is created or its e-mail address
* has changed.
*
* If the code is invalid or has expired, returns NULL.
*
* @param string $code Confirmation code
* @return User|null
*/
public static function newFromConfirmationCode( $code ) {
$dbr = wfGetDB( DB_SLAVE );
$id = $dbr->selectField( 'user', 'user_id', array(
'user_email_token' => md5( $code ),
'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
) );
if ( $id !== false ) {
return User::newFromId( $id );
} else {
return null;
}
}
/**
* Create a new user object using data from session or cookies. If the
* login credentials are invalid, the result is an anonymous user.
*
* @param WebRequest $request Object to use; $wgRequest will be used if omitted.
* @return User object
*/
public static function newFromSession( WebRequest $request = null ) {
$user = new User;
$user->mFrom = 'session';
$user->mRequest = $request;
return $user;
}
/**
* Create a new user object from a user row.
* The row should have the following fields from the user table in it:
* - either user_name or user_id to load further data if needed (or both)
* - user_real_name
* - all other fields (email, password, etc.)
* It is useless to provide the remaining fields if either user_id,
* user_name and user_real_name are not provided because the whole row
* will be loaded once more from the database when accessing them.
*
* @param stdClass $row A row from the user table
* @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
* @return User
*/
public static function newFromRow( $row, $data = null ) {
$user = new User;
$user->loadFromRow( $row, $data );
return $user;
}
//@}
/**
* Get the username corresponding to a given user ID
* @param int $id User ID
* @return string|bool The corresponding username
*/
public static function whoIs( $id ) {
return UserCache::singleton()->getProp( $id, 'name' );
}
/**
* Get the real name of a user given their user ID
*
* @param int $id User ID
* @return string|bool The corresponding user's real name
*/
public static function whoIsReal( $id ) {
return UserCache::singleton()->getProp( $id, 'real_name' );
}
/**
* Get database id given a user name
* @param string $name Username
* @return int|null The corresponding user's ID, or null if user is nonexistent
*/
public static function idFromName( $name ) {
$nt = Title::makeTitleSafe( NS_USER, $name );
if ( is_null( $nt ) ) {
// Illegal name
return null;
}
if ( isset( self::$idCacheByName[$name] ) ) {
return self::$idCacheByName[$name];
}
$dbr = wfGetDB( DB_SLAVE );
$s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
if ( $s === false ) {
$result = null;
} else {
$result = $s->user_id;
}
self::$idCacheByName[$name] = $result;
if ( count( self::$idCacheByName ) > 1000 ) {
self::$idCacheByName = array();
}
return $result;
}
/**
* Reset the cache used in idFromName(). For use in tests.
*/
public static function resetIdByNameCache() {
self::$idCacheByName = array();
}
/**
* Does the string match an anonymous IPv4 address?
*
* This function exists for username validation, in order to reject
* usernames which are similar in form to IP addresses. Strings such
* as 300.300.300.300 will return true because it looks like an IP
* address, despite not being strictly valid.
*
* We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
* address because the usemod software would "cloak" anonymous IP
* addresses like this, if we allowed accounts like this to be created
* new users could get the old edits of these anonymous users.
*
* @param string $name Name to match
* @return bool
*/
public static function isIP( $name ) {
return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
}
/**
* Is the input a valid username?
*
* Checks if the input is a valid username, we don't want an empty string,
* an IP address, anything that contains slashes (would mess up subpages),
* is longer than the maximum allowed username size or doesn't begin with
* a capital letter.
*
* @param string $name Name to match
* @return bool
*/
public static function isValidUserName( $name ) {
global $wgContLang, $wgMaxNameChars;
if ( $name == ''
|| User::isIP( $name )
|| strpos( $name, '/' ) !== false
|| strlen( $name ) > $wgMaxNameChars
|| $name != $wgContLang->ucfirst( $name ) ) {
wfDebugLog( 'username', __METHOD__ .
": '$name' invalid due to empty, IP, slash, length, or lowercase" );
return false;
}
// Ensure that the name can't be misresolved as a different title,
// such as with extra namespace keys at the start.
$parsed = Title::newFromText( $name );
if ( is_null( $parsed )
|| $parsed->getNamespace()
|| strcmp( $name, $parsed->getPrefixedText() ) ) {
wfDebugLog( 'username', __METHOD__ .
": '$name' invalid due to ambiguous prefixes" );
return false;
}
// Check an additional blacklist of troublemaker characters.
// Should these be merged into the title char list?
$unicodeBlacklist = '/[' .
'\x{0080}-\x{009f}' . # iso-8859-1 control chars
'\x{00a0}' . # non-breaking space
'\x{2000}-\x{200f}' . # various whitespace
'\x{2028}-\x{202f}' . # breaks and control chars
'\x{3000}' . # ideographic space
'\x{e000}-\x{f8ff}' . # private use
']/u';
if ( preg_match( $unicodeBlacklist, $name ) ) {
wfDebugLog( 'username', __METHOD__ .
": '$name' invalid due to blacklisted characters" );
return false;
}
return true;
}
/**
* Usernames which fail to pass this function will be blocked
* from user login and new account registrations, but may be used
* internally by batch processes.
*
* If an account already exists in this form, login will be blocked
* by a failure to pass this function.
*
* @param string $name Name to match
* @return bool
*/
public static function isUsableName( $name ) {
global $wgReservedUsernames;
// Must be a valid username, obviously ;)
if ( !self::isValidUserName( $name ) ) {
return false;
}
static $reservedUsernames = false;
if ( !$reservedUsernames ) {
$reservedUsernames = $wgReservedUsernames;
wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
}
// Certain names may be reserved for batch processes.
foreach ( $reservedUsernames as $reserved ) {
if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
$reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
}
if ( $reserved == $name ) {
return false;
}
}
return true;
}
/**
* Usernames which fail to pass this function will be blocked
* from new account registrations, but may be used internally
* either by batch processes or by user accounts which have
* already been created.
*
* Additional blacklisting may be added here rather than in
* isValidUserName() to avoid disrupting existing accounts.
*
* @param string $name to match
* @return bool
*/
public static function isCreatableName( $name ) {
global $wgInvalidUsernameCharacters;
// Ensure that the username isn't longer than 235 bytes, so that
// (at least for the builtin skins) user javascript and css files
// will work. (bug 23080)
if ( strlen( $name ) > 235 ) {
wfDebugLog( 'username', __METHOD__ .
": '$name' invalid due to length" );
return false;
}
// Preg yells if you try to give it an empty string
if ( $wgInvalidUsernameCharacters !== '' ) {
if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
wfDebugLog( 'username', __METHOD__ .
": '$name' invalid due to wgInvalidUsernameCharacters" );
return false;
}
}
return self::isUsableName( $name );
}
/**
* Is the input a valid password for this user?
*
* @param string $password Desired password
* @return bool
*/
public function isValidPassword( $password ) {
//simple boolean wrapper for getPasswordValidity
return $this->getPasswordValidity( $password ) === true;
}
/**
* Given unvalidated password input, return error message on failure.
*
* @param string $password Desired password
* @return mixed: true on success, string or array of error message on failure
*/
public function getPasswordValidity( $password ) {
$result = $this->checkPasswordValidity( $password );
if ( $result->isGood() ) {
return true;
} else {
$messages = array();
foreach ( $result->getErrorsByType( 'error' ) as $error ) {
$messages[] = $error['message'];
}
foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
$messages[] = $warning['message'];
}
if ( count( $messages ) === 1 ) {
return $messages[0];
}
return $messages;
}
}
/**
* Check if this is a valid password for this user. Status will be good if
* the password is valid, or have an array of error messages if not.
*
* @param string $password Desired password
* @return Status
* @since 1.23
*/
public function checkPasswordValidity( $password ) {
global $wgMinimalPasswordLength, $wgContLang;
static $blockedLogins = array(
'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
);
$status = Status::newGood();
$result = false; //init $result to false for the internal checks
if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
$status->error( $result );
return $status;
}
if ( $result === false ) {
if ( strlen( $password ) < $wgMinimalPasswordLength ) {
$status->error( 'passwordtooshort', $wgMinimalPasswordLength );
return $status;
} elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
$status->error( 'password-name-match' );
return $status;
} elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
$status->error( 'password-login-forbidden' );
return $status;
} else {
//it seems weird returning a Good status here, but this is because of the
//initialization of $result to false above. If the hook is never run or it
//doesn't modify $result, then we will likely get down into this if with
//a valid password.
return $status;
}
} elseif ( $result === true ) {
return $status;
} else {
$status->error( $result );
return $status; //the isValidPassword hook set a string $result and returned true
}
}
/**
* Expire a user's password
* @since 1.23
* @param $ts Mixed: optional timestamp to convert, default 0 for the current time
*/
public function expirePassword( $ts = 0 ) {
$this->load();
$timestamp = wfTimestamp( TS_MW, $ts );
$this->mPasswordExpires = $timestamp;
$this->saveSettings();
}
/**
* Clear the password expiration for a user
* @since 1.23
* @param bool $load ensure user object is loaded first
*/
public function resetPasswordExpiration( $load = true ) {
global $wgPasswordExpirationDays;
if ( $load ) {
$this->load();
}
$newExpire = null;
if ( $wgPasswordExpirationDays ) {
$newExpire = wfTimestamp(
TS_MW,
time() + ( $wgPasswordExpirationDays * 24 * 3600 )
);
}
// Give extensions a chance to force an expiration
wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
$this->mPasswordExpires = $newExpire;
}
/**
* Check if the user's password is expired.
* TODO: Put this and password length into a PasswordPolicy object
* @since 1.23
* @return string|bool The expiration type, or false if not expired
* hard: A password change is required to login
* soft: Allow login, but encourage password change
* false: Password is not expired
*/
public function getPasswordExpired() {
global $wgPasswordExpireGrace;
$expired = false;
$now = wfTimestamp();
$expiration = $this->getPasswordExpireDate();
$expUnix = wfTimestamp( TS_UNIX, $expiration );
if ( $expiration !== null && $expUnix < $now ) {
$expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
}
return $expired;
}
/**
* Get this user's password expiration date. Since this may be using
* the cached User object, we assume that whatever mechanism is setting
* the expiration date is also expiring the User cache.
* @since 1.23
* @return string|false the datestamp of the expiration, or null if not set
*/
public function getPasswordExpireDate() {
$this->load();
return $this->mPasswordExpires;
}
/**
* Does a string look like an e-mail address?
*
* This validates an email address using an HTML5 specification found at:
* http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
* Which as of 2011-01-24 says:
*
* A valid e-mail address is a string that matches the ABNF production
* 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
* in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
* 3.5.
*
* This function is an implementation of the specification as requested in
* bug 22449.
*
* Client-side forms will use the same standard validation rules via JS or
* HTML 5 validation; additional restrictions can be enforced server-side
* by extensions via the 'isValidEmailAddr' hook.
*
* Note that this validation doesn't 100% match RFC 2822, but is believed
* to be liberal enough for wide use. Some invalid addresses will still
* pass validation here.
*
* @param string $addr E-mail address
* @return bool
* @deprecated since 1.18 call Sanitizer::isValidEmail() directly
*/
public static function isValidEmailAddr( $addr ) {
wfDeprecated( __METHOD__, '1.18' );
return Sanitizer::validateEmail( $addr );
}
/**
* Given unvalidated user input, return a canonical username, or false if
* the username is invalid.
* @param string $name User input
* @param string|bool $validate type of validation to use:
* - false No validation
* - 'valid' Valid for batch processes
* - 'usable' Valid for batch processes and login
* - 'creatable' Valid for batch processes, login and account creation
*
* @throws MWException
* @return bool|string
*/
public static function getCanonicalName( $name, $validate = 'valid' ) {
// Force usernames to capital
global $wgContLang;
$name = $wgContLang->ucfirst( $name );
# Reject names containing '#'; these will be cleaned up
# with title normalisation, but then it's too late to
# check elsewhere
if ( strpos( $name, '#' ) !== false ) {
return false;
}
// Clean up name according to title rules
$t = ( $validate === 'valid' ) ?
Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
// Check for invalid titles
if ( is_null( $t ) ) {
return false;
}
// Reject various classes of invalid names
global $wgAuth;
$name = $wgAuth->getCanonicalName( $t->getText() );
switch ( $validate ) {
case false:
break;
case 'valid':
if ( !User::isValidUserName( $name ) ) {
$name = false;
}
break;
case 'usable':
if ( !User::isUsableName( $name ) ) {
$name = false;
}
break;
case 'creatable':
if ( !User::isCreatableName( $name ) ) {
$name = false;
}
break;
default:
throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
}
return $name;
}
/**
* Count the number of edits of a user
*
* @param int $uid User ID to check
* @return int The user's edit count
*
* @deprecated since 1.21 in favour of User::getEditCount
*/
public static function edits( $uid ) {
wfDeprecated( __METHOD__, '1.21' );
$user = self::newFromId( $uid );
return $user->getEditCount();
}
/**
* Return a random password.
*
* @return string New random password
*/
public static function randomPassword() {
global $wgMinimalPasswordLength;
// Decide the final password length based on our min password length, stopping at a minimum of 10 chars
$length = max( 10, $wgMinimalPasswordLength );
// Multiply by 1.25 to get the number of hex characters we need
// Generate random hex chars
$hex = MWCryptRand::generateHex( ceil( $length * 1.25 ) );
// Convert from base 16 to base 32 to get a proper password like string
return substr( wfBaseConvert( $hex, 16, 32, $length ), -$length );
}
/**
* Set cached properties to default.
*
* @note This no longer clears uncached lazy-initialised properties;
* the constructor does that instead.
*
* @param $name string|bool
*/
public function loadDefaults( $name = false ) {
wfProfileIn( __METHOD__ );
$this->mId = 0;
$this->mName = $name;
$this->mRealName = '';
$this->mPassword = $this->mNewpassword = '';
$this->mNewpassTime = null;
$this->mEmail = '';
$this->mOptionOverrides = null;
$this->mOptionsLoaded = false;
$loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
if ( $loggedOut !== null ) {
$this->mTouched = wfTimestamp( TS_MW, $loggedOut );
} else {
$this->mTouched = '1'; # Allow any pages to be cached
}
$this->mToken = null; // Don't run cryptographic functions till we need a token
$this->mEmailAuthenticated = null;
$this->mEmailToken = '';
$this->mEmailTokenExpires = null;
$this->mPasswordExpires = null;
$this->resetPasswordExpiration( false );
$this->mRegistration = wfTimestamp( TS_MW );