1
+ − 1
<?php
+ − 2
+ − 3
/*
+ − 4
* Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
21
663fcf528726
Updated all version numbers back to Banshee; a few preliminary steps towards full UTF-8 support in page URLs
Dan
diff
changeset
+ − 5
* Version 1.0 (Banshee)
1
+ − 6
* Copyright (C) 2006-2007 Dan Fuhry
+ − 7
* sessions.php - everything related to security and user management
+ − 8
*
+ − 9
* This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
+ − 10
* as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+ − 11
*
+ − 12
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ − 13
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
+ − 14
*/
+ − 15
+ − 16
// Prepare a string for insertion into a MySQL database
+ − 17
function filter($str) { return $db->escape($str); }
+ − 18
+ − 19
/**
+ − 20
* Anything and everything related to security and user management. This includes AES encryption, which is illegal in some countries.
+ − 21
* Documenting the API was not easy - I hope you folks enjoy it.
+ − 22
* @package Enano
+ − 23
* @subpackage Session manager
+ − 24
* @category security, user management, logins, etc.
+ − 25
*/
+ − 26
+ − 27
class sessionManager {
+ − 28
+ − 29
# Variables
+ − 30
+ − 31
/**
+ − 32
* Whether we're logged in or not
+ − 33
* @var bool
+ − 34
*/
+ − 35
+ − 36
var $user_logged_in = false;
+ − 37
+ − 38
/**
+ − 39
* Our current low-privilege session key
+ − 40
* @var string
+ − 41
*/
+ − 42
+ − 43
var $sid;
+ − 44
+ − 45
/**
+ − 46
* Username of currently logged-in user, or IP address if not logged in
+ − 47
* @var string
+ − 48
*/
+ − 49
+ − 50
var $username;
+ − 51
+ − 52
/**
+ − 53
* User ID of currently logged-in user, or -1 if not logged in
+ − 54
* @var int
+ − 55
*/
+ − 56
+ − 57
var $user_id;
+ − 58
+ − 59
/**
+ − 60
* Real name of currently logged-in user, or blank if not logged in
+ − 61
* @var string
+ − 62
*/
+ − 63
+ − 64
var $real_name;
+ − 65
+ − 66
/**
+ − 67
* E-mail address of currently logged-in user, or blank if not logged in
+ − 68
* @var string
+ − 69
*/
+ − 70
+ − 71
var $email;
+ − 72
+ − 73
/**
+ − 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 ''.
30
+ − 1299
* @param bool $coppa Optional. If true, the account is not activated initially and an admin activation request is sent. The caller is responsible for sending the address info and notice.
1
+ − 1300
*/
+ − 1301
30
+ − 1302
function create_user($username, $password, $email, $real_name = '', $coppa = false)
13
fdd6b9dd42c3
Installer actually works now on dev servers; minor language change in template.php; code cleanliness fix in sessions.php
Dan
diff
changeset
+ − 1303
{
1
+ − 1304
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1305
+ − 1306
// Initialize AES
+ − 1307
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1308
+ − 1309
if(!preg_match('#^'.$this->valid_username.'$#', $username)) return 'The username you chose contains invalid characters.';
+ − 1310
$username = $this->prepare_text($username);
+ − 1311
$email = $this->prepare_text($email);
+ − 1312
$real_name = $this->prepare_text($real_name);
+ − 1313
$password = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1314
+ − 1315
$nameclause = ( $real_name != '' ) ? ' OR real_name=\''.$real_name.'\'' : '';
+ − 1316
$q = $this->sql('SELECT * FROM '.table_prefix.'users WHERE lcase(username)=\''.strtolower($username).'\' OR email=\''.$email.'\''.$nameclause.';');
+ − 1317
if($db->numrows() > 0) {
+ − 1318
$r = 'The ';
+ − 1319
$i=0;
+ − 1320
$row = $db->fetchrow();
+ − 1321
// Wow! An error checker that actually speaks English with the properest grammar! :-P
+ − 1322
if($row['username'] == $username) { $r .= 'username'; $i++; }
+ − 1323
if($row['email'] == $email) { if($i) $r.=', '; $r .= 'e-mail address'; $i++; }
+ − 1324
if($row['real_name'] == $real_name && $real_name != '') { if($i) $r.=', and '; $r .= 'real name'; $i++; }
+ − 1325
$r .= ' that you entered ';
+ − 1326
$r .= ( $i == 1 ) ? 'is' : 'are';
+ − 1327
$r .= ' already in use by another user.';
+ − 1328
return $r;
+ − 1329
}
+ − 1330
+ − 1331
// Require the account to be activated?
+ − 1332
switch(getConfig('account_activation'))
+ − 1333
{
+ − 1334
case 'none':
+ − 1335
default:
+ − 1336
$active = '1';
+ − 1337
break;
+ − 1338
case 'user':
+ − 1339
$active = '0';
+ − 1340
break;
+ − 1341
case 'admin':
+ − 1342
$active = '0';
+ − 1343
break;
+ − 1344
}
30
+ − 1345
if ( $coppa )
+ − 1346
$active = '0';
+ − 1347
+ − 1348
$coppa_col = ( $coppa ) ? '1' : '0';
1
+ − 1349
+ − 1350
// Generate a totally random activation key
+ − 1351
$actkey = sha1 ( microtime() . mt_rand() );
+ − 1352
30
+ − 1353
// We good, create the user
+ − 1354
$this->sql('INSERT INTO '.table_prefix.'users ( username, password, email, real_name, theme, style, reg_time, account_active, activation_key, user_level, user_coppa ) VALUES ( \''.$username.'\', \''.$password.'\', \''.$email.'\', \''.$real_name.'\', \''.$template->default_theme.'\', \''.$template->default_style.'\', '.time().', '.$active.', \''.$actkey.'\', '.USER_LEVEL_CHPREF.', ' . $coppa_col . ' );');
1
+ − 1355
+ − 1356
// Require the account to be activated?
30
+ − 1357
if ( $coppa )
+ − 1358
{
+ − 1359
$this->admin_activation_request($username);
+ − 1360
$this->send_coppa_mail($username,$email);
+ − 1361
}
+ − 1362
else
1
+ − 1363
{
30
+ − 1364
switch(getConfig('account_activation'))
+ − 1365
{
+ − 1366
case 'none':
+ − 1367
default:
+ − 1368
break;
+ − 1369
case 'user':
+ − 1370
$a = $this->send_activation_mail($username);
+ − 1371
if(!$a)
+ − 1372
{
+ − 1373
$this->admin_activation_request($username);
+ − 1374
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;
+ − 1375
}
+ − 1376
break;
+ − 1377
case 'admin':
1
+ − 1378
$this->admin_activation_request($username);
30
+ − 1379
break;
+ − 1380
}
1
+ − 1381
}
+ − 1382
+ − 1383
// Leave some data behind for the hook
+ − 1384
$code = $plugins->setHook('user_registered'); // , Array('username'=>$username));
+ − 1385
foreach ( $code as $cmd )
+ − 1386
{
+ − 1387
eval($cmd);
+ − 1388
}
+ − 1389
+ − 1390
// $this->register_session($username, $password);
+ − 1391
return 'success';
+ − 1392
}
+ − 1393
+ − 1394
/**
+ − 1395
* Attempts to send an e-mail to the specified user with activation instructions.
+ − 1396
* @param string $u The usernamd of the user requesting activation
+ − 1397
* @return bool true on success, false on failure
+ − 1398
*/
+ − 1399
+ − 1400
function send_activation_mail($u, $actkey = false)
+ − 1401
{
+ − 1402
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1403
$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;');
+ − 1404
$un = $db->fetchrow();
+ − 1405
$admin_user = $un['username'];
+ − 1406
$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
+ − 1407
$r = $db->fetchrow();
+ − 1408
if ( empty($r['email']) )
+ − 1409
$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
+ − 1410
$message = 'Dear '.$u.',
+ − 1411
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:
+ − 1412
+ − 1413
';
+ − 1414
if(isset($_SERVER['HTTPS'])) $prot = 'https';
+ − 1415
else $prot = 'http';
+ − 1416
if($_SERVER['SERVER_PORT'] == '80') $p = '';
+ − 1417
else $p = ':'.$_SERVER['SERVER_PORT'];
+ − 1418
$sidbak = false;
+ − 1419
if($this->sid_super)
+ − 1420
$sidbak = $this->sid_super;
+ − 1421
$this->sid_super = false;
+ − 1422
$aklink = makeUrlNS('Special', 'ActivateAccount/'.str_replace(' ', '_', $u).'/'. ( ( is_string($actkey) ) ? $actkey : $r['activation_key'] ) );
+ − 1423
if($sidbak)
+ − 1424
$this->sid_super = $sidbak;
+ − 1425
unset($sidbak);
+ − 1426
$message .= "$prot://".$_SERVER['HTTP_HOST'].$p.$aklink;
+ − 1427
$message .= "\n\nSincerely yours, \n$admin_user and the ".$_SERVER['HTTP_HOST']." administration team";
+ − 1428
error_reporting(E_ALL);
+ − 1429
dc_dump($r, 'session: about to send activation e-mail to '.$r['email']);
+ − 1430
if(getConfig('smtp_enabled') == '1')
+ − 1431
{
+ − 1432
$result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1433
if($result == 'success') $result = true;
+ − 1434
else { echo $result; $result = false; }
+ − 1435
} else {
+ − 1436
$result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1437
}
+ − 1438
return $result;
+ − 1439
}
+ − 1440
+ − 1441
/**
30
+ − 1442
* Attempts to send an e-mail to the specified user's e-mail address on file intended for the parents
+ − 1443
* @param string $u The usernamd of the user requesting activation
+ − 1444
* @return bool true on success, false on failure
+ − 1445
*/
+ − 1446
+ − 1447
function send_coppa_mail($u, $actkey = false)
+ − 1448
{
+ − 1449
+ − 1450
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1451
+ − 1452
$q = $this->sql('SELECT username,email FROM '.table_prefix.'users WHERE user_id=2 OR user_level=' . USER_LEVEL_ADMIN . ' ORDER BY user_id ASC;');
+ − 1453
$un = $db->fetchrow();
+ − 1454
$admin_user = $un['username'];
+ − 1455
+ − 1456
$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
+ − 1457
$r = $db->fetchrow();
+ − 1458
if ( empty($r['email']) )
+ − 1459
$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
+ − 1460
+ − 1461
if(isset($_SERVER['HTTPS'])) $prot = 'https';
+ − 1462
else $prot = 'http';
+ − 1463
if($_SERVER['SERVER_PORT'] == '80') $p = '';
+ − 1464
else $p = ':'.$_SERVER['SERVER_PORT'];
+ − 1465
$sidbak = false;
+ − 1466
if($this->sid_super)
+ − 1467
$sidbak = $this->sid_super;
+ − 1468
$this->sid_super = false;
+ − 1469
if($sidbak)
+ − 1470
$this->sid_super = $sidbak;
+ − 1471
unset($sidbak);
+ − 1472
$link = "$prot://".$_SERVER['HTTP_HOST'].scriptPath;
+ − 1473
+ − 1474
$message = 'Dear parent or legal guardian,
+ − 1475
A child under the username ' . $u . ' recently registered on our website. The child provided your e-mail address as the one of his or her authorized parent or legal guardian, and to comply with the United States Childrens\' Online Privacy Protection act, we ask that all parents of children ages 13 or under please mail us a written form authorizing their child\'s use of our website.
+ − 1476
+ − 1477
If you wish for your child to be allowed access to our website, please print and fill out the form below, and mail it to this address:
+ − 1478
+ − 1479
' . getConfig('coppa_address') . '
+ − 1480
+ − 1481
If you do NOT wish for your child to be allowed access to our site, you do not need to do anything - your child will not be able to access our site as a registered user unless you authorize their account activation.
+ − 1482
+ − 1483
Authorization form:
+ − 1484
-------------------------------- Cut here --------------------------------
+ − 1485
+ − 1486
I, _______________________________________, the legal parent or guardian of the child registered on the website "' . getConfig('site_name') . '" as ' . $u . ', hereby give my authorization for the child\'s e-mail address, instant messaging information, location, and real name, to be collected and stored in a database owned and maintained by ' . getConfig('site_name') . ' at the child\'s option, and for the administrators of this website to use this information according to the privacy policy displayed on their website <' . $link . '>.
+ − 1487
+ − 1488
Child\'s name: _____________________________________
+ − 1489
+ − 1490
Child\'s e-mail address: _____________________________________
+ − 1491
(optional - if you don\'t provide this, we\'ll just send site-related e-mails to your e-mail address)
+ − 1492
+ − 1493
Signature of parent or guardian:
+ − 1494
+ − 1495
____________________________________________________
+ − 1496
+ − 1497
Date (YYYY-MM-DD): ______ / _____ / _____
+ − 1498
+ − 1499
-------------------------------- Cut here --------------------------------';
+ − 1500
$message .= "\n\nSincerely yours, \n$admin_user and the ".$_SERVER['HTTP_HOST']." administration team";
+ − 1501
+ − 1502
error_reporting(E_ALL);
+ − 1503
+ − 1504
dc_dump($r, 'session: about to send COPPA e-mail to '.$r['email']);
+ − 1505
if(getConfig('smtp_enabled') == '1')
+ − 1506
{
+ − 1507
$result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1508
if($result == 'success')
+ − 1509
{
+ − 1510
$result = true;
+ − 1511
}
+ − 1512
else
+ − 1513
{
+ − 1514
echo $result;
+ − 1515
$result = false;
+ − 1516
}
+ − 1517
}
+ − 1518
else
+ − 1519
{
+ − 1520
$result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1521
}
+ − 1522
return $result;
+ − 1523
}
+ − 1524
+ − 1525
/**
1
+ − 1526
* Sends an e-mail to a user so they can reset their password.
+ − 1527
* @param int $user The user ID, or username if it's a string
+ − 1528
* @return bool true on success, false on failure
+ − 1529
*/
+ − 1530
+ − 1531
function mail_password_reset($user)
+ − 1532
{
+ − 1533
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1534
if(is_int($user))
+ − 1535
{
+ − 1536
$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
+ − 1537
}
+ − 1538
elseif(is_string($user))
+ − 1539
{
+ − 1540
$q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($user).'\';');
+ − 1541
}
+ − 1542
else
+ − 1543
{
+ − 1544
return false;
+ − 1545
}
+ − 1546
+ − 1547
$row = $db->fetchrow();
+ − 1548
$temp_pass = $this->random_pass();
+ − 1549
+ − 1550
$this->register_temp_password($row['user_id'], $temp_pass);
+ − 1551
+ − 1552
$site_name = getConfig('site_name');
+ − 1553
+ − 1554
$message = "Dear {$row['username']},
+ − 1555
+ − 1556
Someone (hopefully you) on the {$site_name} website requested that a new password be created.
+ − 1557
+ − 1558
The request was sent from the IP address {$_SERVER['REMOTE_ADDR']}.
+ − 1559
+ − 1560
If you did not request the new password, then you do not need to do anything; the password will be invalidated after 24 hours.
+ − 1561
+ − 1562
If you did request this password, then please log in using the password shown below:
+ − 1563
+ − 1564
Password: {$temp_pass}
+ − 1565
+ − 1566
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.
+ − 1567
+ − 1568
Sincerely yours,
+ − 1569
The {$site_name} administration team
+ − 1570
";
+ − 1571
+ − 1572
if(getConfig('smtp_enabled') == '1')
+ − 1573
{
+ − 1574
$result = smtp_send_email($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
+ − 1575
if($result == 'success')
+ − 1576
{
+ − 1577
$result = true;
+ − 1578
}
+ − 1579
else
+ − 1580
{
+ − 1581
echo '<p>'.$result.'</p>';
+ − 1582
$result = false;
+ − 1583
}
+ − 1584
} else {
+ − 1585
$result = mail($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
+ − 1586
}
+ − 1587
return $result;
+ − 1588
}
+ − 1589
+ − 1590
/**
+ − 1591
* Sets the temporary password for the specified user to whatever is specified.
+ − 1592
* @param int $user_id
+ − 1593
* @param string $password
+ − 1594
* @return bool
+ − 1595
*/
+ − 1596
+ − 1597
function register_temp_password($user_id, $password)
+ − 1598
{
+ − 1599
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1600
$temp_pass = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1601
$this->sql('UPDATE '.table_prefix.'users SET temp_password=\'' . $temp_pass . '\',temp_password_time='.time().' WHERE user_id='.intval($user_id).';');
+ − 1602
}
+ − 1603
+ − 1604
/**
+ − 1605
* Sends a request to the admin panel to have the username $u activated.
+ − 1606
* @param string $u The username of the user requesting activation
+ − 1607
*/
+ − 1608
+ − 1609
function admin_activation_request($u)
+ − 1610
{
+ − 1611
global $db;
+ − 1612
$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).'\');');
+ − 1613
}
+ − 1614
+ − 1615
/**
+ − 1616
* Activates a user account. If the action fails, a report is sent to the admin.
+ − 1617
* @param string $user The username of the user requesting activation
+ − 1618
* @param string $key The activation key
+ − 1619
*/
+ − 1620
+ − 1621
function activate_account($user, $key)
+ − 1622
{
+ − 1623
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1624
$this->sql('UPDATE '.table_prefix.'users SET account_active=1 WHERE username=\''.$db->escape($user).'\' AND activation_key=\''.$db->escape($key).'\';');
+ − 1625
$r = mysql_affected_rows();
+ − 1626
if ( $r > 0 )
+ − 1627
{
+ − 1628
$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'].'\')');
+ − 1629
}
+ − 1630
else
+ − 1631
{
+ − 1632
$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'].'\')');
+ − 1633
}
+ − 1634
return $r;
+ − 1635
}
+ − 1636
+ − 1637
/**
+ − 1638
* For a given user level identifier (USER_LEVEL_*), returns a string describing that user level.
+ − 1639
* @param int User level
+ − 1640
* @return string
+ − 1641
*/
+ − 1642
+ − 1643
function userlevel_to_string($user_level)
+ − 1644
{
+ − 1645
switch ( $user_level )
+ − 1646
{
+ − 1647
case USER_LEVEL_GUEST:
+ − 1648
return 'Low - guest privileges';
+ − 1649
case USER_LEVEL_MEMBER:
+ − 1650
return 'Standard - normal member level';
+ − 1651
case USER_LEVEL_CHPREF:
+ − 1652
return 'Medium - user can change his/her own e-mail address and password';
+ − 1653
case USER_LEVEL_MOD:
+ − 1654
return 'High - moderator privileges';
+ − 1655
case USER_LEVEL_ADMIN:
+ − 1656
return 'Highest - administrative privileges';
+ − 1657
default:
+ − 1658
return "Unknown ($user_level)";
+ − 1659
}
+ − 1660
}
+ − 1661
+ − 1662
/**
+ − 1663
* 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.
+ − 1664
* @param int $user_id The user ID of the user to update - this cannot be changed
+ − 1665
* @param string $username The new username
+ − 1666
* @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
+ − 1667
* @param string $password The new password
+ − 1668
* @param string $email The new e-mail address
+ − 1669
* @param string $realname The new real name
+ − 1670
* @param string $signature The updated forum/comment signature
+ − 1671
* @param int $user_level The updated user level
+ − 1672
* @return string 'success' if successful, or array of error strings on failure
+ − 1673
*/
+ − 1674
+ − 1675
function update_user($user_id, $username = false, $old_pass = false, $password = false, $email = false, $realname = false, $signature = false, $user_level = false)
+ − 1676
{
+ − 1677
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1678
+ − 1679
// Create some arrays
+ − 1680
+ − 1681
$errors = Array(); // Used to hold error strings
+ − 1682
$strs = Array(); // Sub-query statements
+ − 1683
+ − 1684
// Scan the user ID for problems
+ − 1685
if(intval($user_id) < 1) $errors[] = 'SQL injection attempt';
+ − 1686
+ − 1687
// Instanciate the AES encryption class
+ − 1688
$aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+ − 1689
+ − 1690
// If all of our input vars are false, then we've effectively done our job so get out of here
+ − 1691
if($username === false && $password === false && $email === false && $realname === false && $signature === false && $user_level === false)
+ − 1692
{
+ − 1693
// echo 'debug: $session->update_user(): success (no changes requested)';
+ − 1694
return 'success';
+ − 1695
}
+ − 1696
+ − 1697
// Initialize our authentication check
+ − 1698
$authed = false;
+ − 1699
+ − 1700
// Verify the inputted password
+ − 1701
if(is_string($old_pass))
+ − 1702
{
+ − 1703
$q = $this->sql('SELECT password FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1704
if($db->numrows() < 1)
+ − 1705
{
+ − 1706
$errors[] = 'The password data could not be selected for verification.';
+ − 1707
}
+ − 1708
else
+ − 1709
{
+ − 1710
$row = $db->fetchrow();
+ − 1711
$real = $aes->decrypt($row['password'], $this->private_key, ENC_HEX);
+ − 1712
if($real == $old_pass)
+ − 1713
$authed = true;
+ − 1714
}
+ − 1715
}
+ − 1716
+ − 1717
elseif(is_array($old_pass))
+ − 1718
{
+ − 1719
$old_pass = $aes->decrypt($old_pass[0], $old_pass[1]);
+ − 1720
$q = $this->sql('SELECT password FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1721
if($db->numrows() < 1)
+ − 1722
{
+ − 1723
$errors[] = 'The password data could not be selected for verification.';
+ − 1724
}
+ − 1725
else
+ − 1726
{
+ − 1727
$row = $db->fetchrow();
+ − 1728
$real = $aes->decrypt($row['password'], $this->private_key, ENC_HEX);
+ − 1729
if($real == $old_pass)
+ − 1730
$authed = true;
+ − 1731
}
+ − 1732
}
+ − 1733
+ − 1734
// Initialize our query
+ − 1735
$q = 'UPDATE '.table_prefix.'users SET ';
+ − 1736
+ − 1737
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
+ − 1738
{
+ − 1739
// Username
+ − 1740
if(is_string($username))
+ − 1741
{
+ − 1742
// Check the username for problems
+ − 1743
if(!preg_match('#^'.$this->valid_username.'$#', $username))
+ − 1744
$errors[] = 'The username you entered contains invalid characters.';
+ − 1745
$strs[] = 'username=\''.$db->escape($username).'\'';
+ − 1746
}
+ − 1747
// Password
+ − 1748
if(is_string($password) && strlen($password) >= 6)
+ − 1749
{
+ − 1750
// Password needs to be encrypted before being stashed
+ − 1751
$encpass = $aes->encrypt($password, $this->private_key, ENC_HEX);
+ − 1752
if(!$encpass)
+ − 1753
$errors[] = 'The password could not be encrypted due to an internal error.';
+ − 1754
$strs[] = 'password=\''.$encpass.'\'';
+ − 1755
}
+ − 1756
// E-mail addy
+ − 1757
if(is_string($email))
+ − 1758
{
+ − 1759
// I didn't write this regex.
+ − 1760
if(!preg_match('/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/', $email))
+ − 1761
$errors[] = 'The e-mail address you entered is invalid.';
+ − 1762
$strs[] = 'email=\''.$db->escape($email).'\'';
+ − 1763
}
+ − 1764
}
+ − 1765
// Real name
+ − 1766
if(is_string($realname))
+ − 1767
{
+ − 1768
$strs[] = 'real_name=\''.$db->escape($realname).'\'';
+ − 1769
}
+ − 1770
// Forum/comment signature
+ − 1771
if(is_string($signature))
+ − 1772
{
+ − 1773
$strs[] = 'signature=\''.$db->escape($signature).'\'';
+ − 1774
}
+ − 1775
// User level
+ − 1776
if(is_int($user_level))
+ − 1777
{
+ − 1778
$strs[] = 'user_level='.$user_level;
+ − 1779
}
+ − 1780
+ − 1781
// Add our generated query to the query string
+ − 1782
$q .= implode(',', $strs);
+ − 1783
+ − 1784
// One last error check
+ − 1785
if(sizeof($strs) < 1) $errors[] = 'An internal error occured building the SQL query, this is a bug';
+ − 1786
if(sizeof($errors) > 0) return $errors;
+ − 1787
+ − 1788
// Free our temp arrays
+ − 1789
unset($strs, $errors);
+ − 1790
+ − 1791
// Finalize the query and run it
+ − 1792
$q .= ' WHERE user_id='.$user_id.';';
+ − 1793
$this->sql($q);
+ − 1794
+ − 1795
// We also need to trigger re-activation.
+ − 1796
if ( is_string($email) )
+ − 1797
{
+ − 1798
switch(getConfig('account_activation'))
+ − 1799
{
+ − 1800
case 'user':
+ − 1801
case 'admin':
+ − 1802
+ − 1803
if ( $session->user_level >= USER_LEVEL_MOD && getConfig('account_activation') == 'admin' )
+ − 1804
// Don't require re-activation by admins for admins
+ − 1805
break;
+ − 1806
+ − 1807
// retrieve username
+ − 1808
if ( !$username )
+ − 1809
{
+ − 1810
$q = $this->sql('SELECT username FROM '.table_prefix.'users WHERE user_id='.$user_id.';');
+ − 1811
if($db->numrows() < 1)
+ − 1812
{
+ − 1813
$errors[] = 'The username could not be selected.';
+ − 1814
}
+ − 1815
else
+ − 1816
{
+ − 1817
$row = $db->fetchrow();
+ − 1818
$username = $row['username'];
+ − 1819
}
+ − 1820
}
+ − 1821
if ( !$username )
+ − 1822
return $errors;
+ − 1823
+ − 1824
// Generate a totally random activation key
+ − 1825
$actkey = sha1 ( microtime() . mt_rand() );
+ − 1826
$a = $this->send_activation_mail($username, $actkey);
+ − 1827
if(!$a)
+ − 1828
{
+ − 1829
$this->admin_activation_request($username);
+ − 1830
}
+ − 1831
// Deactivate the account until e-mail is confirmed
+ − 1832
$q = $db->sql_query('UPDATE '.table_prefix.'users SET account_active=0,activation_key=\'' . $actkey . '\' WHERE user_id=' . $user_id . ';');
+ − 1833
break;
+ − 1834
}
+ − 1835
}
+ − 1836
+ − 1837
// Yay! We're done
+ − 1838
return 'success';
+ − 1839
}
+ − 1840
+ − 1841
#
+ − 1842
# Access Control Lists
+ − 1843
#
+ − 1844
+ − 1845
/**
+ − 1846
* Creates a new permission field in memory. If the permissions are set in the database, they are used. Otherwise, $default_perm is used.
+ − 1847
* @param string $acl_type An identifier for this field
+ − 1848
* @param int $default_perm Whether permission should be granted or not if it's not specified in the ACLs.
+ − 1849
* @param string $desc A human readable name for the permission type
+ − 1850
* @param array $deps The list of dependencies - this should be an array of ACL types
+ − 1851
* @param string $scope Which namespaces this field should apply to. This should be either a pipe-delimited list of namespace IDs or just "All".
+ − 1852
*/
+ − 1853
+ − 1854
function register_acl_type($acl_type, $default_perm = AUTH_DISALLOW, $desc = false, $deps = Array(), $scope = 'All')
+ − 1855
{
+ − 1856
if(isset($this->acl_types[$acl_type]))
+ − 1857
return false;
+ − 1858
else
+ − 1859
{
+ − 1860
if(!$desc)
+ − 1861
{
+ − 1862
$desc = capitalize_first_letter(str_replace('_', ' ', $acl_type));
+ − 1863
}
+ − 1864
$this->acl_types[$acl_type] = $default_perm;
+ − 1865
$this->acl_descs[$acl_type] = $desc;
+ − 1866
$this->acl_deps[$acl_type] = $deps;
+ − 1867
$this->acl_scope[$acl_type] = explode('|', $scope);
+ − 1868
}
+ − 1869
return true;
+ − 1870
}
+ − 1871
+ − 1872
/**
+ − 1873
* Tells us whether permission $type is allowed or not based on the current rules.
+ − 1874
* @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
+ − 1875
* @param bool $no_deps If true, disables dependency checking
+ − 1876
* @return bool True if allowed, false if denied or if an error occured
+ − 1877
*/
+ − 1878
+ − 1879
function get_permissions($type, $no_deps = false)
+ − 1880
{
+ − 1881
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1882
if ( isset( $this->perms[$type] ) )
+ − 1883
{
+ − 1884
if ( $this->perms[$type] == AUTH_DENY )
+ − 1885
$ret = false;
+ − 1886
else if ( $this->perms[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 1887
$ret = true;
+ − 1888
else if ( $this->perms[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 1889
$ret = false;
+ − 1890
else if ( $this->perms[$type] == AUTH_ALLOW )
+ − 1891
$ret = true;
+ − 1892
else if ( $this->perms[$type] == AUTH_DISALLOW )
+ − 1893
$ret = false;
+ − 1894
}
+ − 1895
else if(isset($this->acl_types[$type]))
+ − 1896
{
+ − 1897
if ( $this->acl_types[$type] == AUTH_DENY )
+ − 1898
$ret = false;
+ − 1899
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 1900
$ret = true;
+ − 1901
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 1902
$ret = false;
+ − 1903
else if ( $this->acl_types[$type] == AUTH_ALLOW )
+ − 1904
$ret = true;
+ − 1905
else if ( $this->acl_types[$type] == AUTH_DISALLOW )
+ − 1906
$ret = false;
+ − 1907
}
+ − 1908
else
+ − 1909
{
+ − 1910
// ACL type is undefined
+ − 1911
trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
+ − 1912
return false; // Be on the safe side and deny access
+ − 1913
}
+ − 1914
if ( !$no_deps )
+ − 1915
{
+ − 1916
if ( !$this->acl_check_deps($type) )
+ − 1917
return false;
+ − 1918
}
+ − 1919
return $ret;
+ − 1920
}
+ − 1921
+ − 1922
/**
+ − 1923
* Fetch the permissions that apply to the current user for the page specified. The object you get will have the get_permissions method
+ − 1924
* and several other abilities.
+ − 1925
* @param string $page_id
+ − 1926
* @param string $namespace
+ − 1927
* @return object
+ − 1928
*/
+ − 1929
+ − 1930
function fetch_page_acl($page_id, $namespace)
+ − 1931
{
+ − 1932
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1933
+ − 1934
if ( count ( $this->acl_base_cache ) < 1 )
+ − 1935
{
+ − 1936
// Permissions table not yet initialized
+ − 1937
return false;
+ − 1938
}
+ − 1939
+ − 1940
//if ( !isset( $paths->pages[$paths->nslist[$namespace] . $page_id] ) )
+ − 1941
//{
+ − 1942
// // Page does not exist
+ − 1943
// return false;
+ − 1944
//}
+ − 1945
+ − 1946
$object = new Session_ACLPageInfo( $page_id, $namespace, $this->acl_types, $this->acl_descs, $this->acl_deps, $this->acl_base_cache );
+ − 1947
+ − 1948
return $object;
+ − 1949
+ − 1950
}
+ − 1951
+ − 1952
/**
+ − 1953
* Read all of our permissions from the database and process/apply them. This should be called after the page is determined.
+ − 1954
* @access private
+ − 1955
*/
+ − 1956
+ − 1957
function init_permissions()
+ − 1958
{
+ − 1959
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 1960
// Initialize the permissions list with some defaults
+ − 1961
$this->perms = $this->acl_types;
+ − 1962
$this->acl_defaults_used = $this->perms;
+ − 1963
+ − 1964
// Fetch sitewide defaults from the permissions table
+ − 1965
$bs = 'SELECT rules FROM '.table_prefix.'acl WHERE page_id IS NULL AND namespace IS NULL AND ( ';
+ − 1966
+ − 1967
$q = Array();
+ − 1968
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
+ − 1969
if(count($this->groups) > 0)
+ − 1970
{
+ − 1971
foreach($this->groups as $g_id => $g_name)
+ − 1972
{
+ − 1973
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 1974
}
+ − 1975
}
+ − 1976
$bs .= implode(' OR ', $q) . ' ) ORDER BY target_type ASC, target_id ASC;';
+ − 1977
$q = $this->sql($bs);
+ − 1978
if ( $row = $db->fetchrow() )
+ − 1979
{
+ − 1980
do {
+ − 1981
$rules = $this->string_to_perm($row['rules']);
+ − 1982
$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
+ − 1983
$this->acl_merge_with_current($rules, $is_everyone);
+ − 1984
} while ( $row = $db->fetchrow() );
+ − 1985
}
+ − 1986
+ − 1987
// Eliminate types that don't apply to this namespace
+ − 1988
foreach ( $this->perms AS $i => $perm )
+ − 1989
{
+ − 1990
if ( !in_array ( $paths->namespace, $this->acl_scope[$i] ) && !in_array('All', $this->acl_scope[$i]) )
+ − 1991
{
+ − 1992
unset($this->perms[$i]);
+ − 1993
}
+ − 1994
}
+ − 1995
+ − 1996
// Cache the sitewide permissions for later use
+ − 1997
$this->acl_base_cache = $this->perms;
+ − 1998
+ − 1999
// Build a query to grab ACL info
+ − 2000
$bs = 'SELECT rules,target_type,target_id FROM '.table_prefix.'acl WHERE ( ';
+ − 2001
$q = Array();
+ − 2002
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
+ − 2003
if(count($this->groups) > 0)
+ − 2004
{
+ − 2005
foreach($this->groups as $g_id => $g_name)
+ − 2006
{
+ − 2007
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 2008
}
+ − 2009
}
+ − 2010
// 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
+ − 2011
// permissions to override group permissions.
+ − 2012
$bs .= implode(' OR ', $q) . ' ) AND ( page_id=\''.$db->escape($paths->cpage['urlname_nons']).'\' AND namespace=\''.$db->escape($paths->namespace).'\' )
+ − 2013
ORDER BY target_type ASC, page_id ASC, namespace ASC;';
+ − 2014
$q = $this->sql($bs);
+ − 2015
if ( $row = $db->fetchrow() )
+ − 2016
{
+ − 2017
do {
+ − 2018
$rules = $this->string_to_perm($row['rules']);
+ − 2019
$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
+ − 2020
$this->acl_merge_with_current($rules, $is_everyone);
+ − 2021
} while ( $row = $db->fetchrow() );
+ − 2022
}
+ − 2023
+ − 2024
}
+ − 2025
+ − 2026
/**
+ − 2027
* Extends the scope of a permission type.
+ − 2028
* @param string The name of the permission type
+ − 2029
* @param string The namespace(s) that should be covered. This can be either one namespace ID or a pipe-delimited list.
+ − 2030
* @param object Optional - the current $paths object, in case we're doing this from the acl_rule_init hook
+ − 2031
*/
+ − 2032
+ − 2033
function acl_extend_scope($perm_type, $namespaces, &$p_in)
+ − 2034
{
+ − 2035
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2036
$p_obj = ( is_object($p_in) ) ? $p_in : $paths;
+ − 2037
$nslist = explode('|', $namespaces);
+ − 2038
foreach ( $nslist as $i => $ns )
+ − 2039
{
+ − 2040
if ( !isset($p_obj->nslist[$ns]) )
+ − 2041
{
+ − 2042
unset($nslist[$i]);
+ − 2043
}
+ − 2044
else
+ − 2045
{
+ − 2046
$this->acl_scope[$perm_type][] = $ns;
+ − 2047
if ( isset($this->acl_types[$perm_type]) && !isset($this->perms[$perm_type]) )
+ − 2048
{
+ − 2049
$this->perms[$perm_type] = $this->acl_types[$perm_type];
+ − 2050
}
+ − 2051
}
+ − 2052
}
+ − 2053
}
+ − 2054
+ − 2055
/**
+ − 2056
* Converts a permissions field into a string for database insertion. Similar in spirit to serialize().
+ − 2057
* @param array $perms An associative array with only integers as values
+ − 2058
* @return string
+ − 2059
*/
+ − 2060
+ − 2061
function perm_to_string($perms)
+ − 2062
{
+ − 2063
$s = '';
+ − 2064
foreach($perms as $perm => $ac)
+ − 2065
{
+ − 2066
$s .= "$perm=$ac;";
+ − 2067
}
+ − 2068
return $s;
+ − 2069
}
+ − 2070
+ − 2071
/**
+ − 2072
* Converts a permissions string back to an array.
+ − 2073
* @param string $perms The result from sessionManager::perm_to_string()
+ − 2074
* @return array
+ − 2075
*/
+ − 2076
+ − 2077
function string_to_perm($perms)
+ − 2078
{
+ − 2079
$ret = Array();
+ − 2080
preg_match_all('#([a-z0-9_-]+)=([0-9]+);#i', $perms, $matches);
+ − 2081
foreach($matches[1] as $i => $t)
+ − 2082
{
+ − 2083
$ret[$t] = intval($matches[2][$i]);
+ − 2084
}
+ − 2085
return $ret;
+ − 2086
}
+ − 2087
+ − 2088
/**
+ − 2089
* Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence over the first, but AUTH_DENY always prevails.
+ − 2090
* @param array $perm1 The first set of permissions
+ − 2091
* @param array $perm2 The second set of permissions
+ − 2092
* @return array
+ − 2093
*/
+ − 2094
+ − 2095
function acl_merge($perm1, $perm2)
+ − 2096
{
+ − 2097
$ret = $perm1;
+ − 2098
foreach ( $perm2 as $type => $level )
+ − 2099
{
+ − 2100
if ( isset( $ret[$type] ) )
+ − 2101
{
+ − 2102
if ( $ret[$type] != AUTH_DENY )
+ − 2103
$ret[$type] = $level;
+ − 2104
}
+ − 2105
// else
+ − 2106
// {
+ − 2107
// $ret[$type] = $level;
+ − 2108
// }
+ − 2109
}
+ − 2110
return $ret;
+ − 2111
}
+ − 2112
+ − 2113
/**
+ − 2114
* Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
+ − 2115
* @param array The array to merge into the master ACL list
+ − 2116
* @param bool If true, $perm is treated as the "new default"
+ − 2117
* @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
+ − 2118
*/
+ − 2119
+ − 2120
function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
+ − 2121
{
+ − 2122
foreach ( $this->perms as $i => $p )
+ − 2123
{
+ − 2124
if ( isset($perm[$i]) )
+ − 2125
{
+ − 2126
if ( $is_everyone && !$this->acl_defaults_used[$i] )
+ − 2127
continue;
+ − 2128
// Decide precedence
+ − 2129
if ( isset($this->acl_defaults_used[$i]) )
+ − 2130
{
+ − 2131
//echo "$i: default in use, overriding to: {$perm[$i]}<br />";
+ − 2132
// Defaults are in use, override
+ − 2133
$this->perms[$i] = $perm[$i];
+ − 2134
$this->acl_defaults_used[$i] = ( $is_everyone );
+ − 2135
}
+ − 2136
else
+ − 2137
{
+ − 2138
//echo "$i: default NOT in use";
+ − 2139
// Defaults are not in use, merge as normal
+ − 2140
if ( $this->perms[$i] != AUTH_DENY )
+ − 2141
{
+ − 2142
//echo ", but overriding";
+ − 2143
$this->perms[$i] = $perm[$i];
+ − 2144
}
+ − 2145
//echo "<br />";
+ − 2146
}
+ − 2147
}
+ − 2148
}
+ − 2149
}
+ − 2150
+ − 2151
/**
+ − 2152
* Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence
+ − 2153
* over the first, without exceptions. This is used to merge the hardcoded defaults with admin-specified
+ − 2154
* defaults, which take precedence.
+ − 2155
* @param array $perm1 The first set of permissions
+ − 2156
* @param array $perm2 The second set of permissions
+ − 2157
* @return array
+ − 2158
*/
+ − 2159
+ − 2160
function acl_merge_complete($perm1, $perm2)
+ − 2161
{
+ − 2162
$ret = $perm1;
+ − 2163
foreach ( $perm2 as $type => $level )
+ − 2164
{
+ − 2165
$ret[$type] = $level;
+ − 2166
}
+ − 2167
return $ret;
+ − 2168
}
+ − 2169
+ − 2170
/**
+ − 2171
* Tell us if the dependencies for a given permission are met.
+ − 2172
* @param string The ACL permission ID
+ − 2173
* @return bool
+ − 2174
*/
+ − 2175
+ − 2176
function acl_check_deps($type)
+ − 2177
{
+ − 2178
if(!isset($this->acl_deps[$type])) // This will only happen if the permissions table is hacked or improperly accessed
+ − 2179
return true;
+ − 2180
if(sizeof($this->acl_deps[$type]) < 1)
+ − 2181
return true;
+ − 2182
$deps = $this->acl_deps[$type];
+ − 2183
while(true)
+ − 2184
{
+ − 2185
$full_resolved = true;
+ − 2186
$j = sizeof($deps);
+ − 2187
for ( $i = 0; $i < $j; $i++ )
+ − 2188
{
+ − 2189
$b = $deps;
+ − 2190
$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
+ − 2191
if( $b == $deps )
+ − 2192
{
+ − 2193
break 2;
+ − 2194
}
+ − 2195
$j = sizeof($deps);
+ − 2196
}
+ − 2197
}
+ − 2198
//die('<pre>'.print_r($deps, true).'</pre>');
+ − 2199
foreach($deps as $d)
+ − 2200
{
+ − 2201
if ( !$this->get_permissions($d) )
+ − 2202
{
+ − 2203
return false;
+ − 2204
}
+ − 2205
}
+ − 2206
return true;
+ − 2207
}
+ − 2208
+ − 2209
/**
+ − 2210
* Makes a CAPTCHA code and caches the code in the database
+ − 2211
* @param int $len The length of the code, in bytes
+ − 2212
* @return string A unique identifier assigned to the code. This hash should be passed to sessionManager::getCaptcha() to retrieve the code.
+ − 2213
*/
+ − 2214
+ − 2215
function make_captcha($len = 7)
+ − 2216
{
+ − 2217
$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');
+ − 2218
$s = '';
+ − 2219
for($i=0;$i<$len;$i++) $s .= $chars[mt_rand(0, count($chars)-1)];
+ − 2220
$hash = md5(microtime() . mt_rand());
+ − 2221
$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);');
+ − 2222
return $hash;
+ − 2223
}
+ − 2224
+ − 2225
/**
+ − 2226
* For the given code ID, returns the correct CAPTCHA code, or false on failure
+ − 2227
* @param string $hash The unique ID assigned to the code
+ − 2228
* @return string The correct confirmation code
+ − 2229
*/
+ − 2230
+ − 2231
function get_captcha($hash)
+ − 2232
{
+ − 2233
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2234
$s = $this->sql('SELECT salt FROM '.table_prefix.'session_keys WHERE session_key=\''.$db->escape($hash).'\' AND source_ip=\''.ip2hex($_SERVER['REMOTE_ADDR']).'\';');
+ − 2235
if($db->numrows() < 1) return false;
+ − 2236
$r = $db->fetchrow();
+ − 2237
return $r['salt'];
+ − 2238
}
+ − 2239
+ − 2240
/**
+ − 2241
* Deletes all CAPTCHA codes cached in the DB for this user.
+ − 2242
*/
+ − 2243
+ − 2244
function kill_captcha()
+ − 2245
{
+ − 2246
$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE user_id=-2 AND source_ip=\''.ip2hex($_SERVER['REMOTE_ADDR']).'\';');
+ − 2247
}
+ − 2248
+ − 2249
/**
+ − 2250
* Generates a random password.
+ − 2251
* @param int $length Optional - length of password
+ − 2252
* @return string
+ − 2253
*/
+ − 2254
+ − 2255
function random_pass($length = 10)
+ − 2256
{
+ − 2257
$valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+@#%&<>';
+ − 2258
$valid_chars = enano_str_split($valid_chars);
+ − 2259
$ret = '';
+ − 2260
for ( $i = 0; $i < $length; $i++ )
+ − 2261
{
+ − 2262
$ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
+ − 2263
}
+ − 2264
return $ret;
+ − 2265
}
+ − 2266
+ − 2267
/**
+ − 2268
* Generates some Javascript that calls the AES encryption library.
+ − 2269
* @param string The name of the form
+ − 2270
* @param string The name of the password field
+ − 2271
* @param string The name of the field that switches encryption on or off
+ − 2272
* @param string The name of the field that contains the encryption key
+ − 2273
* @param string The name of the field that will contain the encrypted password
+ − 2274
* @param string The name of the field that handles MD5 challenge data
+ − 2275
* @return string
+ − 2276
*/
+ − 2277
+ − 2278
function aes_javascript($form_name, $pw_field, $use_crypt, $crypt_key, $crypt_data, $challenge)
+ − 2279
{
+ − 2280
$code = '
+ − 2281
<script type="text/javascript">
+ − 2282
disableJSONExts();
+ − 2283
str = \'\';
+ − 2284
for(i=0;i<keySizeInBits/4;i++) str+=\'0\';
+ − 2285
var key = hexToByteArray(str);
+ − 2286
var pt = hexToByteArray(str);
+ − 2287
var ct = rijndaelEncrypt(pt, key, \'ECB\');
+ − 2288
var ct = byteArrayToHex(ct);
+ − 2289
switch(keySizeInBits)
+ − 2290
{
+ − 2291
case 128:
+ − 2292
v = \'66e94bd4ef8a2c3b884cfa59ca342b2e\';
+ − 2293
break;
+ − 2294
case 192:
+ − 2295
v = \'aae06992acbf52a3e8f4a96ec9300bd7aae06992acbf52a3e8f4a96ec9300bd7\';
+ − 2296
break;
+ − 2297
case 256:
+ − 2298
v = \'dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087\';
+ − 2299
break;
+ − 2300
}
+ − 2301
var testpassed = ' . ( ( isset($_GET['use_crypt']) && $_GET['use_crypt']=='0') ? 'false; // CRYPTO-AUTH DISABLED ON USER REQUEST // ' : '' ) . '( ct == v && md5_vm_test() );
+ − 2302
var frm = document.forms.'.$form_name.';
+ − 2303
if(testpassed)
+ − 2304
{
+ − 2305
frm.'.$use_crypt.'.value = \'yes\';
+ − 2306
var cryptkey = frm.'.$crypt_key.'.value;
+ − 2307
frm.'.$crypt_key.'.value = hex_md5(cryptkey);
+ − 2308
cryptkey = hexToByteArray(cryptkey);
+ − 2309
if(!cryptkey || ( ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ) && cryptkey.length != keySizeInBits / 8 )
+ − 2310
{
+ − 2311
if ( frm._login ) frm._login.disabled = true;
+ − 2312
len = ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ? \'\\nLen: \'+cryptkey.length : \'\';
+ − 2313
alert(\'The key is messed up\\nType: \'+typeof(cryptkey)+len);
+ − 2314
}
+ − 2315
}
+ − 2316
if(frm.username) frm.username.focus();
+ − 2317
function runEncryption()
+ − 2318
{
+ − 2319
if(testpassed)
+ − 2320
{
+ − 2321
pass = frm.'.$pw_field.'.value;
+ − 2322
chal = frm.'.$challenge.'.value;
+ − 2323
challenge = hex_md5(pass + chal) + chal;
+ − 2324
frm.'.$challenge.'.value = challenge;
+ − 2325
pass = stringToByteArray(pass);
+ − 2326
cryptstring = rijndaelEncrypt(pass, cryptkey, \'ECB\');
+ − 2327
if(!cryptstring)
+ − 2328
{
+ − 2329
return false;
+ − 2330
}
+ − 2331
cryptstring = byteArrayToHex(cryptstring);
+ − 2332
frm.'.$crypt_data.'.value = cryptstring;
+ − 2333
frm.'.$pw_field.'.value = \'\';
+ − 2334
}
+ − 2335
return false;
+ − 2336
}
+ − 2337
</script>
+ − 2338
';
+ − 2339
return $code;
+ − 2340
}
+ − 2341
+ − 2342
}
+ − 2343
+ − 2344
/**
+ − 2345
* Class used to fetch permissions for a specific page. Used internally by SessionManager.
+ − 2346
* @package Enano
+ − 2347
* @subpackage Session manager
+ − 2348
* @license http://www.gnu.org/copyleft/gpl.html
+ − 2349
* @access private
+ − 2350
*/
+ − 2351
+ − 2352
class Session_ACLPageInfo {
+ − 2353
+ − 2354
/**
+ − 2355
* The page ID of this ACL info package
+ − 2356
* @var string
+ − 2357
*/
+ − 2358
+ − 2359
var $page_id;
+ − 2360
+ − 2361
/**
+ − 2362
* The namespace of the page being checked
+ − 2363
* @var string
+ − 2364
*/
+ − 2365
+ − 2366
var $namespace;
+ − 2367
+ − 2368
/**
+ − 2369
* Our list of permission types.
+ − 2370
* @access private
+ − 2371
* @var array
+ − 2372
*/
+ − 2373
+ − 2374
var $acl_types = Array();
+ − 2375
+ − 2376
/**
+ − 2377
* The list of descriptions for the permission types
+ − 2378
* @var array
+ − 2379
*/
+ − 2380
+ − 2381
var $acl_descs = Array();
+ − 2382
+ − 2383
/**
+ − 2384
* A list of dependencies for ACL types.
+ − 2385
* @var array
+ − 2386
*/
+ − 2387
+ − 2388
var $acl_deps = Array();
+ − 2389
+ − 2390
/**
+ − 2391
* Our tell-all list of permissions.
+ − 2392
* @access private - or, preferably, protected...too bad this has to be PHP4 compatible
+ − 2393
* @var array
+ − 2394
*/
+ − 2395
+ − 2396
var $perms = Array();
+ − 2397
+ − 2398
/**
+ − 2399
* Constructor.
+ − 2400
* @param string $page_id The ID of the page to check
+ − 2401
* @param string $namespace The namespace of the page to check.
+ − 2402
* @param array $acl_types List of ACL types
+ − 2403
* @param array $acl_descs List of human-readable descriptions for permissions (associative)
+ − 2404
* @param array $acl_deps List of dependencies for permissions. For example, viewing history/diffs depends on the ability to read the page.
+ − 2405
* @param array $base What to start with - this is an attempt to reduce the number of SQL queries.
+ − 2406
*/
+ − 2407
+ − 2408
function Session_ACLPageInfo($page_id, $namespace, $acl_types, $acl_descs, $acl_deps, $base)
+ − 2409
{
+ − 2410
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2411
+ − 2412
$this->perms = $session->acl_merge_complete($acl_types, $base);
+ − 2413
$this->acl_deps = $acl_deps;
+ − 2414
$this->acl_types = $acl_types;
+ − 2415
$this->acl_descs = $acl_descs;
+ − 2416
+ − 2417
// Build a query to grab ACL info
+ − 2418
$bs = 'SELECT rules FROM '.table_prefix.'acl WHERE ( ';
+ − 2419
$q = Array();
+ − 2420
$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$session->user_id.' )';
+ − 2421
if(count($session->groups) > 0)
+ − 2422
{
+ − 2423
foreach($session->groups as $g_id => $g_name)
+ − 2424
{
+ − 2425
$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
+ − 2426
}
+ − 2427
}
+ − 2428
// 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
+ − 2429
// permissions to override group permissions.
+ − 2430
$bs .= implode(' OR ', $q) . ' ) AND ( page_id=\''.$db->escape($page_id).'\' AND namespace=\''.$db->escape($namespace).'\' )
+ − 2431
ORDER BY target_type ASC, page_id ASC, namespace ASC;';
+ − 2432
$q = $session->sql($bs);
+ − 2433
if ( $row = $db->fetchrow() )
+ − 2434
{
+ − 2435
do {
+ − 2436
$rules = $session->string_to_perm($row['rules']);
+ − 2437
$this->perms = $session->acl_merge($this->perms, $rules);
+ − 2438
} while ( $row = $db->fetchrow() );
+ − 2439
}
+ − 2440
+ − 2441
$this->page_id = $page_id;
+ − 2442
$this->namespace = $namespace;
+ − 2443
}
+ − 2444
+ − 2445
/**
+ − 2446
* Tells us whether permission $type is allowed or not based on the current rules.
+ − 2447
* @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
+ − 2448
* @param bool $no_deps If true, disables dependency checking
+ − 2449
* @return bool True if allowed, false if denied or if an error occured
+ − 2450
*/
+ − 2451
+ − 2452
function get_permissions($type, $no_deps = false)
+ − 2453
{
+ − 2454
global $db, $session, $paths, $template, $plugins; // Common objects
+ − 2455
if ( isset( $this->perms[$type] ) )
+ − 2456
{
+ − 2457
if ( $this->perms[$type] == AUTH_DENY )
+ − 2458
$ret = false;
+ − 2459
else if ( $this->perms[$type] == AUTH_WIKIMODE &&
+ − 2460
( isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id]) &&
+ − 2461
( $paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '1' ||
+ − 2462
( $paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '2'
+ − 2463
&& getConfig('wiki_mode') == '1'
+ − 2464
) ) ) )
+ − 2465
$ret = true;
+ − 2466
else if ( $this->perms[$type] == AUTH_WIKIMODE && (
+ − 2467
!isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id])
+ − 2468
|| (
+ − 2469
isset($paths->pages[$paths->nslist[$this->namespace].$this->page_id]) && (
+ − 2470
$paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '0'
+ − 2471
|| (
+ − 2472
$paths->pages[$paths->nslist[$this->namespace].$this->page_id]['wiki_mode'] == '2' && getConfig('wiki_mode') != '1'
+ − 2473
) ) ) ) )
+ − 2474
$ret = false;
+ − 2475
else if ( $this->perms[$type] == AUTH_ALLOW )
+ − 2476
$ret = true;
+ − 2477
else if ( $this->perms[$type] == AUTH_DISALLOW )
+ − 2478
$ret = false;
+ − 2479
}
+ − 2480
else if(isset($this->acl_types[$type]))
+ − 2481
{
+ − 2482
if ( $this->acl_types[$type] == AUTH_DENY )
+ − 2483
$ret = false;
+ − 2484
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
+ − 2485
$ret = true;
+ − 2486
else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
+ − 2487
$ret = false;
+ − 2488
else if ( $this->acl_types[$type] == AUTH_ALLOW )
+ − 2489
$ret = true;
+ − 2490
else if ( $this->acl_types[$type] == AUTH_DISALLOW )
+ − 2491
$ret = false;
+ − 2492
}
+ − 2493
else
+ − 2494
{
+ − 2495
// ACL type is undefined
+ − 2496
trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
+ − 2497
return false; // Be on the safe side and deny access
+ − 2498
}
+ − 2499
if ( !$no_deps )
+ − 2500
{
+ − 2501
if ( !$this->acl_check_deps($type) )
+ − 2502
return false;
+ − 2503
}
+ − 2504
return $ret;
+ − 2505
}
+ − 2506
+ − 2507
/**
+ − 2508
* Tell us if the dependencies for a given permission are met.
+ − 2509
* @param string The ACL permission ID
+ − 2510
* @return bool
+ − 2511
*/
+ − 2512
+ − 2513
function acl_check_deps($type)
+ − 2514
{
+ − 2515
if(!isset($this->acl_deps[$type])) // This will only happen if the permissions table is hacked or improperly accessed
+ − 2516
return true;
+ − 2517
if(sizeof($this->acl_deps[$type]) < 1)
+ − 2518
return true;
+ − 2519
$deps = $this->acl_deps[$type];
+ − 2520
while(true)
+ − 2521
{
+ − 2522
$full_resolved = true;
+ − 2523
$j = sizeof($deps);
+ − 2524
for ( $i = 0; $i < $j; $i++ )
+ − 2525
{
+ − 2526
$b = $deps;
+ − 2527
$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
+ − 2528
if( $b == $deps )
+ − 2529
{
+ − 2530
break 2;
+ − 2531
}
+ − 2532
$j = sizeof($deps);
+ − 2533
}
+ − 2534
}
+ − 2535
//die('<pre>'.print_r($deps, true).'</pre>');
+ − 2536
foreach($deps as $d)
+ − 2537
{
+ − 2538
if ( !$this->get_permissions($d) )
+ − 2539
{
+ − 2540
return false;
+ − 2541
}
+ − 2542
}
+ − 2543
return true;
+ − 2544
}
+ − 2545
+ − 2546
}
+ − 2547
+ − 2548
?>