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