-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUser.php
5278 lines (4746 loc) · 153 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
*/
/**
* String Some punctuation to prevent editing from broken text-mangling proxies.
* @ingroup Constants
*/
define( 'EDIT_TOKEN_SUFFIX', '+\\' );
/**
* 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 implements IDBAccessObject {
/**
* @const int Number of characters in user_token field.
*/
const TOKEN_LENGTH = 32;
/**
* Global constant made accessible as class constants so that autoloader
* magic can be used.
*/
const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
/**
* @const int Serialized record version.
*/
const VERSION = 10;
/**
* Maximum items in $mWatchedItems
*/
const MAX_WATCHED_ITEMS_CACHE = 100;
/**
* Exclude user options that are set to their default value.
* @since 1.25
*/
const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
/**
* @var PasswordFactory Lazily loaded factory object for passwords
*/
private static $mPasswordFactory = null;
/**
* 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
*/
protected static $mCacheVars = array(
// user table
'mId',
'mName',
'mRealName',
'mEmail',
'mTouched',
'mToken',
'mEmailAuthenticated',
'mEmailToken',
'mEmailTokenExpires',
'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
*/
protected static $mCoreRights = array(
'apihighlimits',
'applychangetags',
'autoconfirmed',
'autopatrol',
'bigdelete',
'block',
'blockemail',
'bot',
'browsearchive',
'changetags',
'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',
'managechangetags',
'markbotedits',
'mergehistory',
'minoredit',
'move',
'movefile',
'move-categorypages',
'move-rootuserpages',
'move-subpages',
'nominornewtalk',
'noratelimit',
'override-export-depth',
'pagelang',
'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',
'viewsuppressed',
'writeapi',
);
/**
* String Cached results of getAllRights()
*/
protected static $mAllRights = false;
/** Cache variables */
//@{
public $mId;
/** @var string */
public $mName;
/** @var string */
public $mRealName;
/**
* @todo Make this actually private
* @private
* @var Password
*/
public $mPassword;
/**
* @todo Make this actually private
* @private
* @var Password
*/
public $mNewpassword;
/** @var string */
public $mNewpassTime;
/** @var string */
public $mEmail;
/** @var string TS_MW timestamp from the DB */
public $mTouched;
/** @var string TS_MW timestamp from cache */
protected $mQuickTouched;
/** @var string */
protected $mToken;
/** @var string */
public $mEmailAuthenticated;
/** @var string */
protected $mEmailToken;
/** @var string */
protected $mEmailTokenExpires;
/** @var string */
protected $mRegistration;
/** @var int */
protected $mEditCount;
/** @var array */
public $mGroups;
/** @var array */
protected $mOptionOverrides;
/** @var string */
protected $mPasswordExpires;
//@}
/**
* Bool Whether the cache variables have been loaded.
*/
//@{
public $mOptionsLoaded;
/**
* Array with already loaded items or true if all items have been loaded.
*/
protected $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.
*/
public $mFrom;
/**
* Lazy-initialized variables, invalidated with clearInstanceCache
*/
protected $mNewtalk;
/** @var string */
protected $mDatePreference;
/** @var string */
public $mBlockedby;
/** @var string */
protected $mHash;
/** @var array */
public $mRights;
/** @var string */
protected $mBlockreason;
/** @var array */
protected $mEffectiveGroups;
/** @var array */
protected $mImplicitGroups;
/** @var array */
protected $mFormerGroups;
/** @var bool */
protected $mBlockedGlobally;
/** @var bool */
protected $mLocked;
/** @var bool */
public $mHideName;
/** @var array */
public $mOptions;
/**
* @var WebRequest
*/
private $mRequest;
/** @var Block */
public $mBlock;
/** @var bool */
protected $mAllowUsertalk;
/** @var Block */
private $mBlockedFromCreateAccount = false;
/** @var array */
private $mWatchedItems = array();
/** @var integer User::READ_* constant bitfield used to load data */
protected $queryFlagsUsed = self::READ_NORMAL;
public 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.
*
* @param integer $flags User::READ_* constant bitfield
*/
public function load( $flags = self::READ_NORMAL ) {
if ( $this->mLoadedItems === true ) {
return;
}
// Set it now to avoid infinite recursion in accessors
$this->mLoadedItems = true;
$this->queryFlagsUsed = $flags;
switch ( $this->mFrom ) {
case 'defaults':
$this->loadDefaults();
break;
case 'name':
// Make sure this thread sees its own changes
if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
$flags |= self::READ_LATEST;
$this->queryFlagsUsed = $flags;
}
$this->mId = self::idFromName( $this->mName, $flags );
if ( !$this->mId ) {
// Nonexistent user placeholder object
$this->loadDefaults( $this->mName );
} else {
$this->loadFromId( $flags );
}
break;
case 'id':
$this->loadFromId( $flags );
break;
case 'session':
if ( !$this->loadFromSession() ) {
// Loading from session failed. Load defaults.
$this->loadDefaults();
}
Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
break;
default:
throw new UnexpectedValueException(
"Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
}
}
/**
* Load user table data, given mId has already been set.
* @param integer $flags User::READ_* constant bitfield
* @return bool False if the ID does not exist, true otherwise
*/
public function loadFromId( $flags = self::READ_NORMAL ) {
if ( $this->mId == 0 ) {
$this->loadDefaults();
return false;
}
// Try cache (unless this needs to lock the DB).
// NOTE: if this thread called saveSettings(), the cache was cleared.
$locking = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING );
if ( $locking || !$this->loadFromCache() ) {
wfDebug( "User: cache miss for user {$this->mId}\n" );
// Load from DB (make sure this thread sees its own changes)
if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
$flags |= self::READ_LATEST;
}
if ( !$this->loadFromDatabase( $flags ) ) {
// Can't load from ID, user is anonymous
return false;
}
$this->saveToCache();
}
$this->mLoadedItems = true;
$this->queryFlagsUsed = $flags;
return true;
}
/**
* Load user data from shared cache, given mId has already been set.
*
* @return bool false if the ID does not exist or data is invalid, true otherwise
* @since 1.25
*/
protected function loadFromCache() {
if ( $this->mId == 0 ) {
$this->loadDefaults();
return false;
}
$key = wfMemcKey( 'user', 'id', $this->mId );
$data = ObjectCache::getMainWANInstance()->get( $key );
if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
// Object is expired
return false;
}
wfDebug( "User: got user {$this->mId} from cache\n" );
// Restore from cache
foreach ( self::$mCacheVars as $name ) {
$this->$name = $data[$name];
}
return true;
}
/**
* Save user data to the shared cache
*
* This method should not be called outside the User class
*/
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'] = self::VERSION;
$key = wfMemcKey( 'user', 'id', $this->mId );
ObjectCache::getMainWANInstance()->set( $key, $data, 3600 );
}
/** @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
* @param int $flags User::READ_* bitfield
* @return User|null
*/
public static function newFromConfirmationCode( $code, $flags = 0 ) {
$db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
? wfGetDB( DB_MASTER )
: wfGetDB( DB_SLAVE );
$id = $db->selectField(
'user',
'user_id',
array(
'user_email_token' => md5( $code ),
'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
)
);
return $id ? User::newFromId( $id ) : 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|null $request Object to use; $wgRequest will be used if omitted.
* @return User
*/
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
* @param integer $flags User::READ_* constant bitfield
* @return int|null The corresponding user's ID, or null if user is nonexistent
*/
public static function idFromName( $name, $flags = self::READ_NORMAL ) {
$nt = Title::makeTitleSafe( NS_USER, $name );
if ( is_null( $nt ) ) {
// Illegal name
return null;
}
if ( isset( self::$idCacheByName[$name] ) ) {
return self::$idCacheByName[$name];
}
$db = ( $flags & self::READ_LATEST )
? wfGetDB( DB_MASTER )
: wfGetDB( DB_SLAVE );
$s = $db->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;
Hooks::run( '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 String 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 bool|string|array 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
*
* Create a Status object based on the password's validity.
* The Status should be set to fatal if the user should not
* be allowed to log in, and should have any errors that
* would block changing the password.
*
* If the return value of this is not OK, the password
* should not be checked. If the return value is not Good,
* the password can be checked, but the user should not be
* able to set their password to this.
*
* @param string $password Desired password
* @param string $purpose one of 'login', 'create', 'reset'
* @return Status
* @since 1.23
*/
public function checkPasswordValidity( $password, $purpose = 'login' ) {
global $wgPasswordPolicy;
$upp = new UserPasswordPolicy(
$wgPasswordPolicy['policies'],
$wgPasswordPolicy['checks']
);
$status = Status::newGood();
$result = false; //init $result to false for the internal checks
if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
$status->error( $result );
return $status;
}
if ( $result === false ) {
$status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
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 int $ts Optional timestamp to convert, default 0 for the current time
*/
public function expirePassword( $ts = 0 ) {
$this->loadPasswords();
$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
Hooks::run( '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|bool The datestamp of the expiration, or null if not set
*/
public function getPasswordExpireDate() {
$this->load();
return $this->mPasswordExpires;
}
/**
* 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 InvalidArgumentException
* @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,
// but only when validation is requested (bug 12654)
$t = ( $validate !== false ) ?
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: