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