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