1
+ − 1
<?php
+ − 2
+ − 3
/*
+ − 4
* Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
21
663fcf528726
Updated all version numbers back to Banshee; a few preliminary steps towards full UTF-8 support in page URLs
Dan
diff
changeset
+ − 5
* Version 1.0 (Banshee)
1
+ − 6
* Copyright (C) 2006-2007 Dan Fuhry
+ − 7
* sessions.php - everything related to security and user management
+ − 8
*
+ − 9
* This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
+ − 10
* as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+ − 11
*
+ − 12
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ − 13
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
+ − 14
*/
+ − 15
+ − 16
// Prepare a string for insertion into a MySQL database
+ − 17
function filter($str) { return $db->escape($str); }
+ − 18
+ − 19
/**
+ − 20
* Anything and everything related to security and user management. This includes AES encryption, which is illegal in some countries.
+ − 21
* Documenting the API was not easy - I hope you folks enjoy it.
+ − 22
* @package Enano
+ − 23
* @subpackage Session manager
+ − 24
* @category security, user management, logins, etc.
+ − 25
*/
+ − 26
+ − 27
class sessionManager {
+ − 28
+ − 29
# Variables
+ − 30
+ − 31
/**
+ − 32
* Whether we're logged in or not
+ − 33
* @var bool
+ − 34
*/
+ − 35
+ − 36
var $user_logged_in = false;
+ − 37
+ − 38
/**
+ − 39
* Our current low-privilege session key
+ − 40
* @var string
+ − 41
*/
+ − 42
+ − 43
var $sid;
+ − 44
+ − 45
/**
+ − 46
* Username of currently logged-in user, or IP address if not logged in
+ − 47
* @var string
+ − 48
*/
+ − 49
+ − 50
var $username;
+ − 51
+ − 52
/**
+ − 53
* User ID of currently logged-in user, or -1 if not logged in
+ − 54
* @var int
+ − 55
*/
+ − 56
+ − 57
var $user_id;
+ − 58
+ − 59
/**
+ − 60
* Real name of currently logged-in user, or blank if not logged in
+ − 61
* @var string
+ − 62
*/
+ − 63
+ − 64
var $real_name;
+ − 65
+ − 66
/**
+ − 67
* E-mail address of currently logged-in user, or blank if not logged in
+ − 68
* @var string
+ − 69
*/
+ − 70
+ − 71
var $email;
+ − 72
+ − 73
/**
31
+ − 74
* List of "extra" user information fields (IM handles, etc.)
+ − 75
* @var array (associative)
+ − 76
*/
+ − 77
+ − 78
var $user_extra;
+ − 79
+ − 80
/**
1
+ − 81
* User level of current user
+ − 82
* USER_LEVEL_GUEST: guest
+ − 83
* USER_LEVEL_MEMBER: regular user
+ − 84
* USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
+ − 85
* USER_LEVEL_MOD: moderator
+ − 86
* USER_LEVEL_ADMIN: administrator
+ − 87
* @var int
+ − 88
*/
+ − 89
+ − 90
var $user_level;
+ − 91
+ − 92
/**
+ − 93
* High-privilege session key
+ − 94
* @var string or false if not running on high-level authentication
+ − 95
*/
+ − 96
+ − 97
var $sid_super;
+ − 98
+ − 99
/**
+ − 100
* The user's theme preference, defaults to $template->default_theme
+ − 101
* @var string
+ − 102
*/
+ − 103
+ − 104
var $theme;
+ − 105
+ − 106
/**
+ − 107
* The user's style preference, or style auto-detected based on theme if not logged in
+ − 108
* @var string
+ − 109
*/
+ − 110
+ − 111
var $style;
+ − 112
+ − 113
/**
+ − 114
* Signature of current user - appended to comments, etc.
+ − 115
* @var string
+ − 116
*/
+ − 117
+ − 118
var $signature;
+ − 119
+ − 120
/**
+ − 121
* UNIX timestamp of when we were registered, or 0 if not logged in
+ − 122
* @var int
+ − 123
*/
+ − 124
+ − 125
var $reg_time;
+ − 126
+ − 127
/**
+ − 128
* MD5 hash of the current user's password, if applicable
+ − 129
* @var string OR bool false
+ − 130
*/
+ − 131
+ − 132
var $password_hash;
+ − 133
+ − 134
/**
+ − 135
* The number of unread private messages this user has.
+ − 136
* @var int
+ − 137
*/
+ − 138
+ − 139
var $unread_pms = 0;
+ − 140
+ − 141
/**
+ − 142
* AES key used to encrypt passwords and session key info - irreversibly destroyed when disallow_password_grab() is called
+ − 143
* @var string
+ − 144
*/
+ − 145
+ − 146
var $private_key;
+ − 147
+ − 148
/**
+ − 149
* Regex that defines a valid username, minus the ^ and $, these are added later
+ − 150
* @var string
+ − 151
*/
+ − 152
+ − 153
var $valid_username = '([A-Za-z0-9 \!\@\(\)-]+)';
+ − 154
+ − 155
/**
+ − 156
* What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
+ − 157
* @var string
+ − 158
*/
+ − 159
+ − 160
var $auth_level = -1;
+ − 161
+ − 162
/**
+ − 163
* State variable to track if a session timed out
+ − 164
* @var bool
+ − 165
*/
+ − 166
+ − 167
var $sw_timed_out = false;
+ − 168
+ − 169
/**
+ − 170
* Switch to track if we're started or not.
+ − 171
* @access private
+ − 172
* @var bool
+ − 173
*/
+ − 174
+ − 175
var $started = false;
+ − 176
+ − 177
/**
+ − 178
* Switch to control compatibility mode (for older Enano websites being upgraded)
+ − 179
* @access private
+ − 180
* @var bool
+ − 181
*/
+ − 182
+ − 183
var $compat = false;
+ − 184
+ − 185
/**
+ − 186
* Our list of permission types.
+ − 187
* @access private
+ − 188
* @var array
+ − 189
*/
+ − 190
+ − 191
var $acl_types = Array();
+ − 192
+ − 193
/**
+ − 194
* The list of descriptions for the permission types
+ − 195
* @var array
+ − 196
*/
+ − 197
+ − 198
var $acl_descs = Array();
+ − 199
+ − 200
/**
+ − 201
* A list of dependencies for ACL types.
+ − 202
* @var array
+ − 203
*/
+ − 204
+ − 205
var $acl_deps = Array();
+ − 206
+ − 207
/**
+ − 208
* Our tell-all list of permissions.
+ − 209
* @access private - or, preferably, protected
+ − 210
* @var array
+ − 211
*/
+ − 212
+ − 213
var $perms = Array();
+ − 214
+ − 215
/**
+ − 216
* A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
+ − 217
* @var array
+ − 218
* @access private
+ − 219
*/
+ − 220
+ − 221
var $acl_base_cache = Array();
+ − 222
+ − 223
/**
+ − 224
* Stores the scope information for ACL types.
+ − 225
* @var array
+ − 226
* @access private
+ − 227
*/
+ − 228
+ − 229
var $acl_scope = Array();
+ − 230
+ − 231
/**
+ − 232
* Array to track which default permissions are being used
+ − 233
* @var array
+ − 234
* @access private
+ − 235
*/
+ − 236
+ − 237
var $acl_defaults_used = Array();
+ − 238
+ − 239
/**
+ − 240
* Array to track group membership.
+ − 241
* @var array
+ − 242
*/
+ − 243
+ − 244
var $groups = Array();
+ − 245
+ − 246
/**
+ − 247
* Associative array to track group modship.
+ − 248
* @var array
+ − 249
*/
+ − 250
+ − 251
var $group_mod = Array();
+ − 252
+ − 253
# Basic functions
+ − 254
+ − 255
/**
+ − 256
* Constructor.
+ − 257
*/
+ − 258
+ − 259
function __construct()
+ − 260
{
+ − 261
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 262
include(ENANO_ROOT.'/config.php');
+ − 263
unset($dbhost, $dbname, $dbuser, $dbpasswd);
+ − 264
if(isset($crypto_key))
+ − 265
{
+ − 266
$this->private_key = $crypto_key;
+ − 267
$this->private_key = hexdecode($this->private_key);
+ − 268
}
+ − 269
else
+ − 270
{
+ − 271
if(is_writable(ENANO_ROOT.'/config.php'))
+ − 272
{
+ − 273
// Generate and stash a private key
+ − 274
// This should only happen during an automated silent gradual migration to the new encryption platform.
+ − 275
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 276
$this->private_key = $aes->gen_readymade_key();
+ − 277
+ − 278
$config = file_get_contents(ENANO_ROOT.'/config.php');
+ − 279
if(!$config)
+ − 280
{
+ − 281
die('$session->__construct(): can\'t get the contents of config.php');
+ − 282
}
+ − 283
+ − 284
$config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
+ − 285
// And while we're at it...
+ − 286
$config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
+ − 287
$fh = @fopen(ENANO_ROOT.'/config.php', 'w');
+ − 288
if ( !$fh )
+ − 289
{
+ − 290
die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
+ − 291
}
+ − 292
+ − 293
fwrite($fh, $config);
+ − 294
fclose($fh);
+ − 295
}
+ − 296
else
+ − 297
{
+ − 298
die_semicritical('Crypto error', '<p>No private key was found in the config file, and we can\'t generate one because we don\'t have write access to the config file. Please CHMOD config.php to 666 or 777 and reload this page.</p>');
+ − 299
}
+ − 300
}
+ − 301
// Check for compatibility mode
+ − 302
if(defined('IN_ENANO_INSTALL'))
+ − 303
{
+ − 304
$q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
+ − 305
if(!$q)
+ − 306
{
+ − 307
$error = mysql_error();
+ − 308
if(strstr($error, "Unknown column 'old_encryption'"))
+ − 309
$this->compat = true;
+ − 310
else
+ − 311
$db->_die('This should never happen and is a bug - the only error that was supposed to happen here didn\'t happen. (sessions.php in constructor, during compat mode check)');
+ − 312
}
+ − 313
$db->free_result();
+ − 314
}
+ − 315
}
+ − 316
+ − 317
/**
+ − 318
* PHP 4 compatible constructor.
+ − 319
*/
+ − 320
+ − 321
function sessionManager()
+ − 322
{
+ − 323
$this->__construct();
+ − 324
}
+ − 325
+ − 326
/**
+ − 327
* Wrapper function to sanitize strings for MySQL and HTML
+ − 328
* @param string $text The text to sanitize
+ − 329
* @return string
+ − 330
*/
+ − 331
+ − 332
function prepare_text($text)
+ − 333
{
+ − 334
global $db;
+ − 335
return $db->escape(htmlspecialchars($text));
+ − 336
}
+ − 337
+ − 338
/**
+ − 339
* Makes a SQL query and handles error checking
+ − 340
* @param string $query The SQL query to make
+ − 341
* @return resource
+ − 342
*/
+ − 343
+ − 344
function sql($query)
+ − 345
{
+ − 346
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 347
$result = $db->sql_query($query);
+ − 348
if(!$result)
+ − 349
{
+ − 350
$db->_die('The error seems to have occurred somewhere in the session management code.');
+ − 351
}
+ − 352
return $result;
+ − 353
}
+ − 354
+ − 355
# Session restoration and permissions
+ − 356
+ − 357
/**
+ − 358
* Initializes the basic state of things, including most user prefs, login data, cookie stuff
+ − 359
*/
+ − 360
+ − 361
function start()
+ − 362
{
+ − 363
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 364
if($this->started) return;
+ − 365
$this->started = true;
+ − 366
$user = false;
+ − 367
if(isset($_COOKIE['sid']))
+ − 368
{
+ − 369
if($this->compat)
+ − 370
{
+ − 371
$userdata = $this->compat_validate_session($_COOKIE['sid']);
+ − 372
}
+ − 373
else
+ − 374
{
+ − 375
$userdata = $this->validate_session($_COOKIE['sid']);
+ − 376
}
+ − 377
if(is_array($userdata))
+ − 378
{
+ − 379
$data = RenderMan::strToPageID($paths->get_pageid_from_url());
+ − 380
+ − 381
if(!$this->compat && $userdata['account_active'] != 1 && $data[1] != 'Special' && $data[1] != 'Admin')
+ − 382
{
+ − 383
$this->logout();
+ − 384
$a = getConfig('account_activation');
+ − 385
switch($a)
+ − 386
{
+ − 387
case 'none':
+ − 388
default:
+ − 389
$solution = 'Your account was most likely deactivated by an administrator. Please contact the site administration for further assistance.';
+ − 390
break;
+ − 391
case 'user':
+ − 392
$solution = 'Please check your e-mail; you should have been sent a message with instructions on how to activate your account. If you do not receive an e-mail from this site within 24 hours, please contact the site administration for further assistance.';
+ − 393
break;
+ − 394
case 'admin':
+ − 395
$solution = 'This website has been configured so that all user accounts must be activated by the administrator before they can be used, so your account will most likely be activated the next time the one of the administrators visits the site.';
+ − 396
break;
+ − 397
}
+ − 398
die_semicritical('Account error', '<p>It appears that your user account has not yet been activated. '.$solution.'</p>');
+ − 399
}
+ − 400
+ − 401
$this->sid = $_COOKIE['sid'];
+ − 402
$this->user_logged_in = true;
+ − 403
$this->user_id = intval($userdata['user_id']);
+ − 404
$this->username = $userdata['username'];
+ − 405
$this->password_hash = $userdata['password'];
+ − 406
$this->user_level = intval($userdata['user_level']);
+ − 407
$this->real_name = $userdata['real_name'];
+ − 408
$this->email = $userdata['email'];
+ − 409
$this->unread_pms = $userdata['num_pms'];
+ − 410
if(!$this->compat)
+ − 411
{
+ − 412
$this->theme = $userdata['theme'];
+ − 413
$this->style = $userdata['style'];
+ − 414
$this->signature = $userdata['signature'];
+ − 415
$this->reg_time = $userdata['reg_time'];
+ − 416
}
+ − 417
// Small security risk here - it allows someone who has already authenticated as an administrator to store the "super" key in
+ − 418
// the cookie. Change this to USER_LEVEL_MEMBER to override that. The same 15-minute restriction applies to this "exploit".
+ − 419
$this->auth_level = $userdata['auth_level'];
+ − 420
if(!isset($template->named_theme_list[$this->theme]))
+ − 421
{
+ − 422
if($this->compat || !is_object($template))
+ − 423
{
+ − 424
$this->theme = 'oxygen';
+ − 425
$this->style = 'bleu';
+ − 426
}
+ − 427
else
+ − 428
{
+ − 429
$this->theme = $template->default_theme;
+ − 430
$this->style = $template->default_style;
+ − 431
}
+ − 432
}
+ − 433
$user = true;
+ − 434
+ − 435
if(isset($_REQUEST['auth']) && !$this->sid_super)
+ − 436
{
+ − 437
// Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
+ − 438
if($this->compat)
+ − 439
{
+ − 440
$key = $_REQUEST['auth'];
+ − 441
$super = $this->compat_validate_session($key);
+ − 442
}
+ − 443
else
+ − 444
{
+ − 445
$key = strrev($_REQUEST['auth']);
+ − 446
$super = $this->validate_session($key);
+ − 447
}
+ − 448
if(is_array($super))
+ − 449
{
+ − 450
$this->auth_level = intval($super['auth_level']);
+ − 451
$this->sid_super = $_REQUEST['auth'];
+ − 452
}
+ − 453
}
+ − 454
}
+ − 455
}
+ − 456
if(!$user)
+ − 457
{
+ − 458
//exit;
+ − 459
$this->register_guest_session();
+ − 460
}
+ − 461
if(!$this->compat)
+ − 462
{
+ − 463
// init groups
+ − 464
$q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g
+ − 465
LEFT JOIN '.table_prefix.'group_members AS m
+ − 466
ON g.group_id=m.group_id
+ − 467
WHERE ( m.user_id='.$this->user_id.'
+ − 468
OR g.group_name=\'Everyone\')
+ − 469
' . ( enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '
+ − 470
ORDER BY group_id ASC;'); // Make sure "Everyone" comes first so the permissions can be overridden
+ − 471
if($row = $db->fetchrow())
+ − 472
{
+ − 473
do {
+ − 474
$this->groups[$row['group_id']] = $row['group_name'];
+ − 475
$this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
+ − 476
} while($row = $db->fetchrow());
+ − 477
}
+ − 478
else
+ − 479
{
+ − 480
die('No group info');
+ − 481
}
+ − 482
}
+ − 483
$this->check_banlist();
+ − 484
+ − 485
if ( isset ( $_GET['printable'] ) )
+ − 486
{
+ − 487
$this->theme = 'printable';
+ − 488
$this->style = 'default';
+ − 489
}
+ − 490
+ − 491
}
+ − 492
+ − 493
# Logins
+ − 494
+ − 495
/**
+ − 496
* Attempts to perform a login using crypto functions
+ − 497
* @param string $username The username
+ − 498
* @param string $aes_data The encrypted password, hex-encoded
+ − 499
* @param string $aes_key The MD5 hash of the encryption key, hex-encoded
+ − 500
* @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
+ − 501
* @param int $level The privilege level we're authenticating for, defaults to 0
+ − 502
* @return string 'success' on success, or error string on failure
+ − 503
*/
+ − 504
+ − 505
function login_with_crypto($username, $aes_data, $aes_key, $challenge, $level = USER_LEVEL_MEMBER)
+ − 506
{
+ − 507
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 508
+ − 509
$privcache = $this->private_key;
+ − 510
+ − 511
// Instanciate the Rijndael encryption object
+ − 512
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 513
+ − 514
// Fetch our decryption key
+ − 515
+ − 516
$aes_key = $this->fetch_public_key($aes_key);
+ − 517
if(!$aes_key)
+ − 518
return 'Couldn\'t look up public key "'.$aes_key.'" for decryption';
+ − 519
+ − 520
// Convert the key to a binary string
+ − 521
$bin_key = hexdecode($aes_key);
+ − 522
+ − 523
if(strlen($bin_key) != AES_BITS / 8)
+ − 524
return 'The decryption key is the wrong length';
+ − 525
+ − 526
// Decrypt our password
+ − 527
$password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
+ − 528
+ − 529
// Initialize our success switch
+ − 530
$success = false;
+ − 531
+ − 532
// Select the user data from the table, and decrypt that so we can verify the password
+ − 533
$this->sql('SELECT password,old_encryption,user_id,user_level,theme,style,temp_password,temp_password_time FROM '.table_prefix.'users WHERE lcase(username)=\''.$this->prepare_text(strtolower($username)).'\';');
+ − 534
if($db->numrows() < 1)
+ − 535
return 'The username and/or password is incorrect.';
+ − 536
$row = $db->fetchrow();
+ − 537
+ − 538
// Check to see if we're logging in using a temporary password
+ − 539
+ − 540
if((intval($row['temp_password_time']) + 3600*24) > time() )
+ − 541
{
+ − 542
$temp_pass = $aes->decrypt( $row['temp_password'], $this->private_key, ENC_HEX );
+ − 543
if( $temp_pass == $password )
+ − 544
{
+ − 545
$url = makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $row['temp_password']);
+ − 546
+ − 547
$code = $plugins->setHook('login_password_reset');
+ − 548
foreach ( $code as $cmd )
+ − 549
{
+ − 550
eval($cmd);
+ − 551
}
+ − 552
+ − 553
redirect($url, 'Login sucessful', 'Please wait while you are transferred to the Password Reset form.');
+ − 554
exit;
+ − 555
}
+ − 556
}
+ − 557
+ − 558
if($row['old_encryption'] == 1)
+ − 559
{
+ − 560
// The user's password is stored using the obsolete and insecure MD5 algorithm, so we'll update the field with the new password
+ − 561
if(md5($password) == $row['password'])
+ − 562
{
+ − 563
$pass_stashed = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 564
$this->sql('UPDATE '.table_prefix.'users SET password=\''.$pass_stashed.'\',old_encryption=0 WHERE user_id='.$row['user_id'].';');
+ − 565
$success = true;
+ − 566
}
+ − 567
}
+ − 568
else
+ − 569
{
+ − 570
// Our password field is up-to-date with the >=1.0RC1 encryption standards, so decrypt the password in the table and see if we have a match; if so then do challenge authentication
+ − 571
$real_pass = $aes->decrypt(hexdecode($row['password']), $this->private_key, ENC_BINARY);
+ − 572
if($password == $real_pass)
+ − 573
{
+ − 574
// Yay! We passed AES authentication, now do an MD5 challenge check to make sure we weren't spoofed
+ − 575
$chal = substr($challenge, 0, 32);
+ − 576
$salt = substr($challenge, 32, 32);
+ − 577
$correct_challenge = md5( $real_pass . $salt );
+ − 578
if($chal == $correct_challenge)
+ − 579
$success = true;
+ − 580
}
+ − 581
}
+ − 582
if($success)
+ − 583
{
+ − 584
if($level > $row['user_level'])
+ − 585
return 'You are not authorized for this level of access.';
+ − 586
+ − 587
$sess = $this->register_session(intval($row['user_id']), $username, $password, $level);
+ − 588
if($sess)
+ − 589
{
+ − 590
$this->username = $username;
+ − 591
$this->user_id = intval($row['user_id']);
+ − 592
$this->theme = $row['theme'];
+ − 593
$this->style = $row['style'];
+ − 594
+ − 595
if($level > USER_LEVEL_MEMBER)
+ − 596
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ − 597
else
+ − 598
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+ − 599
+ − 600
$code = $plugins->setHook('login_success');
+ − 601
foreach ( $code as $cmd )
+ − 602
{
+ − 603
eval($cmd);
+ − 604
}
+ − 605
return 'success';
+ − 606
}
+ − 607
else
+ − 608
return 'Your login credentials were correct, but an internal error occurred while registering the session key in the database.';
+ − 609
}
+ − 610
else
+ − 611
{
+ − 612
if($level > USER_LEVEL_MEMBER)
+ − 613
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ − 614
else
+ − 615
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+ − 616
+ − 617
return 'The username and/or password is incorrect.';
+ − 618
}
+ − 619
}
+ − 620
+ − 621
/**
+ − 622
* Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
+ − 623
* This method of authentication is inherently insecure, there's really nothing we can do about it except hope and pray that everyone moves to Firefox
+ − 624
* Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
+ − 625
* @param string $username The username
+ − 626
* @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
+ − 627
* @param bool $already_md5ed This should be set to true if $password is an MD5 hash, and should be false if it's plaintext. Defaults to false.
+ − 628
* @param int $level The privilege level we're authenticating for, defaults to 0
+ − 629
*/
+ − 630
+ − 631
function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER)
+ − 632
{
+ − 633
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 634
+ − 635
$pass_hashed = ( $already_md5ed ) ? $password : md5($password);
+ − 636
+ − 637
// Perhaps we're upgrading Enano?
+ − 638
if($this->compat)
+ − 639
{
+ − 640
return $this->login_compat($username, $pass_hashed, $level);
+ − 641
}
+ − 642
+ − 643
// Instanciate the Rijndael encryption object
+ − 644
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 645
+ − 646
// Initialize our success switch
+ − 647
$success = false;
+ − 648
+ − 649
// Retrieve the real password from the database
+ − 650
$this->sql('SELECT password,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix.'users WHERE lcase(username)=\''.$this->prepare_text(strtolower($username)).'\';');
+ − 651
if($db->numrows() < 1)
+ − 652
return 'The username and/or password is incorrect.';
+ − 653
$row = $db->fetchrow();
+ − 654
+ − 655
// Check to see if we're logging in using a temporary password
+ − 656
+ − 657
if((intval($row['temp_password_time']) + 3600*24) > time() )
+ − 658
{
+ − 659
$temp_pass = $aes->decrypt( $row['temp_password'], $this->private_key, ENC_HEX );
+ − 660
if( md5($temp_pass) == $pass_hashed )
+ − 661
{
+ − 662
$code = $plugins->setHook('login_password_reset');
+ − 663
foreach ( $code as $cmd )
+ − 664
{
+ − 665
eval($cmd);
+ − 666
}
+ − 667
+ − 668
header('Location: ' . makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $row['temp_password']) );
+ − 669
+ − 670
exit;
+ − 671
}
+ − 672
}
+ − 673
+ − 674
if($row['old_encryption'] == 1)
+ − 675
{
+ − 676
// The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
+ − 677
if($pass_hashed == $row['password'] && !$already_md5ed)
+ − 678
{
+ − 679
$pass_stashed = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 680
$this->sql('UPDATE '.table_prefix.'users SET password=\''.$pass_stashed.'\',old_encryption=0 WHERE user_id='.$row['user_id'].';');
+ − 681
$success = true;
+ − 682
}
+ − 683
elseif($pass_hashed == $row['password'] && $already_md5ed)
+ − 684
{
+ − 685
// We don't have the real password so don't bother with encrypting it, just call it success and get out of here
+ − 686
$success = true;
+ − 687
}
+ − 688
}
+ − 689
else
+ − 690
{
+ − 691
// Our password field is up-to-date with the >=1.0RC1 encryption standards, so decrypt the password in the table and see if we have a match
+ − 692
$real_pass = $aes->decrypt($row['password'], $this->private_key);
+ − 693
if($pass_hashed == md5($real_pass))
+ − 694
{
+ − 695
$success = true;
+ − 696
}
+ − 697
}
+ − 698
if($success)
+ − 699
{
+ − 700
if((int)$level > (int)$row['user_level'])
+ − 701
return 'You are not authorized for this level of access.';
+ − 702
$sess = $this->register_session(intval($row['user_id']), $username, $real_pass, $level);
+ − 703
if($sess)
+ − 704
{
+ − 705
if($level > USER_LEVEL_MEMBER)
+ − 706
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ − 707
else
+ − 708
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+ − 709
+ − 710
$code = $plugins->setHook('login_success');
+ − 711
foreach ( $code as $cmd )
+ − 712
{
+ − 713
eval($cmd);
+ − 714
}
+ − 715
return 'success';
+ − 716
}
+ − 717
else
+ − 718
return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
+ − 719
}
+ − 720
else
+ − 721
{
+ − 722
if($level > USER_LEVEL_MEMBER)
+ − 723
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
+ − 724
else
+ − 725
$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
+ − 726
+ − 727
return 'The username and/or password is incorrect.';
+ − 728
}
+ − 729
}
+ − 730
+ − 731
/**
+ − 732
* Attempts to log in using the old table structure and algorithm.
+ − 733
* @param string $username
+ − 734
* @param string $password This should be an MD5 hash
+ − 735
* @return string 'success' if successful, or error message on failure
+ − 736
*/
+ − 737
+ − 738
function login_compat($username, $password, $level = 0)
+ − 739
{
+ − 740
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 741
$pass_hashed =& $password;
+ − 742
$this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
+ − 743
if($db->numrows() < 1)
+ − 744
return 'The username and/or password is incorrect.';
+ − 745
$row = $db->fetchrow();
+ − 746
if($row['password'] == $password)
+ − 747
{
+ − 748
if((int)$level > (int)$row['user_level'])
+ − 749
return 'You are not authorized for this level of access.';
+ − 750
$sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
+ − 751
if($sess)
+ − 752
return 'success';
+ − 753
else
+ − 754
return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
+ − 755
}
+ − 756
else
+ − 757
{
+ − 758
return 'The username and/or password is incorrect.';
+ − 759
}
+ − 760
}
+ − 761
+ − 762
/**
+ − 763
* Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
+ − 764
* Basically the session key is a base64-encoded cookie (encrypted with the site's private key) that says "u=[username];p=[sha1 of password]"
+ − 765
* @param int $user_id
+ − 766
* @param string $username
+ − 767
* @param string $password
+ − 768
* @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
+ − 769
* @return bool
+ − 770
*/
+ − 771
+ − 772
function register_session($user_id, $username, $password, $level = USER_LEVEL_MEMBER)
+ − 773
{
+ − 774
$salt = md5(microtime() . mt_rand());
+ − 775
$passha1 = sha1($password);
+ − 776
$session_key = "u=$username;p=$passha1;s=$salt";
+ − 777
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 778
$session_key = $aes->encrypt($session_key, $this->private_key, ENC_HEX);
+ − 779
if($level > USER_LEVEL_MEMBER)
+ − 780
{
+ − 781
$hexkey = strrev($session_key);
+ − 782
$this->sid_super = $hexkey;
+ − 783
$_GET['auth'] = $hexkey;
+ − 784
}
+ − 785
else
+ − 786
{
+ − 787
setcookie( 'sid', $session_key, time()+315360000, scriptPath.'/' );
+ − 788
$_COOKIE['sid'] = $session_key;
+ − 789
}
+ − 790
$keyhash = md5($session_key);
+ − 791
$ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ − 792
if(!$ip)
+ − 793
die('$session->register_session: Remote-Addr was spoofed');
+ − 794
$time = time();
+ − 795
if(!is_int($user_id))
+ − 796
die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
+ − 797
if(!is_int($level))
+ − 798
die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
+ − 799
+ − 800
$query = $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$keyhash.'\', \''.$salt.'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
+ − 801
return true;
+ − 802
}
+ − 803
+ − 804
/**
+ − 805
* Identical to register_session in nature, but uses the old login/table structure. DO NOT use this.
+ − 806
* @see sessionManager::register_session()
+ − 807
* @access private
+ − 808
*/
+ − 809
+ − 810
function register_session_compat($user_id, $username, $password, $level = 0)
+ − 811
{
+ − 812
$salt = md5(microtime() . mt_rand());
+ − 813
$thekey = md5($password . $salt);
+ − 814
if($level > 0)
+ − 815
{
+ − 816
$this->sid_super = $thekey;
+ − 817
}
+ − 818
else
+ − 819
{
+ − 820
setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
+ − 821
$_COOKIE['sid'] = $thekey;
+ − 822
}
+ − 823
$ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ − 824
if(!$ip)
+ − 825
die('$session->register_session: Remote-Addr was spoofed');
+ − 826
$time = time();
+ − 827
if(!is_int($user_id))
+ − 828
die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
+ − 829
if(!is_int($level))
+ − 830
die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
+ − 831
$query = $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$thekey.'\', \''.$salt.'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
+ − 832
return true;
+ − 833
}
+ − 834
+ − 835
/**
+ − 836
* Creates/restores a guest session
+ − 837
* @todo implement real session management for guests
+ − 838
*/
+ − 839
+ − 840
function register_guest_session()
+ − 841
{
+ − 842
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 843
$this->username = $_SERVER['REMOTE_ADDR'];
+ − 844
$this->user_level = USER_LEVEL_GUEST;
+ − 845
if($this->compat || defined('IN_ENANO_INSTALL'))
+ − 846
{
+ − 847
$this->theme = 'oxygen';
+ − 848
$this->style = 'bleu';
+ − 849
}
+ − 850
else
+ − 851
{
+ − 852
$this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
+ − 853
$this->style = ( isset($_GET['style']) && file_exists(ENANO_ROOT.'/themes/'.$this->theme . '/css/'.$_GET['style'].'.css' )) ? $_GET['style'] : substr($template->named_theme_list[$this->theme]['default_style'], 0, strlen($template->named_theme_list[$this->theme]['default_style'])-4);
+ − 854
}
+ − 855
$this->user_id = 1;
+ − 856
}
+ − 857
+ − 858
/**
+ − 859
* Validates a session key, and returns the userdata associated with the key or false
+ − 860
* @param string $key The session key to validate
+ − 861
* @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
+ − 862
*/
+ − 863
+ − 864
function validate_session($key)
+ − 865
{
+ − 866
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 867
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE, true);
+ − 868
$decrypted_key = $aes->decrypt($key, $this->private_key, ENC_HEX);
+ − 869
+ − 870
if ( !$decrypted_key )
+ − 871
{
+ − 872
die_semicritical('AES encryption error', '<p>Something went wrong during the AES decryption process.</p><pre>'.print_r($decrypted_key, true).'</pre>');
+ − 873
}
+ − 874
+ − 875
$n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=([A-Fa-f0-9]+?)$/', $decrypted_key, $keydata);
+ − 876
if($n < 1)
+ − 877
{
+ − 878
// echo '(debug) $session->validate_session: Key does not match regex<br />Decrypted key: '.$decrypted_key;
+ − 879
return false;
+ − 880
}
+ − 881
$keyhash = md5($key);
+ − 882
$salt = $db->escape($keydata[3]);
18
+ − 883
$query = $db->sql_query('SELECT u.user_id AS uid,u.username,u.password,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,COUNT(p.message_id) AS num_pms,x.* FROM '.table_prefix.'session_keys AS k
+ − 884
LEFT JOIN '.table_prefix.'users AS u
+ − 885
ON ( u.user_id=k.user_id )
+ − 886
LEFT JOIN '.table_prefix.'users_extra AS x
+ − 887
ON ( u.user_id=x.user_id OR x.user_id IS NULL )
+ − 888
LEFT JOIN '.table_prefix.'privmsgs AS p
+ − 889
ON ( p.message_to=u.username AND p.message_read=0 )
+ − 890
WHERE k.session_key=\''.$keyhash.'\'
+ − 891
AND k.salt=\''.$salt.'\'
+ − 892
GROUP BY u.user_id;');
+ − 893
if ( !$query )
+ − 894
{
+ − 895
$query = $this->sql('SELECT u.user_id AS uid,u.username,u.password,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,COUNT(p.message_id) AS num_pms FROM '.table_prefix.'session_keys AS k
+ − 896
LEFT JOIN '.table_prefix.'users AS u
+ − 897
ON ( u.user_id=k.user_id )
+ − 898
LEFT JOIN '.table_prefix.'privmsgs AS p
+ − 899
ON ( p.message_to=u.username AND p.message_read=0 )
+ − 900
WHERE k.session_key=\''.$keyhash.'\'
+ − 901
AND k.salt=\''.$salt.'\'
+ − 902
GROUP BY u.user_id;');
+ − 903
}
1
+ − 904
if($db->numrows() < 1)
+ − 905
{
+ − 906
// echo '(debug) $session->validate_session: Key was not found in database<br />';
+ − 907
return false;
+ − 908
}
+ − 909
$row = $db->fetchrow();
+ − 910
$row['user_id'] =& $row['uid'];
+ − 911
$ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ − 912
if($row['auth_level'] > $row['user_level'])
+ − 913
{
+ − 914
// Failed authorization check
+ − 915
// echo '(debug) $session->validate_session: access to this auth level denied<br />';
+ − 916
return false;
+ − 917
}
+ − 918
if($ip != $row['source_ip'])
+ − 919
{
+ − 920
// Failed IP address check
+ − 921
// echo '(debug) $session->validate_session: IP address mismatch<br />';
+ − 922
return false;
+ − 923
}
+ − 924
+ − 925
// Do the password validation
+ − 926
$real_pass = $aes->decrypt($row['password'], $this->private_key, ENC_HEX);
+ − 927
+ − 928
//die('<pre>'.print_r($keydata, true).'</pre>');
+ − 929
if(sha1($real_pass) != $keydata[2])
+ − 930
{
+ − 931
// Failed password check
+ − 932
// echo '(debug) $session->validate_session: encrypted password is wrong<br />Real password: '.$real_pass.'<br />Real hash: '.sha1($real_pass).'<br />User hash: '.$keydata[2];
+ − 933
return false;
+ − 934
}
+ − 935
+ − 936
$time_now = time();
+ − 937
$time_key = $row['time'] + 900;
+ − 938
if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
+ − 939
{
+ − 940
// Session timed out
+ − 941
// echo '(debug) $session->validate_session: super session timed out<br />';
+ − 942
$this->sw_timed_out = true;
+ − 943
return false;
+ − 944
}
+ − 945
+ − 946
// If this is an elevated-access session key, update the time
+ − 947
if( $row['auth_level'] > USER_LEVEL_MEMBER )
+ − 948
{
+ − 949
$this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.$keyhash.'\';');
+ − 950
}
+ − 951
31
+ − 952
$user_extra = array();
+ − 953
foreach ( array('user_aim', 'user_yahoo', 'user_msn', 'user_xmpp', 'user_homepage', 'user_location', 'user_job', 'user_hobbies', 'email_public') as $column )
+ − 954
{
+ − 955
$user_extra[$column] = $row[$column];
+ − 956
}
+ − 957
+ − 958
$this->user_extra = $user_extra;
+ − 959
// Leave the rest to PHP's automatic garbage collector ;-)
+ − 960
1
+ − 961
$row['password'] = md5($real_pass);
+ − 962
return $row;
+ − 963
}
+ − 964
+ − 965
/**
+ − 966
* Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
+ − 967
* @param string $key The session key to validate
+ − 968
* @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
+ − 969
*/
+ − 970
+ − 971
function compat_validate_session($key)
+ − 972
{
+ − 973
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 974
$key = $db->escape($key);
+ − 975
+ − 976
$query = $this->sql('SELECT u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,k.source_ip,k.salt,k.time,k.auth_level FROM '.table_prefix.'session_keys AS k
+ − 977
LEFT JOIN '.table_prefix.'users AS u
+ − 978
ON u.user_id=k.user_id
+ − 979
WHERE k.session_key=\''.$key.'\';');
+ − 980
if($db->numrows() < 1)
+ − 981
{
+ − 982
// echo '(debug) $session->validate_session: Key '.$key.' was not found in database<br />';
+ − 983
return false;
+ − 984
}
+ − 985
$row = $db->fetchrow();
+ − 986
$ip = ip2hex($_SERVER['REMOTE_ADDR']);
+ − 987
if($row['auth_level'] > $row['user_level'])
+ − 988
{
+ − 989
// Failed authorization check
+ − 990
// echo '(debug) $session->validate_session: user not authorized for this access level';
+ − 991
return false;
+ − 992
}
+ − 993
if($ip != $row['source_ip'])
+ − 994
{
+ − 995
// Failed IP address check
+ − 996
// echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
+ − 997
return false;
+ − 998
}
+ − 999
+ − 1000
// Do the password validation
+ − 1001
$real_key = md5($row['password'] . $row['salt']);
+ − 1002
+ − 1003
//die('<pre>'.print_r($keydata, true).'</pre>');
+ − 1004
if($real_key != $key)
+ − 1005
{
+ − 1006
// Failed password check
+ − 1007
// echo '(debug) $session->validate_session: supplied password is wrong<br />Real key: '.$real_key.'<br />User key: '.$key;
+ − 1008
return false;
+ − 1009
}
+ − 1010
+ − 1011
$time_now = time();
+ − 1012
$time_key = $row['time'] + 900;
+ − 1013
if($time_now > $time_key && $row['auth_level'] >= 1)
+ − 1014
{
+ − 1015
$this->sw_timed_out = true;
+ − 1016
// Session timed out
+ − 1017
// echo '(debug) $session->validate_session: super session timed out<br />';
+ − 1018
return false;
+ − 1019
}
+ − 1020
+ − 1021
return $row;
+ − 1022
}
+ − 1023
+ − 1024
/**
+ − 1025
* Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
+ − 1026
* @param int $level How low we should go - USER_LEVEL_MEMBER means demote to USER_LEVEL_GUEST, and anything more powerful than USER_LEVEL_MEMBER means demote to USER_LEVEL_MEMBER
+ − 1027
* @return string 'success' if successful, or error on failure
+ − 1028
*/
+ − 1029
+ − 1030
function logout($level = USER_LEVEL_MEMBER)
+ − 1031
{
+ − 1032
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1033
$ou = $this->username;
+ − 1034
$oid = $this->user_id;
+ − 1035
if($level > USER_LEVEL_CHPREF)
+ − 1036
{
+ − 1037
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1038
if(!$this->user_logged_in || $this->auth_level < USER_LEVEL_MOD) return 'success';
+ − 1039
// Destroy elevated privileges
+ − 1040
$keyhash = md5(strrev($this->sid_super));
+ − 1041
$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
+ − 1042
$this->sid_super = false;
+ − 1043
$this->auth_level = USER_LEVEL_MEMBER;
+ − 1044
}
+ − 1045
else
+ − 1046
{
+ − 1047
if($this->user_logged_in)
+ − 1048
{
+ − 1049
// Completely destroy our session
+ − 1050
if($this->auth_level > USER_LEVEL_CHPREF)
+ − 1051
{
+ − 1052
$this->logout(USER_LEVEL_ADMIN);
+ − 1053
}
+ − 1054
$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
+ − 1055
setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
+ − 1056
}
+ − 1057
}
+ − 1058
$code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
+ − 1059
foreach ( $code as $cmd )
+ − 1060
{
+ − 1061
eval($cmd);
+ − 1062
}
+ − 1063
return 'success';
+ − 1064
}
+ − 1065
+ − 1066
# Miscellaneous stuff
+ − 1067
+ − 1068
/**
+ − 1069
* Appends the high-privilege session key to the URL if we are authorized to do high-privilege stuff
+ − 1070
* @param string $url The URL to add session data to
+ − 1071
* @return string
+ − 1072
*/
+ − 1073
+ − 1074
function append_sid($url)
+ − 1075
{
+ − 1076
$sep = ( strstr($url, '?') ) ? '&' : '?';
+ − 1077
if ( $this->sid_super )
+ − 1078
{
+ − 1079
$url = $url . $sep . 'auth=' . urlencode($this->sid_super);
+ − 1080
// echo($this->sid_super.'<br/>');
+ − 1081
}
+ − 1082
return $url;
+ − 1083
}
+ − 1084
+ − 1085
/**
+ − 1086
* Grabs the user's password MD5
+ − 1087
* @return string, or bool false if access denied
+ − 1088
*/
+ − 1089
+ − 1090
function grab_password_hash()
+ − 1091
{
+ − 1092
if(!$this->password_hash) return false;
+ − 1093
return $this->password_hash;
+ − 1094
}
+ − 1095
+ − 1096
/**
+ − 1097
* Destroys the user's password MD5 in memory
+ − 1098
*/
+ − 1099
+ − 1100
function disallow_password_grab()
+ − 1101
{
+ − 1102
$this->password_hash = false;
+ − 1103
return false;
+ − 1104
}
+ − 1105
+ − 1106
/**
+ − 1107
* Generates an AES key and stashes it in the database
+ − 1108
* @return string Hex-encoded AES key
+ − 1109
*/
+ − 1110
+ − 1111
function rijndael_genkey()
+ − 1112
{
+ − 1113
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1114
$key = $aes->gen_readymade_key();
+ − 1115
$keys = getConfig('login_key_cache');
+ − 1116
if(is_string($keys))
+ − 1117
$keys .= $key;
+ − 1118
else
+ − 1119
$keys = $key;
+ − 1120
setConfig('login_key_cache', $keys);
+ − 1121
return $key;
+ − 1122
}
+ − 1123
+ − 1124
/**
+ − 1125
* Generate a totally random 128-bit value for MD5 challenges
+ − 1126
* @return string
+ − 1127
*/
+ − 1128
+ − 1129
function dss_rand()
+ − 1130
{
+ − 1131
$aes = new AESCrypt();
+ − 1132
$random = $aes->randkey(128);
+ − 1133
unset($aes);
+ − 1134
return md5(microtime() . $random);
+ − 1135
}
+ − 1136
+ − 1137
/**
+ − 1138
* Fetch a cached login public key using the MD5sum as an identifier. Each key can only be fetched once before it is destroyed.
+ − 1139
* @param string $md5 The MD5 sum of the key
+ − 1140
* @return string, or bool false on failure
+ − 1141
*/
+ − 1142
+ − 1143
function fetch_public_key($md5)
+ − 1144
{
+ − 1145
$keys = getConfig('login_key_cache');
+ − 1146
$keys = enano_str_split($keys, AES_BITS / 4);
+ − 1147
+ − 1148
foreach($keys as $i => $k)
+ − 1149
{
+ − 1150
if(md5($k) == $md5)
+ − 1151
{
+ − 1152
unset($keys[$i]);
+ − 1153
if(count($keys) > 0)
+ − 1154
{
+ − 1155
if ( strlen(getConfig('login_key_cache') ) > 64000 )
+ − 1156
{
+ − 1157
// This should only need to be done once every month or so for an average-size site
+ − 1158
setConfig('login_key_cache', '');
+ − 1159
}
+ − 1160
else
+ − 1161
{
+ − 1162
$keys = implode('', array_values($keys));
+ − 1163
setConfig('login_key_cache', $keys);
+ − 1164
}
+ − 1165
}
+ − 1166
else
+ − 1167
{
+ − 1168
setConfig('login_key_cache', '');
+ − 1169
}
+ − 1170
return $k;
+ − 1171
}
+ − 1172
}
+ − 1173
// Couldn't find the key...
+ − 1174
return false;
+ − 1175
}
+ − 1176
+ − 1177
/**
+ − 1178
* Adds a user to a group.
+ − 1179
* @param int User ID
+ − 1180
* @param int Group ID
+ − 1181
* @param bool Group moderator - defaults to false
+ − 1182
* @return bool True on success, false on failure
+ − 1183
*/
+ − 1184
+ − 1185
function add_user_to_group($user_id, $group_id, $is_mod = false)
+ − 1186
{
+ − 1187
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1188
+ − 1189
// Validation
+ − 1190
if ( !is_int($user_id) || !is_int($group_id) || !is_bool($is_mod) )
+ − 1191
return false;
+ − 1192
if ( $user_id < 1 || $group_id < 1 )
+ − 1193
return false;
+ − 1194
+ − 1195
$mod_switch = ( $is_mod ) ? '1' : '0';
+ − 1196
$q = $this->sql('SELECT member_id,is_mod FROM '.table_prefix.'group_members WHERE user_id=' . $user_id . ' AND group_id=' . $group_id . ';');
+ − 1197
if ( !$q )
+ − 1198
$db->_die();
+ − 1199
if ( $db->numrows() < 1 )
+ − 1200
{
+ − 1201
// User is not in group
+ − 1202
$this->sql('INSERT INTO '.table_prefix.'group_members(user_id,group_id,is_mod) VALUES(' . $user_id . ', ' . $group_id . ', ' . $mod_switch . ');');
+ − 1203
return true;
+ − 1204
}
+ − 1205
else
+ − 1206
{
+ − 1207
$row = $db->fetchrow();
+ − 1208
// Update modship status
+ − 1209
if ( strval($row['is_mod']) == $mod_switch )
+ − 1210
{
+ − 1211
// Modship unchanged
+ − 1212
return true;
+ − 1213
}
+ − 1214
else
+ − 1215
{
+ − 1216
// Modship changed
+ − 1217
$this->sql('UPDATE '.table_prefix.'group_members SET is_mod=' . $mod_switch . ' WHERE member_id=' . $row['member_id'] . ';');
+ − 1218
return true;
+ − 1219
}
+ − 1220
}
+ − 1221
return false;
+ − 1222
}
+ − 1223
+ − 1224
/**
+ − 1225
* Removes a user from a group.
+ − 1226
* @param int User ID
+ − 1227
* @param int Group ID
+ − 1228
* @return bool True on success, false on failure
+ − 1229
* @todo put a little more error checking in...
+ − 1230
*/
+ − 1231
+ − 1232
function remove_user_from_group($user_id, $group_id)
+ − 1233
{
+ − 1234
if ( !is_int($user_id) || !is_int($group_id) )
+ − 1235
return false;
+ − 1236
$this->sql('DELETE FROM '.table_prefix."group_members WHERE user_id=$user_id AND group_id=$group_id;");
+ − 1237
return true;
+ − 1238
}
+ − 1239
+ − 1240
/**
+ − 1241
* Checks the banlist to ensure that we're an allowed user. Doesn't return anything because it dies if the user is banned.
+ − 1242
*/
+ − 1243
+ − 1244
function check_banlist()
+ − 1245
{
+ − 1246
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1247
if($this->compat)
+ − 1248
$q = $this->sql('SELECT ban_id,ban_type,ban_value,is_regex FROM '.table_prefix.'banlist ORDER BY ban_type;');
+ − 1249
else
+ − 1250
$q = $this->sql('SELECT ban_id,ban_type,ban_value,is_regex,reason FROM '.table_prefix.'banlist ORDER BY ban_type;');
+ − 1251
if(!$q) $db->_die('The banlist data could not be selected.');
+ − 1252
$banned = false;
+ − 1253
while($row = $db->fetchrow())
+ − 1254
{
+ − 1255
if($this->compat)
+ − 1256
$row['reason'] = 'None available - session manager is in compatibility mode';
+ − 1257
switch($row['ban_type'])
+ − 1258
{
+ − 1259
case BAN_IP:
+ − 1260
if(intval($row['is_regex'])==1) {
+ − 1261
if(preg_match('#'.$row['ban_value'].'#i', $_SERVER['REMOTE_ADDR']))
+ − 1262
{
+ − 1263
$banned = true;
+ − 1264
$reason = $row['reason'];
+ − 1265
}
+ − 1266
}
+ − 1267
else {
+ − 1268
if($row['ban_value']==$_SERVER['REMOTE_ADDR']) { $banned = true; $reason = $row['reason']; }
+ − 1269
}
+ − 1270
break;
+ − 1271
case BAN_USER:
+ − 1272
if(intval($row['is_regex'])==1) {
+ − 1273
if(preg_match('#'.$row['ban_value'].'#i', $this->username))
+ − 1274
{
+ − 1275
$banned = true;
+ − 1276
$reason = $row['reason'];
+ − 1277
}
+ − 1278
}
+ − 1279
else {
+ − 1280
if($row['ban_value']==$this->username) { $banned = true; $reason = $row['reason']; }
+ − 1281
}
+ − 1282
break;
+ − 1283
case BAN_EMAIL:
+ − 1284
if(intval($row['is_regex'])==1) {
+ − 1285
if(preg_match('#'.$row['ban_value'].'#i', $this->email))
+ − 1286
{
+ − 1287
$banned = true;
+ − 1288
$reason = $row['reason'];
+ − 1289
}
+ − 1290
}
+ − 1291
else {
+ − 1292
if($row['ban_value']==$this->email) { $banned = true; $reason = $row['reason']; }
+ − 1293
}
+ − 1294
break;
+ − 1295
default:
+ − 1296
die('Ban error: rule "'.$row['ban_value'].'" has an invalid type ('.$row['ban_type'].')');
+ − 1297
}
+ − 1298
}
+ − 1299
if($banned && $paths->get_pageid_from_url() != $paths->nslist['Special'].'CSS')
+ − 1300
{
+ − 1301
// This guy is banned - kill the session, kill the database connection, bail out, and be pretty about it
+ − 1302
die_semicritical('Ban notice', '<div class="error-box">You have been banned from this website. Please contact the site administrator for more information.<br /><br />Reason:<br />'.$reason.'</div>');
+ − 1303
exit;
+ − 1304
}
+ − 1305
}
+ − 1306
+ − 1307
# Registration
+ − 1308
+ − 1309
/**
+ − 1310
* Registers a user. This does not perform any type of login.
+ − 1311
* @param string $username
+ − 1312
* @param string $password This should be unencrypted.
+ − 1313
* @param string $email
+ − 1314
* @param string $real_name Optional, defaults to ''.
30
+ − 1315
* @param bool $coppa Optional. If true, the account is not activated initially and an admin activation request is sent. The caller is responsible for sending the address info and notice.
1
+ − 1316
*/
+ − 1317
30
+ − 1318
function create_user($username, $password, $email, $real_name = '', $coppa = false)
13
fdd6b9dd42c3
Installer actually works now on dev servers; minor language change in template.php; code cleanliness fix in sessions.php
Dan
diff
changeset
+ − 1319
{
1
+ − 1320
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1321
+ − 1322
// Initialize AES
+ − 1323
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1324
+ − 1325
if(!preg_match('#^'.$this->valid_username.'$#', $username)) return 'The username you chose contains invalid characters.';
+ − 1326
$username = $this->prepare_text($username);
+ − 1327
$email = $this->prepare_text($email);
+ − 1328
$real_name = $this->prepare_text($real_name);
+ − 1329
$password = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1330
+ − 1331
$nameclause = ( $real_name != '' ) ? ' OR real_name=\''.$real_name.'\'' : '';
+ − 1332
$q = $this->sql('SELECT * FROM '.table_prefix.'users WHERE lcase(username)=\''.strtolower($username).'\' OR email=\''.$email.'\''.$nameclause.';');
+ − 1333
if($db->numrows() > 0) {
+ − 1334
$r = 'The ';
+ − 1335
$i=0;
+ − 1336
$row = $db->fetchrow();
+ − 1337
// Wow! An error checker that actually speaks English with the properest grammar! :-P
+ − 1338
if($row['username'] == $username) { $r .= 'username'; $i++; }
+ − 1339
if($row['email'] == $email) { if($i) $r.=', '; $r .= 'e-mail address'; $i++; }
+ − 1340
if($row['real_name'] == $real_name && $real_name != '') { if($i) $r.=', and '; $r .= 'real name'; $i++; }
+ − 1341
$r .= ' that you entered ';
+ − 1342
$r .= ( $i == 1 ) ? 'is' : 'are';
+ − 1343
$r .= ' already in use by another user.';
+ − 1344
return $r;
+ − 1345
}
+ − 1346
+ − 1347
// Require the account to be activated?
+ − 1348
switch(getConfig('account_activation'))
+ − 1349
{
+ − 1350
case 'none':
+ − 1351
default:
+ − 1352
$active = '1';
+ − 1353
break;
+ − 1354
case 'user':
+ − 1355
$active = '0';
+ − 1356
break;
+ − 1357
case 'admin':
+ − 1358
$active = '0';
+ − 1359
break;
+ − 1360
}
30
+ − 1361
if ( $coppa )
+ − 1362
$active = '0';
+ − 1363
+ − 1364
$coppa_col = ( $coppa ) ? '1' : '0';
1
+ − 1365
+ − 1366
// Generate a totally random activation key
+ − 1367
$actkey = sha1 ( microtime() . mt_rand() );
+ − 1368
30
+ − 1369
// We good, create the user
+ − 1370
$this->sql('INSERT INTO '.table_prefix.'users ( username, password, email, real_name, theme, style, reg_time, account_active, activation_key, user_level, user_coppa ) VALUES ( \''.$username.'\', \''.$password.'\', \''.$email.'\', \''.$real_name.'\', \''.$template->default_theme.'\', \''.$template->default_style.'\', '.time().', '.$active.', \''.$actkey.'\', '.USER_LEVEL_CHPREF.', ' . $coppa_col . ' );');
1
+ − 1371
31
+ − 1372
// Get user ID and create users_extra entry
+ − 1373
$q = $this->sql('SELECT user_id FROM '.table_prefix."users WHERE username='$username';");
+ − 1374
if ( $db->numrows() > 0 )
+ − 1375
{
+ − 1376
$row = $db->fetchrow();
+ − 1377
$db->free_result();
+ − 1378
+ − 1379
$user_id =& $row['user_id'];
+ − 1380
$this->sql('INSERT INTO '.table_prefix.'user_extra(user_id) VALUES(' . $user_id . ');');
+ − 1381
}
+ − 1382
1
+ − 1383
// Require the account to be activated?
30
+ − 1384
if ( $coppa )
+ − 1385
{
+ − 1386
$this->admin_activation_request($username);
+ − 1387
$this->send_coppa_mail($username,$email);
+ − 1388
}
+ − 1389
else
1
+ − 1390
{
30
+ − 1391
switch(getConfig('account_activation'))
+ − 1392
{
+ − 1393
case 'none':
+ − 1394
default:
+ − 1395
break;
+ − 1396
case 'user':
+ − 1397
$a = $this->send_activation_mail($username);
+ − 1398
if(!$a)
+ − 1399
{
+ − 1400
$this->admin_activation_request($username);
+ − 1401
return 'The activation e-mail could not be sent due to an internal error. This could possibly be due to an incorrect SMTP configuration. A request has been sent to the administrator to activate your account for you. ' . $a;
+ − 1402
}
+ − 1403
break;
+ − 1404
case 'admin':
1
+ − 1405
$this->admin_activation_request($username);
30
+ − 1406
break;
+ − 1407
}
1
+ − 1408
}
+ − 1409
+ − 1410
// Leave some data behind for the hook
+ − 1411
$code = $plugins->setHook('user_registered'); // , Array('username'=>$username));
+ − 1412
foreach ( $code as $cmd )
+ − 1413
{
+ − 1414
eval($cmd);
+ − 1415
}
+ − 1416
+ − 1417
// $this->register_session($username, $password);
+ − 1418
return 'success';
+ − 1419
}
+ − 1420
+ − 1421
/**
+ − 1422
* Attempts to send an e-mail to the specified user with activation instructions.
+ − 1423
* @param string $u The usernamd of the user requesting activation
+ − 1424
* @return bool true on success, false on failure
+ − 1425
*/
+ − 1426
+ − 1427
function send_activation_mail($u, $actkey = false)
+ − 1428
{
+ − 1429
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1430
$q = $this->sql('SELECT username,email FROM '.table_prefix.'users WHERE user_id=1 OR user_level=' . USER_LEVEL_ADMIN . ' ORDER BY user_id ASC;');
+ − 1431
$un = $db->fetchrow();
+ − 1432
$admin_user = $un['username'];
+ − 1433
$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
+ − 1434
$r = $db->fetchrow();
+ − 1435
if ( empty($r['email']) )
+ − 1436
$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
+ − 1437
$message = 'Dear '.$u.',
+ − 1438
Thank you for registering on '.getConfig('site_name').'. Your account creation is almost complete. To complete the registration process, please click the following link or paste it into your web browser:
+ − 1439
+ − 1440
';
+ − 1441
if(isset($_SERVER['HTTPS'])) $prot = 'https';
+ − 1442
else $prot = 'http';
+ − 1443
if($_SERVER['SERVER_PORT'] == '80') $p = '';
+ − 1444
else $p = ':'.$_SERVER['SERVER_PORT'];
+ − 1445
$sidbak = false;
+ − 1446
if($this->sid_super)
+ − 1447
$sidbak = $this->sid_super;
+ − 1448
$this->sid_super = false;
+ − 1449
$aklink = makeUrlNS('Special', 'ActivateAccount/'.str_replace(' ', '_', $u).'/'. ( ( is_string($actkey) ) ? $actkey : $r['activation_key'] ) );
+ − 1450
if($sidbak)
+ − 1451
$this->sid_super = $sidbak;
+ − 1452
unset($sidbak);
+ − 1453
$message .= "$prot://".$_SERVER['HTTP_HOST'].$p.$aklink;
+ − 1454
$message .= "\n\nSincerely yours, \n$admin_user and the ".$_SERVER['HTTP_HOST']." administration team";
+ − 1455
error_reporting(E_ALL);
+ − 1456
dc_dump($r, 'session: about to send activation e-mail to '.$r['email']);
+ − 1457
if(getConfig('smtp_enabled') == '1')
+ − 1458
{
+ − 1459
$result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1460
if($result == 'success') $result = true;
+ − 1461
else { echo $result; $result = false; }
+ − 1462
} else {
+ − 1463
$result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1464
}
+ − 1465
return $result;
+ − 1466
}
+ − 1467
+ − 1468
/**
30
+ − 1469
* Attempts to send an e-mail to the specified user's e-mail address on file intended for the parents
+ − 1470
* @param string $u The usernamd of the user requesting activation
+ − 1471
* @return bool true on success, false on failure
+ − 1472
*/
+ − 1473
+ − 1474
function send_coppa_mail($u, $actkey = false)
+ − 1475
{
+ − 1476
+ − 1477
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1478
+ − 1479
$q = $this->sql('SELECT username,email FROM '.table_prefix.'users WHERE user_id=2 OR user_level=' . USER_LEVEL_ADMIN . ' ORDER BY user_id ASC;');
+ − 1480
$un = $db->fetchrow();
+ − 1481
$admin_user = $un['username'];
+ − 1482
+ − 1483
$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
+ − 1484
$r = $db->fetchrow();
+ − 1485
if ( empty($r['email']) )
+ − 1486
$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
+ − 1487
+ − 1488
if(isset($_SERVER['HTTPS'])) $prot = 'https';
+ − 1489
else $prot = 'http';
+ − 1490
if($_SERVER['SERVER_PORT'] == '80') $p = '';
+ − 1491
else $p = ':'.$_SERVER['SERVER_PORT'];
+ − 1492
$sidbak = false;
+ − 1493
if($this->sid_super)
+ − 1494
$sidbak = $this->sid_super;
+ − 1495
$this->sid_super = false;
+ − 1496
if($sidbak)
+ − 1497
$this->sid_super = $sidbak;
+ − 1498
unset($sidbak);
+ − 1499
$link = "$prot://".$_SERVER['HTTP_HOST'].scriptPath;
+ − 1500
+ − 1501
$message = 'Dear parent or legal guardian,
+ − 1502
A child under the username ' . $u . ' recently registered on our website. The child provided your e-mail address as the one of his or her authorized parent or legal guardian, and to comply with the United States Childrens\' Online Privacy Protection act, we ask that all parents of children ages 13 or under please mail us a written form authorizing their child\'s use of our website.
+ − 1503
+ − 1504
If you wish for your child to be allowed access to our website, please print and fill out the form below, and mail it to this address:
+ − 1505
+ − 1506
' . getConfig('coppa_address') . '
+ − 1507
+ − 1508
If you do NOT wish for your child to be allowed access to our site, you do not need to do anything - your child will not be able to access our site as a registered user unless you authorize their account activation.
+ − 1509
+ − 1510
Authorization form:
+ − 1511
-------------------------------- Cut here --------------------------------
+ − 1512
+ − 1513
I, _______________________________________, the legal parent or guardian of the child registered on the website "' . getConfig('site_name') . '" as ' . $u . ', hereby give my authorization for the child\'s e-mail address, instant messaging information, location, and real name, to be collected and stored in a database owned and maintained by ' . getConfig('site_name') . ' at the child\'s option, and for the administrators of this website to use this information according to the privacy policy displayed on their website <' . $link . '>.
+ − 1514
+ − 1515
Child\'s name: _____________________________________
+ − 1516
+ − 1517
Child\'s e-mail address: _____________________________________
+ − 1518
(optional - if you don\'t provide this, we\'ll just send site-related e-mails to your e-mail address)
+ − 1519
+ − 1520
Signature of parent or guardian:
+ − 1521
+ − 1522
____________________________________________________
+ − 1523
+ − 1524
Date (YYYY-MM-DD): ______ / _____ / _____
+ − 1525
+ − 1526
-------------------------------- Cut here --------------------------------';
+ − 1527
$message .= "\n\nSincerely yours, \n$admin_user and the ".$_SERVER['HTTP_HOST']." administration team";
+ − 1528
+ − 1529
error_reporting(E_ALL);
+ − 1530
+ − 1531
dc_dump($r, 'session: about to send COPPA e-mail to '.$r['email']);
+ − 1532
if(getConfig('smtp_enabled') == '1')
+ − 1533
{
+ − 1534
$result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1535
if($result == 'success')
+ − 1536
{
+ − 1537
$result = true;
+ − 1538
}
+ − 1539
else
+ − 1540
{
+ − 1541
echo $result;
+ − 1542
$result = false;
+ − 1543
}
+ − 1544
}
+ − 1545
else
+ − 1546
{
+ − 1547
$result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1548
}
+ − 1549
return $result;
+ − 1550
}
+ − 1551
+ − 1552
/**
1
+ − 1553
* Sends an e-mail to a user so they can reset their password.
+ − 1554
* @param int $user The user ID, or username if it's a string
+ − 1555
* @return bool true on success, false on failure
+ − 1556
*/
+ − 1557
+ − 1558
function mail_password_reset($user)
+ − 1559
{
+ − 1560
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1561
if(is_int($user))
+ − 1562
{
+ − 1563
$q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE user_id='.$user.';'); // This is SAFE! This is only called if $user is an integer
+ − 1564
}
+ − 1565
elseif(is_string($user))
+ − 1566
{
+ − 1567
$q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($user).'\';');
+ − 1568
}
+ − 1569
else
+ − 1570
{
+ − 1571
return false;
+ − 1572
}
+ − 1573
+ − 1574
$row = $db->fetchrow();
+ − 1575
$temp_pass = $this->random_pass();
+ − 1576
+ − 1577
$this->register_temp_password($row['user_id'], $temp_pass);
+ − 1578
+ − 1579
$site_name = getConfig('site_name');
+ − 1580
+ − 1581
$message = "Dear {$row['username']},
+ − 1582
+ − 1583
Someone (hopefully you) on the {$site_name} website requested that a new password be created.
+ − 1584
+ − 1585
The request was sent from the IP address {$_SERVER['REMOTE_ADDR']}.
+ − 1586
+ − 1587
If you did not request the new password, then you do not need to do anything; the password will be invalidated after 24 hours.
+ − 1588
+ − 1589
If you did request this password, then please log in using the password shown below:
+ − 1590
+ − 1591
Password: {$temp_pass}
+ − 1592
+ − 1593
After you log in using this password, you will be able to reset your real password. You can only log in using this temporary password once.
+ − 1594
+ − 1595
Sincerely yours,
+ − 1596
The {$site_name} administration team
+ − 1597
";
+ − 1598
+ − 1599
if(getConfig('smtp_enabled') == '1')
+ − 1600
{
+ − 1601
$result = smtp_send_email($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1602
if($result == 'success')
+ − 1603
{
+ − 1604
$result = true;
+ − 1605
}
+ − 1606
else
+ − 1607
{
+ − 1608
echo '<p>'.$result.'</p>';
+ − 1609
$result = false;
+ − 1610
}
+ − 1611
} else {
+ − 1612
$result = mail($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1613
}
+ − 1614
return $result;
+ − 1615
}
+ − 1616
+ − 1617
/**
+ − 1618
* Sets the temporary password for the specified user to whatever is specified.
+ − 1619
* @param int $user_id
+ − 1620
* @param string $password
+ − 1621
* @return bool
+ − 1622
*/
+ − 1623
+ − 1624
function register_temp_password($user_id, $password)
+ − 1625
{
+ − 1626
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1627
$temp_pass = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1628
$this->sql('UPDATE '.table_prefix.'users SET temp_password=\'' . $temp_pass . '\',temp_password_time='.time().' WHERE user_id='.intval($user_id).';');
+ − 1629
}
+ − 1630
+ − 1631
/**
+ − 1632
* Sends a request to the admin panel to have the username $u activated.
+ − 1633
* @param string $u The username of the user requesting activation
+ − 1634
*/
+ − 1635
+ − 1636
function admin_activation_request($u)
+ − 1637
{
+ − 1638
global $db;
+ − 1639
$this->sql('INSERT INTO '.table_prefix.'logs(log_type, action, time_id, date_string, author, edit_summary) VALUES(\'admin\', \'activ_req\', '.time().', \''.date('d M Y h:i a').'\', \''.$this->username.'\', \''.$db->escape($u).'\');');
+ − 1640
}
+ − 1641
+ − 1642
/**
+ − 1643
* Activates a user account. If the action fails, a report is sent to the admin.
+ − 1644
* @param string $user The username of the user requesting activation
+ − 1645
* @param string $key The activation key
+ − 1646
*/
+ − 1647
+ − 1648
function activate_account($user, $key)
+ − 1649
{
+ − 1650
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1651
$this->sql('UPDATE '.table_prefix.'users SET account_active=1 WHERE username=\''.$db->escape($user).'\' AND activation_key=\''.$db->escape($key).'\';');
+ − 1652
$r = mysql_affected_rows();
+ − 1653
if ( $r > 0 )
+ − 1654
{
+ − 1655
$e = $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_good\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
+ − 1656
}
+ − 1657
else
+ − 1658
{
+ − 1659
$e = $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
+ − 1660
}
+ − 1661
return $r;
+ − 1662
}
+ − 1663
+ − 1664
/**
+ − 1665
* For a given user level identifier (USER_LEVEL_*), returns a string describing that user level.
+ − 1666
* @param int User level
+ − 1667
* @return string
+ − 1668
*/
+ − 1669
+ − 1670
function userlevel_to_string($user_level)
+ − 1671
{
+ − 1672
switch ( $user_level )
+ − 1673
{
+ − 1674
case USER_LEVEL_GUEST:
+ − 1675
return 'Low - guest privileges';
+ − 1676
case USER_LEVEL_MEMBER:
+ − 1677
return 'Standard - normal member level';
+ − 1678
case USER_LEVEL_CHPREF:
+ − 1679
return 'Medium - user can change his/her own e-mail address and password';
+ − 1680
case USER_LEVEL_MOD:
+ − 1681
return 'High - moderator privileges';
+ − 1682
case USER_LEVEL_ADMIN:
+ − 1683
return 'Highest - administrative privileges';
+ − 1684
default:
+ − 1685
return "Unknown ($user_level)";
+ − 1686
}
+ − 1687
}
+ − 1688
+ − 1689
/**
+ − 1690
* Updates a user's information in the database. Note that any of the values except $user_id can be false if you want to preserve the old values.
+ − 1691
* @param int $user_id The user ID of the user to update - this cannot be changed
+ − 1692
* @param string $username The new username
+ − 1693
* @param string $old_pass The current password - only required if sessionManager::$user_level < USER_LEVEL_ADMIN. This should usually be an UNENCRYPTED string. This can also be an array - if it is, key 0 is treated as data AES-encrypted with key 1
+ − 1694
* @param string $password The new password
+ − 1695
* @param string $email The new e-mail address
+ − 1696
* @param string $realname The new real name
+ − 1697
* @param string $signature The updated forum/comment signature
+ − 1698
* @param int $user_level The updated user level
+ − 1699
* @return string 'success' if successful, or array of error strings on failure
+ − 1700
*/
+ − 1701
+ − 1702
function update_user($user_id, $username = false, $old_pass = false, $password = false, $email = false, $realname = false, $signature = false, $user_level = false)
+ − 1703
{
+ − 1704
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1705
+ − 1706
// Create some arrays
+ − 1707
+ − 1708
$errors = Array(); // Used to hold error strings
+ − 1709
$strs = Array(); // Sub-query statements
+ − 1710
+ − 1711
// Scan the user ID for problems
+ − 1712
if(intval($user_id) < 1) $errors[] = 'SQL injection attempt';
+ − 1713
+ − 1714
// Instanciate the AES encryption class
+ − 1715
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1716
+ − 1717
// If all of our input vars are false, then we've effectively done our job so get out of here
+ − 1718
if($username === false && $password === false && $email === false && $realname === false && $signature === false && $user_level === false)
+ − 1719
{
+ − 1720
// echo 'debug: $session->update_user(): success (no changes requested)';
+ − 1721
return 'success';
+ − 1722
}
+ − 1723
+ − 1724
// Initialize our authentication check
+ − 1725
$authed = false;
+ − 1726
+ − 1727
// Verify the inputted password
+ − 1728
if(is_string($old_pass))
+ − 1729
{
+ − 1730
$q = $this->sql('SELECT password FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1731
if($db->numrows() < 1)
+ − 1732
{
+ − 1733
$errors[] = 'The password data could not be selected for verification.';
+ − 1734
}
+ − 1735
else
+ − 1736
{
+ − 1737
$row = $db->fetchrow();
+ − 1738
$real = $aes->decrypt($row['password'], $this->private_key, ENC_HEX);
+ − 1739
if($real == $old_pass)
+ − 1740
$authed = true;
+ − 1741
}
+ − 1742
}
+ − 1743
+ − 1744
elseif(is_array($old_pass))
+ − 1745
{
+ − 1746
$old_pass = $aes->decrypt($old_pass[0], $old_pass[1]);
+ − 1747
$q = $this->sql('SELECT password FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1748
if($db->numrows() < 1)
+ − 1749
{
+ − 1750
$errors[] = 'The password data could not be selected for verification.';
+ − 1751
}
+ − 1752
else
+ − 1753
{
+ − 1754
$row = $db->fetchrow();
+ − 1755
$real = $aes->decrypt($row['password'], $this->private_key, ENC_HEX);
+ − 1756
if($real == $old_pass)
+ − 1757
$authed = true;
+ − 1758
}
+ − 1759
}
+ − 1760
+ − 1761
// Initialize our query
+ − 1762
$q = 'UPDATE '.table_prefix.'users SET ';
+ − 1763
+ − 1764
if($this->auth_level >= USER_LEVEL_ADMIN || $authed) // Need the current password in order to update the e-mail address, change the username, or reset the password
+ − 1765
{
+ − 1766
// Username
+ − 1767
if(is_string($username))
+ − 1768
{
+ − 1769
// Check the username for problems
+ − 1770
if(!preg_match('#^'.$this->valid_username.'$#', $username))
+ − 1771
$errors[] = 'The username you entered contains invalid characters.';
+ − 1772
$strs[] = 'username=\''.$db->escape($username).'\'';
+ − 1773
}
+ − 1774
// Password
+ − 1775
if(is_string($password) && strlen($password) >= 6)
+ − 1776
{
+ − 1777
// Password needs to be encrypted before being stashed
+ − 1778
$encpass = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1779
if(!$encpass)
+ − 1780
$errors[] = 'The password could not be encrypted due to an internal error.';
+ − 1781
$strs[] = 'password=\''.$encpass.'\'';
+ − 1782
}
+ − 1783
// E-mail addy
+ − 1784
if(is_string($email))
+ − 1785
{
+ − 1786
// I didn't write this regex.
+ − 1787
if(!preg_match('/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/', $email))
+ − 1788
$errors[] = 'The e-mail address you entered is invalid.';
+ − 1789
$strs[] = 'email=\''.$db->escape($email).'\'';
+ − 1790
}
+ − 1791
}
+ − 1792
// Real name
+ − 1793
if(is_string($realname))
+ − 1794
{
+ − 1795
$strs[] = 'real_name=\''.$db->escape($realname).'\'';
+ − 1796
}
+ − 1797
// Forum/comment signature
+ − 1798
if(is_string($signature))
+ − 1799
{
+ − 1800
$strs[] = 'signature=\''.$db->escape($signature).'\'';
+ − 1801
}
+ − 1802
// User level
+ − 1803
if(is_int($user_level))
+ − 1804
{
+ − 1805
$strs[] = 'user_level='.$user_level;
+ − 1806
}
+ − 1807
+ − 1808
// Add our generated query to the query string
+ − 1809
$q .= implode(',', $strs);
+ − 1810
+ − 1811
// One last error check
+ − 1812
if(sizeof($strs) < 1) $errors[] = 'An internal error occured building the SQL query, this is a bug';
+ − 1813
if(sizeof($errors) > 0) return $errors;
+ − 1814
+ − 1815
// Free our temp arrays
+ − 1816
unset($strs, $errors);
+ − 1817
+ − 1818
// Finalize the query and run it
+ − 1819
$q .= ' WHERE user_id='.$user_id.';';
+ − 1820
$this->sql($q);
+ − 1821
+ − 1822
// We also need to trigger re-activation.
+ − 1823
if ( is_string($email) )
+ − 1824
{
+ − 1825
switch(getConfig('account_activation'))
+ − 1826
{
+ − 1827
case 'user':
+ − 1828
case 'admin':
+ − 1829
+ − 1830
if ( $session->user_level >= USER_LEVEL_MOD && getConfig('account_activation') == 'admin' )
+ − 1831
// Don't require re-activation by admins for admins
+ − 1832
break;
+ − 1833
+ − 1834
// retrieve username
+ − 1835
if ( !$username )
+ − 1836
{
+ − 1837
$q = $this->sql('SELECT username FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1838
if($db->numrows() < 1)
+ − 1839
{
+ − 1840
$errors[] = 'The username could not be selected.';
+ − 1841
}
+ − 1842
else
+ − 1843
{
+ − 1844
$row = $db->fetchrow();
+ − 1845
$username = $row['username'];
+ − 1846
}
+ − 1847
}
+ − 1848
if ( !$username )
+ − 1849
return $errors;
+ − 1850
+ − 1851
// Generate a totally random activation key
+ − 1852
$actkey = sha1 ( microtime() . mt_rand() );
+ − 1853
$a = $this->send_activation_mail($username, $actkey);
+ − 1854
if(!$a)
+ − 1855
{
+ − 1856
$this->admin_activation_request($username);
+ − 1857
}
+ − 1858
// Deactivate the account until e-mail is confirmed
+ − 1859
$q = $db->sql_query('UPDATE '.table_prefix.'users SET account_active=0,activation_key=\'' . $actkey . '\' WHERE user_id=' . $user_id . ';');
+ − 1860
break;
+ − 1861
}
+ − 1862
}
+ − 1863
+ − 1864
// Yay! We're done
+ − 1865
return 'success';
+ − 1866
}
+ − 1867
+ − 1868
#
+ − 1869
# Access Control Lists
+ − 1870
#
+ − 1871
+ − 1872
/**
+ − 1873
* Creates a new permission field in memory. If the permissions are set in the database, they are used. Otherwise, $default_perm is used.
+ − 1874
* @param string $acl_type An identifier for this field
+ − 1875
* @param int $default_perm Whether permission should be granted or not if it's not specified in the ACLs.
+ − 1876
* @param string $desc A human readable name for the permission type
+ − 1877
* @param array $deps The list of dependencies - this should be an array of ACL types
+ − 1878
* @param string $scope Which namespaces this field should apply to. This should be either a pipe-delimited list of namespace IDs or just "All".
+ − 1879
*/
+ − 1880
+ − 1881
function register_acl_type($acl_type, $default_perm = AUTH_DISALLOW, $desc = false, $deps = Array(), $scope = 'All')
+ − 1882
{
+ − 1883
if(isset($this->acl_types[$acl_type]))
+ − 1884
return false;
+ − 1885
else
+ − 1886
{
+ − 1887
if(!$desc)
+ − 1888
{
+ − 1889
$desc = capitalize_first_letter(str_replace('_', ' ', $acl_type));
+ − 1890
}
+ − 1891
$this->acl_types[$acl_type] = $default_perm;
+ − 1892
$this->acl_descs[$acl_type] = $desc;
+ − 1893
$this->acl_deps[$acl_type] = $deps;
+ − 1894
$this->acl_scope[$acl_type] = explode('|', $scope);
+ − 1895
}
+ − 1896
return true;
+ − 1897
}
+ − 1898
+ − 1899
/**
+ − 1900
* Tells us whether permission $type is allowed or not based on the current rules.
+ − 1901
* @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
+ − 1902
* @param bool $no_deps If true, disables dependency checking
+ − 1903
* @return bool True if allowed, false if denied or if an error occured
+ − 1904
*/
+ − 1905
+ − 1906
function get_permissions($type, $no_deps = false)
+ − 1907
{
+ − 1908
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1909
if ( isset( $this->perms[$type] ) )
+ − 1910
{
+ − 1911
if ( $this->perms[$type] == AUTH_DENY )
+ − 1912
$ret = false;
+ − 1913
else if ( $this->perms[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 1914
$ret = true;
+ − 1915
else if ( $this->perms[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 1916
$ret = false;
+ − 1917
else if ( $this->perms[$type] == AUTH_ALLOW )
+ − 1918
$ret = true;
+ − 1919
else if ( $this->perms[$type] == AUTH_DISALLOW )
+ − 1920
$ret = false;
+ − 1921
}
+ − 1922
else if(isset($this->acl_types[$type]))
+ − 1923
{
+ − 1924
if ( $this->acl_types[$type] == AUTH_DENY )
+ − 1925
$ret = false;
+ − 1926
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 1927
$ret = true;
+ − 1928
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 1929
$ret = false;
+ − 1930
else if ( $this->acl_types[$type] == AUTH_ALLOW )
+ − 1931
$ret = true;
+ − 1932
else if ( $this->acl_types[$type] == AUTH_DISALLOW )
+ − 1933
$ret = false;
+ − 1934
}
+ − 1935
else
+ − 1936
{
+ − 1937
// ACL type is undefined
+ − 1938
trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
+ − 1939
return false; // Be on the safe side and deny access
+ − 1940
}
+ − 1941
if ( !$no_deps )
+ − 1942
{
+ − 1943
if ( !$this->acl_check_deps($type) )
+ − 1944
return false;
+ − 1945
}
+ − 1946
return $ret;
+ − 1947
}
+ − 1948
+ − 1949
/**
+ − 1950
* Fetch the permissions that apply to the current user for the page specified. The object you get will have the get_permissions method
+ − 1951
* and several other abilities.
+ − 1952
* @param string $page_id
+ − 1953
* @param string $namespace
+ − 1954
* @return object
+ − 1955
*/
+ − 1956
+ − 1957
function fetch_page_acl($page_id, $namespace)
+ − 1958
{
+ − 1959
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1960
+ − 1961
if ( count ( $this->acl_base_cache ) < 1 )
+ − 1962
{
+ − 1963
// Permissions table not yet initialized
+ − 1964
return false;
+ − 1965
}
+ − 1966
+ − 1967
//if ( !isset( $paths->pages[$paths->nslist[$namespace] . $page_id] ) )
+ − 1968
//{
+ − 1969
// // Page does not exist
+ − 1970
// return false;
+ − 1971
//}
+ − 1972
+ − 1973
$object = new Session_ACLPageInfo( $page_id, $namespace, $this->acl_types, $this->acl_descs, $this->acl_deps, $this->acl_base_cache );
+ − 1974
+ − 1975
return $object;
+ − 1976
+ − 1977
}
+ − 1978
+ − 1979
/**
+ − 1980
* Read all of our permissions from the database and process/apply them. This should be called after the page is determined.
+ − 1981
* @access private
+ − 1982
*/
+ − 1983
+ − 1984
function init_permissions()
+ − 1985
{
+ − 1986
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1987
// Initialize the permissions list with some defaults
+ − 1988
$this->perms = $this->acl_types;
+ − 1989
$this->acl_defaults_used = $this->perms;
+ − 1990
+ − 1991
// Fetch sitewide defaults from the permissions table
+ − 1992
$bs = 'SELECT rules FROM '.table_prefix.'acl WHERE page_id IS NULL AND namespace IS NULL AND ( ';
+ − 1993
+ − 1994
$q = Array();
+ − 1995
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
+ − 1996
if(count($this->groups) > 0)
+ − 1997
{
+ − 1998
foreach($this->groups as $g_id => $g_name)
+ − 1999
{
+ − 2000
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 2001
}
+ − 2002
}
+ − 2003
$bs .= implode(' OR ', $q) . ' ) ORDER BY target_type ASC, target_id ASC;';
+ − 2004
$q = $this->sql($bs);
+ − 2005
if ( $row = $db->fetchrow() )
+ − 2006
{
+ − 2007
do {
+ − 2008
$rules = $this->string_to_perm($row['rules']);
+ − 2009
$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
+ − 2010
$this->acl_merge_with_current($rules, $is_everyone);
+ − 2011
} while ( $row = $db->fetchrow() );
+ − 2012
}
+ − 2013
+ − 2014
// Eliminate types that don't apply to this namespace
+ − 2015
foreach ( $this->perms AS $i => $perm )
+ − 2016
{
+ − 2017
if ( !in_array ( $paths->namespace, $this->acl_scope[$i] ) && !in_array('All', $this->acl_scope[$i]) )
+ − 2018
{
+ − 2019
unset($this->perms[$i]);
+ − 2020
}
+ − 2021
}
+ − 2022
+ − 2023
// Cache the sitewide permissions for later use
+ − 2024
$this->acl_base_cache = $this->perms;
+ − 2025
+ − 2026
// Build a query to grab ACL info
+ − 2027
$bs = 'SELECT rules,target_type,target_id FROM '.table_prefix.'acl WHERE ( ';
+ − 2028
$q = Array();
+ − 2029
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
+ − 2030
if(count($this->groups) > 0)
+ − 2031
{
+ − 2032
foreach($this->groups as $g_id => $g_name)
+ − 2033
{
+ − 2034
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 2035
}
+ − 2036
}
+ − 2037
// The reason we're using an ORDER BY statement here is because ACL_TYPE_GROUP is less than ACL_TYPE_USER, causing the user's individual
+ − 2038
// permissions to override group permissions.
+ − 2039
$bs .= implode(' OR ', $q) . ' ) AND ( page_id=\''.$db->escape($paths->cpage['urlname_nons']).'\' AND namespace=\''.$db->escape($paths->namespace).'\' )
+ − 2040
ORDER BY target_type ASC, page_id ASC, namespace ASC;';
+ − 2041
$q = $this->sql($bs);
+ − 2042
if ( $row = $db->fetchrow() )
+ − 2043
{
+ − 2044
do {
+ − 2045
$rules = $this->string_to_perm($row['rules']);
+ − 2046
$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
+ − 2047
$this->acl_merge_with_current($rules, $is_everyone);
+ − 2048
} while ( $row = $db->fetchrow() );
+ − 2049
}
+ − 2050
+ − 2051
}
+ − 2052
+ − 2053
/**
+ − 2054
* Extends the scope of a permission type.
+ − 2055
* @param string The name of the permission type
+ − 2056
* @param string The namespace(s) that should be covered. This can be either one namespace ID or a pipe-delimited list.
+ − 2057
* @param object Optional - the current $paths object, in case we're doing this from the acl_rule_init hook
+ − 2058
*/
+ − 2059
+ − 2060
function acl_extend_scope($perm_type, $namespaces, &$p_in)
+ − 2061
{
+ − 2062
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2063
$p_obj = ( is_object($p_in) ) ? $p_in : $paths;
+ − 2064
$nslist = explode('|', $namespaces);
+ − 2065
foreach ( $nslist as $i => $ns )
+ − 2066
{
+ − 2067
if ( !isset($p_obj->nslist[$ns]) )
+ − 2068
{
+ − 2069
unset($nslist[$i]);
+ − 2070
}
+ − 2071
else
+ − 2072
{
+ − 2073
$this->acl_scope[$perm_type][] = $ns;
+ − 2074
if ( isset($this->acl_types[$perm_type]) && !isset($this->perms[$perm_type]) )
+ − 2075
{
+ − 2076
$this->perms[$perm_type] = $this->acl_types[$perm_type];
+ − 2077
}
+ − 2078
}
+ − 2079
}
+ − 2080
}
+ − 2081
+ − 2082
/**
+ − 2083
* Converts a permissions field into a string for database insertion. Similar in spirit to serialize().
+ − 2084
* @param array $perms An associative array with only integers as values
+ − 2085
* @return string
+ − 2086
*/
+ − 2087
+ − 2088
function perm_to_string($perms)
+ − 2089
{
+ − 2090
$s = '';
+ − 2091
foreach($perms as $perm => $ac)
+ − 2092
{
+ − 2093
$s .= "$perm=$ac;";
+ − 2094
}
+ − 2095
return $s;
+ − 2096
}
+ − 2097
+ − 2098
/**
+ − 2099
* Converts a permissions string back to an array.
+ − 2100
* @param string $perms The result from sessionManager::perm_to_string()
+ − 2101
* @return array
+ − 2102
*/
+ − 2103
+ − 2104
function string_to_perm($perms)
+ − 2105
{
+ − 2106
$ret = Array();
+ − 2107
preg_match_all('#([a-z0-9_-]+)=([0-9]+);#i', $perms, $matches);
+ − 2108
foreach($matches[1] as $i => $t)
+ − 2109
{
+ − 2110
$ret[$t] = intval($matches[2][$i]);
+ − 2111
}
+ − 2112
return $ret;
+ − 2113
}
+ − 2114
+ − 2115
/**
+ − 2116
* Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence over the first, but AUTH_DENY always prevails.
+ − 2117
* @param array $perm1 The first set of permissions
+ − 2118
* @param array $perm2 The second set of permissions
+ − 2119
* @return array
+ − 2120
*/
+ − 2121
+ − 2122
function acl_merge($perm1, $perm2)
+ − 2123
{
+ − 2124
$ret = $perm1;
+ − 2125
foreach ( $perm2 as $type => $level )
+ − 2126
{
+ − 2127
if ( isset( $ret[$type] ) )
+ − 2128
{
+ − 2129
if ( $ret[$type] != AUTH_DENY )
+ − 2130
$ret[$type] = $level;
+ − 2131
}
+ − 2132
// else
+ − 2133
// {
+ − 2134
// $ret[$type] = $level;
+ − 2135
// }
+ − 2136
}
+ − 2137
return $ret;
+ − 2138
}
+ − 2139
+ − 2140
/**
+ − 2141
* Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
+ − 2142
* @param array The array to merge into the master ACL list
+ − 2143
* @param bool If true, $perm is treated as the "new default"
+ − 2144
* @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
+ − 2145
*/
+ − 2146
+ − 2147
function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
+ − 2148
{
+ − 2149
foreach ( $this->perms as $i => $p )
+ − 2150
{
+ − 2151
if ( isset($perm[$i]) )
+ − 2152
{
+ − 2153
if ( $is_everyone && !$this->acl_defaults_used[$i] )
+ − 2154
continue;
+ − 2155
// Decide precedence
+ − 2156
if ( isset($this->acl_defaults_used[$i]) )
+ − 2157
{
+ − 2158
//echo "$i: default in use, overriding to: {$perm[$i]}<br />";
+ − 2159
// Defaults are in use, override
+ − 2160
$this->perms[$i] = $perm[$i];
+ − 2161
$this->acl_defaults_used[$i] = ( $is_everyone );
+ − 2162
}
+ − 2163
else
+ − 2164
{
+ − 2165
//echo "$i: default NOT in use";
+ − 2166
// Defaults are not in use, merge as normal
+ − 2167
if ( $this->perms[$i] != AUTH_DENY )
+ − 2168
{
+ − 2169
//echo ", but overriding";
+ − 2170
$this->perms[$i] = $perm[$i];
+ − 2171
}
+ − 2172
//echo "<br />";
+ − 2173
}
+ − 2174
}
+ − 2175
}
+ − 2176
}
+ − 2177
+ − 2178
/**
+ − 2179
* Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence
+ − 2180
* over the first, without exceptions. This is used to merge the hardcoded defaults with admin-specified
+ − 2181
* defaults, which take precedence.
+ − 2182
* @param array $perm1 The first set of permissions
+ − 2183
* @param array $perm2 The second set of permissions
+ − 2184
* @return array
+ − 2185
*/
+ − 2186
+ − 2187
function acl_merge_complete($perm1, $perm2)
+ − 2188
{
+ − 2189
$ret = $perm1;
+ − 2190
foreach ( $perm2 as $type => $level )
+ − 2191
{
+ − 2192
$ret[$type] = $level;
+ − 2193
}
+ − 2194
return $ret;
+ − 2195
}
+ − 2196
+ − 2197
/**
+ − 2198
* Tell us if the dependencies for a given permission are met.
+ − 2199
* @param string The ACL permission ID
+ − 2200
* @return bool
+ − 2201
*/
+ − 2202
+ − 2203
function acl_check_deps($type)
+ − 2204
{
+ − 2205
if(!isset($this->acl_deps[$type])) // This will only happen if the permissions table is hacked or improperly accessed
+ − 2206
return true;
+ − 2207
if(sizeof($this->acl_deps[$type]) < 1)
+ − 2208
return true;
+ − 2209
$deps = $this->acl_deps[$type];
+ − 2210
while(true)
+ − 2211
{
+ − 2212
$full_resolved = true;
+ − 2213
$j = sizeof($deps);
+ − 2214
for ( $i = 0; $i < $j; $i++ )
+ − 2215
{
+ − 2216
$b = $deps;
+ − 2217
$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
+ − 2218
if( $b == $deps )
+ − 2219
{
+ − 2220
break 2;
+ − 2221
}
+ − 2222
$j = sizeof($deps);
+ − 2223
}
+ − 2224
}
+ − 2225
//die('<pre>'.print_r($deps, true).'</pre>');
+ − 2226
foreach($deps as $d)
+ − 2227
{
+ − 2228
if ( !$this->get_permissions($d) )
+ − 2229
{
+ − 2230
return false;
+ − 2231
}
+ − 2232
}
+ − 2233
return true;
+ − 2234
}
+ − 2235
+ − 2236
/**
+ − 2237
* Makes a CAPTCHA code and caches the code in the database
+ − 2238
* @param int $len The length of the code, in bytes
+ − 2239
* @return string A unique identifier assigned to the code. This hash should be passed to sessionManager::getCaptcha() to retrieve the code.
+ − 2240
*/
+ − 2241
+ − 2242
function make_captcha($len = 7)
+ − 2243
{
+ − 2244
$chars = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9');
+ − 2245
$s = '';
+ − 2246
for($i=0;$i<$len;$i++) $s .= $chars[mt_rand(0, count($chars)-1)];
+ − 2247
$hash = md5(microtime() . mt_rand());
+ − 2248
$this->sql('INSERT INTO '.table_prefix.'session_keys(session_key,salt,auth_level,source_ip,user_id) VALUES(\''.$hash.'\', \''.$s.'\', -1, \''.ip2hex($_SERVER['REMOTE_ADDR']).'\', -2);');
+ − 2249
return $hash;
+ − 2250
}
+ − 2251
+ − 2252
/**
+ − 2253
* For the given code ID, returns the correct CAPTCHA code, or false on failure
+ − 2254
* @param string $hash The unique ID assigned to the code
+ − 2255
* @return string The correct confirmation code
+ − 2256
*/
+ − 2257
+ − 2258
function get_captcha($hash)
+ − 2259
{
+ − 2260
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2261
$s = $this->sql('SELECT salt FROM '.table_prefix.'session_keys WHERE session_key=\''.$db->escape($hash).'\' AND source_ip=\''.ip2hex($_SERVER['REMOTE_ADDR']).'\';');
+ − 2262
if($db->numrows() < 1) return false;
+ − 2263
$r = $db->fetchrow();
+ − 2264
return $r['salt'];
+ − 2265
}
+ − 2266
+ − 2267
/**
+ − 2268
* Deletes all CAPTCHA codes cached in the DB for this user.
+ − 2269
*/
+ − 2270
+ − 2271
function kill_captcha()
+ − 2272
{
+ − 2273
$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE user_id=-2 AND source_ip=\''.ip2hex($_SERVER['REMOTE_ADDR']).'\';');
+ − 2274
}
+ − 2275
+ − 2276
/**
+ − 2277
* Generates a random password.
+ − 2278
* @param int $length Optional - length of password
+ − 2279
* @return string
+ − 2280
*/
+ − 2281
+ − 2282
function random_pass($length = 10)
+ − 2283
{
+ − 2284
$valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+@#%&<>';
+ − 2285
$valid_chars = enano_str_split($valid_chars);
+ − 2286
$ret = '';
+ − 2287
for ( $i = 0; $i < $length; $i++ )
+ − 2288
{
+ − 2289
$ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
+ − 2290
}
+ − 2291
return $ret;
+ − 2292
}
+ − 2293
+ − 2294
/**
+ − 2295
* Generates some Javascript that calls the AES encryption library.
+ − 2296
* @param string The name of the form
+ − 2297
* @param string The name of the password field
+ − 2298
* @param string The name of the field that switches encryption on or off
+ − 2299
* @param string The name of the field that contains the encryption key
+ − 2300
* @param string The name of the field that will contain the encrypted password
+ − 2301
* @param string The name of the field that handles MD5 challenge data
+ − 2302
* @return string
+ − 2303
*/
+ − 2304
+ − 2305
function aes_javascript($form_name, $pw_field, $use_crypt, $crypt_key, $crypt_data, $challenge)
+ − 2306
{
+ − 2307
$code = '
+ − 2308
<script type="text/javascript">
+ − 2309
disableJSONExts();
+ − 2310
str = \'\';
+ − 2311
for(i=0;i<keySizeInBits/4;i++) str+=\'0\';
+ − 2312
var key = hexToByteArray(str);
+ − 2313
var pt = hexToByteArray(str);
+ − 2314
var ct = rijndaelEncrypt(pt, key, \'ECB\');
+ − 2315
var ct = byteArrayToHex(ct);
+ − 2316
switch(keySizeInBits)
+ − 2317
{
+ − 2318
case 128:
+ − 2319
v = \'66e94bd4ef8a2c3b884cfa59ca342b2e\';
+ − 2320
break;
+ − 2321
case 192:
+ − 2322
v = \'aae06992acbf52a3e8f4a96ec9300bd7aae06992acbf52a3e8f4a96ec9300bd7\';
+ − 2323
break;
+ − 2324
case 256:
+ − 2325
v = \'dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087\';
+ − 2326
break;
+ − 2327
}
+ − 2328
var testpassed = ' . ( ( isset($_GET['use_crypt']) && $_GET['use_crypt']=='0') ? 'false; // CRYPTO-AUTH DISABLED ON USER REQUEST // ' : '' ) . '( ct == v && md5_vm_test() );
+ − 2329
var frm = document.forms.'.$form_name.';
+ − 2330
if(testpassed)
+ − 2331
{
+ − 2332
frm.'.$use_crypt.'.value = \'yes\';
+ − 2333
var cryptkey = frm.'.$crypt_key.'.value;
+ − 2334
frm.'.$crypt_key.'.value = hex_md5(cryptkey);
+ − 2335
cryptkey = hexToByteArray(cryptkey);
+ − 2336
if(!cryptkey || ( ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ) && cryptkey.length != keySizeInBits / 8 )
+ − 2337
{
+ − 2338
if ( frm._login ) frm._login.disabled = true;
+ − 2339
len = ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ? \'\\nLen: \'+cryptkey.length : \'\';
+ − 2340
alert(\'The key is messed up\\nType: \'+typeof(cryptkey)+len);
+ − 2341
}
+ − 2342
}
+ − 2343
if(frm.username) frm.username.focus();
+ − 2344
function runEncryption()
+ − 2345
{
+ − 2346
if(testpassed)
+ − 2347
{
+ − 2348
pass = frm.'.$pw_field.'.value;
+ − 2349
chal = frm.'.$challenge.'.value;
+ − 2350
challenge = hex_md5(pass + chal) + chal;
+ − 2351
frm.'.$challenge.'.value = challenge;
+ − 2352
pass = stringToByteArray(pass);
+ − 2353
cryptstring = rijndaelEncrypt(pass, cryptkey, \'ECB\');
+ − 2354
if(!cryptstring)
+ − 2355
{
+ − 2356
return false;
+ − 2357
}
+ − 2358
cryptstring = byteArrayToHex(cryptstring);
+ − 2359
frm.'.$crypt_data.'.value = cryptstring;
+ − 2360
frm.'.$pw_field.'.value = \'\';
+ − 2361
}
+ − 2362
return false;
+ − 2363
}
+ − 2364
</script>
+ − 2365
';
+ − 2366
return $code;
+ − 2367
}
+ − 2368
+ − 2369
}
+ − 2370
+ − 2371
/**
+ − 2372
* Class used to fetch permissions for a specific page. Used internally by SessionManager.
+ − 2373
* @package Enano
+ − 2374
* @subpackage Session manager
+ − 2375
* @license http://www.gnu.org/copyleft/gpl.html
+ − 2376
* @access private
+ − 2377
*/
+ − 2378
+ − 2379
class Session_ACLPageInfo {
+ − 2380
+ − 2381
/**
+ − 2382
* The page ID of this ACL info package
+ − 2383
* @var string
+ − 2384
*/
+ − 2385
+ − 2386
var $page_id;
+ − 2387
+ − 2388
/**
+ − 2389
* The namespace of the page being checked
+ − 2390
* @var string
+ − 2391
*/
+ − 2392
+ − 2393
var $namespace;
+ − 2394
+ − 2395
/**
+ − 2396
* Our list of permission types.
+ − 2397
* @access private
+ − 2398
* @var array
+ − 2399
*/
+ − 2400
+ − 2401
var $acl_types = Array();
+ − 2402
+ − 2403
/**
+ − 2404
* The list of descriptions for the permission types
+ − 2405
* @var array
+ − 2406
*/
+ − 2407
+ − 2408
var $acl_descs = Array();
+ − 2409
+ − 2410
/**
+ − 2411
* A list of dependencies for ACL types.
+ − 2412
* @var array
+ − 2413
*/
+ − 2414
+ − 2415
var $acl_deps = Array();
+ − 2416
+ − 2417
/**
+ − 2418
* Our tell-all list of permissions.
+ − 2419
* @access private - or, preferably, protected...too bad this has to be PHP4 compatible
+ − 2420
* @var array
+ − 2421
*/
+ − 2422
+ − 2423
var $perms = Array();
+ − 2424
+ − 2425
/**
+ − 2426
* Constructor.
+ − 2427
* @param string $page_id The ID of the page to check
+ − 2428
* @param string $namespace The namespace of the page to check.
+ − 2429
* @param array $acl_types List of ACL types
+ − 2430
* @param array $acl_descs List of human-readable descriptions for permissions (associative)
+ − 2431
* @param array $acl_deps List of dependencies for permissions. For example, viewing history/diffs depends on the ability to read the page.
+ − 2432
* @param array $base What to start with - this is an attempt to reduce the number of SQL queries.
+ − 2433
*/
+ − 2434
+ − 2435
function Session_ACLPageInfo($page_id, $namespace, $acl_types, $acl_descs, $acl_deps, $base)
+ − 2436
{
+ − 2437
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2438
+ − 2439
$this->perms = $session->acl_merge_complete($acl_types, $base);
+ − 2440
$this->acl_deps = $acl_deps;
+ − 2441
$this->acl_types = $acl_types;
+ − 2442
$this->acl_descs = $acl_descs;
+ − 2443
+ − 2444
// Build a query to grab ACL info
+ − 2445
$bs = 'SELECT rules FROM '.table_prefix.'acl WHERE ( ';
+ − 2446
$q = Array();
+ − 2447
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$session->user_id.' )';
+ − 2448
if(count($session->groups) > 0)
+ − 2449
{
+ − 2450
foreach($session->groups as $g_id => $g_name)
+ − 2451
{
+ − 2452
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 2453
}
+ − 2454
}
+ − 2455
// The reason we're using an ORDER BY statement here is because ACL_TYPE_GROUP is less than ACL_TYPE_USER, causing the user's individual
+ − 2456
// permissions to override group permissions.
+ − 2457
$bs .= implode(' OR ', $q) . ' ) AND ( page_id=\''.$db->escape($page_id).'\' AND namespace=\''.$db->escape($namespace).'\' )
+ − 2458
ORDER BY target_type ASC, page_id ASC, namespace ASC;';
+ − 2459
$q = $session->sql($bs);
+ − 2460
if ( $row = $db->fetchrow() )
+ − 2461
{
+ − 2462
do {
+ − 2463
$rules = $session->string_to_perm($row['rules']);
+ − 2464
$this->perms = $session->acl_merge($this->perms, $rules);
+ − 2465
} while ( $row = $db->fetchrow() );
+ − 2466
}
+ − 2467
+ − 2468
$this->page_id = $page_id;
+ − 2469
$this->namespace = $namespace;
+ − 2470
}
+ − 2471
+ − 2472
/**
+ − 2473
* Tells us whether permission $type is allowed or not based on the current rules.
+ − 2474
* @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
+ − 2475
* @param bool $no_deps If true, disables dependency checking
+ − 2476
* @return bool True if allowed, false if denied or if an error occured
+ − 2477
*/
+ − 2478
+ − 2479
function get_permissions($type, $no_deps = false)
+ − 2480
{
+ − 2481
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2482
if ( isset( $this->perms[$type] ) )
+ − 2483
{
+ − 2484
if ( $this->perms[$type] == AUTH_DENY )
+ − 2485
$ret = false;
+ − 2486
else if ( $this->perms[$type] == AUTH_WIKIMODE &&
+ − 2487
( isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id]) &&
+ − 2488
( $paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '1' ||
+ − 2489
( $paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '2'
+ − 2490
&& getConfig('wiki_mode') == '1'
+ − 2491
) ) ) )
+ − 2492
$ret = true;
+ − 2493
else if ( $this->perms[$type] == AUTH_WIKIMODE && (
+ − 2494
!isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id])
+ − 2495
|| (
+ − 2496
isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id]) && (
+ − 2497
$paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '0'
+ − 2498
|| (
+ − 2499
$paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '2' && getConfig('wiki_mode') != '1'
+ − 2500
) ) ) ) )
+ − 2501
$ret = false;
+ − 2502
else if ( $this->perms[$type] == AUTH_ALLOW )
+ − 2503
$ret = true;
+ − 2504
else if ( $this->perms[$type] == AUTH_DISALLOW )
+ − 2505
$ret = false;
+ − 2506
}
+ − 2507
else if(isset($this->acl_types[$type]))
+ − 2508
{
+ − 2509
if ( $this->acl_types[$type] == AUTH_DENY )
+ − 2510
$ret = false;
+ − 2511
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 2512
$ret = true;
+ − 2513
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 2514
$ret = false;
+ − 2515
else if ( $this->acl_types[$type] == AUTH_ALLOW )
+ − 2516
$ret = true;
+ − 2517
else if ( $this->acl_types[$type] == AUTH_DISALLOW )
+ − 2518
$ret = false;
+ − 2519
}
+ − 2520
else
+ − 2521
{
+ − 2522
// ACL type is undefined
+ − 2523
trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
+ − 2524
return false; // Be on the safe side and deny access
+ − 2525
}
+ − 2526
if ( !$no_deps )
+ − 2527
{
+ − 2528
if ( !$this->acl_check_deps($type) )
+ − 2529
return false;
+ − 2530
}
+ − 2531
return $ret;
+ − 2532
}
+ − 2533
+ − 2534
/**
+ − 2535
* Tell us if the dependencies for a given permission are met.
+ − 2536
* @param string The ACL permission ID
+ − 2537
* @return bool
+ − 2538
*/
+ − 2539
+ − 2540
function acl_check_deps($type)
+ − 2541
{
+ − 2542
if(!isset($this->acl_deps[$type])) // This will only happen if the permissions table is hacked or improperly accessed
+ − 2543
return true;
+ − 2544
if(sizeof($this->acl_deps[$type]) < 1)
+ − 2545
return true;
+ − 2546
$deps = $this->acl_deps[$type];
+ − 2547
while(true)
+ − 2548
{
+ − 2549
$full_resolved = true;
+ − 2550
$j = sizeof($deps);
+ − 2551
for ( $i = 0; $i < $j; $i++ )
+ − 2552
{
+ − 2553
$b = $deps;
+ − 2554
$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
+ − 2555
if( $b == $deps )
+ − 2556
{
+ − 2557
break 2;
+ − 2558
}
+ − 2559
$j = sizeof($deps);
+ − 2560
}
+ − 2561
}
+ − 2562
//die('<pre>'.print_r($deps, true).'</pre>');
+ − 2563
foreach($deps as $d)
+ − 2564
{
+ − 2565
if ( !$this->get_permissions($d) )
+ − 2566
{
+ − 2567
return false;
+ − 2568
}
+ − 2569
}
+ − 2570
return true;
+ − 2571
}
+ − 2572
+ − 2573
}
+ − 2574
+ − 2575
?>