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