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