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