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