don't just assume we get a valid title object
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 # Serialized record version
17 define( 'MW_USER_VERSION', 2 );
18
19 /**
20 *
21 * @package MediaWiki
22 */
23 class User {
24 /**#@+
25 * @access private
26 */
27 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
28 var $mEmailAuthenticated;
29 var $mRights, $mOptions;
30 var $mDataLoaded, $mNewpassword;
31 var $mSkin;
32 var $mBlockedby, $mBlockreason;
33 var $mTouched;
34 var $mToken;
35 var $mRealName;
36 var $mHash;
37 var $mGroups;
38 var $mVersion; // serialized version
39
40 /** Construct using User:loadDefaults() */
41 function User() {
42 $this->loadDefaults();
43 $this->mVersion = MW_USER_VERSION;
44 }
45
46 /**
47 * Static factory method
48 * @param string $name Username, validated by Title:newFromText()
49 * @return User
50 * @static
51 */
52 function newFromName( $name ) {
53 $u = new User();
54
55 # Force usernames to capital
56 global $wgContLang;
57 $name = $wgContLang->ucfirst( $name );
58
59 # Clean up name according to title rules
60 $t = Title::newFromText( $name );
61 if( is_null( $t ) ) {
62 return null;
63 }
64
65 # Reject various classes of invalid names
66 $canonicalName = $t->getText();
67 if( !User::isValidUserName( $canonicalName ) ) {
68 return null;
69 }
70
71 $u->setName( $canonicalName );
72 $u->setId( $u->idFromName( $t->getText() ) );
73 return $u;
74 }
75
76 /**
77 * Factory method to fetch whichever use has a given email confirmation code.
78 * This code is generated when an account is created or its e-mail address
79 * has changed.
80 *
81 * If the code is invalid or has expired, returns NULL.
82 *
83 * @param string $code
84 * @return User
85 * @static
86 */
87 function newFromConfirmationCode( $code ) {
88 $dbr =& wfGetDB( DB_SLAVE );
89 $name = $dbr->selectField( 'user', 'user_name', array(
90 'user_email_token' => md5( $code ),
91 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
92 ) );
93 if( is_string( $name ) ) {
94 return User::newFromName( $name );
95 } else {
96 return null;
97 }
98 }
99
100 /**
101 * Serialze sleep function, for better cache efficiency and avoidance of
102 * silly "incomplete type" errors when skins are cached
103 */
104 function __sleep() {
105 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
106 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
107 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
108 'mToken', 'mRealName', 'mHash', 'mGroups' );
109 }
110
111 /**
112 * Get username given an id.
113 * @param integer $id Database user id
114 * @return string Nickname of a user
115 * @static
116 */
117 function whoIs( $id ) {
118 $dbr =& wfGetDB( DB_SLAVE );
119 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
120 }
121
122 /**
123 * Get real username given an id.
124 * @param integer $id Database user id
125 * @return string Realname of a user
126 * @static
127 */
128 function whoIsReal( $id ) {
129 $dbr =& wfGetDB( DB_SLAVE );
130 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
131 }
132
133 /**
134 * Get database id given a user name
135 * @param string $name Nickname of a user
136 * @return integer|null Database user id (null: if non existent
137 * @static
138 */
139 function idFromName( $name ) {
140 $fname = "User::idFromName";
141
142 $nt = Title::newFromText( $name );
143 if( is_null( $nt ) ) {
144 # Illegal name
145 return null;
146 }
147 $dbr =& wfGetDB( DB_SLAVE );
148 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
149
150 if ( $s === false ) {
151 return 0;
152 } else {
153 return $s->user_id;
154 }
155 }
156
157 /**
158 * does the string match an anonymous IPv4 address?
159 *
160 * @static
161 * @param string $name Nickname of a user
162 * @return bool
163 */
164 function isIP( $name ) {
165 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
166 /*return preg_match("/^
167 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
168 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
169 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
170 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
171 $/x", $name);*/
172 }
173
174 /**
175 * Is the input a valid username?
176 *
177 * Checks if the input is a valid username, we don't want an empty string,
178 * an IP address, anything that containins slashes (would mess up subpages),
179 * is longer than the maximum allowed username size or doesn't begin with
180 * a capital letter.
181 *
182 * @param string $name
183 * @return bool
184 * @static
185 */
186 function isValidUserName( $name ) {
187 global $wgContLang, $wgMaxNameChars;
188
189 if ( $name == ''
190 || User::isIP( $name )
191 || strpos( $name, '/' ) !== false
192 || strlen( $name ) > $wgMaxNameChars
193 || $name != $wgContLang->ucfirst( $name ) )
194 return false;
195 else
196 return true;
197 }
198
199 /**
200 * Is the input a valid password?
201 *
202 * @param string $password
203 * @return bool
204 * @static
205 */
206 function isValidPassword( $password ) {
207 global $wgMinimalPasswordLength;
208 return strlen( $password ) >= $wgMinimalPasswordLength;
209 }
210
211 /**
212 * does the string match roughly an email address ?
213 *
214 * @todo Check for RFC 2822 compilance
215 * @bug 959
216 *
217 * @param string $addr email address
218 * @static
219 * @return bool
220 */
221 function isValidEmailAddr ( $addr ) {
222 # There used to be a regular expression here, it got removed because it
223 # rejected valid addresses.
224 return ( trim( $addr ) != '' ) &&
225 (false !== strpos( $addr, '@' ) );
226 }
227
228 /**
229 * probably return a random password
230 * @return string probably a random password
231 * @static
232 * @todo Check what is doing really [AV]
233 */
234 function randomPassword() {
235 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
236 $l = strlen( $pwchars ) - 1;
237
238 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
239 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
240 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
241 $pwchars{mt_rand( 0, $l )};
242 return $np;
243 }
244
245 /**
246 * Set properties to default
247 * Used at construction. It will load per language default settings only
248 * if we have an available language object.
249 */
250 function loadDefaults() {
251 static $n=0;
252 $n++;
253 $fname = 'User::loadDefaults' . $n;
254 wfProfileIn( $fname );
255
256 global $wgContLang, $wgIP, $wgDBname;
257 global $wgNamespacesToBeSearchedDefault;
258
259 $this->mId = 0;
260 $this->mNewtalk = -1;
261 $this->mName = $wgIP;
262 $this->mRealName = $this->mEmail = '';
263 $this->mEmailAuthenticated = null;
264 $this->mPassword = $this->mNewpassword = '';
265 $this->mRights = array();
266 $this->mGroups = array();
267 $this->mOptions = User::getDefaultOptions();
268
269 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
270 $this->mOptions['searchNs'.$nsnum] = $val;
271 }
272 unset( $this->mSkin );
273 $this->mDataLoaded = false;
274 $this->mBlockedby = -1; # Unset
275 $this->setToken(); # Random
276 $this->mHash = false;
277
278 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
279 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
280 }
281 else {
282 $this->mTouched = '0'; # Allow any pages to be cached
283 }
284
285 wfProfileOut( $fname );
286 }
287
288 /**
289 * Combine the language default options with any site-specific options
290 * and add the default language variants.
291 *
292 * @return array
293 * @static
294 * @access private
295 */
296 function getDefaultOptions() {
297 /**
298 * Site defaults will override the global/language defaults
299 */
300 global $wgContLang, $wgDefaultUserOptions;
301 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
302
303 /**
304 * default language setting
305 */
306 $variant = $wgContLang->getPreferredVariant();
307 $defOpt['variant'] = $variant;
308 $defOpt['language'] = $variant;
309
310 return $defOpt;
311 }
312
313 /**
314 * Get a given default option value.
315 *
316 * @param string $opt
317 * @return string
318 * @static
319 * @access public
320 */
321 function getDefaultOption( $opt ) {
322 $defOpts = User::getDefaultOptions();
323 if( isset( $defOpts[$opt] ) ) {
324 return $defOpts[$opt];
325 } else {
326 return '';
327 }
328 }
329
330 /**
331 * Get blocking information
332 * @access private
333 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
334 * non-critical checks are done against slaves. Check when actually saving should be done against
335 * master.
336 *
337 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
338 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
339 * just slightly outta sync and soon corrected - safer to block slightly more that less.
340 * And it's cheaper to check slave first, then master if needed, than master always.
341 */
342 function getBlockedStatus( $bFromSlave = true ) {
343 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
344
345 if ( -1 != $this->mBlockedby ) { return; }
346
347 $this->mBlockedby = 0;
348
349 # User blocking
350 if ( $this->mId ) {
351 $block = new Block();
352 $block->forUpdate( $bFromSlave );
353 if ( $block->load( $wgIP , $this->mId ) ) {
354 $this->mBlockedby = $block->mBy;
355 $this->mBlockreason = $block->mReason;
356 $this->spreadBlock();
357 }
358 }
359
360 # IP/range blocking
361 if ( !$this->mBlockedby ) {
362 # Check first against slave, and optionally from master.
363 $block = $wgBlockCache->get( $wgIP, true );
364 if ( !$block && !$bFromSlave )
365 {
366 # Not blocked: check against master, to make sure.
367 $wgBlockCache->clearLocal( );
368 $block = $wgBlockCache->get( $wgIP, false );
369 }
370 if ( $block !== false ) {
371 $this->mBlockedby = $block->mBy;
372 $this->mBlockreason = $block->mReason;
373 }
374 }
375
376 # Proxy blocking
377 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
378
379 # Local list
380 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
381 $this->mBlockedby = wfMsg( 'proxyblocker' );
382 $this->mBlockreason = wfMsg( 'proxyblockreason' );
383 }
384
385 # DNSBL
386 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
387 if ( $this->inSorbsBlacklist( $wgIP ) ) {
388 $this->mBlockedby = wfMsg( 'sorbs' );
389 $this->mBlockreason = wfMsg( 'sorbsreason' );
390 }
391 }
392 }
393 }
394
395 function inSorbsBlacklist( $ip ) {
396 global $wgEnableSorbs;
397 return $wgEnableSorbs &&
398 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
399 }
400
401 function inOpmBlacklist( $ip ) {
402 global $wgEnableOpm;
403 return $wgEnableOpm &&
404 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
405 }
406
407 function inDnsBlacklist( $ip, $base ) {
408 $fname = 'User::inDnsBlacklist';
409 wfProfileIn( $fname );
410
411 $found = false;
412 $host = '';
413
414 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
415 # Make hostname
416 for ( $i=4; $i>=1; $i-- ) {
417 $host .= $m[$i] . '.';
418 }
419 $host .= $base;
420
421 # Send query
422 $ipList = gethostbynamel( $host );
423
424 if ( $ipList ) {
425 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
426 $found = true;
427 } else {
428 wfDebug( "Requested $host, not found in $base.\n" );
429 }
430 }
431
432 wfProfileOut( $fname );
433 return $found;
434 }
435
436 /**
437 * Primitive rate limits: enforce maximum actions per time period
438 * to put a brake on flooding.
439 *
440 * Note: when using a shared cache like memcached, IP-address
441 * last-hit counters will be shared across wikis.
442 *
443 * @return bool true if a rate limiter was tripped
444 * @access public
445 */
446 function pingLimiter( $action='edit' ) {
447 global $wgRateLimits;
448 if( !isset( $wgRateLimits[$action] ) ) {
449 return false;
450 }
451 if( $this->isAllowed( 'delete' ) ) {
452 // goddam cabal
453 return false;
454 }
455
456 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
457 $fname = 'User::pingLimiter';
458 $limits = $wgRateLimits[$action];
459 $keys = array();
460 $id = $this->getId();
461
462 if( isset( $limits['anon'] ) && $id == 0 ) {
463 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
464 }
465
466 if( isset( $limits['user'] ) && $id != 0 ) {
467 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
468 }
469 if( $this->isNewbie() ) {
470 if( isset( $limits['newbie'] ) && $id != 0 ) {
471 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
472 }
473 if( isset( $limits['ip'] ) ) {
474 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
475 }
476 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
477 $subnet = $matches[1];
478 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
479 }
480 }
481
482 $triggered = false;
483 foreach( $keys as $key => $limit ) {
484 list( $max, $period ) = $limit;
485 $summary = "(limit $max in {$period}s)";
486 $count = $wgMemc->get( $key );
487 if( $count ) {
488 if( $count > $max ) {
489 wfDebug( "$fname: tripped! $key at $count $summary\n" );
490 if( $wgRateLimitLog ) {
491 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
492 }
493 $triggered = true;
494 } else {
495 wfDebug( "$fname: ok. $key at $count $summary\n" );
496 }
497 } else {
498 wfDebug( "$fname: adding record for $key $summary\n" );
499 $wgMemc->add( $key, 1, IntVal( $period ) );
500 }
501 $wgMemc->incr( $key );
502 }
503
504 return $triggered;
505 }
506
507 /**
508 * Check if user is blocked
509 * @return bool True if blocked, false otherwise
510 */
511 function isBlocked( $bFromSlave = false ) {
512 $this->getBlockedStatus( $bFromSlave );
513 return $this->mBlockedby !== 0;
514 }
515
516 /**
517 * Get name of blocker
518 * @return string name of blocker
519 */
520 function blockedBy() {
521 $this->getBlockedStatus();
522 return $this->mBlockedby;
523 }
524
525 /**
526 * Get blocking reason
527 * @return string Blocking reason
528 */
529 function blockedFor() {
530 $this->getBlockedStatus();
531 return $this->mBlockreason;
532 }
533
534 /**
535 * Initialise php session
536 */
537 function SetupSession() {
538 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
539 if( $wgSessionsInMemcached ) {
540 require_once( 'MemcachedSessions.php' );
541 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
542 # If it's left on 'user' or another setting from another
543 # application, it will end up failing. Try to recover.
544 ini_set ( 'session.save_handler', 'files' );
545 }
546 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
547 session_cache_limiter( 'private, must-revalidate' );
548 @session_start();
549 }
550
551 /**
552 * Read datas from session
553 * @static
554 */
555 function loadFromSession() {
556 global $wgMemc, $wgDBname;
557
558 if ( isset( $_SESSION['wsUserID'] ) ) {
559 if ( 0 != $_SESSION['wsUserID'] ) {
560 $sId = $_SESSION['wsUserID'];
561 } else {
562 return new User();
563 }
564 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
565 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
566 $_SESSION['wsUserID'] = $sId;
567 } else {
568 return new User();
569 }
570 if ( isset( $_SESSION['wsUserName'] ) ) {
571 $sName = $_SESSION['wsUserName'];
572 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
573 $sName = $_COOKIE["{$wgDBname}UserName"];
574 $_SESSION['wsUserName'] = $sName;
575 } else {
576 return new User();
577 }
578
579 $passwordCorrect = FALSE;
580 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
581 if( !is_object( $user ) || $user->mVersion < MW_USER_VERSION ) {
582 # Expire old serialized objects; they may be corrupt.
583 $user = false;
584 }
585 if($makenew = !$user) {
586 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
587 $user = new User();
588 $user->mId = $sId;
589 $user->loadFromDatabase();
590 } else {
591 wfDebug( "User::loadFromSession() got from cache!\n" );
592 }
593
594 if ( isset( $_SESSION['wsToken'] ) ) {
595 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
596 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
597 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
598 } else {
599 return new User(); # Can't log in from session
600 }
601
602 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
603 if($makenew) {
604 if($wgMemc->set( $key, $user ))
605 wfDebug( "User::loadFromSession() successfully saved user\n" );
606 else
607 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
608 }
609 return $user;
610 }
611 return new User(); # Can't log in from session
612 }
613
614 /**
615 * Load a user from the database
616 */
617 function loadFromDatabase() {
618 global $wgCommandLineMode;
619 $fname = "User::loadFromDatabase";
620
621 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
622 # loading in a command line script, don't assume all command line scripts need it like this
623 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
624 if ( $this->mDataLoaded ) {
625 return;
626 }
627
628 # Paranoia
629 $this->mId = IntVal( $this->mId );
630
631 /** Anonymous user */
632 if( !$this->mId ) {
633 /** Get rights */
634 $this->mRights = $this->getGroupPermissions( array( '*' ) );
635 $this->mDataLoaded = true;
636 return;
637 } # the following stuff is for non-anonymous users only
638
639 $dbr =& wfGetDB( DB_SLAVE );
640 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
641 'user_email_authenticated',
642 'user_real_name','user_options','user_touched', 'user_token' ),
643 array( 'user_id' => $this->mId ), $fname );
644
645 if ( $s !== false ) {
646 $this->mName = $s->user_name;
647 $this->mEmail = $s->user_email;
648 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
649 $this->mRealName = $s->user_real_name;
650 $this->mPassword = $s->user_password;
651 $this->mNewpassword = $s->user_newpassword;
652 $this->decodeOptions( $s->user_options );
653 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
654 $this->mToken = $s->user_token;
655
656 $res = $dbr->select( 'user_groups',
657 array( 'ug_group' ),
658 array( 'ug_user' => $this->mId ),
659 $fname );
660 $this->mGroups = array();
661 while( $row = $dbr->fetchObject( $res ) ) {
662 $this->mGroups[] = $row->ug_group;
663 }
664 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
665 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
666 }
667
668 $this->mDataLoaded = true;
669 }
670
671 function getID() { return $this->mId; }
672 function setID( $v ) {
673 $this->mId = $v;
674 $this->mDataLoaded = false;
675 }
676
677 function getName() {
678 $this->loadFromDatabase();
679 return $this->mName;
680 }
681
682 function setName( $str ) {
683 $this->loadFromDatabase();
684 $this->mName = $str;
685 }
686
687
688 /**
689 * Return the title dbkey form of the name, for eg user pages.
690 * @return string
691 * @access public
692 */
693 function getTitleKey() {
694 return str_replace( ' ', '_', $this->getName() );
695 }
696
697 function getNewtalk() {
698 global $wgUseEnotif;
699 $fname = 'User::getNewtalk';
700 $this->loadFromDatabase();
701
702 # Load the newtalk status if it is unloaded (mNewtalk=-1)
703 if( $this->mNewtalk == -1 ) {
704 $this->mNewtalk = 0; # reset talk page status
705
706 # Check memcached separately for anons, who have no
707 # entire User object stored in there.
708 if( !$this->mId ) {
709 global $wgDBname, $wgMemc;
710 $key = "$wgDBname:newtalk:ip:{$this->mName}";
711 $newtalk = $wgMemc->get( $key );
712 if( is_integer( $newtalk ) ) {
713 $this->mNewtalk = $newtalk ? 1 : 0;
714 return (bool)$this->mNewtalk;
715 }
716 }
717
718 $dbr =& wfGetDB( DB_SLAVE );
719 if ( $wgUseEnotif ) {
720 $res = $dbr->select( 'watchlist',
721 array( 'wl_user' ),
722 array( 'wl_title' => $this->getTitleKey(),
723 'wl_namespace' => NS_USER_TALK,
724 'wl_user' => $this->mId,
725 'wl_notificationtimestamp != 0' ),
726 'User::getNewtalk' );
727 if( $dbr->numRows($res) > 0 ) {
728 $this->mNewtalk = 1;
729 }
730 $dbr->freeResult( $res );
731 } elseif ( $this->mId ) {
732 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId ), $fname );
733
734 if ( $dbr->numRows($res)>0 ) {
735 $this->mNewtalk= 1;
736 }
737 $dbr->freeResult( $res );
738 } else {
739 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName ), $fname );
740 $this->mNewtalk = $dbr->numRows( $res ) > 0 ? 1 : 0;
741 $dbr->freeResult( $res );
742 }
743
744 if( !$this->mId ) {
745 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
746 }
747 }
748
749 return ( 0 != $this->mNewtalk );
750 }
751
752 function setNewtalk( $val ) {
753 $this->loadFromDatabase();
754 $this->mNewtalk = $val;
755 $this->invalidateCache();
756 }
757
758 function invalidateCache() {
759 global $wgClockSkewFudge;
760 $this->loadFromDatabase();
761 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
762 # Don't forget to save the options after this or
763 # it won't take effect!
764 }
765
766 function validateCache( $timestamp ) {
767 $this->loadFromDatabase();
768 return ($timestamp >= $this->mTouched);
769 }
770
771 /**
772 * Salt a password.
773 * Will only be salted if $wgPasswordSalt is true
774 * @param string Password.
775 * @return string Salted password or clear password.
776 */
777 function addSalt( $p ) {
778 global $wgPasswordSalt;
779 if($wgPasswordSalt)
780 return md5( "{$this->mId}-{$p}" );
781 else
782 return $p;
783 }
784
785 /**
786 * Encrypt a password.
787 * It can eventuall salt a password @see User::addSalt()
788 * @param string $p clear Password.
789 * @param string Encrypted password.
790 */
791 function encryptPassword( $p ) {
792 return $this->addSalt( md5( $p ) );
793 }
794
795 # Set the password and reset the random token
796 function setPassword( $str ) {
797 $this->loadFromDatabase();
798 $this->setToken();
799 $this->mPassword = $this->encryptPassword( $str );
800 $this->mNewpassword = '';
801 }
802
803 # Set the random token (used for persistent authentication)
804 function setToken( $token = false ) {
805 global $wgSecretKey, $wgProxyKey, $wgDBname;
806 if ( !$token ) {
807 if ( $wgSecretKey ) {
808 $key = $wgSecretKey;
809 } elseif ( $wgProxyKey ) {
810 $key = $wgProxyKey;
811 } else {
812 $key = microtime();
813 }
814 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
815 } else {
816 $this->mToken = $token;
817 }
818 }
819
820
821 function setCookiePassword( $str ) {
822 $this->loadFromDatabase();
823 $this->mCookiePassword = md5( $str );
824 }
825
826 function setNewpassword( $str ) {
827 $this->loadFromDatabase();
828 $this->mNewpassword = $this->encryptPassword( $str );
829 }
830
831 function getEmail() {
832 $this->loadFromDatabase();
833 return $this->mEmail;
834 }
835
836 function getEmailAuthenticationTimestamp() {
837 $this->loadFromDatabase();
838 return $this->mEmailAuthenticated;
839 }
840
841 function setEmail( $str ) {
842 $this->loadFromDatabase();
843 $this->mEmail = $str;
844 }
845
846 function getRealName() {
847 $this->loadFromDatabase();
848 return $this->mRealName;
849 }
850
851 function setRealName( $str ) {
852 $this->loadFromDatabase();
853 $this->mRealName = $str;
854 }
855
856 function getOption( $oname ) {
857 $this->loadFromDatabase();
858 if ( array_key_exists( $oname, $this->mOptions ) ) {
859 return trim( $this->mOptions[$oname] );
860 } else {
861 return '';
862 }
863 }
864
865 function setOption( $oname, $val ) {
866 $this->loadFromDatabase();
867 if ( $oname == 'skin' ) {
868 # Clear cached skin, so the new one displays immediately in Special:Preferences
869 unset( $this->mSkin );
870 }
871 $this->mOptions[$oname] = $val;
872 $this->invalidateCache();
873 }
874
875 function getRights() {
876 $this->loadFromDatabase();
877 return $this->mRights;
878 }
879
880 /**
881 * Get the list of explicit group memberships this user has.
882 * The implicit * and user groups are not included.
883 * @return array of strings
884 */
885 function getGroups() {
886 $this->loadFromDatabase();
887 return $this->mGroups;
888 }
889
890 /**
891 * Get the list of implicit group memberships this user has.
892 * This includes all explicit groups, plus 'user' if logged in
893 * and '*' for all accounts.
894 * @return array of strings
895 */
896 function getEffectiveGroups() {
897 $base = array( '*' );
898 if( $this->isLoggedIn() ) {
899 $base[] = 'user';
900 }
901 return array_merge( $base, $this->getGroups() );
902 }
903
904 /**
905 * Remove the user from the given group.
906 * This takes immediate effect.
907 * @string $group
908 */
909 function addGroup( $group ) {
910 $dbw =& wfGetDB( DB_MASTER );
911 $dbw->insert( 'user_groups',
912 array(
913 'ug_user' => $this->getID(),
914 'ug_group' => $group,
915 ),
916 'User::addGroup',
917 array( 'IGNORE' ) );
918
919 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
920 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
921
922 $this->invalidateCache();
923 $this->saveSettings();
924 }
925
926 /**
927 * Remove the user from the given group.
928 * This takes immediate effect.
929 * @string $group
930 */
931 function removeGroup( $group ) {
932 $dbw =& wfGetDB( DB_MASTER );
933 $dbw->delete( 'user_groups',
934 array(
935 'ug_user' => $this->getID(),
936 'ug_group' => $group,
937 ),
938 'User::removeGroup' );
939
940 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
941 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
942
943 $this->invalidateCache();
944 $this->saveSettings();
945 }
946
947
948 /**
949 * A more legible check for non-anonymousness.
950 * Returns true if the user is not an anonymous visitor.
951 *
952 * @return bool
953 */
954 function isLoggedIn() {
955 return( $this->getID() != 0 );
956 }
957
958 /**
959 * A more legible check for anonymousness.
960 * Returns true if the user is an anonymous visitor.
961 *
962 * @return bool
963 */
964 function isAnon() {
965 return !$this->isLoggedIn();
966 }
967
968 /**
969 * Check if a user is sysop
970 * Die with backtrace. Use User:isAllowed() instead.
971 * @deprecated
972 */
973 function isSysop() {
974 return $this->isAllowed( 'protect' );
975 }
976
977 /** @deprecated */
978 function isDeveloper() {
979 return $this->isAllowed( 'siteadmin' );
980 }
981
982 /** @deprecated */
983 function isBureaucrat() {
984 return $this->isAllowed( 'makesysop' );
985 }
986
987 /**
988 * Whether the user is a bot
989 * @todo need to be migrated to the new user level management sytem
990 */
991 function isBot() {
992 $this->loadFromDatabase();
993 return in_array( 'bot', $this->mRights );
994 }
995
996 /**
997 * Check if user is allowed to access a feature / make an action
998 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
999 * @return boolean True: action is allowed, False: action should not be allowed
1000 */
1001 function isAllowed($action='') {
1002 $this->loadFromDatabase();
1003 return in_array( $action , $this->mRights );
1004 }
1005
1006 /**
1007 * Load a skin if it doesn't exist or return it
1008 * @todo FIXME : need to check the old failback system [AV]
1009 */
1010 function &getSkin() {
1011 global $IP;
1012 if ( ! isset( $this->mSkin ) ) {
1013 $fname = 'User::getSkin';
1014 wfProfileIn( $fname );
1015
1016 # get all skin names available
1017 $skinNames = Skin::getSkinNames();
1018
1019 # get the user skin
1020 $userSkin = $this->getOption( 'skin' );
1021 if ( $userSkin == '' ) { $userSkin = 'standard'; }
1022
1023 if ( !isset( $skinNames[$userSkin] ) ) {
1024 # in case the user skin could not be found find a replacement
1025 $fallback = array(
1026 0 => 'Standard',
1027 1 => 'Nostalgia',
1028 2 => 'CologneBlue');
1029 # if phptal is enabled we should have monobook skin that
1030 # superseed the good old SkinStandard.
1031 if ( isset( $skinNames['monobook'] ) ) {
1032 $fallback[0] = 'MonoBook';
1033 }
1034
1035 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
1036 $sn = $fallback[$userSkin];
1037 } else {
1038 $sn = 'Standard';
1039 }
1040 } else {
1041 # The user skin is available
1042 $sn = $skinNames[$userSkin];
1043 }
1044
1045 # Grab the skin class and initialise it. Each skin checks for PHPTal
1046 # and will not load if it's not enabled.
1047 require_once( $IP.'/skins/'.$sn.'.php' );
1048
1049 # Check if we got if not failback to default skin
1050 $className = 'Skin'.$sn;
1051 if( !class_exists( $className ) ) {
1052 # DO NOT die if the class isn't found. This breaks maintenance
1053 # scripts and can cause a user account to be unrecoverable
1054 # except by SQL manipulation if a previously valid skin name
1055 # is no longer valid.
1056 $className = 'SkinStandard';
1057 require_once( $IP.'/skins/Standard.php' );
1058 }
1059 $this->mSkin =& new $className;
1060 wfProfileOut( $fname );
1061 }
1062 return $this->mSkin;
1063 }
1064
1065 /**#@+
1066 * @param string $title Article title to look at
1067 */
1068
1069 /**
1070 * Check watched status of an article
1071 * @return bool True if article is watched
1072 */
1073 function isWatched( $title ) {
1074 $wl = WatchedItem::fromUserTitle( $this, $title );
1075 return $wl->isWatched();
1076 }
1077
1078 /**
1079 * Watch an article
1080 */
1081 function addWatch( $title ) {
1082 $wl = WatchedItem::fromUserTitle( $this, $title );
1083 $wl->addWatch();
1084 $this->invalidateCache();
1085 }
1086
1087 /**
1088 * Stop watching an article
1089 */
1090 function removeWatch( $title ) {
1091 $wl = WatchedItem::fromUserTitle( $this, $title );
1092 $wl->removeWatch();
1093 $this->invalidateCache();
1094 }
1095
1096 /**
1097 * Clear the user's notification timestamp for the given title.
1098 * If e-notif e-mails are on, they will receive notification mails on
1099 * the next change of the page if it's watched etc.
1100 */
1101 function clearNotification( &$title ) {
1102 global $wgUser, $wgUseEnotif;
1103
1104 if ( !$wgUseEnotif ) {
1105 return;
1106 }
1107
1108 $userid = $this->getID();
1109 if ($userid==0) {
1110 return;
1111 }
1112
1113 // Only update the timestamp if the page is being watched.
1114 // The query to find out if it is watched is cached both in memcached and per-invocation,
1115 // and when it does have to be executed, it can be on a slave
1116 // If this is the user's newtalk page, we always update the timestamp
1117 if ($title->getNamespace() == NS_USER_TALK &&
1118 $title->getText() == $wgUser->getName())
1119 {
1120 $watched = true;
1121 } elseif ( $this->getID() == $wgUser->getID() ) {
1122 $watched = $title->userIsWatching();
1123 } else {
1124 $watched = true;
1125 }
1126
1127 // If the page is watched by the user (or may be watched), update the timestamp on any
1128 // any matching rows
1129 if ( $watched ) {
1130 $dbw =& wfGetDB( DB_MASTER );
1131 $success = $dbw->update( 'watchlist',
1132 array( /* SET */
1133 'wl_notificationtimestamp' => 0
1134 ), array( /* WHERE */
1135 'wl_title' => $title->getDBkey(),
1136 'wl_namespace' => $title->getNamespace(),
1137 'wl_user' => $this->getID()
1138 ), 'User::clearLastVisited'
1139 );
1140 }
1141 }
1142
1143 /**#@-*/
1144
1145 /**
1146 * Resets all of the given user's page-change notification timestamps.
1147 * If e-notif e-mails are on, they will receive notification mails on
1148 * the next change of any watched page.
1149 *
1150 * @param int $currentUser user ID number
1151 * @access public
1152 */
1153 function clearAllNotifications( $currentUser ) {
1154 global $wgUseEnotif;
1155 if ( !$wgUseEnotif ) {
1156 return;
1157 }
1158 if( $currentUser != 0 ) {
1159
1160 $dbw =& wfGetDB( DB_MASTER );
1161 $success = $dbw->update( 'watchlist',
1162 array( /* SET */
1163 'wl_notificationtimestamp' => 0
1164 ), array( /* WHERE */
1165 'wl_user' => $currentUser
1166 ), 'UserMailer::clearAll'
1167 );
1168
1169 # we also need to clear here the "you have new message" notification for the own user_talk page
1170 # This is cleared one page view later in Article::viewUpdates();
1171 }
1172 }
1173
1174 /**
1175 * @access private
1176 * @return string Encoding options
1177 */
1178 function encodeOptions() {
1179 $a = array();
1180 foreach ( $this->mOptions as $oname => $oval ) {
1181 array_push( $a, $oname.'='.$oval );
1182 }
1183 $s = implode( "\n", $a );
1184 return $s;
1185 }
1186
1187 /**
1188 * @access private
1189 */
1190 function decodeOptions( $str ) {
1191 $a = explode( "\n", $str );
1192 foreach ( $a as $s ) {
1193 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1194 $this->mOptions[$m[1]] = $m[2];
1195 }
1196 }
1197 }
1198
1199 function setCookies() {
1200 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1201 if ( 0 == $this->mId ) return;
1202 $this->loadFromDatabase();
1203 $exp = time() + $wgCookieExpiration;
1204
1205 $_SESSION['wsUserID'] = $this->mId;
1206 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1207
1208 $_SESSION['wsUserName'] = $this->mName;
1209 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1210
1211 $_SESSION['wsToken'] = $this->mToken;
1212 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1213 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1214 } else {
1215 setcookie( $wgDBname.'Token', '', time() - 3600 );
1216 }
1217 }
1218
1219 /**
1220 * Logout user
1221 * It will clean the session cookie
1222 */
1223 function logout() {
1224 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1225 $this->loadDefaults();
1226 $this->setLoaded( true );
1227
1228 $_SESSION['wsUserID'] = 0;
1229
1230 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1231 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1232
1233 # Remember when user logged out, to prevent seeing cached pages
1234 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1235 }
1236
1237 /**
1238 * Save object settings into database
1239 */
1240 function saveSettings() {
1241 global $wgMemc, $wgDBname, $wgUseEnotif;
1242 $fname = 'User::saveSettings';
1243
1244 if ( wfReadOnly() ) { return; }
1245 $this->saveNewtalk();
1246 if ( 0 == $this->mId ) { return; }
1247
1248 $dbw =& wfGetDB( DB_MASTER );
1249 $dbw->update( 'user',
1250 array( /* SET */
1251 'user_name' => $this->mName,
1252 'user_password' => $this->mPassword,
1253 'user_newpassword' => $this->mNewpassword,
1254 'user_real_name' => $this->mRealName,
1255 'user_email' => $this->mEmail,
1256 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1257 'user_options' => $this->encodeOptions(),
1258 'user_touched' => $dbw->timestamp($this->mTouched),
1259 'user_token' => $this->mToken
1260 ), array( /* WHERE */
1261 'user_id' => $this->mId
1262 ), $fname
1263 );
1264 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1265 }
1266
1267 /**
1268 * Save value of new talk flag.
1269 */
1270 function saveNewtalk() {
1271 global $wgDBname, $wgMemc, $wgUseEnotif;
1272
1273 $fname = 'User::saveNewtalk';
1274
1275 $changed = false;
1276
1277 if ( wfReadOnly() ) { return ; }
1278 $dbr =& wfGetDB( DB_SLAVE );
1279 $dbw =& wfGetDB( DB_MASTER );
1280 $changed = false;
1281 if ( $wgUseEnotif ) {
1282 if ( ! $this->getNewtalk() ) {
1283 # Delete the watchlist entry for user_talk page X watched by user X
1284 $dbw->delete( 'watchlist',
1285 array( 'wl_user' => $this->mId,
1286 'wl_title' => $this->getTitleKey(),
1287 'wl_namespace' => NS_USER_TALK ),
1288 $fname );
1289 if ( $dbw->affectedRows() ) {
1290 $changed = true;
1291 }
1292 if( !$this->mId ) {
1293 # Anon users have a separate memcache space for newtalk
1294 # since they don't store their own info. Trim...
1295 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1296 }
1297 }
1298 } else {
1299 if ($this->getID() != 0) {
1300 $field = 'user_id';
1301 $value = $this->getID();
1302 $key = false;
1303 } else {
1304 $field = 'user_ip';
1305 $value = $this->mName;
1306 $key = "$wgDBname:newtalk:ip:$this->mName";
1307 }
1308
1309 $dbr =& wfGetDB( DB_SLAVE );
1310 $dbw =& wfGetDB( DB_MASTER );
1311
1312 $res = $dbr->selectField('user_newtalk', $field,
1313 array($field => $value), $fname);
1314
1315 $changed = true;
1316 if ($res !== false && $this->mNewtalk == 0) {
1317 $dbw->delete('user_newtalk', array($field => $value), $fname);
1318 if ( $key ) {
1319 $wgMemc->set( $key, 0 );
1320 }
1321 } else if ($res === false && $this->mNewtalk == 1) {
1322 $dbw->insert('user_newtalk', array($field => $value), $fname);
1323 if ( $key ) {
1324 $wgMemc->set( $key, 1 );
1325 }
1326 } else {
1327 $changed = false;
1328 }
1329 }
1330
1331 # Update user_touched, so that newtalk notifications in the client cache are invalidated
1332 if ( $changed && $this->getID() ) {
1333 $dbw->update('user',
1334 /*SET*/ array( 'user_touched' => $this->mTouched ),
1335 /*WHERE*/ array( 'user_id' => $this->getID() ),
1336 $fname);
1337 $wgMemc->set( "$wgDBname:user:id:{$this->mId}", $this, 86400 );
1338 }
1339 }
1340
1341 /**
1342 * Checks if a user with the given name exists, returns the ID
1343 */
1344 function idForName() {
1345 $fname = 'User::idForName';
1346
1347 $gotid = 0;
1348 $s = trim( $this->mName );
1349 if ( 0 == strcmp( '', $s ) ) return 0;
1350
1351 $dbr =& wfGetDB( DB_SLAVE );
1352 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1353 if ( $id === false ) {
1354 $id = 0;
1355 }
1356 return $id;
1357 }
1358
1359 /**
1360 * Add user object to the database
1361 */
1362 function addToDatabase() {
1363 $fname = 'User::addToDatabase';
1364 $dbw =& wfGetDB( DB_MASTER );
1365 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1366 $dbw->insert( 'user',
1367 array(
1368 'user_id' => $seqVal,
1369 'user_name' => $this->mName,
1370 'user_password' => $this->mPassword,
1371 'user_newpassword' => $this->mNewpassword,
1372 'user_email' => $this->mEmail,
1373 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1374 'user_real_name' => $this->mRealName,
1375 'user_options' => $this->encodeOptions(),
1376 'user_token' => $this->mToken
1377 ), $fname
1378 );
1379 $this->mId = $dbw->insertId();
1380 }
1381
1382 function spreadBlock() {
1383 global $wgIP;
1384 # If the (non-anonymous) user is blocked, this function will block any IP address
1385 # that they successfully log on from.
1386 $fname = 'User::spreadBlock';
1387
1388 wfDebug( "User:spreadBlock()\n" );
1389 if ( $this->mId == 0 ) {
1390 return;
1391 }
1392
1393 $userblock = Block::newFromDB( '', $this->mId );
1394 if ( !$userblock->isValid() ) {
1395 return;
1396 }
1397
1398 # Check if this IP address is already blocked
1399 $ipblock = Block::newFromDB( $wgIP );
1400 if ( $ipblock->isValid() ) {
1401 # Just update the timestamp
1402 $ipblock->updateTimestamp();
1403 return;
1404 }
1405
1406 # Make a new block object with the desired properties
1407 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1408 $ipblock->mAddress = $wgIP;
1409 $ipblock->mUser = 0;
1410 $ipblock->mBy = $userblock->mBy;
1411 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1412 $ipblock->mTimestamp = wfTimestampNow();
1413 $ipblock->mAuto = 1;
1414 # If the user is already blocked with an expiry date, we don't
1415 # want to pile on top of that!
1416 if($userblock->mExpiry) {
1417 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1418 } else {
1419 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1420 }
1421
1422 # Insert it
1423 $ipblock->insert();
1424
1425 }
1426
1427 function getPageRenderingHash() {
1428 global $wgContLang;
1429 if( $this->mHash ){
1430 return $this->mHash;
1431 }
1432
1433 // stubthreshold is only included below for completeness,
1434 // it will always be 0 when this function is called by parsercache.
1435
1436 $confstr = $this->getOption( 'math' );
1437 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1438 $confstr .= '!' . $this->getOption( 'editsection' );
1439 $confstr .= '!' . $this->getOption( 'date' );
1440 $confstr .= '!' . $this->getOption( 'numberheadings' );
1441 $confstr .= '!' . $this->getOption( 'language' );
1442 $confstr .= '!' . $this->getOption( 'thumbsize' );
1443 // add in language specific options, if any
1444 $extra = $wgContLang->getExtraHashOptions();
1445 $confstr .= $extra;
1446
1447 $this->mHash = $confstr;
1448 return $confstr ;
1449 }
1450
1451 function isAllowedToCreateAccount() {
1452 return $this->isAllowed( 'createaccount' );
1453 }
1454
1455 /**
1456 * Set mDataLoaded, return previous value
1457 * Use this to prevent DB access in command-line scripts or similar situations
1458 */
1459 function setLoaded( $loaded ) {
1460 return wfSetVar( $this->mDataLoaded, $loaded );
1461 }
1462
1463 /**
1464 * Get this user's personal page title.
1465 *
1466 * @return Title
1467 * @access public
1468 */
1469 function getUserPage() {
1470 return Title::makeTitle( NS_USER, $this->mName );
1471 }
1472
1473 /**
1474 * Get this user's talk page title.
1475 *
1476 * @return Title
1477 * @access public
1478 */
1479 function getTalkPage() {
1480 $title = $this->getUserPage();
1481 return $title->getTalkPage();
1482 }
1483
1484 /**
1485 * @static
1486 */
1487 function getMaxID() {
1488 $dbr =& wfGetDB( DB_SLAVE );
1489 return $dbr->selectField( 'user', 'max(user_id)', false );
1490 }
1491
1492 /**
1493 * Determine whether the user is a newbie. Newbies are either
1494 * anonymous IPs, or the 1% most recently created accounts.
1495 * Bots and sysops are excluded.
1496 * @return bool True if it is a newbie.
1497 */
1498 function isNewbie() {
1499 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1500 }
1501
1502 /**
1503 * Check to see if the given clear-text password is one of the accepted passwords
1504 * @param string $password User password.
1505 * @return bool True if the given password is correct otherwise False.
1506 */
1507 function checkPassword( $password ) {
1508 global $wgAuth, $wgMinimalPasswordLength;
1509 $this->loadFromDatabase();
1510
1511 // Even though we stop people from creating passwords that
1512 // are shorter than this, doesn't mean people wont be able
1513 // to. Certain authentication plugins do NOT want to save
1514 // domain passwords in a mysql database, so we should
1515 // check this (incase $wgAuth->strict() is false).
1516 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1517 return false;
1518 }
1519
1520 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1521 return true;
1522 } elseif( $wgAuth->strict() ) {
1523 /* Auth plugin doesn't allow local authentication */
1524 return false;
1525 }
1526 $ep = $this->encryptPassword( $password );
1527 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1528 return true;
1529 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1530 return true;
1531 } elseif ( function_exists( 'iconv' ) ) {
1532 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1533 # Check for this with iconv
1534 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1535 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1536 return true;
1537 }
1538 }
1539 return false;
1540 }
1541
1542 /**
1543 * Initialize (if necessary) and return a session token value
1544 * which can be used in edit forms to show that the user's
1545 * login credentials aren't being hijacked with a foreign form
1546 * submission.
1547 *
1548 * @param mixed $salt - Optional function-specific data for hash.
1549 * Use a string or an array of strings.
1550 * @return string
1551 * @access public
1552 */
1553 function editToken( $salt = '' ) {
1554 if( !isset( $_SESSION['wsEditToken'] ) ) {
1555 $token = $this->generateToken();
1556 $_SESSION['wsEditToken'] = $token;
1557 } else {
1558 $token = $_SESSION['wsEditToken'];
1559 }
1560 if( is_array( $salt ) ) {
1561 $salt = implode( '|', $salt );
1562 }
1563 return md5( $token . $salt );
1564 }
1565
1566 /**
1567 * Generate a hex-y looking random token for various uses.
1568 * Could be made more cryptographically sure if someone cares.
1569 * @return string
1570 */
1571 function generateToken( $salt = '' ) {
1572 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1573 return md5( $token . $salt );
1574 }
1575
1576 /**
1577 * Check given value against the token value stored in the session.
1578 * A match should confirm that the form was submitted from the
1579 * user's own login session, not a form submission from a third-party
1580 * site.
1581 *
1582 * @param string $val - the input value to compare
1583 * @param string $salt - Optional function-specific data for hash
1584 * @return bool
1585 * @access public
1586 */
1587 function matchEditToken( $val, $salt = '' ) {
1588 return ( $val == $this->editToken( $salt ) );
1589 }
1590
1591 /**
1592 * Generate a new e-mail confirmation token and send a confirmation
1593 * mail to the user's given address.
1594 *
1595 * @return mixed True on success, a WikiError object on failure.
1596 */
1597 function sendConfirmationMail() {
1598 global $wgIP, $wgContLang;
1599 $url = $this->confirmationTokenUrl( $expiration );
1600 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1601 wfMsg( 'confirmemail_body',
1602 $wgIP,
1603 $this->getName(),
1604 $url,
1605 $wgContLang->timeanddate( $expiration, false ) ) );
1606 }
1607
1608 /**
1609 * Send an e-mail to this user's account. Does not check for
1610 * confirmed status or validity.
1611 *
1612 * @param string $subject
1613 * @param string $body
1614 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1615 * @return mixed True on success, a WikiError object on failure.
1616 */
1617 function sendMail( $subject, $body, $from = null ) {
1618 if( is_null( $from ) ) {
1619 global $wgPasswordSender;
1620 $from = $wgPasswordSender;
1621 }
1622
1623 require_once( 'UserMailer.php' );
1624 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1625
1626 if( $error == '' ) {
1627 return true;
1628 } else {
1629 return new WikiError( $error );
1630 }
1631 }
1632
1633 /**
1634 * Generate, store, and return a new e-mail confirmation code.
1635 * A hash (unsalted since it's used as a key) is stored.
1636 * @param &$expiration mixed output: accepts the expiration time
1637 * @return string
1638 * @access private
1639 */
1640 function confirmationToken( &$expiration ) {
1641 $fname = 'User::confirmationToken';
1642
1643 $now = time();
1644 $expires = $now + 7 * 24 * 60 * 60;
1645 $expiration = wfTimestamp( TS_MW, $expires );
1646
1647 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1648 $hash = md5( $token );
1649
1650 $dbw =& wfGetDB( DB_MASTER );
1651 $dbw->update( 'user',
1652 array( 'user_email_token' => $hash,
1653 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1654 array( 'user_id' => $this->mId ),
1655 $fname );
1656
1657 return $token;
1658 }
1659
1660 /**
1661 * Generate and store a new e-mail confirmation token, and return
1662 * the URL the user can use to confirm.
1663 * @param &$expiration mixed output: accepts the expiration time
1664 * @return string
1665 * @access private
1666 */
1667 function confirmationTokenUrl( &$expiration ) {
1668 $token = $this->confirmationToken( $expiration );
1669 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1670 return $title->getFullUrl();
1671 }
1672
1673 /**
1674 * Mark the e-mail address confirmed and save.
1675 */
1676 function confirmEmail() {
1677 $this->loadFromDatabase();
1678 $this->mEmailAuthenticated = wfTimestampNow();
1679 $this->saveSettings();
1680 return true;
1681 }
1682
1683 /**
1684 * Is this user allowed to send e-mails within limits of current
1685 * site configuration?
1686 * @return bool
1687 */
1688 function canSendEmail() {
1689 return $this->isEmailConfirmed();
1690 }
1691
1692 /**
1693 * Is this user allowed to receive e-mails within limits of current
1694 * site configuration?
1695 * @return bool
1696 */
1697 function canReceiveEmail() {
1698 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1699 }
1700
1701 /**
1702 * Is this user's e-mail address valid-looking and confirmed within
1703 * limits of the current site configuration?
1704 *
1705 * If $wgEmailAuthentication is on, this may require the user to have
1706 * confirmed their address by returning a code or using a password
1707 * sent to the address from the wiki.
1708 *
1709 * @return bool
1710 */
1711 function isEmailConfirmed() {
1712 global $wgEmailAuthentication;
1713 $this->loadFromDatabase();
1714 if( $this->isAnon() )
1715 return false;
1716 if( !$this->isValidEmailAddr( $this->mEmail ) )
1717 return false;
1718 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1719 return false;
1720 return true;
1721 }
1722
1723 /**
1724 * @param array $groups list of groups
1725 * @return array list of permission key names for given groups combined
1726 * @static
1727 */
1728 function getGroupPermissions( $groups ) {
1729 global $wgGroupPermissions;
1730 $rights = array();
1731 foreach( $groups as $group ) {
1732 if( isset( $wgGroupPermissions[$group] ) ) {
1733 $rights = array_merge( $rights,
1734 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1735 }
1736 }
1737 return $rights;
1738 }
1739
1740 /**
1741 * @param string $group key name
1742 * @return string localized descriptive name, if provided
1743 * @static
1744 */
1745 function getGroupName( $group ) {
1746 $key = "group-$group-name";
1747 $name = wfMsg( $key );
1748 if( $name == '' || $name == "&lt;$key&gt;" ) {
1749 return $group;
1750 } else {
1751 return $name;
1752 }
1753 }
1754
1755 /**
1756 * Return the set of defined explicit groups.
1757 * The * and 'user' groups are not included.
1758 * @return array
1759 * @static
1760 */
1761 function getAllGroups() {
1762 global $wgGroupPermissions;
1763 return array_diff(
1764 array_keys( $wgGroupPermissions ),
1765 array( '*', 'user' ) );
1766 }
1767
1768 }
1769
1770 ?>