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