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