PageRenderTime 67ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/sessions.php

https://code.google.com/p/enanocms/
PHP | 4735 lines | 3152 code | 576 blank | 1007 comment | 654 complexity | 496688a8a19ea62f9a4bfaaaf0aec9fa MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /*
  3. * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
  4. * Copyright (C) 2006-2009 Dan Fuhry
  5. * sessions.php - everything related to security and user management
  6. *
  7. * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
  11. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
  12. */
  13. /**
  14. * Anything and everything related to security and user management. This includes AES encryption, which is illegal in some countries.
  15. * Documenting the API was not easy - I hope you folks enjoy it.
  16. * @package Enano
  17. * @subpackage Session manager
  18. * @category security, user management, logins, etc.
  19. */
  20. class sessionManager {
  21. # Variables
  22. /**
  23. * Whether we're logged in or not
  24. * @var bool
  25. */
  26. var $user_logged_in = false;
  27. /**
  28. * Our current low-privilege session key
  29. * @var string
  30. */
  31. var $sid;
  32. /**
  33. * Username of currently logged-in user, or IP address if not logged in
  34. * @var string
  35. */
  36. var $username;
  37. /**
  38. * User ID of currently logged-in user, or 1 if not logged in
  39. * @var int
  40. */
  41. var $user_id = 1;
  42. /**
  43. * Real name of currently logged-in user, or blank if not logged in
  44. * @var string
  45. */
  46. var $real_name;
  47. /**
  48. * E-mail address of currently logged-in user, or blank if not logged in
  49. * @var string
  50. */
  51. var $email;
  52. /**
  53. * List of "extra" user information fields (IM handles, etc.)
  54. * @var array (associative)
  55. */
  56. var $user_extra;
  57. /**
  58. * User level of current user
  59. * USER_LEVEL_GUEST: guest
  60. * USER_LEVEL_MEMBER: regular user
  61. * USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
  62. * USER_LEVEL_MOD: moderator
  63. * USER_LEVEL_ADMIN: administrator
  64. * @var int
  65. */
  66. var $user_level;
  67. /**
  68. * High-privilege session key
  69. * @var string or false if not running on high-level authentication
  70. */
  71. var $sid_super;
  72. /**
  73. * The user's theme preference, defaults to $template->default_theme
  74. * @var string
  75. */
  76. var $theme;
  77. /**
  78. * The user's style preference, or style auto-detected based on theme if not logged in
  79. * @var string
  80. */
  81. var $style;
  82. /**
  83. * Signature of current user - appended to comments, etc.
  84. * @var string
  85. */
  86. var $signature;
  87. /**
  88. * UNIX timestamp of when we were registered, or 0 if not logged in
  89. * @var int
  90. */
  91. var $reg_time;
  92. /**
  93. * The number of unread private messages this user has.
  94. * @var int
  95. */
  96. var $unread_pms = 0;
  97. /**
  98. * AES key used to encrypt passwords and session key info.
  99. * @var string
  100. * @access private
  101. */
  102. protected $private_key;
  103. /**
  104. * Regex that defines a valid username, minus the ^ and $, these are added later
  105. * @var string
  106. */
  107. var $valid_username = '([^<>&\?\'"%\n\r\t\a\/]+)';
  108. /**
  109. * The current user's user title. Defaults to NULL.
  110. * @var string
  111. */
  112. var $user_title = null;
  113. /**
  114. * What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
  115. * @var string
  116. */
  117. var $auth_level = 1;
  118. /**
  119. * Preference for date formatting
  120. * @var string
  121. */
  122. var $date_format = DATE_4;
  123. /**
  124. * Preference for time formatting
  125. * @var string
  126. */
  127. var $time_format = TIME_24_NS;
  128. /**
  129. * State variable to track if a session timed out
  130. * @var bool
  131. */
  132. var $sw_timed_out = false;
  133. /**
  134. * Token appended to some important forms to prevent CSRF.
  135. * @var string
  136. */
  137. var $csrf_token = false;
  138. /**
  139. * Password change disabled, for auth plugins
  140. * @var bool
  141. */
  142. var $password_change_disabled = false;
  143. /**
  144. * Password change page URL + title, for auth plugins
  145. * @var array
  146. */
  147. var $password_change_dest = array('url' => '', 'title' => '');
  148. /**
  149. * Switch to track if we're started or not.
  150. * @access private
  151. * @var bool
  152. */
  153. var $started = false;
  154. /**
  155. * Switch to control compatibility mode (for older Enano websites being upgraded)
  156. * @access private
  157. * @var bool
  158. */
  159. var $compat = false;
  160. /**
  161. * Our list of permission types.
  162. * @access private
  163. * @var array
  164. */
  165. var $acl_types = Array();
  166. /**
  167. * The list of descriptions for the permission types
  168. * @var array
  169. */
  170. var $acl_descs = Array();
  171. /**
  172. * A list of dependencies for ACL types.
  173. * @var array
  174. */
  175. var $acl_deps = Array();
  176. /**
  177. * Our tell-all list of permissions. Do not even try to change this.
  178. * @access private
  179. * @var array
  180. */
  181. var $perms = Array();
  182. /**
  183. * A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
  184. * @var array
  185. * @access private
  186. */
  187. var $acl_base_cache = Array();
  188. /**
  189. * Stores the scope information for ACL types.
  190. * @var array
  191. * @access private
  192. */
  193. var $acl_scope = Array();
  194. /**
  195. * Array to track which default permissions are being used
  196. * @var array
  197. * @access private
  198. */
  199. var $acl_defaults_used = Array();
  200. /**
  201. * Array to track group membership.
  202. * @var array
  203. */
  204. var $groups = Array();
  205. /**
  206. * Associative array to track group modship.
  207. * @var array
  208. */
  209. var $group_mod = Array();
  210. /**
  211. * A constant array of user-level-to-rank default associations.
  212. * @var array
  213. */
  214. var $level_rank_table = array(
  215. USER_LEVEL_ADMIN => RANK_ID_ADMIN,
  216. USER_LEVEL_MOD => RANK_ID_MOD,
  217. USER_LEVEL_MEMBER => RANK_ID_MEMBER,
  218. USER_LEVEL_CHPREF => RANK_ID_MEMBER,
  219. USER_LEVEL_GUEST => RANK_ID_GUEST
  220. );
  221. /**
  222. * A constant array that maps precedence constants to language strings
  223. * @var array
  224. */
  225. var $acl_inherit_lang_table = array(
  226. ACL_INHERIT_ENANO_DEFAULT => 'acl_inherit_enano_default',
  227. ACL_INHERIT_GLOBAL_EVERYONE => 'acl_inherit_global_everyone',
  228. ACL_INHERIT_GLOBAL_GROUP => 'acl_inherit_global_group',
  229. ACL_INHERIT_GLOBAL_USER => 'acl_inherit_global_user',
  230. ACL_INHERIT_PG_EVERYONE => 'acl_inherit_pg_everyone',
  231. ACL_INHERIT_PG_GROUP => 'acl_inherit_pg_group',
  232. ACL_INHERIT_PG_USER => 'acl_inherit_pg_user',
  233. ACL_INHERIT_LOCAL_EVERYONE => 'acl_inherit_local_everyone',
  234. ACL_INHERIT_LOCAL_GROUP => 'acl_inherit_local_group',
  235. ACL_INHERIT_LOCAL_USER => 'acl_inherit_local_user'
  236. );
  237. # Basic functions
  238. /**
  239. * Constructor.
  240. */
  241. function __construct()
  242. {
  243. global $db, $session, $paths, $template, $plugins; // Common objects
  244. if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
  245. {
  246. @include(ENANO_ROOT.'/config.new.php');
  247. }
  248. else
  249. {
  250. @include(ENANO_ROOT.'/config.php');
  251. }
  252. unset($dbhost, $dbname, $dbuser, $dbpasswd);
  253. if(isset($crypto_key))
  254. {
  255. $this->private_key = $crypto_key;
  256. $this->private_key = hexdecode($this->private_key);
  257. }
  258. else
  259. {
  260. if(is_writable(ENANO_ROOT.'/config.php'))
  261. {
  262. // Generate and stash a private key
  263. // This should only happen during an automated silent gradual migration to the new encryption platform.
  264. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  265. $this->private_key = $aes->gen_readymade_key();
  266. $config = file_get_contents(ENANO_ROOT.'/config.php');
  267. if(!$config)
  268. {
  269. die('$session->__construct(): can\'t get the contents of config.php');
  270. }
  271. $config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
  272. // And while we're at it...
  273. $config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
  274. $fh = @fopen(ENANO_ROOT.'/config.php', 'w');
  275. if ( !$fh )
  276. {
  277. die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
  278. }
  279. fwrite($fh, $config);
  280. fclose($fh);
  281. }
  282. else
  283. {
  284. 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>');
  285. }
  286. }
  287. // Check for compatibility mode
  288. if(defined('IN_ENANO_INSTALL'))
  289. {
  290. $q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
  291. if(!$q)
  292. {
  293. $error = mysql_error();
  294. if(strstr($error, "Unknown column 'old_encryption'"))
  295. $this->compat = true;
  296. else
  297. $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)');
  298. }
  299. $db->free_result();
  300. }
  301. }
  302. /**
  303. * PHP 4 compatible constructor. Deprecated in 1.1.x.
  304. */
  305. /*
  306. function sessionManager()
  307. {
  308. $this->__construct();
  309. }
  310. */
  311. /**
  312. * Wrapper function to sanitize strings for MySQL and HTML
  313. * @param string $text The text to sanitize
  314. * @return string
  315. */
  316. function prepare_text($text)
  317. {
  318. global $db;
  319. return $db->escape(htmlspecialchars($text));
  320. }
  321. /**
  322. * Makes a SQL query and handles error checking
  323. * @param string $query The SQL query to make
  324. * @return resource
  325. */
  326. function sql($query)
  327. {
  328. global $db, $session, $paths, $template, $plugins; // Common objects
  329. $result = $db->sql_query($query);
  330. if(!$result)
  331. {
  332. $db->_die('The error seems to have occurred somewhere in the session management code.');
  333. }
  334. return $result;
  335. }
  336. /**
  337. * Returns true if we're currently on a page that shouldn't be blocked even if we have an inactive or banned account
  338. * @param bool strict - if true, whitelist of pages is even stricter (Login, Logout and CSS only). if false (default), admin access is allowed, assuming other factors allow it
  339. * @return bool
  340. */
  341. function on_critical_page($strict = false)
  342. {
  343. global $urlname;
  344. list($page_id, $namespace) = RenderMan::strToPageID($urlname);
  345. list($page_id) = explode('/', $page_id);
  346. if ( $strict )
  347. {
  348. return $namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'LangExportJSON', 'ActivateAccount'));
  349. }
  350. else
  351. {
  352. return $namespace == 'Admin' || ($namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'Administration', 'LangExportJSON', 'ActivateAccount')));
  353. }
  354. }
  355. # Session restoration and permissions
  356. /**
  357. * Initializes the basic state of things, including most user prefs, login data, cookie stuff
  358. */
  359. function start()
  360. {
  361. global $db, $session, $paths, $template, $plugins; // Common objects
  362. global $lang;
  363. global $timezone;
  364. if($this->started) return;
  365. $this->started = true;
  366. $user = false;
  367. if ( isset($_COOKIE['sid']) )
  368. {
  369. if ( $this->compat )
  370. {
  371. $userdata = $this->compat_validate_session($_COOKIE['sid']);
  372. }
  373. else
  374. {
  375. $userdata = $this->validate_session($_COOKIE['sid']);
  376. }
  377. if ( is_array($userdata) )
  378. {
  379. $this->sid = $_COOKIE['sid'];
  380. $this->user_logged_in = true;
  381. $this->user_id = intval($userdata['user_id']);
  382. $this->username = $userdata['username'];
  383. $this->user_level = intval($userdata['user_level']);
  384. $this->real_name = $userdata['real_name'];
  385. $this->email = $userdata['email'];
  386. $this->unread_pms = $userdata['num_pms'];
  387. $this->user_title = ( isset($userdata['user_title']) ) ? $userdata['user_title'] : null;
  388. if(!$this->compat)
  389. {
  390. $this->theme = $userdata['theme'];
  391. $this->style = $userdata['style'];
  392. $this->signature = $userdata['signature'];
  393. $this->reg_time = $userdata['reg_time'];
  394. }
  395. $this->auth_level = USER_LEVEL_MEMBER;
  396. // generate an anti-CSRF token
  397. $this->csrf_token = sha1($this->username . $this->sid . $this->user_id);
  398. if(!isset($template->named_theme_list[$this->theme]))
  399. {
  400. if($this->compat || !is_object($template))
  401. {
  402. $this->theme = 'oxygen';
  403. $this->style = 'bleu';
  404. }
  405. else
  406. {
  407. $this->theme = $template->default_theme;
  408. $this->style = $template->default_style;
  409. }
  410. }
  411. $user = true;
  412. // set timezone params
  413. $GLOBALS['timezone'] = $userdata['user_timezone'];
  414. $GLOBALS['dst_params'] = explode(';', $userdata['user_dst']);
  415. foreach ( $GLOBALS['dst_params'] as &$parm )
  416. {
  417. if ( substr($parm, -1) != 'd' )
  418. $parm = intval($parm);
  419. }
  420. // Set language
  421. if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
  422. {
  423. $lang_id = intval($userdata['user_lang']);
  424. $lang = new Language($lang_id);
  425. @setlocale(LC_ALL, $lang->lang_code);
  426. }
  427. if(isset($_REQUEST['auth']) && !$this->sid_super)
  428. {
  429. // Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
  430. if($this->compat)
  431. {
  432. $key = $_REQUEST['auth'];
  433. $super = $this->compat_validate_session($key);
  434. }
  435. else
  436. {
  437. $key = $_REQUEST['auth'];
  438. if ( !empty($key) && ( strlen($key) / 2 ) % 4 == 0 )
  439. {
  440. $super = $this->validate_session($key);
  441. }
  442. }
  443. if(is_array(@$super))
  444. {
  445. $this->auth_level = intval($super['auth_level']);
  446. $this->sid_super = $_REQUEST['auth'];
  447. }
  448. }
  449. }
  450. }
  451. if(!$user)
  452. {
  453. //exit;
  454. $this->register_guest_session();
  455. }
  456. if(!$this->compat)
  457. {
  458. // init groups
  459. $q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g' . "\n"
  460. . ' LEFT JOIN '.table_prefix.'group_members AS m' . "\n"
  461. . ' ON g.group_id=m.group_id' . "\n"
  462. . ' WHERE ( m.user_id='.$this->user_id.'' . "\n"
  463. . ' OR g.group_name=\'Everyone\')' . "\n"
  464. . ' ' . ( /* quick hack for upgrade compatibility reasons */ enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '' . "\n"
  465. . ' ORDER BY group_id ASC;'); // The ORDER BY is to make sure "Everyone" comes first so the permissions can be overridden
  466. if($row = $db->fetchrow())
  467. {
  468. do {
  469. $this->groups[$row['group_id']] = $row['group_name'];
  470. $this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
  471. } while($row = $db->fetchrow());
  472. }
  473. else
  474. {
  475. die('No group info');
  476. }
  477. profiler_log('Fetched group memberships');
  478. }
  479. // make sure we aren't banned
  480. $this->check_banlist();
  481. // make sure the account is active
  482. if ( !$this->compat && $this->user_logged_in && $userdata['account_active'] < 1 && !$this->on_critical_page() )
  483. {
  484. $this->show_inactive_error($userdata);
  485. }
  486. // Printable page view? Probably the wrong place to control
  487. // it but $template is pretty dumb, it will just about always
  488. // do what you ask it to do, which isn't always what we want
  489. if ( isset ( $_GET['printable'] ) )
  490. {
  491. $this->theme = 'printable';
  492. $this->style = 'default';
  493. }
  494. // setup theme ACLs
  495. $template->process_theme_acls();
  496. profiler_log('Sessions started. Banlist and theme ACLs initialized');
  497. }
  498. # Logins
  499. /**
  500. * Attempts to perform a login using crypto functions
  501. * @param string $username The username
  502. * @param string $aes_data The encrypted password, hex-encoded
  503. * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
  504. * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
  505. * @param int $level The privilege level we're authenticating for, defaults to 0
  506. * @param string $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
  507. * @param string $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
  508. * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
  509. * @param bool $lookup_key Optional. If true (default) this queries the database for the "real" encryption key. Else, uses what is given.
  510. * @return string 'success' on success, or error string on failure
  511. */
  512. function login_with_crypto($username, $aes_data, $aes_key_id, $challenge, $level = USER_LEVEL_MEMBER, $captcha_hash = false, $captcha_code = false, $remember = false, $lookup_key = true)
  513. {
  514. global $db, $session, $paths, $template, $plugins; // Common objects
  515. // Instanciate the Rijndael encryption object
  516. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  517. // Fetch our decryption key
  518. if ( $lookup_key )
  519. {
  520. $aes_key = $this->fetch_public_key($aes_key_id);
  521. if ( !$aes_key )
  522. {
  523. // It could be that our key cache is full. If it seems larger than 65KB, clear it
  524. if ( strlen(getConfig('login_key_cache')) > 65000 )
  525. {
  526. setConfig('login_key_cache', '');
  527. return array(
  528. 'success' => false,
  529. 'error' => 'key_not_found_cleared',
  530. );
  531. }
  532. return array(
  533. 'success' => false,
  534. 'error' => 'key_not_found'
  535. );
  536. }
  537. }
  538. else
  539. {
  540. $aes_key =& $aes_key_id;
  541. }
  542. // Convert the key to a binary string
  543. $bin_key = hexdecode($aes_key);
  544. if(strlen($bin_key) != AES_BITS / 8)
  545. return array(
  546. 'success' => false,
  547. 'error' => 'key_wrong_length'
  548. );
  549. // Decrypt our password
  550. $password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
  551. // Let the LoginAPI do the rest.
  552. return $this->login_without_crypto($username, $password, false, $level, $captcha_hash, $captcha_code, $remember);
  553. }
  554. /**
  555. * Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
  556. * 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
  557. * Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
  558. * @param string $username The username
  559. * @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
  560. * @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.
  561. * @param int $level The privilege level we're authenticating for, defaults to 0
  562. * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
  563. */
  564. function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER, $remember = false)
  565. {
  566. global $db, $session, $paths, $template, $plugins; // Common objects
  567. if ( $already_md5ed )
  568. {
  569. // No longer supported
  570. return array(
  571. 'mode' => 'error',
  572. 'error' => '$already_md5ed is no longer supported (set this parameter to false and make sure the password you send to $session->login_without_crypto() is not hashed)'
  573. );
  574. }
  575. // Replace underscores with spaces in username
  576. // (Added in 1.0.2)
  577. $username = str_replace('_', ' ', $username);
  578. // Perhaps we're upgrading Enano?
  579. if($this->compat)
  580. {
  581. return $this->login_compat($username, md5($password), $level);
  582. }
  583. // Instanciate the Rijndael encryption object
  584. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  585. // Initialize our success switch
  586. $success = false;
  587. // Retrieve the real password from the database
  588. $username_db = $db->escape(strtolower($username));
  589. $username_db_upper = $db->escape($username);
  590. if ( !$db->sql_query('SELECT password,password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
  591. . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );") )
  592. {
  593. $this->sql('SELECT password,\'\' AS password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
  594. . " WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );");
  595. }
  596. if ( $db->numrows() < 1 )
  597. {
  598. // This wasn't logged in <1.0.2, dunno how it slipped through
  599. if ( $level > USER_LEVEL_MEMBER )
  600. $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES\n"
  601. . ' (\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
  602. . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  603. else
  604. $this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary) VALUES\n"
  605. . ' (\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
  606. . '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  607. // Do we also need to increment the lockout countdown?
  608. if ( !defined('IN_ENANO_INSTALL') )
  609. $lockout_data = $this->get_lockout_info();
  610. else
  611. $lockout_data = array(
  612. 'lockout_policy' => 'disable'
  613. );
  614. if ( $lockout_data['policy'] != 'disable' && !defined('IN_ENANO_INSTALL') )
  615. {
  616. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  617. // increment fail count
  618. $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
  619. $lockout_data['fails']++;
  620. return array(
  621. 'success' => false,
  622. 'error' => ( $lockout_data['fails'] >= $lockout_data['threshold'] ) ? 'locked_out' : 'invalid_credentials',
  623. 'lockout_threshold' => $lockout_data['threshold'],
  624. 'lockout_duration' => ( $lockout_data['duration'] ),
  625. 'lockout_fails' => $lockout_data['fails'],
  626. 'lockout_policy' => $lockout_data['policy']
  627. );
  628. }
  629. return array(
  630. 'success' => false,
  631. 'error' => 'invalid_credentials'
  632. );
  633. }
  634. $row = $db->fetchrow();
  635. // Check to see if we're logging in using a temporary password
  636. if((intval($row['temp_password_time']) + 3600*24) > time() )
  637. {
  638. $temp_pass = hmac_sha1($password, $row['password_salt']);
  639. if( $temp_pass === $row['temp_password'] )
  640. {
  641. $code = $plugins->setHook('login_password_reset');
  642. foreach ( $code as $cmd )
  643. {
  644. eval($cmd);
  645. }
  646. return array(
  647. 'success' => false,
  648. 'error' => 'valid_reset',
  649. 'redirect_url' => makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $this->pk_encrypt($password))
  650. );
  651. }
  652. }
  653. if ( $row['old_encryption'] == 1 )
  654. {
  655. // The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
  656. if(md5($password) === $row['password'])
  657. {
  658. if ( !defined('IN_ENANO_UPGRADE') )
  659. {
  660. $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
  661. $password_hmac = hmac_sha1($password, $hmac_secret);
  662. $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
  663. }
  664. $success = true;
  665. }
  666. }
  667. else if ( $row['old_encryption'] == 2 || ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') ) && strlen($row['password']) != 40 )
  668. {
  669. // Our password field uses the 1.0RC1-1.1.5 encryption format
  670. $real_pass = $aes->decrypt($row['password'], $this->private_key);
  671. if($password === $real_pass)
  672. {
  673. if ( !defined('IN_ENANO_UPGRADE') )
  674. {
  675. $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
  676. $password_hmac = hmac_sha1($password, $hmac_secret);
  677. $this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
  678. }
  679. $success = true;
  680. }
  681. }
  682. else
  683. {
  684. // Password uses HMAC-SHA1
  685. $user_challenge = hmac_sha1($password, $row['password_salt']);
  686. $password_hmac =& $row['password'];
  687. if ( $user_challenge === $password_hmac )
  688. {
  689. $success = true;
  690. }
  691. }
  692. if($success)
  693. {
  694. if((int)$level > (int)$row['user_level'])
  695. return array(
  696. 'success' => false,
  697. 'error' => 'too_big_for_britches'
  698. );
  699. // grant session
  700. $sess = $this->register_session($row['user_id'], $username, ( isset($password_hmac) ? $password_hmac : $password ), $level, $remember);
  701. if($sess)
  702. {
  703. if ( getConfig('db_version') >= 1125 )
  704. {
  705. if($level > USER_LEVEL_MEMBER)
  706. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  707. else
  708. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  709. }
  710. else
  711. {
  712. if($level > USER_LEVEL_MEMBER)
  713. $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().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  714. else
  715. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  716. }
  717. $code = $plugins->setHook('login_success');
  718. foreach ( $code as $cmd )
  719. {
  720. eval($cmd);
  721. }
  722. return array(
  723. 'success' => true
  724. );
  725. }
  726. else
  727. return array(
  728. 'success' => false,
  729. 'error' => 'backend_fail'
  730. );
  731. }
  732. else
  733. {
  734. if($level > USER_LEVEL_MEMBER)
  735. $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().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
  736. else
  737. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
  738. // Do we also need to increment the lockout countdown?
  739. if ( !defined('IN_ENANO_INSTALL') && getConfig('lockout_policy', 'lockout') !== 'disable' )
  740. {
  741. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  742. // increment fail count
  743. $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
  744. }
  745. return array(
  746. 'success' => false,
  747. 'error' => 'invalid_credentials'
  748. );
  749. }
  750. }
  751. /**
  752. * Attempts to log in using the old table structure and algorithm. This is for upgrades from old 1.0.x releases.
  753. * @param string $username
  754. * @param string $password This should be an MD5 hash
  755. * @return string 'success' if successful, or error message on failure
  756. */
  757. function login_compat($username, $password, $level = 0)
  758. {
  759. global $db, $session, $paths, $template, $plugins; // Common objects
  760. $pass_hashed =& $password;
  761. $this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
  762. if($db->numrows() < 1)
  763. return 'The username and/or password is incorrect.';
  764. $row = $db->fetchrow();
  765. if($row['password'] == $password)
  766. {
  767. if((int)$level > (int)$row['user_level'])
  768. return 'You are not authorized for this level of access.';
  769. $sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
  770. if($sess)
  771. return 'success';
  772. else
  773. return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
  774. }
  775. else
  776. {
  777. return 'The username and/or password is incorrect.';
  778. }
  779. }
  780. /**
  781. * Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
  782. * Basically the session key is a hex-encoded cookie (encrypted with the site's private key) that says "u=[username];p=[sha1 of password];s=[unique key id]"
  783. * @param int $user_id
  784. * @param string $username
  785. * @param string $password_hmac The HMAC of the user's password, right from the database
  786. * @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
  787. * @param bool $remember Whether the session should be long-term (true) or not (false). Defaults to short-term.
  788. * @return bool
  789. */
  790. function register_session($user_id, $username, $password_hmac, $level = USER_LEVEL_MEMBER, $remember = false)
  791. {
  792. global $db, $session, $paths, $template, $plugins; // Common objects
  793. // Random key identifier
  794. $salt = '';
  795. for ( $i = 0; $i < 32; $i++ )
  796. {
  797. $salt .= chr(mt_rand(32, 126));
  798. }
  799. // Session key
  800. if ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') )
  801. {
  802. $session_key = $this->pk_encrypt("u=$username;p=" . sha1($password_hmac) . ";s=$salt");
  803. }
  804. else
  805. {
  806. $key_pieces = array($password_hmac);
  807. $sk_mode = 'generate';
  808. $code = $plugins->setHook('session_key_calc');
  809. foreach ( $code as $cmd )
  810. {
  811. eval($cmd);
  812. }
  813. $key_pieces = implode("\xFF", $key_pieces);
  814. $session_key = hmac_sha1($key_pieces, $salt);
  815. }
  816. // Minimum level
  817. $level = max(array($level, USER_LEVEL_MEMBER));
  818. // Type of key
  819. $key_type = ( $level > USER_LEVEL_MEMBER ) ? SK_ELEV : ( $remember ? SK_LONG : SK_SHORT );
  820. // If we're registering an elevated-privilege key, it needs to be on GET
  821. if($level > USER_LEVEL_MEMBER)
  822. {
  823. $this->sid_super = $session_key;
  824. $_GET['auth'] = $session_key;
  825. }
  826. else
  827. {
  828. // Stash it in a cookie
  829. // For now, make the cookie last forever, we can change this in 1.1.x
  830. setcookie( 'sid', $session_key, time()+15552000, scriptPath.'/', null, $GLOBALS['is_https']);
  831. $_COOKIE['sid'] = $session_key;
  832. $this->sid = $session_key;
  833. }
  834. // $keyhash is stored in the database, this is for compatibility with the older DB structure
  835. $keyhash = md5($session_key);
  836. // Record the user's IP
  837. $ip = $_SERVER['REMOTE_ADDR'];
  838. if(!is_valid_ip($ip))
  839. die('$session->register_session: Remote-Addr was spoofed');
  840. // The time needs to be stashed to enforce the 15-minute limit on elevated session keys
  841. $time = time();
  842. // Sanity check
  843. if(!is_int($user_id))
  844. die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
  845. if(!is_int($level))
  846. die(var_dump($level) . '<br />Somehow an SQL injection attempt crawled into our session registrar! (2)');
  847. // Update RAM
  848. $this->user_id = $user_id;
  849. $this->user_level = max(array($this->user_level, $level));
  850. // All done!
  851. $query = $db->sql_query('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time, key_type) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.', ' . $key_type . ');');
  852. if ( !$query && defined('IN_ENANO_UPGRADE') )
  853. // we're trying to upgrade so the key_type column is probably missing - try it again without specifying the key type
  854. $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
  855. return true;
  856. }
  857. /**
  858. * Identical to register_session in nature, but uses the old login/table structure. DO NOT use this except in the upgrade script under very controlled circumstances.
  859. * @see sessionManager::register_session()
  860. * @access private
  861. */
  862. function register_session_compat($user_id, $username, $password, $level = 0)
  863. {
  864. $salt = md5(microtime() . mt_rand());
  865. $thekey = md5($password . $salt);
  866. if($level > 0)
  867. {
  868. $this->sid_super = $thekey;
  869. }
  870. else
  871. {
  872. setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
  873. $_COOKIE['sid'] = $thekey;
  874. }
  875. $ip = ip2hex($_SERVER['REMOTE_ADDR']);
  876. if(!$ip)
  877. die('$session->register_session: Remote-Addr was spoofed');
  878. $time = time();
  879. if(!is_int($user_id))
  880. die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
  881. if(!is_int($level))
  882. die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
  883. $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.');');
  884. return true;
  885. }
  886. /**
  887. * Tells us if we're locked out from logging in or not.
  888. * @param reference will be filled with information regarding in-progress lockout
  889. * @return bool True if locked out, false otherwise
  890. */
  891. function get_lockout_info()
  892. {
  893. global $db;
  894. // this has to be initialized to hide warnings
  895. $lockdata = null;
  896. // Query database for lockout info
  897. $locked_out = false;
  898. $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
  899. $duration = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
  900. // convert to seconds
  901. $duration = $duration * 60;
  902. // decide on policy
  903. $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
  904. if ( $policy != 'disable' )
  905. {
  906. // enabled; make decision
  907. $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
  908. $timestamp_cutoff = time() - $duration;
  909. $q = $this->sql('SELECT timestamp FROM ' . table_prefix . 'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
  910. $fails = $db->numrows($q);
  911. $row = $db->fetchrow($q);
  912. $locked_out = ( $fails >= $threshold );
  913. $lockdata = array(
  914. 'active' => $locked_out,
  915. 'threshold' => $threshold,
  916. 'duration' => ( $duration / 60 ),
  917. 'fails' => $fails,
  918. 'policy' => $policy,
  919. 'last_time' => $row['timestamp'],
  920. 'time_rem' => $locked_out ? ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ) : 0,
  921. 'captcha' => $policy == 'captcha' ? $this->make_captcha() : ''
  922. );
  923. $db->free_result();
  924. }
  925. else
  926. {
  927. // disabled; send back default dataset
  928. $lockdata = array(
  929. 'active' => false,
  930. 'threshold' => $threshold,
  931. 'duration' => ( $duration / 60 ),
  932. 'fails' => 0,
  933. 'policy' => $policy,
  934. 'last_time' => 0,
  935. 'time_rem' => 0,
  936. 'captcha' => ''
  937. );
  938. }
  939. return $lockdata;
  940. }
  941. /**
  942. * Creates/restores a guest session
  943. * @todo implement real session management for guests
  944. */
  945. function register_guest_session()
  946. {
  947. global $db, $session, $paths, $template, $plugins; // Common objects
  948. global $lang;
  949. $this->username = $_SERVER['REMOTE_ADDR'];
  950. $this->user_level = USER_LEVEL_GUEST;
  951. if($this->compat || defined('IN_ENANO_INSTALL'))
  952. {
  953. $this->theme = 'oxygen';
  954. $this->style = 'bleu';
  955. }
  956. else
  957. {
  958. $this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
  959. $this->style = ( isset($_GET['style']) && file_exists(ENANO_ROOT.'/themes/'.$this->theme . '/css/'.$_GET['style'].'.css' )) ? $_GET['style'] : preg_replace('/\.css$/', '', $template->named_theme_list[$this->theme]['default_style']);
  960. }
  961. $this->user_id = 1;
  962. // This is a VERY special case we are allowing. It lets the installer create languages using the Enano API.
  963. if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
  964. {
  965. $language = ( isset($_GET['lang']) && preg_match('/^[a-z0-9-_]+$/', @$_GET['lang']) ) ? $_GET['lang'] : intval(getConfig('default_language'));
  966. $lang = new Language($language);
  967. @setlocale(LC_ALL, $lang->lang_code);
  968. }
  969. // make a CSRF token
  970. $this->csrf_token = hmac_sha1($_SERVER['REMOTE_ADDR'], sha1($this->private_key));
  971. }
  972. /**
  973. * Validates a session key, and returns the userdata associated with the key or false
  974. * @param string $key The session key to validate
  975. * @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.
  976. */
  977. function validate_session($key)
  978. {
  979. global $db, $session, $paths, $template, $plugins; // Common objects
  980. profiler_log("SessionManager: checking session: " . sha1($key));
  981. if ( strlen($key) > 48 )
  982. {
  983. return $this->validate_aes_session($key);
  984. }
  985. profiler_log("SessionManager: checking session: " . $key);
  986. return $this->validate_session_shared($key, '');
  987. }
  988. /**
  989. * Validates an old-format AES session key. DO NOT USE THIS. Will return false if called outside of an upgrade.
  990. * @param string Session key
  991. * @return array
  992. */
  993. protected function validate_aes_session($key)
  994. {
  995. global $db, $session, $paths, $template, $plugins; // Common objects
  996. // No valid use except during upgrades
  997. if ( !preg_match('/^upg-/', enano_version()) && !defined('IN_ENANO_UPGRADE') )
  998. return false;
  999. $decrypted_key = $this->pk_decrypt($key);
  1000. if ( !$decrypted_key )
  1001. {
  1002. // die_semicritical('AES encryption error', '<p>Something went wrong during the AES decryption process.</p><pre>'.print_r($decrypted_key, true).'</pre>');
  1003. return false;
  1004. }
  1005. $n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=(.{32})$/', $decrypted_key, $keydata);
  1006. if($n < 1)
  1007. {
  1008. echo '(debug) $session->validate_session: Key does not match regex<br />Decrypted key: '.$decrypted_key;
  1009. return false;
  1010. }
  1011. $keyhash = md5($key);
  1012. $salt = $db->escape($keydata[3]);
  1013. return $this->validate_session_shared($keyhash, $salt, true);
  1014. }
  1015. /**
  1016. * Shared portion of session validation. Do not try to call this.
  1017. * @return array
  1018. * @access private
  1019. */
  1020. protected function validate_session_shared($key, $salt, $loose_call = false)
  1021. {
  1022. global $db, $session, $paths, $template, $plugins; // Common objects
  1023. // using a normal call to $db->sql_query to avoid failing on errors here
  1024. $columns_select = "u.user_id AS uid, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme,\n"
  1025. . " u.style,u.signature, u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_title, k.salt, k.source_ip,\n"
  1026. . " k.time, k.auth_level, k.key_type, COUNT(p.message_id) AS num_pms, u.user_timezone, u.user_dst, x.*";
  1027. $columns_groupby = "u.user_id, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme, u.style, u.signature,\n"
  1028. . " u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_timezone, u.user_title, u.user_dst,\n"
  1029. . " k.salt, k.source_ip, k.time, k.auth_level, k.key_type, x.user_id, x.user_aim, x.user_yahoo, x.user_msn,\n"
  1030. . " x.user_xmpp, x.user_homepage, x.user_location, x.user_job, x.user_hobbies, x.email_public,\n"
  1031. . " x.disable_js_fx, x.date_format, x.time_format";
  1032. $joins = " LEFT JOIN " . table_prefix . "users AS u\n"
  1033. . " ON ( u.user_id=k.user_id )\n"
  1034. . " LEFT JOIN " . table_prefix . "users_extra AS x\n"
  1035. . " ON ( u.user_id=x.user_id OR x.user_id IS NULL )\n"
  1036. . " LEFT JOIN " . table_prefix . "privmsgs AS p\n"
  1037. . " ON ( p.message_to=u.username AND p.message_read=0 )\n";
  1038. if ( !$loose_call )
  1039. {
  1040. $key_md5 = md5($key);
  1041. $query = $db->sql_query("SELECT $columns_select\n"
  1042. . "FROM " . table_prefix . "session_keys AS k\n"
  1043. . $joins
  1044. . " WHERE k.session_key='$key_md5'\n"
  1045. . " GROUP BY $columns_groupby;");
  1046. }
  1047. else
  1048. {
  1049. $query = $db->sql_query("SELECT $columns_select\n"
  1050. . "FROM " . table_prefix . "session_keys AS k\n"
  1051. . $joins
  1052. . " WHERE k.session_key='$key'\n"
  1053. . " AND k.salt='$salt'\n"
  1054. . " GROUP BY $columns_groupby;");
  1055. }
  1056. if ( !$query && ( defined('IN_ENANO_INSTALL') or defined('IN_ENANO_UPGRADE') ) )
  1057. {
  1058. $key_md5 = $loose_call ? $key : md5($key);
  1059. $query = $this->sql('SELECT u.user_id AS uid,u.username,u.password,\'\' AS password_salt,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, 1440 AS user_timezone, \'0;0;0;0;60\' AS user_dst, ' . SK_SHORT . ' AS key_type, k.salt FROM '.table_prefix.'session_keys AS k
  1060. LEFT JOIN '.table_prefix.'users AS u
  1061. ON ( u.user_id=k.user_id )
  1062. LEFT JOIN '.table_prefix.'privmsgs AS p
  1063. ON ( p.message_to=u.username AND p.message_read=0 )
  1064. WHERE k.session_key=\''.$key_md5.'\'
  1065. GROUP BY u.user_id,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,k.salt;');
  1066. }
  1067. else if ( !$query )
  1068. {
  1069. $db->_die();
  1070. }
  1071. if($db->numrows() < 1)
  1072. {
  1073. // echo '(debug) $session->validate_session: Key was not found in database: ' . $key_md5 . '<br />';
  1074. return false;
  1075. }
  1076. $row = $db->fetchrow();
  1077. profiler_log("SessionManager: session check: selected and fetched results");
  1078. $row['user_id'] =& $row['uid'];
  1079. $ip = $_SERVER['REMOTE_ADDR'];
  1080. if($row['auth_level'] > $row['user_level'])
  1081. {
  1082. // Failed authorization check
  1083. // echo '(debug) $session->validate_session: access to this auth level denied<br />';
  1084. return false;
  1085. }
  1086. if($ip != $row['source_ip'])
  1087. {
  1088. // Special exception for 1.1.x upgrade - the 1.1.3 upgrade changes the size of the column and this is what validate_session
  1089. // expects, but if the column size hasn't changed yet just check the first 10 digits of the IP.
  1090. $fail = true;
  1091. if ( defined('IN_ENANO_UPGRADE') )
  1092. {
  1093. if ( substr($ip, 0, 10) == substr($row['source_ip'], 0, 10) )
  1094. $fail = false;
  1095. }
  1096. // Failed IP address check
  1097. // echo '(debug) $session->validate_session: IP address mismatch<br />';
  1098. if ( $fail )
  1099. return false;
  1100. }
  1101. // $loose_call is turned on only from validate_aes_session
  1102. if ( !$loose_call )
  1103. {
  1104. $key_pieces = array($row['password']);
  1105. $user_id =& $row['uid'];
  1106. $sk_mode = 'validate';
  1107. $code = $plugins->setHook('session_key_calc');
  1108. foreach ( $code as $cmd )
  1109. {
  1110. eval($cmd);
  1111. }
  1112. $key_pieces = implode("\xFF", $key_pieces);
  1113. $correct_key = hexdecode(hmac_sha1($key_pieces, $row['salt']));
  1114. $user_key = hexdecode($key);
  1115. if ( $correct_key !== $user_key || !is_string($user_key) )
  1116. {
  1117. return false;
  1118. }
  1119. }
  1120. else
  1121. {
  1122. // if this is a "loose call", this only works once (during the final upgrade stage). Destroy the contents of session_keys.
  1123. if ( $row['auth_level'] == USER_LEVEL_ADMIN && preg_match('/^upg-/', enano_version()) )
  1124. $this->sql('DELETE FROM ' . table_prefix . "session_keys;");
  1125. }
  1126. // timestamp check
  1127. switch ( $row['key_type'] )
  1128. {
  1129. case SK_SHORT:
  1130. $time_now = time();
  1131. $time_key = $row['time'] + ( 60 * intval(getConfig('session_short', '720')) );
  1132. if ( $time_now > $time_key )
  1133. {
  1134. // Session timed out
  1135. return false;
  1136. }
  1137. break;
  1138. case SK_LONG:
  1139. if ( intval(getConfig('session_remember_time', '0')) === 0 )
  1140. {
  1141. // sessions last infinitely, timestamp validation is therefore successful
  1142. break;
  1143. }
  1144. $time_now = time();
  1145. $time_key = $row['time'] + ( 86400 * intval(getConfig('session_remember_time', '30')) );
  1146. if ( $time_now > $time_key )
  1147. {
  1148. // Session timed out
  1149. return false;
  1150. }
  1151. break;
  1152. case SK_ELEV:
  1153. $time_now = time();
  1154. $time_key = $row['time'] + 900;
  1155. if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
  1156. {
  1157. // Session timed out
  1158. // echo '(debug) $session->validate_session: super session timed out<br />';
  1159. $this->sw_timed_out = true;
  1160. return false;
  1161. }
  1162. break;
  1163. }
  1164. // If this is an elevated-access or short-term session key, update the time
  1165. if( $row['key_type'] == SK_ELEV || $row['key_type'] == SK_SHORT )
  1166. {
  1167. $this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.md5($key).'\';');
  1168. }
  1169. $user_extra = array();
  1170. foreach ( array('user_aim', 'user_yahoo', 'user_msn', 'user_xmpp', 'user_homepage', 'user_location', 'user_job', 'user_hobbies', 'email_public', 'disable_js_fx') as $column )
  1171. {
  1172. if ( isset($row[$column]) )
  1173. $user_extra[$column] = $row[$column];
  1174. else
  1175. $user_extra[$column] = '';
  1176. }
  1177. if ( isset($row['date_format']) )
  1178. $this->date_format = $row['date_format'];
  1179. if ( isset($row['time_format']) )
  1180. $this->time_format = $row['time_format'];
  1181. $this->user_extra = $user_extra;
  1182. // Leave the rest to PHP's automatic garbage collector ;-)
  1183. $row['password'] = '';
  1184. $row['user_timezone'] = intval($row['user_timezone']) - 1440;
  1185. profiler_log("SessionManager: finished session check");
  1186. return $row;
  1187. }
  1188. /**
  1189. * Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
  1190. * @param string $key The session key to validate
  1191. * @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.
  1192. */
  1193. function compat_validate_session($key)
  1194. {
  1195. global $db, $session, $paths, $template, $plugins; // Common objects
  1196. $key = $db->escape($key);
  1197. $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,1440 AS user_timezone FROM '.table_prefix.'session_keys AS k
  1198. LEFT JOIN '.table_prefix.'users AS u
  1199. ON u.user_id=k.user_id
  1200. WHERE k.session_key=\''.$key.'\';');
  1201. if($db->numrows() < 1)
  1202. {
  1203. // echo '(debug) $session->validate_session: Key '.$key.' was not found in database<br />';
  1204. return false;
  1205. }
  1206. $row = $db->fetchrow();
  1207. $ip = ip2hex($_SERVER['REMOTE_ADDR']);
  1208. if($row['auth_level'] > $row['user_level'])
  1209. {
  1210. // Failed authorization check
  1211. // echo '(debug) $session->validate_session: user not authorized for this access level';
  1212. return false;
  1213. }
  1214. if($ip != $row['source_ip'])
  1215. {
  1216. // Failed IP address check
  1217. // echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
  1218. return false;
  1219. }
  1220. // Do the password validation
  1221. $real_key = md5($row['password'] . $row['salt']);
  1222. //die('<pre>'.print_r($keydata, true).'</pre>');
  1223. if($real_key != $key)
  1224. {
  1225. // Failed password check
  1226. // echo '(debug) $session->validate_session: supplied password is wrong<br />Real key: '.$real_key.'<br />User key: '.$key;
  1227. return false;
  1228. }
  1229. $time_now = time();
  1230. $time_key = $row['time'] + 900;
  1231. if($time_now > $time_key && $row['auth_level'] >= 1)
  1232. {
  1233. $this->sw_timed_out = true;
  1234. // Session timed out
  1235. // echo '(debug) $session->validate_session: super session timed out<br />';
  1236. return false;
  1237. }
  1238. $row['user_timezone'] = intval($row['user_timezone']) - 1440;
  1239. return $row;
  1240. }
  1241. /**
  1242. * Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
  1243. * @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
  1244. * @return string 'success' if successful, or error on failure
  1245. */
  1246. function logout($level = USER_LEVEL_MEMBER)
  1247. {
  1248. global $db, $session, $paths, $template, $plugins; // Common objects
  1249. $ou = $this->username;
  1250. $oid = $this->user_id;
  1251. if($level > USER_LEVEL_MEMBER)
  1252. {
  1253. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1254. if(!$this->user_logged_in || $this->auth_level < ( USER_LEVEL_MEMBER + 1))
  1255. {
  1256. return 'success';
  1257. }
  1258. // Destroy elevated privileges
  1259. $keyhash = md5($this->sid_super);
  1260. $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
  1261. $this->sid_super = false;
  1262. $this->auth_level = USER_LEVEL_MEMBER;
  1263. }
  1264. else
  1265. {
  1266. if($this->user_logged_in)
  1267. {
  1268. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1269. // Completely destroy our session
  1270. if($this->auth_level > USER_LEVEL_MEMBER)
  1271. {
  1272. $this->logout(USER_LEVEL_ADMIN);
  1273. }
  1274. $this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
  1275. setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
  1276. }
  1277. }
  1278. $code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
  1279. foreach ( $code as $cmd )
  1280. {
  1281. eval($cmd);
  1282. }
  1283. return 'success';
  1284. }
  1285. # Miscellaneous stuff
  1286. /**
  1287. * Alerts the user that their account is inactive, and tells them appropriate steps to remedy the situation. Halts execution.
  1288. * @param array Return from validate_session()
  1289. */
  1290. function show_inactive_error($userdata)
  1291. {
  1292. global $db, $session, $paths, $template, $plugins; // Common objects
  1293. global $lang;
  1294. global $title;
  1295. $paths->init($title);
  1296. $language = intval(getConfig('default_language'));
  1297. $lang = new Language($language);
  1298. @setlocale(LC_ALL, $lang->lang_code);
  1299. $a = getConfig('account_activation');
  1300. switch($a)
  1301. {
  1302. case 'none':
  1303. default:
  1304. $solution = $lang->get('user_login_noact_solution_none');
  1305. break;
  1306. case 'user':
  1307. $solution = $lang->get('user_login_noact_solution_user');
  1308. break;
  1309. case 'admin':
  1310. $solution = $lang->get('user_login_noact_solution_admin');
  1311. break;
  1312. }
  1313. // admin activation request opportunity
  1314. $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'logs WHERE log_type=\'admin\' AND action=\'activ_req\' AND edit_summary=\'' . $db->escape($userdata['username']) . '\';');
  1315. if ( !$q )
  1316. $db->_die();
  1317. $can_request = ( $db->numrows() < 1 );
  1318. $db->free_result();
  1319. if ( isset($_POST['logout']) )
  1320. {
  1321. $this->sid = $_COOKIE['sid'];
  1322. $this->user_logged_in = true;
  1323. $this->user_id = intval($userdata['user_id']);
  1324. $this->username = $userdata['username'];
  1325. $this->auth_level = USER_LEVEL_MEMBER;
  1326. $this->user_level = USER_LEVEL_MEMBER;
  1327. $this->logout();
  1328. redirect(scriptPath . '/', $lang->get('user_login_noact_msg_logout_success_title'), $lang->get('user_login_noact_msg_logout_success_body'), 5);
  1329. }
  1330. if ( $can_request && !isset($_POST['activation_request']) )
  1331. {
  1332. $form = '<p>' . $lang->get('user_login_noact_msg_ask_admins') . '</p>
  1333. <form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
  1334. <p><input type="submit" name="activation_request" value="' . $lang->get('user_login_noact_btn_request_activation') . '" /> <input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
  1335. </form>';
  1336. }
  1337. else
  1338. {
  1339. if ( $can_request && isset($_POST['activation_request']) )
  1340. {
  1341. $this->admin_activation_request($userdata['username']);
  1342. $form = '<p>' . $lang->get('user_login_noact_msg_admins_just_asked') . '</p>
  1343. <form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
  1344. <p><input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
  1345. </form>';
  1346. }
  1347. else
  1348. {
  1349. $form = '<p>' . $lang->get('user_login_noact_msg_admins_asked') . '</p>
  1350. <form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
  1351. <p><input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
  1352. </form>';
  1353. }
  1354. }
  1355. global $output;
  1356. $output = new Output_HTML();
  1357. $output->set_title($lang->get('user_login_noact_title'));
  1358. die_friendly($lang->get('user_login_noact_title'), '<p>' . $lang->get('user_login_noact_msg_intro') . ' '.$solution.'</p>' . $form);
  1359. }
  1360. /**
  1361. * Appends the high-privilege session key to the URL if we are authorized to do high-privilege stuff
  1362. * @param string $url The URL to add session data to
  1363. * @return string
  1364. */
  1365. function append_sid($url)
  1366. {
  1367. $sep = ( strstr($url, '?') ) ? '&' : '?';
  1368. if ( $this->sid_super )
  1369. {
  1370. $url = $url . $sep . 'auth=' . urlencode($this->sid_super);
  1371. // echo($this->sid_super.'<br/>');
  1372. }
  1373. return $url;
  1374. }
  1375. /**
  1376. * Prevent the user from changing their password. Authentication plugins may call this to enforce single sign-on.
  1377. * @param string URL to page where the user may change their password
  1378. * @param string Title of the page where the user may change their password
  1379. * @return null
  1380. */
  1381. function disable_password_change($change_url = false, $change_title = false)
  1382. {
  1383. if ( $this->password_change_disabled )
  1384. {
  1385. // don't allow calling twice. if we have two plugins doing this, somebody is bad at configuring websites.
  1386. return false;
  1387. }
  1388. if ( is_string($change_url) && is_string($change_title) )
  1389. {
  1390. $this->password_change_dest = array(
  1391. 'url' => $change_url,
  1392. 'title' => $change_title
  1393. );
  1394. }
  1395. else
  1396. {
  1397. $this->password_change_dest = array(
  1398. 'url' => false,
  1399. 'title' => false
  1400. );
  1401. }
  1402. $this->password_change_disabled = true;
  1403. }
  1404. /**
  1405. * Grabs the user's password MD5 - NOW DEPRECATED AND DISABLED.
  1406. * @return bool false
  1407. */
  1408. function grab_password_hash()
  1409. {
  1410. return false;
  1411. }
  1412. /**
  1413. * Destroys the user's password MD5 in memory
  1414. */
  1415. function disallow_password_grab()
  1416. {
  1417. $this->password_hash = false;
  1418. return false;
  1419. }
  1420. /**
  1421. * Generates an AES key and stashes it in the database
  1422. * @return string Hex-encoded AES key
  1423. */
  1424. static function rijndael_genkey()
  1425. {
  1426. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1427. $key = $aes->gen_readymade_key();
  1428. $keys = getConfig('login_key_cache');
  1429. if(is_string($keys))
  1430. $keys .= $key;
  1431. else
  1432. $keys = $key;
  1433. setConfig('login_key_cache', $keys);
  1434. return $key;
  1435. }
  1436. /**
  1437. * Generate a totally random 128-bit value for MD5 challenges
  1438. * @return string
  1439. */
  1440. static function dss_rand()
  1441. {
  1442. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1443. $random = $aes->randkey(128);
  1444. unset($aes);
  1445. return md5(microtime() . $random);
  1446. }
  1447. /**
  1448. * Fetch a cached login public key using the MD5sum as an identifier. Each key can only be fetched once before it is destroyed.
  1449. * @param string $md5 The MD5 sum of the key
  1450. * @return string, or bool false on failure
  1451. */
  1452. function fetch_public_key($md5)
  1453. {
  1454. $keys = getConfig('login_key_cache');
  1455. $keys = enano_str_split($keys, AES_BITS / 4);
  1456. foreach($keys as $i => $k)
  1457. {
  1458. if(md5($k) == $md5)
  1459. {
  1460. unset($keys[$i]);
  1461. if(count($keys) > 0)
  1462. {
  1463. if ( strlen(getConfig('login_key_cache') ) > 64000 )
  1464. {
  1465. // This should only need to be done once every month or so for an average-size site
  1466. setConfig('login_key_cache', '');
  1467. }
  1468. else
  1469. {
  1470. $keys = implode('', array_values($keys));
  1471. setConfig('login_key_cache', $keys);
  1472. }
  1473. }
  1474. else
  1475. {
  1476. setConfig('login_key_cache', '');
  1477. }
  1478. return $k;
  1479. }
  1480. }
  1481. // Couldn't find the key...
  1482. return false;
  1483. }
  1484. /**
  1485. * Adds a user to a group.
  1486. * @param int User ID
  1487. * @param int Group ID
  1488. * @param bool Group moderator - defaults to false
  1489. * @return bool True on success, false on failure
  1490. */
  1491. function add_user_to_group($user_id, $group_id, $is_mod = false)
  1492. {
  1493. global $db, $session, $paths, $template, $plugins; // Common objects
  1494. // Validation
  1495. if ( !is_int($user_id) || !is_int($group_id) || !is_bool($is_mod) )
  1496. return false;
  1497. if ( $user_id < 1 || $group_id < 1 )
  1498. return false;
  1499. $mod_switch = ( $is_mod ) ? '1' : '0';
  1500. $q = $this->sql('SELECT member_id,is_mod FROM '.table_prefix.'group_members WHERE user_id=' . $user_id . ' AND group_id=' . $group_id . ';');
  1501. if ( !$q )
  1502. $db->_die();
  1503. if ( $db->numrows() < 1 )
  1504. {
  1505. // User is not in group
  1506. $this->sql('INSERT INTO '.table_prefix.'group_members(user_id,group_id,is_mod) VALUES(' . $user_id . ', ' . $group_id . ', ' . $mod_switch . ');');
  1507. return true;
  1508. }
  1509. else
  1510. {
  1511. $row = $db->fetchrow();
  1512. // Update modship status
  1513. if ( strval($row['is_mod']) == $mod_switch )
  1514. {
  1515. // Modship unchanged
  1516. return true;
  1517. }
  1518. else
  1519. {
  1520. // Modship changed
  1521. $this->sql('UPDATE '.table_prefix.'group_members SET is_mod=' . $mod_switch . ' WHERE member_id=' . $row['member_id'] . ';');
  1522. return true;
  1523. }
  1524. }
  1525. return false;
  1526. }
  1527. /**
  1528. * Removes a user from a group.
  1529. * @param int User ID
  1530. * @param int Group ID
  1531. * @return bool True on success, false on failure
  1532. * @todo put a little more error checking in...
  1533. */
  1534. function remove_user_from_group($user_id, $group_id)
  1535. {
  1536. if ( !is_int($user_id) || !is_int($group_id) )
  1537. return false;
  1538. $this->sql('DELETE FROM '.table_prefix."group_members WHERE user_id=$user_id AND group_id=$group_id;");
  1539. return true;
  1540. }
  1541. /**
  1542. * Checks the banlist to ensure that we're an allowed user. Doesn't return anything because it dies if the user is banned.
  1543. */
  1544. function check_banlist()
  1545. {
  1546. global $db, $session, $paths, $template, $plugins; // Common objects
  1547. global $lang;
  1548. $col_reason = ( $this->compat ) ? '\'No reason available (session manager is in compatibility mode)\' AS reason' : 'reason';
  1549. $remote_addr = ( strstr($_SERVER['REMOTE_ADDR'], ':') ) ? expand_ipv6_address($_SERVER['REMOTE_ADDR']) : $_SERVER['REMOTE_ADDR'];
  1550. $banned = false;
  1551. if ( $this->user_logged_in )
  1552. {
  1553. // check by IP, email, and username
  1554. if ( ENANO_DBLAYER == 'MYSQL' )
  1555. {
  1556. $sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE \n"
  1557. . " ( ban_type = " . BAN_IP . " AND is_regex = 0 ) OR \n"
  1558. . " ( ban_type = " . BAN_IP . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' REGEXP ban_value ) OR \n"
  1559. . " ( ban_type = " . BAN_USER . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->username) . "' ) OR \n"
  1560. . " ( ban_type = " . BAN_USER . " AND is_regex = 1 AND '" . $db->escape($this->username) . "' REGEXP ban_value ) OR \n"
  1561. . " ( ban_type = " . BAN_EMAIL . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->email) . "' ) OR \n"
  1562. . " ( ban_type = " . BAN_EMAIL . " AND is_regex = 1 AND '" . $db->escape($this->email) . "' REGEXP ban_value ) \n"
  1563. . " ORDER BY ban_type ASC;";
  1564. }
  1565. else if ( ENANO_DBLAYER == 'PGSQL' )
  1566. {
  1567. $sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE \n"
  1568. . " ( ban_type = " . BAN_IP . " AND is_regex = 0 ) OR \n"
  1569. . " ( ban_type = " . BAN_IP . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' ~ ban_value ) OR \n"
  1570. . " ( ban_type = " . BAN_USER . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->username) . "' ) OR \n"
  1571. . " ( ban_type = " . BAN_USER . " AND is_regex = 1 AND '" . $db->escape($this->username) . "' ~ ban_value ) OR \n"
  1572. . " ( ban_type = " . BAN_EMAIL . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->email) . "' ) OR \n"
  1573. . " ( ban_type = " . BAN_EMAIL . " AND is_regex = 1 AND '" . $db->escape($this->email) . "' ~ ban_value ) \n"
  1574. . " ORDER BY ban_type ASC;";
  1575. }
  1576. $q = $this->sql($sql);
  1577. if ( $db->numrows() > 0 )
  1578. {
  1579. while ( list($reason_temp, $ban_value, $ban_type, $is_regex) = $db->fetchrow_num() )
  1580. {
  1581. if ( $ban_type == BAN_IP && $is_regex != 1 )
  1582. {
  1583. // check range
  1584. $regexp = parse_ip_range_regex($ban_value);
  1585. if ( !$regexp )
  1586. {
  1587. continue;
  1588. }
  1589. if ( preg_match("/$regexp/", $remote_addr) )
  1590. {
  1591. $reason = $reason_temp;
  1592. $banned = true;
  1593. }
  1594. }
  1595. else
  1596. {
  1597. // User is banned
  1598. $banned = true;
  1599. $reason = $reason_temp;
  1600. }
  1601. }
  1602. }
  1603. $db->free_result();
  1604. }
  1605. else
  1606. {
  1607. // check by IP only
  1608. if ( ENANO_DBLAYER == 'MYSQL' )
  1609. {
  1610. $sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE
  1611. ( ban_type = " . BAN_IP . " AND is_regex = 0 ) OR
  1612. ( ban_type = " . BAN_IP . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' REGEXP ban_value )
  1613. ORDER BY ban_type ASC;";
  1614. }
  1615. else if ( ENANO_DBLAYER == 'PGSQL' )
  1616. {
  1617. $sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE
  1618. ( ban_type = " . BAN_IP . " AND is_regex = 0 ) OR
  1619. ( ban_type = " . BAN_IP . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' ~ ban_value )
  1620. ORDER BY ban_type ASC;";
  1621. }
  1622. $q = $this->sql($sql);
  1623. if ( $db->numrows() > 0 )
  1624. {
  1625. while ( list($reason_temp, $ban_value, $ban_type, $is_regex) = $db->fetchrow_num() )
  1626. {
  1627. if ( $ban_type == BAN_IP && $is_regex != 1 )
  1628. {
  1629. // check range
  1630. $regexp = parse_ip_range_regex($ban_value);
  1631. if ( !$regexp )
  1632. {
  1633. die("bad regexp for $ban_value");
  1634. continue;
  1635. }
  1636. if ( preg_match("/$regexp/", $remote_addr) )
  1637. {
  1638. $reason = $reason_temp;
  1639. $banned = true;
  1640. }
  1641. }
  1642. else
  1643. {
  1644. // User is banned
  1645. $reason = $reason_temp;
  1646. $banned = true;
  1647. }
  1648. }
  1649. }
  1650. $db->free_result();
  1651. }
  1652. if ( $banned && !$this->on_critical_page(true) )
  1653. {
  1654. // This guy is banned - kill the session, kill the database connection, bail out, and be pretty about it
  1655. die_semicritical($lang->get('user_ban_msg_title'), '<p>' . $lang->get('user_ban_msg_body') . '</p><div class="error-box"><b>' . $lang->get('user_ban_lbl_reason') . '</b><br />' . $reason . '</div>');
  1656. exit;
  1657. }
  1658. }
  1659. # Registration
  1660. /**
  1661. * Registers a user. This does not perform any type of login.
  1662. * @param string New user's username
  1663. * @param string This should be unencrypted.
  1664. * @param string E-mail address.
  1665. * @param string Optional, defaults to ''.
  1666. * @param bool 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.
  1667. */
  1668. function create_user($username, $password, $email, $real_name = '', $coppa = false)
  1669. {
  1670. global $db, $session, $paths, $template, $plugins; // Common objects
  1671. global $lang;
  1672. // Initialize AES
  1673. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  1674. // Since we're recording IP addresses, make sure the user's IP is safe.
  1675. $ip =& $_SERVER['REMOTE_ADDR'];
  1676. if ( !is_valid_ip($ip) )
  1677. return 'Invalid IP';
  1678. if ( !preg_match('#^'.$this->valid_username.'$#', $username) )
  1679. return $lang->get('user_reg_err_username_banned_chars');
  1680. $username = str_replace('_', ' ', $username);
  1681. $user_orig = $username;
  1682. $username = $this->prepare_text($username);
  1683. $email = $this->prepare_text($email);
  1684. $real_name = $this->prepare_text($real_name);
  1685. $nameclause = ( $real_name != '' ) ? ' OR real_name=\''.$real_name.'\'' : '';
  1686. $q = $this->sql('SELECT * FROM '.table_prefix.'users WHERE ' . ENANO_SQLFUNC_LOWERCASE . '(username)=\''.strtolower($username).'\' OR email=\''.$email.'\''.$nameclause.';');
  1687. if($db->numrows() > 0)
  1688. {
  1689. $row = $db->fetchrow();
  1690. $str = 'user_reg_err_dupe';
  1691. if ( $row['username'] == $username )
  1692. {
  1693. $str .= '_username';
  1694. }
  1695. if ( $row['email'] == $email )
  1696. {
  1697. $str .= '_email';
  1698. }
  1699. if ( $row['real_name'] == $real_name && $real_name != '' )
  1700. {
  1701. $str .= '_realname';
  1702. }
  1703. return $lang->get($str);
  1704. }
  1705. // Is the password strong enough?
  1706. if ( getConfig('pw_strength_enable') )
  1707. {
  1708. $min_score = intval( getConfig('pw_strength_minimum') );
  1709. $pass_score = password_score($password);
  1710. if ( $pass_score < $min_score )
  1711. {
  1712. return $lang->get('user_reg_err_password_too_weak');
  1713. }
  1714. }
  1715. // Require the account to be activated?
  1716. switch(getConfig('account_activation'))
  1717. {
  1718. case 'none':
  1719. default:
  1720. $active = '1';
  1721. break;
  1722. case 'user':
  1723. $active = '0';
  1724. break;
  1725. case 'admin':
  1726. $active = '0';
  1727. break;
  1728. }
  1729. if ( $coppa )
  1730. $active = '0';
  1731. $coppa_col = ( $coppa ) ? '1' : '0';
  1732. // Generate a totally random activation key
  1733. $actkey = sha1 ( microtime() . mt_rand() );
  1734. // We good, create the user
  1735. $this->sql('INSERT INTO ' . table_prefix . "users ( username, email, real_name, theme, style, reg_time, account_active, activation_key, user_level, user_coppa,\n"
  1736. . " user_registration_ip, user_lang, user_has_avatar, avatar_type ) VALUES\n"
  1737. . " ( '$username', '$email', '$real_name', '$template->default_theme', '$template->default_style', " . time() . ", $active, '$actkey', \n"
  1738. . " " . USER_LEVEL_CHPREF . ", $coppa_col, '$ip', $lang->lang_id, 0, 'png' );");
  1739. // Get user ID and create users_extra entry
  1740. $q = $this->sql('SELECT user_id FROM '.table_prefix."users WHERE username='$username';");
  1741. if ( $db->numrows() > 0 )
  1742. {
  1743. list($user_id) = $db->fetchrow_num();
  1744. $db->free_result();
  1745. $this->sql('INSERT INTO '.table_prefix.'users_extra(user_id) VALUES(' . $user_id . ');');
  1746. }
  1747. // Set the password
  1748. $this->set_password($user_id, $password);
  1749. // Config option added, 1.1.5
  1750. if ( getConfig('userpage_grant_acl', '1') == '1' )
  1751. {
  1752. // Grant edit and very limited mod access to the userpage
  1753. $acl_data = array(
  1754. 'read' => AUTH_ALLOW,
  1755. 'view_source' => AUTH_ALLOW,
  1756. 'edit_page' => AUTH_ALLOW,
  1757. 'post_comments' => AUTH_ALLOW,
  1758. 'edit_comments' => AUTH_ALLOW, // only allows editing own comments
  1759. 'history_view' => AUTH_ALLOW,
  1760. 'history_rollback' => AUTH_ALLOW,
  1761. 'rename' => AUTH_ALLOW,
  1762. 'delete_page' => AUTH_ALLOW,
  1763. 'tag_create' => AUTH_ALLOW,
  1764. 'tag_delete_own' => AUTH_ALLOW,
  1765. 'tag_delete_other' => AUTH_ALLOW,
  1766. 'edit_cat' => AUTH_ALLOW,
  1767. 'create_page' => AUTH_ALLOW
  1768. );
  1769. $acl_data = $db->escape($this->perm_to_string($acl_data));
  1770. $userpage = $db->escape(sanitize_page_id($user_orig));
  1771. $cols = "target_type, target_id, page_id, namespace, rules";
  1772. $vals = ACL_TYPE_USER . ", $user_id, '$userpage', 'User', '$acl_data'";
  1773. $q = "INSERT INTO ".table_prefix."acl($cols) VALUES($vals);";
  1774. $this->sql($q);
  1775. }
  1776. // Require the account to be activated?
  1777. if ( $coppa )
  1778. {
  1779. $this->admin_activation_request($user_orig);
  1780. $this->send_coppa_mail($user_orig, $email);
  1781. }
  1782. else
  1783. {
  1784. switch(getConfig('account_activation'))
  1785. {
  1786. case 'none':
  1787. default:
  1788. break;
  1789. case 'user':
  1790. $a = $this->send_activation_mail($user_orig);
  1791. if(!$a)
  1792. {
  1793. $this->admin_activation_request($user_orig);
  1794. return $lang->get('user_reg_err_actmail_failed') . ' ' . $a;
  1795. }
  1796. break;
  1797. case 'admin':
  1798. $this->admin_activation_request($user_orig);
  1799. break;
  1800. }
  1801. }
  1802. // Leave some data behind for the hook
  1803. $code = $plugins->setHook('user_registered');
  1804. foreach ( $code as $cmd )
  1805. {
  1806. eval($cmd);
  1807. }
  1808. return 'success';
  1809. }
  1810. /**
  1811. * Attempts to send an e-mail to the specified user with activation instructions.
  1812. * @param string $u The usernamd of the user requesting activation
  1813. * @return bool true on success, false on failure
  1814. */
  1815. function send_activation_mail($u, $actkey = false)
  1816. {
  1817. global $db, $session, $paths, $template, $plugins; // Common objects
  1818. global $lang;
  1819. $q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
  1820. $r = $db->fetchrow();
  1821. if ( empty($r['email']) )
  1822. $db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
  1823. $aklink = makeUrlComplete('Special', 'ActivateAccount/'.str_replace(' ', '_', $u).'/'. ( ( is_string($actkey) ) ? $actkey : $r['activation_key'] ) );
  1824. $message = $lang->get('user_reg_activation_email', array(
  1825. 'activation_link' => $aklink,
  1826. 'username' => $u
  1827. ));
  1828. if ( getConfig('smtp_enabled') == '1' )
  1829. {
  1830. $result = smtp_send_email($r['email'], $lang->get('user_reg_activation_email_subject'), preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
  1831. if ( $result == 'success' )
  1832. {
  1833. $result = true;
  1834. }
  1835. else
  1836. {
  1837. echo $result;
  1838. $result = false;
  1839. }
  1840. }
  1841. else
  1842. {
  1843. $result = mail($r['email'], $lang->get('user_reg_activation_email_subject'), preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
  1844. }
  1845. return $result;
  1846. }
  1847. /**
  1848. * Attempts to send an e-mail to the specified user's e-mail address on file intended for the parents
  1849. * @param string $u The usernamd of the user requesting activation
  1850. * @return bool true on success, false on failure
  1851. */
  1852. function send_coppa_mail($u, $actkey = false)
  1853. {
  1854. global $db, $session, $paths, $template, $plugins; // Common objects
  1855. global $lang;
  1856. $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;');
  1857. $un = $db->fetchrow();
  1858. $admin_user = $un['username'];
  1859. $q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
  1860. $r = $db->fetchrow();
  1861. if ( empty($r['email']) )
  1862. $db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
  1863. if(isset($_SERVER['HTTPS'])) $prot = 'https';
  1864. else $prot = 'http';
  1865. if($_SERVER['SERVER_PORT'] == '80') $p = '';
  1866. else $p = ':'.$_SERVER['SERVER_PORT'];
  1867. $sidbak = false;
  1868. if($this->sid_super)
  1869. $sidbak = $this->sid_super;
  1870. $this->sid_super = false;
  1871. if($sidbak)
  1872. $this->sid_super = $sidbak;
  1873. unset($sidbak);
  1874. $link = "$prot://".$_SERVER['HTTP_HOST'].scriptPath;
  1875. $message = $lang->get(
  1876. 'user_reg_activation_email_coppa',
  1877. array(
  1878. 'username' => $u,
  1879. 'admin_user' => $admin_user,
  1880. 'site_link' => $link
  1881. )
  1882. );
  1883. if(getConfig('smtp_enabled') == '1')
  1884. {
  1885. $result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
  1886. if($result == 'success')
  1887. {
  1888. $result = true;
  1889. }
  1890. else
  1891. {
  1892. echo $result;
  1893. $result = false;
  1894. }
  1895. }
  1896. else
  1897. {
  1898. $result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
  1899. }
  1900. return $result;
  1901. }
  1902. /**
  1903. * Sends an e-mail to a user so they can reset their password.
  1904. * @param int $user The user ID, or username if it's a string
  1905. * @return bool true on success, false on failure
  1906. */
  1907. function mail_password_reset($user)
  1908. {
  1909. global $db, $session, $paths, $template, $plugins; // Common objects
  1910. global $lang;
  1911. if(is_int($user))
  1912. {
  1913. $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
  1914. }
  1915. elseif(is_string($user))
  1916. {
  1917. $q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE ' . ENANO_SQLFUNC_LOWERCASE . '(username)=' . ENANO_SQLFUNC_LOWERCASE . '(\''.$db->escape($user).'\');');
  1918. }
  1919. else
  1920. {
  1921. return false;
  1922. }
  1923. $row = $db->fetchrow();
  1924. $temp_pass = $this->random_pass();
  1925. // check the seclog
  1926. $ts = time() - 15;
  1927. // Prevent resets on the same UID or from the same IP
  1928. // FIXME: Qatar
  1929. // (http://www.reddit.com/r/todayilearned/comments/k27x6/til_that_the_entire_nation_of_qatar_has_a_single/)
  1930. $q = $this->sql('SELECT log_id, time_id FROM ' . table_prefix . "logs WHERE log_type = 'security' AND action = 'pass_reset' AND ( edit_summary = '{$_SERVER['REMOTE_ADDR']}' OR author_uid = {$row['user_id']} ) AND time_id > $ts;");
  1931. if ( $db->numrows($q) > 0 )
  1932. {
  1933. // rate limit exceeded... one password reset request every 15 seconds is not appropriate
  1934. $db->free_result();
  1935. return false;
  1936. }
  1937. $db->free_result();
  1938. $now = time();
  1939. $uname = $db->escape($row['username']);
  1940. $this->sql('INSERT INTO ' . table_prefix . 'logs ( time_id, log_type, action, author, author_uid, edit_summary ) VALUES'
  1941. . "($now, 'security', 'pass_reset', '$uname', {$row['user_id']}, '{$_SERVER['REMOTE_ADDR']}');");
  1942. $this->register_temp_password($row['user_id'], $temp_pass);
  1943. $site_name = getConfig('site_name');
  1944. $message = $lang->get('userfuncs_passreset_email', array(
  1945. 'username' => $row['username'],
  1946. 'site_name' => $site_name,
  1947. 'remote_addr' => $_SERVER['REMOTE_ADDR'],
  1948. 'temp_pass' => $temp_pass
  1949. ));
  1950. if(getConfig('smtp_enabled') == '1')
  1951. {
  1952. $result = smtp_send_email($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
  1953. if($result == 'success')
  1954. {
  1955. $result = true;
  1956. }
  1957. else
  1958. {
  1959. echo '<p>'.$result.'</p>';
  1960. $result = false;
  1961. }
  1962. } else {
  1963. $result = mail($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
  1964. }
  1965. return $result;
  1966. }
  1967. /**
  1968. * Sets the temporary password for the specified user to whatever is specified.
  1969. * @param int $user_id
  1970. * @param string $password
  1971. * @return bool
  1972. */
  1973. function register_temp_password($user_id, $password)
  1974. {
  1975. global $db;
  1976. if ( !is_int($user_id) )
  1977. return false;
  1978. $this->sql('SELECT password_salt FROM ' . table_prefix . "users WHERE user_id = $user_id;");
  1979. if ( $db->numrows() < 1 )
  1980. return false;
  1981. list($salt) = $db->fetchrow_num();
  1982. $db->free_result();
  1983. $temp_pass = hmac_sha1($password, $salt);
  1984. $this->sql('UPDATE '.table_prefix.'users SET temp_password=\'' . $temp_pass . '\',temp_password_time='.time().' WHERE user_id='.intval($user_id).';');
  1985. }
  1986. /**
  1987. * Sends a request to the admin panel to have the username $u activated.
  1988. * @param string $u The username of the user requesting activation
  1989. */
  1990. function admin_activation_request($u)
  1991. {
  1992. global $db;
  1993. $this->sql('INSERT INTO '.table_prefix.'logs(log_type, action, time_id, date_string, author, edit_summary) VALUES(\'admin\', \'activ_req\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$this->username.'\', \''.$db->escape($u).'\');');
  1994. }
  1995. /**
  1996. * Activates a user account. If the action fails, a report is sent to the admin.
  1997. * @param string $user The username of the user requesting activation
  1998. * @param string $key The activation key
  1999. */
  2000. function activate_account($user, $key)
  2001. {
  2002. global $db, $session, $paths, $template, $plugins; // Common objects
  2003. $q = $this->sql('SELECT 1 FROM ' . table_prefix . 'users WHERE username = \''.$db->escape($user).'\' AND activation_key = \''.$db->escape($key).'\'');
  2004. if ( $db->numrows() > 0 )
  2005. {
  2006. $new_key = md5(AESCrypt::randkey());
  2007. $this->sql('UPDATE ' . table_prefix . 'users SET account_active = 1, activation_key = \'' . $new_key . '\' WHERE username=\''.$db->escape($user).'\' AND activation_key=\''.$db->escape($key).'\';');
  2008. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
  2009. return true;
  2010. }
  2011. else
  2012. {
  2013. $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
  2014. return false;
  2015. }
  2016. }
  2017. /**
  2018. * For a given user level identifier (USER_LEVEL_*), returns a string describing that user level.
  2019. * @param int User level
  2020. * @param bool If true, returns a shorter string. Optional.
  2021. * @return string
  2022. */
  2023. function userlevel_to_string($user_level, $short = false)
  2024. {
  2025. global $lang;
  2026. static $levels = array(
  2027. 'short' => array(
  2028. USER_LEVEL_GUEST => 'Guest',
  2029. USER_LEVEL_MEMBER => 'Member',
  2030. USER_LEVEL_CHPREF => 'Sensitive preferences changeable',
  2031. USER_LEVEL_MOD => 'Moderator',
  2032. USER_LEVEL_ADMIN => 'Administrative'
  2033. ),
  2034. 'long' => array(
  2035. USER_LEVEL_GUEST => 'Low - guest privileges',
  2036. USER_LEVEL_MEMBER => 'Standard - normal member level',
  2037. USER_LEVEL_CHPREF => 'Medium - user can change his/her own e-mail address and password',
  2038. USER_LEVEL_MOD => 'High - moderator privileges',
  2039. USER_LEVEL_ADMIN => 'Highest - administrative privileges'
  2040. ),
  2041. 'l10n' => false
  2042. );
  2043. if ( is_object($lang) && !$levels['l10n'] )
  2044. {
  2045. $levels = array(
  2046. 'short' => array(
  2047. USER_LEVEL_GUEST => $lang->get('user_level_short_guest'),
  2048. USER_LEVEL_MEMBER => $lang->get('user_level_short_member'),
  2049. USER_LEVEL_CHPREF => $lang->get('user_level_short_chpref'),
  2050. USER_LEVEL_MOD => $lang->get('user_level_short_mod'),
  2051. USER_LEVEL_ADMIN => $lang->get('user_level_short_admin')
  2052. ),
  2053. 'long' => array(
  2054. USER_LEVEL_GUEST => $lang->get('user_level_long_guest'),
  2055. USER_LEVEL_MEMBER => $lang->get('user_level_long_member'),
  2056. USER_LEVEL_CHPREF => $lang->get('user_level_long_chpref'),
  2057. USER_LEVEL_MOD => $lang->get('user_level_long_mod'),
  2058. USER_LEVEL_ADMIN => $lang->get('user_level_long_admin')
  2059. ),
  2060. 'l10n' => true
  2061. );
  2062. }
  2063. $key = ( $short ) ? 'short' : 'long';
  2064. if ( isset($levels[$key][$user_level]) )
  2065. {
  2066. return $levels[$key][$user_level];
  2067. }
  2068. else
  2069. {
  2070. if ( $short )
  2071. {
  2072. return ( is_object($lang) ) ? $lang->get('user_level_short_unknown', array('user_level' => $user_level)) : "Unknown - $user_level";
  2073. }
  2074. else
  2075. {
  2076. return ( is_object($lang) ) ? $lang->get('user_level_long_unknown', array('user_level' => $user_level)) : "Unknown level ($user_level)";
  2077. }
  2078. }
  2079. return 'Linux rocks!';
  2080. }
  2081. /**
  2082. * Change a user's e-mail address.
  2083. * @param int $user_id The user ID of the user to update - this cannot be changed
  2084. * @param string $email The new e-mail address
  2085. * @return string 'success' if successful, or array of error strings on failure
  2086. */
  2087. function change_email($user_id, $email)
  2088. {
  2089. global $db, $session, $paths, $template, $plugins; // Common objects
  2090. // Create some arrays
  2091. $errors = array(); // Used to hold error strings
  2092. // Scan the user ID for problems
  2093. if ( intval($user_id) < 1 )
  2094. $errors[] = 'SQL injection attempt';
  2095. $user_id = intval($user_id);
  2096. // Verify e-mail address
  2097. if ( !check_email_address($email) )
  2098. $errors[] = 'user_err_email_not_valid';
  2099. if ( count($errors) > 0 )
  2100. return $errors;
  2101. // Make query
  2102. $email = $db->escape($email);
  2103. $q = $db->sql_query('UPDATE ' . table_prefix . "users SET email = '$email' WHERE user_id = $user_id;");
  2104. // We also need to trigger re-activation.
  2105. switch(getConfig('account_activation', 'none'))
  2106. {
  2107. case 'user':
  2108. case 'admin':
  2109. // Note: even with admin activation, activation e-mails are sent when an e-mail is changed.
  2110. if ( $session->user_level >= USER_LEVEL_MOD && getConfig('account_activation') == 'admin' )
  2111. // Trust admins and moderators
  2112. break;
  2113. // retrieve username
  2114. if ( !$username )
  2115. {
  2116. $q = $this->sql('SELECT username FROM ' . table_prefix . "users WHERE user_id = $user_id;");
  2117. if($db->numrows() < 1)
  2118. {
  2119. $errors[] = 'The username could not be selected.';
  2120. }
  2121. else
  2122. {
  2123. $row = $db->fetchrow();
  2124. $username = $row['username'];
  2125. }
  2126. }
  2127. if ( !$username )
  2128. return $errors;
  2129. // Generate an activation key
  2130. $actkey = sha1 ( microtime() . mt_rand() );
  2131. $a = $this->send_activation_mail($username, $actkey);
  2132. if(!$a)
  2133. {
  2134. $this->admin_activation_request($username);
  2135. }
  2136. // Deactivate the account until e-mail is confirmed
  2137. $q = $db->sql_query('UPDATE ' . table_prefix . "users SET account_active = 0, activation_key = '$actkey' WHERE user_id = $user_id;");
  2138. break;
  2139. }
  2140. // Yay! We're done
  2141. return 'success';
  2142. }
  2143. /**
  2144. * Sets a user's password.
  2145. * @param int|string User ID or username
  2146. * @param string New password
  2147. */
  2148. function set_password($user, $password)
  2149. {
  2150. // Generate new password and salt
  2151. $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
  2152. $password_hmac = hmac_sha1($password, $hmac_secret);
  2153. // Figure out how we want to specify the user
  2154. $uidcol = is_int($user) ? "user_id = $user" : ENANO_SQLFUNC_LOWERCASE . "(username) = '" . strtolower($this->prepare_text($user)) . "'";
  2155. // Perform update
  2156. $this->sql('UPDATE ' . table_prefix . "users SET old_encryption = 0, password = '$password_hmac', password_salt = '$hmac_secret' WHERE $uidcol;");
  2157. return true;
  2158. }
  2159. /**
  2160. * Encrypts a string using the site's private key.
  2161. * @param string
  2162. * @param int Return type - one of ENC_BINARY, ENC_HEX, ENC_BASE64
  2163. * @return string
  2164. */
  2165. function pk_encrypt($string, $return_type = ENC_HEX)
  2166. {
  2167. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  2168. return $aes->encrypt($string, $this->private_key, $return_type);
  2169. }
  2170. /**
  2171. * Encrypts a string using the site's private key.
  2172. * @param string
  2173. * @param int Input type - one of ENC_BINARY, ENC_HEX, ENC_BASE64
  2174. * @return string
  2175. */
  2176. function pk_decrypt($string, $input_type = ENC_HEX)
  2177. {
  2178. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  2179. return $aes->decrypt($string, $this->private_key, $input_type);
  2180. }
  2181. #
  2182. # USER RANKS
  2183. #
  2184. /**
  2185. * SYNOPSIS OF THE RANK SYSTEM
  2186. * Enano's rank logic calculates a user's rank based on a precedence scale. The way things are checked is:
  2187. * 1. Check to see if the user has a specific rank assigned. Use that if possible.
  2188. * 2. Check the user's primary group to see if it specifies a rank. Use that if possible.
  2189. * 3. Check the other groups a user is in. If one that has a custom rank is encountered, use that rank.
  2190. * 4. See if the user's user level has a specific rank hard-coded to be associated with it. (Always overrideable as can be seen above)
  2191. * 5. Use the "member" rank
  2192. */
  2193. /**
  2194. * Generates a textual SQL query for fetching rank data to be sent to calculate_user_rank().
  2195. * @param string Text to append, possibly a WHERE clause or so
  2196. * @return string
  2197. */
  2198. function generate_rank_sql($append = '')
  2199. {
  2200. // Generate level-to-rank associations
  2201. $assoc = array();
  2202. foreach ( $this->level_rank_table as $level => $rank )
  2203. {
  2204. $assoc[] = " ( u.user_level = $level AND rl.rank_id = $rank )";
  2205. }
  2206. $assoc = implode(" OR\n", $assoc) . "\n";
  2207. $gid_col = ( ENANO_DBLAYER == 'PGSQL' ) ?
  2208. 'array_to_string(' . table_prefix . 'array_accum(m.group_id), \',\') AS group_list' :
  2209. 'GROUP_CONCAT(m.group_id) AS group_list';
  2210. // The actual query
  2211. $sql = "SELECT u.user_id, u.username, u.user_level, u.user_group, u.user_rank, u.user_title, g.group_rank,\n"
  2212. . " COALESCE(ru.rank_id, rg.rank_id, rl.rank_id, rd.rank_id ) AS rank_id,\n"
  2213. . " COALESCE(ru.rank_title, rg.rank_title, rl.rank_title, rd.rank_title) AS rank_title,\n"
  2214. . " COALESCE(ru.rank_style, rg.rank_style, rl.rank_style, rd.rank_style) AS rank_style,\n"
  2215. . " rg.rank_id AS group_rank_id,\n"
  2216. . " ( ru.rank_id IS NULL AND rg.rank_id IS NULL ) AS using_default,\n"
  2217. . " ( ru.rank_id IS NULL AND rg.rank_id IS NOT NULL ) AS using_group,\n"
  2218. . " ( ru.rank_id IS NOT NULL ) AS using_user,\n"
  2219. . " u.user_rank_userset,\n"
  2220. . " $gid_col\n"
  2221. . " FROM " . table_prefix . "users AS u\n"
  2222. . " LEFT JOIN " . table_prefix . "groups AS g\n"
  2223. . " ON ( g.group_id = u.user_group )\n"
  2224. . " LEFT JOIN " . table_prefix . "group_members AS m\n"
  2225. . " ON ( u.user_id = m.user_id AND m.pending < 1 )\n"
  2226. . " LEFT JOIN " . table_prefix . "ranks AS ru\n"
  2227. . " ON ( u.user_rank = ru.rank_id )\n"
  2228. . " LEFT JOIN " . table_prefix . "ranks AS rg\n"
  2229. . " ON ( g.group_rank = rg.rank_id )\n"
  2230. . " LEFT JOIN " . table_prefix . "ranks AS rl\n"
  2231. . " ON (\n"
  2232. . $assoc
  2233. . " )\n"
  2234. . " LEFT JOIN " . table_prefix . "ranks AS rd\n"
  2235. . " ON ( rd.rank_id = 1 )$append\n"
  2236. . " GROUP BY u.user_id, u.username, u.user_level, u.user_group, u.user_rank, u.user_title, u.user_rank_userset, g.group_rank,\n"
  2237. . " ru.rank_id, ru.rank_title, ru.rank_style,rg.rank_id, rg.rank_title, rg.rank_style,\n"
  2238. . " rl.rank_id, rl.rank_title, rl.rank_style,rd.rank_id, rd.rank_title, rd.rank_style;";
  2239. return $sql;
  2240. }
  2241. /**
  2242. * Returns an associative array with a user's rank information.
  2243. * The array will contain the following values:
  2244. * username: string The user's username
  2245. * user_id: integer Numerical user ID
  2246. * rank_id: integer Numerical rank ID
  2247. * rank: string The user's current rank
  2248. * title: string The user's custom user title if applicable; should be displayed one line below the rank
  2249. * style: string CSS for the username
  2250. * @param int|string Username *or* user ID
  2251. * @return array or false on failure
  2252. */
  2253. function get_user_rank($id)
  2254. {
  2255. global $db, $session, $paths, $template, $plugins; // Common objects
  2256. global $lang;
  2257. global $user_ranks;
  2258. // cache info in RAM if possible
  2259. static $_cache = array();
  2260. if ( is_int($id) && $id == 0 )
  2261. $id = 1;
  2262. if ( is_int($id) )
  2263. $col = "u.user_id = $id";
  2264. else if ( is_string($id) )
  2265. $col = ENANO_SQLFUNC_LOWERCASE . "(username) = " . ENANO_SQLFUNC_LOWERCASE . "('" . $db->escape($id) . "')";
  2266. else
  2267. // invalid parameter
  2268. return false;
  2269. // check the RAM cache
  2270. if ( isset($_cache[$id]) )
  2271. return $_cache[$id];
  2272. // check the disk cache
  2273. if ( is_int($id) )
  2274. {
  2275. if ( isset($user_ranks[$id]) )
  2276. {
  2277. $_cache[$id] =& $user_ranks[$id];
  2278. return $user_ranks[$id];
  2279. }
  2280. }
  2281. else if ( is_string($id) )
  2282. {
  2283. foreach ( $user_ranks as $key => $valarray )
  2284. {
  2285. if ( is_string($key) && strtolower($key) == strtolower($id) )
  2286. {
  2287. $_cache[$id] = $valarray;
  2288. return $valarray;
  2289. }
  2290. }
  2291. }
  2292. $sql = $this->generate_rank_sql("\n WHERE $col");
  2293. $q = $this->sql($sql);
  2294. // any results?
  2295. if ( $db->numrows() < 1 )
  2296. {
  2297. // nuttin'.
  2298. $db->free_result();
  2299. $_cache[$id] = false;
  2300. return false;
  2301. }
  2302. // Found something.
  2303. $row = $db->fetchrow();
  2304. $db->free_result();
  2305. $row = $this->calculate_user_rank($row);
  2306. $_cache[$id] = $row;
  2307. return $row;
  2308. }
  2309. /**
  2310. * Performs the actual rank calculation based on the contents of a row.
  2311. * @param array
  2312. * @return array
  2313. */
  2314. function calculate_user_rank($row)
  2315. {
  2316. global $db, $session, $paths, $template, $plugins; // Common objects
  2317. global $lang;
  2318. static $rank_cache = array();
  2319. static $group_ranks = array();
  2320. // try to cache that rank info
  2321. if ( !isset($rank_cache[ intval($row['rank_id']) ]) && $row['rank_id'] )
  2322. {
  2323. $rank_cache[ intval($row['rank_id']) ] = array(
  2324. 'rank_id' => intval($row['rank_id']),
  2325. 'rank_title' => intval($row['rank_title']),
  2326. 'rank_style' => intval($row['rank_style'])
  2327. );
  2328. }
  2329. // cache group info (if appropriate)
  2330. if ( $row['using_group'] && !isset($group_ranks[ intval($row['user_group']) ]) )
  2331. {
  2332. $group_ranks[ intval($row['user_group']) ] = intval($row['group_rank_id']);
  2333. }
  2334. // sanitize and process the as-of-yet rank data
  2335. $row['rank_id'] = intval($row["rank_id"]);
  2336. $row['rank_title'] = $row["rank_title"];
  2337. // if we're falling back to some default, then see if we can use one of the user's other groups
  2338. if ( $row['using_default'] && !empty($row['group_list']) )
  2339. {
  2340. $group_list = explode(',', $row['group_list']);
  2341. if ( array_walk($group_list, 'intval') )
  2342. {
  2343. // go through the group list and see if any of them has a rank assigned
  2344. foreach ( $group_list as $group_id )
  2345. {
  2346. // cached in RAM? Preferably use that.
  2347. if ( !isset($group_ranks[$group_id]) )
  2348. {
  2349. // Not cached - grab it
  2350. $q = $this->sql('SELECT group_rank FROM ' . table_prefix . "groups WHERE group_id = $group_id;");
  2351. if ( $db->numrows() < 1 )
  2352. {
  2353. $db->free_result();
  2354. continue;
  2355. }
  2356. list($result) = $db->fetchrow_num();
  2357. $db->free_result();
  2358. if ( $result === null || $result < 1 )
  2359. {
  2360. $group_ranks[$group_id] = false;
  2361. }
  2362. else
  2363. {
  2364. $group_ranks[$group_id] = intval($result);
  2365. }
  2366. }
  2367. // we've got it now
  2368. if ( $group_ranks[$group_id] )
  2369. {
  2370. // found a group with a rank assigned
  2371. // so get the rank info
  2372. $rank_id =& $group_ranks[$group_id];
  2373. if ( !isset($rank_cache[$rank_id]) )
  2374. {
  2375. $q = $this->sql('SELECT rank_id, rank_title, rank_style FROM ' . table_prefix . "ranks WHERE rank_id = $rank_id;");
  2376. if ( $db->numrows() < 1 )
  2377. {
  2378. $db->free_result();
  2379. continue;
  2380. }
  2381. $rank_cache[$rank_id] = $db->fetchrow();
  2382. $db->free_result();
  2383. }
  2384. // set the final rank parameters
  2385. // die("found member-of-group exception with uid {$row['user_id']} gid $group_id rid $rank_id rt {$rank_cache[$rank_id]['rank_title']}");
  2386. $row['rank_id'] = $rank_id;
  2387. $row['rank_title'] = $rank_cache[$rank_id]['rank_title'];
  2388. $row['rank_style'] = $rank_cache[$rank_id]['rank_style'];
  2389. break;
  2390. }
  2391. }
  2392. }
  2393. }
  2394. if ( $row['user_title'] === NULL )
  2395. $row['user_title'] = false;
  2396. $row['user_id'] = intval($row['user_id']);
  2397. $row['user_level'] = intval($row['user_level']);
  2398. $row['user_group'] = intval($row['user_group']);
  2399. unset($row['user_rank'], $row['group_rank'], $row['group_list'], $row['using_default'], $row['using_group'], $row['user_level'], $row['user_group'], $row['username']);
  2400. return $row;
  2401. }
  2402. /**
  2403. * Get the list of ranks that a user is allowed to use. Returns false if they cannot change it.
  2404. * @param string|int User ID or username
  2405. * @return array Associative by rank ID
  2406. */
  2407. function get_user_possible_ranks($id)
  2408. {
  2409. global $db, $session, $paths, $template, $plugins; // Common objects
  2410. // cache info in RAM if possible
  2411. static $_cache = array();
  2412. if ( is_int($id) && $id == 0 )
  2413. $id = 1;
  2414. if ( is_int($id) )
  2415. $col = "u.user_id = $id";
  2416. else if ( is_string($id) )
  2417. $col = ENANO_SQLFUNC_LOWERCASE . "(username) = " . ENANO_SQLFUNC_LOWERCASE . "('" . $db->escape($id) . "')";
  2418. else
  2419. // invalid parameter
  2420. return false;
  2421. // check the RAM cache
  2422. if ( isset($_cache[$id]) )
  2423. return $_cache[$id];
  2424. $sql = $this->generate_rank_sql("\n WHERE $col");
  2425. $q = $this->sql($sql);
  2426. // any results?
  2427. if ( $db->numrows() < 1 )
  2428. {
  2429. // nuttin'.
  2430. $db->free_result();
  2431. $_cache[$id] = false;
  2432. return false;
  2433. }
  2434. // Found something.
  2435. $row = $db->fetchrow();
  2436. $db->free_result();
  2437. if ( $row['using_user'] && !$row['user_rank_userset'] )
  2438. {
  2439. // The user's rank was set manually by an admin.
  2440. $result = array(
  2441. array(
  2442. 'rank_id' => $row['rank_id'],
  2443. 'rank_title' => $row['rank_title'],
  2444. 'rank_style' => $row['rank_style'],
  2445. 'rank_type' => 'user'
  2446. )
  2447. );
  2448. $_cache[$id] = $result;
  2449. return $result;
  2450. }
  2451. // copy the result to a more permanent array so we can reference this later
  2452. $current_settings = $row;
  2453. unset($row);
  2454. $result = array();
  2455. // first rank available to us will be the one set by the user's user level
  2456. if ( isset($this->level_rank_table[$current_settings['user_level']]) )
  2457. {
  2458. $q = $this->sql('SELECT rank_id, rank_title, rank_style FROM ' . table_prefix . "ranks WHERE rank_id = {$this->level_rank_table[$this->user_level]};");
  2459. if ( $db->numrows() > 0 )
  2460. {
  2461. $row = $db->fetchrow();
  2462. $row['rank_type'] = 'ulevel';
  2463. $result[] = $row;
  2464. }
  2465. $db->free_result();
  2466. }
  2467. // for each group the user is in, figure out if it has a rank associated with it
  2468. $group_list = explode(',', $current_settings['group_list']);
  2469. foreach ( $group_list as $group_id )
  2470. {
  2471. $group_id = intval($group_id);
  2472. $q = $this->sql('SELECT r.rank_id, r.rank_title, r.rank_style FROM ' . table_prefix . "groups AS g\n"
  2473. . " LEFT JOIN " . table_prefix . "ranks AS r\n"
  2474. . " ON ( g.group_rank = r.rank_id )\n"
  2475. . " WHERE g.group_id = $group_id\n"
  2476. . " AND r.rank_id IS NOT NULL;");
  2477. if ( $db->numrows() > 0 )
  2478. {
  2479. $row = $db->fetchrow();
  2480. $row['rank_type'] = 'group';
  2481. $result[] = $row;
  2482. }
  2483. $db->free_result();
  2484. }
  2485. $_cache[$id] = $result;
  2486. return $result;
  2487. }
  2488. #
  2489. # Access Control Lists
  2490. #
  2491. /**
  2492. * Creates a new permission field in memory. If the permissions are set in the database, they are used. Otherwise, $default_perm is used.
  2493. * @param string $acl_type An identifier for this field
  2494. * @param int $default_perm Whether permission should be granted or not if it's not specified in the ACLs.
  2495. * @param string $desc A human readable name for the permission type
  2496. * @param array $deps The list of dependencies - this should be an array of ACL types
  2497. * @param string $scope Which namespaces this field should apply to. This should be either a pipe-delimited list of namespace IDs or just "All".
  2498. */
  2499. function register_acl_type($acl_type, $default_perm = AUTH_DISALLOW, $desc = false, $deps = Array(), $scope = 'All')
  2500. {
  2501. if(isset($this->acl_types[$acl_type]))
  2502. return false;
  2503. else
  2504. {
  2505. if(!$desc)
  2506. {
  2507. $desc = ucfirst(str_replace('_', ' ', $acl_type));
  2508. }
  2509. $this->acl_types[$acl_type] = $default_perm;
  2510. $this->acl_descs[$acl_type] = $desc;
  2511. $this->acl_deps[$acl_type] = $deps;
  2512. $this->acl_scope[$acl_type] = explode('|', $scope);
  2513. }
  2514. return true;
  2515. }
  2516. /**
  2517. * Tells us whether permission $type is allowed or not based on the current rules.
  2518. * @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
  2519. * @param bool $no_deps If true, disables dependency checking
  2520. * @return bool True if allowed, false if denied or if an error occured
  2521. */
  2522. function get_permissions($type, $no_deps = false)
  2523. {
  2524. global $db, $session, $paths, $template, $plugins; // Common objects
  2525. if ( isset( $this->perms[$type] ) )
  2526. {
  2527. if ( $this->perms[$type] == AUTH_DENY )
  2528. $ret = false;
  2529. else if ( $this->perms[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
  2530. $ret = true;
  2531. else if ( $this->perms[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
  2532. $ret = false;
  2533. else if ( $this->perms[$type] == AUTH_ALLOW )
  2534. $ret = true;
  2535. else if ( $this->perms[$type] == AUTH_DISALLOW )
  2536. $ret = false;
  2537. }
  2538. else if(isset($this->acl_types[$type]))
  2539. {
  2540. if ( $this->acl_types[$type] == AUTH_DENY )
  2541. $ret = false;
  2542. else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
  2543. $ret = true;
  2544. else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
  2545. $ret = false;
  2546. else if ( $this->acl_types[$type] == AUTH_ALLOW )
  2547. $ret = true;
  2548. else if ( $this->acl_types[$type] == AUTH_DISALLOW )
  2549. $ret = false;
  2550. }
  2551. else
  2552. {
  2553. // ACL type is undefined
  2554. trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
  2555. return false; // Be on the safe side and deny access
  2556. }
  2557. if ( !$no_deps )
  2558. {
  2559. if ( !$this->acl_check_deps($type) )
  2560. return false;
  2561. }
  2562. return $ret;
  2563. }
  2564. /**
  2565. * Fetch the permissions that apply to the current user for the page specified. The object you get will have the get_permissions method
  2566. * and several other abilities.
  2567. * @param string $page_id
  2568. * @param string $namespace
  2569. * @return object
  2570. */
  2571. function fetch_page_acl($page_id, $namespace)
  2572. {
  2573. global $db, $session, $paths, $template, $plugins; // Common objects
  2574. if ( count ( $this->acl_base_cache ) < 1 )
  2575. {
  2576. // Permissions table not yet initialized
  2577. return false;
  2578. }
  2579. // cache of permission objects (to save RAM and SQL queries)
  2580. static $objcache = array();
  2581. if ( count($objcache) == 0 )
  2582. {
  2583. foreach ( $paths->nslist as $key => $_ )
  2584. {
  2585. $objcache[$key] = array();
  2586. }
  2587. }
  2588. if ( isset($objcache[$namespace][$page_id]) )
  2589. {
  2590. return $objcache[$namespace][$page_id];
  2591. }
  2592. $objcache[$namespace][$page_id] = new Session_ACLPageInfo( $page_id, $namespace, $this->acl_types, $this->acl_descs, $this->acl_deps, $this->acl_base_cache );
  2593. $object =& $objcache[$namespace][$page_id];
  2594. profiler_log("session: fetched ACLs for page {$namespace}:{$page_id}");
  2595. return $object;
  2596. }
  2597. /**
  2598. * Fetch the permissions that apply to an arbitrary user for the page specified. The object you get will have the get_permissions method
  2599. * and several other abilities.
  2600. * @param int|string $user_id_or_name; user ID *or* username of the user
  2601. * @param string $page_id; if null, will be default effective permissions.
  2602. * @param string $namespace; if null, will be default effective permissions.
  2603. * @return object
  2604. */
  2605. function fetch_page_acl_user($user_id_or_name, $page_id, $namespace)
  2606. {
  2607. global $db, $session, $paths, $template, $plugins; // Common objects
  2608. // cache user info
  2609. static $user_info_cache = null;
  2610. if ( isset($user_info_cache[$user_id_or_name]) )
  2611. {
  2612. $user_id =& $user_info_cache[$user_id_or_name]['user_id'];
  2613. $groups =& $user_info_cache[$user_id_or_name]['groups'];
  2614. }
  2615. else
  2616. {
  2617. $uid_column = ( is_int($user_id_or_name) ) ? "user_id = $user_id_or_name" : "username = '" . $db->escape($user_id_or_name) . "'";
  2618. $q = $db->sql_query('SELECT u.user_id, m.group_id, g.group_name FROM ' . table_prefix . "users AS u\n"
  2619. . " LEFT JOIN " . table_prefix . "group_members AS m\n"
  2620. . " ON ( ( u.user_id = m.user_id AND m.pending = 0 ) OR m.member_id IS NULL )\n"
  2621. . " LEFT JOIN " . table_prefix . "groups AS g\n"
  2622. . " ON ( g.group_id = m.group_id )\n"
  2623. . " WHERE $uid_column;");
  2624. if ( !$q )
  2625. $db->_die();
  2626. // The l10n engine takes care of this later.
  2627. $groups = array(1 => 'Everyone');
  2628. if ( $row = $db->fetchrow() )
  2629. {
  2630. $user_id = intval($row['user_id']);
  2631. if ( $row['group_id'] )
  2632. {
  2633. do
  2634. {
  2635. $groups[ intval($row['group_id'] ) ] = $row['group_name'];
  2636. }
  2637. while ( $row = $db->fetchrow() );
  2638. }
  2639. $db->free_result();
  2640. }
  2641. else
  2642. {
  2643. $db->free_result();
  2644. throw new Exception('Unknown user ID or username');
  2645. }
  2646. $user_info_cache[$user_id_or_name] = array(
  2647. 'user_id' => $user_id,
  2648. 'groups' => $groups
  2649. );
  2650. }
  2651. // cache base permissions
  2652. static $base_cache = array();
  2653. if ( !isset($base_cache[$user_id_or_name]) )
  2654. {
  2655. $base_cache[$user_id_or_name] = $this->acl_types;
  2656. $current_perms =& $base_cache[$user_id_or_name];
  2657. $current_perms['__resolve_table'] = array();
  2658. $bs = 'SELECT rules, target_type, target_id, rule_id, page_id, namespace, g.group_name FROM '.table_prefix."acl AS a\n"
  2659. . " LEFT JOIN " . table_prefix . "groups AS g\n"
  2660. . " ON ( ( a.target_type = " . ACL_TYPE_GROUP . " AND a.target_id = g.group_id ) OR ( a.target_type != " . ACL_TYPE_GROUP . " ) )\n"
  2661. . ' WHERE page_id IS NULL AND namespace IS NULL AND' . "\n"
  2662. . ' ( ';
  2663. $q = Array();
  2664. $q[] = '( target_type='.ACL_TYPE_USER.' AND target_id= ' . $user_id . ' )';
  2665. if(count($groups) > 0)
  2666. {
  2667. foreach($groups as $g_id => $g_name)
  2668. {
  2669. $q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
  2670. }
  2671. }
  2672. $bs .= implode(" OR \n ", $q) . " ) \n ORDER BY target_type ASC, target_id ASC;";
  2673. $q = $this->sql($bs);
  2674. foreach ( $this->acl_types as $perm_type => $_ )
  2675. {
  2676. // init the resolver table with blanks
  2677. $current_perms['__resolve_table'][$perm_type] = array(
  2678. 'src' => ACL_INHERIT_ENANO_DEFAULT,
  2679. 'rule_id' => -1
  2680. );
  2681. }
  2682. if ( $row = $db->fetchrow() )
  2683. {
  2684. do {
  2685. $rules = $this->string_to_perm($row['rules']);
  2686. $is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
  2687. // track where these rulings are coming from
  2688. $src = ( $is_everyone ) ? ACL_INHERIT_GLOBAL_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_GLOBAL_GROUP : ACL_INHERIT_GLOBAL_USER );
  2689. foreach ( $rules as $perm_type => $_ )
  2690. {
  2691. $current_perms['__resolve_table'][$perm_type] = array(
  2692. 'src' => $src,
  2693. 'rule_id' => $row['rule_id']
  2694. );
  2695. if ( $row['group_name'] )
  2696. {
  2697. $current_perms['__resolve_table'][$perm_type]['group_name'] = $row['group_name'];
  2698. }
  2699. }
  2700. // merge it in
  2701. $current_perms = $this->acl_merge($current_perms, $rules, $is_everyone, $_defaults_used);
  2702. } while ( $row = $db->fetchrow() );
  2703. }
  2704. }
  2705. // cache of permission objects (to save RAM and SQL queries)
  2706. static $objcache = array();
  2707. if ( count($objcache) == 0 )
  2708. {
  2709. foreach ( $paths->nslist as $key => $_ )
  2710. {
  2711. $objcache[$key] = array();
  2712. }
  2713. }
  2714. if ( !isset($objcache[$namespace][$page_id]) )
  2715. {
  2716. $objcache[$namespace][$page_id] = array();
  2717. }
  2718. if ( isset($objcache[$namespace][$page_id][$user_id_or_name]) )
  2719. {
  2720. return $objcache[$namespace][$page_id][$user_id_or_name];
  2721. }
  2722. //if ( !isset( $paths->pages[$paths->nslist[$namespace] . $page_id] ) )
  2723. //{
  2724. // // Page does not exist
  2725. // return false;
  2726. //}
  2727. $objcache[$namespace][$page_id][$user_id_or_name] = new Session_ACLPageInfo(
  2728. $page_id, // $page_id,
  2729. $namespace, // $namespace,
  2730. $this->acl_types, // $acl_types,
  2731. $this->acl_descs, // $acl_descs,
  2732. $this->acl_deps, // $acl_deps,
  2733. $base_cache[$user_id_or_name], // $base,
  2734. $user_info_cache[$user_id_or_name]['user_id'], // $user_id = null,
  2735. $user_info_cache[$user_id_or_name]['groups'], // $groups = null,
  2736. $base_cache[$user_id_or_name]['__resolve_table'] // $resolve_table = array()
  2737. );
  2738. $object =& $objcache[$namespace][$page_id][$user_id_or_name];
  2739. return $object;
  2740. }
  2741. /**
  2742. * Checks if the given ACL rule type applies to a namespace.
  2743. * @param string ACL rule type
  2744. * @param string Namespace
  2745. * @return bool
  2746. */
  2747. function check_acl_scope($acl_rule, $namespace)
  2748. {
  2749. if ( !isset($this->acl_scope[$acl_rule]) )
  2750. return false;
  2751. if ( $this->acl_scope[$acl_rule] === array('All') )
  2752. return true;
  2753. return ( in_array($namespace, $this->acl_scope[$acl_rule]) ) ? true : false;
  2754. }
  2755. /**
  2756. * Read all of our permissions from the database and process/apply them. This should be called after the page is determined.
  2757. * @access private
  2758. */
  2759. function init_permissions()
  2760. {
  2761. global $db, $session, $paths, $template, $plugins; // Common objects
  2762. // Initialize the permissions list with some defaults
  2763. $this->perms = $this->acl_types;
  2764. $this->acl_defaults_used = $this->perms;
  2765. // Fetch sitewide defaults from the permissions table
  2766. $bs = 'SELECT rules, target_type, target_id FROM '.table_prefix.'acl' . "\n"
  2767. . ' WHERE page_id IS NULL AND namespace IS NULL AND' . "\n"
  2768. . ' ( ';
  2769. $q = Array();
  2770. $q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
  2771. if(count($this->groups) > 0)
  2772. {
  2773. foreach($this->groups as $g_id => $g_name)
  2774. {
  2775. $q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
  2776. }
  2777. }
  2778. $bs .= implode(" OR \n ", $q) . " ) \n ORDER BY target_type ASC, target_id ASC;";
  2779. $q = $this->sql($bs);
  2780. if ( $row = $db->fetchrow() )
  2781. {
  2782. do {
  2783. $rules = $this->string_to_perm($row['rules']);
  2784. $is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
  2785. $this->acl_merge_with_current($rules, $is_everyone);
  2786. } while ( $row = $db->fetchrow() );
  2787. }
  2788. // Cache the sitewide permissions for later use
  2789. $this->acl_base_cache = $this->perms;
  2790. profiler_log('session: base ACL set calculated');
  2791. // Load and calculate permissions for the current page
  2792. $page_acl = $this->fetch_page_acl($paths->page_id, $paths->namespace);
  2793. $this->perms = $page_acl->perms;
  2794. $this->acl_defaults_used = $page_acl->acl_defaults_used;
  2795. }
  2796. /**
  2797. * Extends the scope of a permission type.
  2798. * @param string The name of the permission type
  2799. * @param string The namespace(s) that should be covered. This can be either one namespace ID or a pipe-delimited list.
  2800. * @param object Optional - the current $paths object, in case we're doing this from the acl_rule_init hook
  2801. */
  2802. function acl_extend_scope($perm_type, $namespaces, &$p_in)
  2803. {
  2804. global $db, $session, $paths, $template, $plugins; // Common objects
  2805. $p_obj = ( is_object($p_in) ) ? $p_in : $paths;
  2806. $nslist = explode('|', $namespaces);
  2807. foreach ( $nslist as $i => $ns )
  2808. {
  2809. if ( !isset($p_obj->nslist[$ns]) )
  2810. {
  2811. unset($nslist[$i]);
  2812. }
  2813. else
  2814. {
  2815. if ( $this->acl_scope[$perm_type] !== array('All') )
  2816. $this->acl_scope[$perm_type][] = $ns;
  2817. if ( isset($this->acl_types[$perm_type]) && !isset($this->perms[$perm_type]) )
  2818. {
  2819. $this->perms[$perm_type] = $this->acl_types[$perm_type];
  2820. }
  2821. }
  2822. }
  2823. }
  2824. /**
  2825. * Converts a permissions field into a string for database insertion. Similar in spirit to serialize().
  2826. * @param array $perms An associative array with only integers as values
  2827. * @return string
  2828. */
  2829. function perm_to_string($perms)
  2830. {
  2831. $s = '';
  2832. foreach($perms as $perm => $ac)
  2833. {
  2834. if ( $ac == 'i' )
  2835. continue;
  2836. $s .= "$perm=$ac;";
  2837. }
  2838. return $s;
  2839. }
  2840. /**
  2841. * Converts a permissions string back to an array.
  2842. * @param string $perms The result from sessionManager::perm_to_string()
  2843. * @return array
  2844. */
  2845. function string_to_perm($perms)
  2846. {
  2847. $ret = Array();
  2848. preg_match_all('#([a-z0-9_-]+)=([0-9]+);#i', $perms, $matches);
  2849. foreach($matches[1] as $i => $t)
  2850. {
  2851. $ret[$t] = intval($matches[2][$i]);
  2852. }
  2853. return $ret;
  2854. }
  2855. /**
  2856. * Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence over the first, but AUTH_DENY always prevails.
  2857. * @param array $perm1 The first set of permissions
  2858. * @param array $perm2 The second set of permissions
  2859. * @param bool $is_everyone If true, applies exceptions for "Everyone" group
  2860. * @param array|reference $defaults_used Array that will be filled with default usage data
  2861. * @return array
  2862. */
  2863. function acl_merge($perm1, $perm2, $is_everyone = false, &$defaults_used = array())
  2864. {
  2865. $ret = $perm1;
  2866. if ( !is_array(@$defaults_used) )
  2867. {
  2868. $defaults_used = array();
  2869. }
  2870. foreach ( $perm1 as $i => $p )
  2871. {
  2872. if ( isset($perm2[$i]) )
  2873. {
  2874. if ( $is_everyone && isset($defaults_used[$i]) && $defaults_used[$i] === false )
  2875. continue;
  2876. // Decide precedence
  2877. if ( isset($defaults_used[$i]) )
  2878. {
  2879. // echo "$i: default in use, overriding to: {$perm2[$i]}<br />";
  2880. // Defaults are in use, override
  2881. // CHANGED - 1.1.4:
  2882. // For some time this has been intentionally relaxed so that the following
  2883. // exception is available to Deny permissions:
  2884. // If the rule applies to the group "Everyone" on the entire site,
  2885. // Deny settings could be overriden.
  2886. // This is documented at: http://docs.enanocms.org/Help:4.2
  2887. if ( $perm1[$i] != AUTH_DENY )
  2888. {
  2889. $perm1[$i] = $perm2[$i];
  2890. $defaults_used[$i] = ( $is_everyone );
  2891. }
  2892. }
  2893. else
  2894. {
  2895. // echo "$i: default NOT in use";
  2896. // Defaults are not in use, merge as normal
  2897. if ( $perm1[$i] != AUTH_DENY )
  2898. {
  2899. // echo ", but overriding";
  2900. $perm1[$i] = $perm2[$i];
  2901. }
  2902. // echo "<br />";
  2903. }
  2904. }
  2905. }
  2906. return $perm1;
  2907. }
  2908. /**
  2909. * Merges two ACL arrays, but instead of calculating inheritance for missing permission types, just returns 'i' for that type. Useful
  2910. * for explicitly requiring inheritance in ACL editing interfaces
  2911. * @param array $perm1 The first set of permissions
  2912. * @param array $perm2 The second, authoritative set of permissions
  2913. */
  2914. function acl_merge_inherit($perm1, $perm2)
  2915. {
  2916. foreach ( $perm1 as $type => $level )
  2917. {
  2918. $perm1[$type][$level] = 'i';
  2919. }
  2920. $ret = $perm1;
  2921. foreach ( $perm2 as $type => $level )
  2922. {
  2923. if ( isset( $ret[$type] ) )
  2924. {
  2925. if ( $ret[$type] != AUTH_DENY )
  2926. $ret[$type] = $level;
  2927. }
  2928. }
  2929. return $ret;
  2930. }
  2931. /**
  2932. * Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
  2933. * @param array The array to merge into the master ACL list
  2934. * @param bool If true, $perm is treated as the "new default"
  2935. * @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
  2936. */
  2937. function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
  2938. {
  2939. $this->perms = $this->acl_merge($this->perms, $perm, $is_everyone, $this->acl_defaults_used);
  2940. }
  2941. /**
  2942. * Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence
  2943. * over the first, without exceptions. This is used to merge the hardcoded defaults with admin-specified
  2944. * defaults, which take precedence.
  2945. * @param array $perm1 The first set of permissions
  2946. * @param array $perm2 The second set of permissions
  2947. * @return array
  2948. */
  2949. function acl_merge_complete($perm1, $perm2)
  2950. {
  2951. $ret = $perm1;
  2952. foreach ( $perm2 as $type => $level )
  2953. {
  2954. $ret[$type] = $level;
  2955. }
  2956. return $ret;
  2957. }
  2958. /**
  2959. * Tell us if the dependencies for a given permission are met.
  2960. * @param string The ACL permission ID
  2961. * @return bool
  2962. */
  2963. function acl_check_deps($type, $debug = false)
  2964. {
  2965. global $paths;
  2966. // This will only happen if the permissions table is hacked or improperly accessed
  2967. if(!isset($this->acl_deps[$type]))
  2968. return true;
  2969. // Permission has no dependencies?
  2970. if(sizeof($this->acl_deps[$type]) < 1)
  2971. return true;
  2972. // go through them all and build a flat list of dependencies
  2973. $deps = $this->acl_deps[$type];
  2974. while(true)
  2975. {
  2976. $j = sizeof($deps);
  2977. for ( $i = 0; $i < $j; $i++ )
  2978. {
  2979. $b = $deps;
  2980. if ( !$this->check_acl_scope($deps[$i], $paths->namespace) )
  2981. {
  2982. // Action $type depends on action $deps[$i] which cannot be satisfied because $deps[$i] is out of scope.
  2983. // echo '<pre>' . enano_debug_print_backtrace(true) . '</pre>';
  2984. trigger_error("acl_check_deps: $type depends on {$deps[$i]} which is not within scope of $paths->namespace; this indicates a bug in ACL rule specification. Backtrace:<pre>" . htmlspecialchars(enano_debug_print_backtrace(true)) . "</pre>", E_USER_WARNING);
  2985. return false;
  2986. }
  2987. $deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
  2988. if( $b == $deps )
  2989. {
  2990. break 2;
  2991. }
  2992. $j = sizeof($deps);
  2993. }
  2994. }
  2995. $debugdata = array();
  2996. foreach($deps as $d)
  2997. {
  2998. // Our dependencies are fully resolved, so tell get_permissions() to not recursively call this function
  2999. if ( !$this->get_permissions($d, true) )
  3000. {
  3001. if ( $debug )
  3002. {
  3003. $debugdata[] = $d;
  3004. }
  3005. else
  3006. {
  3007. return false;
  3008. }
  3009. }
  3010. }
  3011. return $debug ? $debugdata : true;
  3012. }
  3013. /**
  3014. * Makes a CAPTCHA code and caches the code in the database
  3015. * @param int $len The length of the code, in bytes
  3016. * @param string Optional, the hash to reuse
  3017. * @return string A unique identifier assigned to the code. This hash should be passed to sessionManager::getCaptcha() to retrieve the code.
  3018. */
  3019. function make_captcha($len = 7, $hash = '')
  3020. {
  3021. global $db, $session, $paths, $template, $plugins; // Common objects
  3022. $code = $this->generate_captcha_code($len);
  3023. if ( !preg_match('/^[a-f0-9]{32}([a-z0-9]{8})?$/', $hash) )
  3024. $hash = md5(microtime() . mt_rand());
  3025. $session_data = $db->escape(serialize(array()));
  3026. // sanity check
  3027. if ( !is_valid_ip(@$_SERVER['REMOTE_ADDR']) || !is_int($this->user_id) )
  3028. return false;
  3029. $this->sql('DELETE FROM ' . table_prefix . "captcha WHERE session_id = '$hash';");
  3030. $this->sql('INSERT INTO ' . table_prefix . 'captcha(session_id, code, session_data, source_ip, user_id)' . " VALUES('$hash', '$code', '$session_data', '{$_SERVER['REMOTE_ADDR']}', {$this->user_id});");
  3031. return $hash;
  3032. }
  3033. /**
  3034. * Generates a "pronouncable" or "human-friendly" word using various phonics rules
  3035. * @param int Optional. The length of the word.
  3036. * @return string
  3037. */
  3038. function generate_captcha_code($len = 7)
  3039. {
  3040. // don't use k and x, they get mixed up a lot
  3041. $consonants = 'bcdfghmnpqrsvwyz';
  3042. $vowels = 'aeiou';
  3043. $prev = 'vowel';
  3044. $prev_l = '';
  3045. $word = '';
  3046. $allow_next_vowel = true;
  3047. for ( $i = 0; $i < $len; $i++ )
  3048. {
  3049. if ( $prev == 'vowel' )
  3050. {
  3051. $allow_next_vowel = false;
  3052. if ( $prev_l == 'o' && mt_rand(0, 3) == 3 && $allow_next_vowel )
  3053. $word .= 'i';
  3054. else if ( $prev_l == 'q' && mt_rand(0, 3) != 1 && $allow_next_vowel )
  3055. $word .= 'u';
  3056. else if ( $prev_l == 'o' && mt_rand(0, 3) == 2 && $allow_next_vowel )
  3057. $word .= 'u';
  3058. else if ( $prev_l == 'a' && mt_rand(0, 3) == 3 && $allow_next_vowel )
  3059. $word .= 'i';
  3060. else if ( $prev_l == 'a' && mt_rand(0, 10) == 7 && $allow_next_vowel )
  3061. $word .= 'o';
  3062. else if ( $prev_l == 'a' && mt_rand(0, 7) == 2 && $allow_next_vowel )
  3063. $word .= 'u';
  3064. else
  3065. {
  3066. $allow_next_vowel = true;
  3067. $word .= $consonants{mt_rand(0, (strlen($consonants)-1))};
  3068. }
  3069. }
  3070. else if ( $prev == 'consonant' )
  3071. {
  3072. if ( $prev_l == 'p' && mt_rand(0, 7) == 4 )
  3073. $word .= 't';
  3074. else if ( $prev_l == 'p' && mt_rand(0, 5) == 1 )
  3075. $word .= 'h';
  3076. // this rule allows "ck" which can result in the occasional "dick", "fuck", etc. that tends
  3077. // to end up on /r/funny, but I decided to keep it, because it increases word complexity.
  3078. else if ( $prev_l == 'c' && mt_rand(0, 3) == 1 )
  3079. $word .= 'k';
  3080. else if ( $prev_l == 'q' && mt_rand(0, 5) != 1 )
  3081. $word .= 'u';
  3082. else
  3083. $word .= $vowels{mt_rand(0, (strlen($vowels)-1))};
  3084. }
  3085. $prev_l = substr($word, -1);
  3086. $l = ( mt_rand(0, 1) == 1 ) ? strtoupper($prev_l) : strtolower($prev_l);
  3087. $word = substr($word, 0, -1) . $l;
  3088. if ( strstr('aeiou', $prev_l) )
  3089. $prev = 'vowel';
  3090. else
  3091. $prev = 'consonant';
  3092. }
  3093. return $word;
  3094. }
  3095. /**
  3096. * For the given code ID, returns the correct CAPTCHA code, or false on failure
  3097. * @param string $hash The unique ID assigned to the code
  3098. * @param bool If true, the code is NOT deleted from the database. Use with caution!
  3099. * @return string The correct confirmation code
  3100. */
  3101. function get_captcha($hash, $nodelete = false)
  3102. {
  3103. global $db, $session, $paths, $template, $plugins; // Common objects
  3104. if ( !preg_match('/^[a-f0-9]{32}([a-z0-9]{8})?$/', $hash) )
  3105. {
  3106. die("session manager: bad captcha_hash $hash");
  3107. return false;
  3108. }
  3109. // sanity check
  3110. if ( !is_valid_ip(@$_SERVER['REMOTE_ADDR']) )
  3111. {
  3112. die("session manager insanity: bad REMOTE_ADDR or invalid UID");
  3113. return false;
  3114. }
  3115. $q = $this->sql('SELECT code_id, code FROM ' . table_prefix . "captcha WHERE session_id = '$hash' AND source_ip = '{$_SERVER['REMOTE_ADDR']}';");
  3116. if ( $db->numrows() < 1 )
  3117. {
  3118. return false;
  3119. }
  3120. list($code_id, $code) = $db->fetchrow_num();
  3121. $db->free_result();
  3122. // delete it
  3123. if ( !$nodelete )
  3124. $this->sql('DELETE FROM ' . table_prefix . "captcha WHERE code_id = $code_id;");
  3125. return $code;
  3126. }
  3127. /**
  3128. * (AS OF 1.0.2: Deprecated. Captcha codes are now killed on first fetch for security.) Deletes all CAPTCHA codes cached in the DB for this user.
  3129. */
  3130. function kill_captcha()
  3131. {
  3132. return true;
  3133. }
  3134. /**
  3135. * Generates a random password.
  3136. * @param int $length Optional - length of password
  3137. * @return string
  3138. */
  3139. function random_pass($length = 10)
  3140. {
  3141. $valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+@#%&<>';
  3142. $valid_chars = enano_str_split($valid_chars);
  3143. $ret = '';
  3144. for ( $i = 0; $i < $length; $i++ )
  3145. {
  3146. $ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
  3147. }
  3148. return $ret;
  3149. }
  3150. /**
  3151. * Generates some Javascript that calls the AES encryption library. Put this after your </form>.
  3152. * @param string The name of the form
  3153. * @param string The name of the password field
  3154. * @param string The name of the field that switches encryption on or off
  3155. * @param string The name of the field that contains the encryption key
  3156. * @param string The name of the field that will contain the encrypted password
  3157. * @param string The name of the field that handles MD5 challenge data
  3158. * @param string The name of the field that tells if the server supports DiffieHellman
  3159. * @param string The name of the field with the DiffieHellman public key
  3160. * @param string The name of the field that the client should populate with its public key
  3161. * @return string
  3162. */
  3163. static function aes_javascript($form_name, $pw_field, $use_crypt = 'use_crypt', $crypt_key = 'crypt_key', $crypt_data = 'crypt_data', $challenge = 'challenge_data', $dh_supported = 'dh_supported', $dh_pubkey = 'dh_public_key', $dh_client_pubkey = 'dh_client_public_key')
  3164. {
  3165. $code = '
  3166. <script type="text/javascript">
  3167. function runEncryption(nowhiteout)
  3168. {
  3169. var frm = document.forms.'.$form_name.';
  3170. if ( !nowhiteout )
  3171. whiteOutForm(frm);
  3172. load_component(\'crypto\');
  3173. var testpassed = ' . ( ( isset($_GET['use_crypt']) && $_GET['use_crypt']=='0') ? 'false; // CRYPTO-AUTH DISABLED ON USER REQUEST // ' : '' ) . '( aes_self_test() && md5_vm_test() );
  3174. var use_diffiehellman = false;' . "\n";
  3175. if ( $dh_supported && $dh_pubkey )
  3176. {
  3177. $code .= <<<EOF
  3178. if ( frm.$dh_supported.value == 'true' && !is_iPhone )
  3179. use_diffiehellman = true;
  3180. EOF;
  3181. }
  3182. $code .= '
  3183. if ( frm[\'' . $dh_supported . '\'] )
  3184. {
  3185. frm[\'' . $dh_supported . '\'].value = ( use_diffiehellman ) ? "true" : "false";
  3186. }
  3187. if ( frm["' . $pw_field . '_confirm"] )
  3188. {
  3189. pass1 = frm.' . $pw_field . '.value;
  3190. pass2 = frm.' . $pw_field . '_confirm.value;
  3191. if ( pass1 != pass2 )
  3192. {
  3193. load_component("l10n");
  3194. alert($lang.get("userfuncs_passreset_err_no_match"));
  3195. return false;
  3196. }
  3197. if ( pass1.length < 6 )
  3198. {
  3199. load_component("l10n");
  3200. alert($lang.get("userfuncs_passreset_err_too_short"));
  3201. return false;
  3202. }
  3203. frm.' . $pw_field . '_confirm.value = "";
  3204. }
  3205. if ( testpassed && use_diffiehellman )
  3206. {
  3207. // try to blank out the table to prevent double submits and what have you
  3208. var el = frm.' . $pw_field . ';
  3209. while ( el.tagName != "BODY" && el.tagName != "TABLE" )
  3210. {
  3211. el = el.parentNode;
  3212. }
  3213. /*
  3214. if ( el.tagName == "TABLE" )
  3215. {
  3216. whiteOutElement(el);
  3217. }
  3218. */
  3219. frm.'.$use_crypt.'.value = \'yes_dh\';
  3220. // Perform Diffie Hellman stuff
  3221. console.info("DiffieHellman: started keygen process");
  3222. var dh_priv = dh_gen_private();
  3223. var dh_pub = dh_gen_public(dh_priv);
  3224. var secret = dh_gen_shared_secret(dh_priv, frm.' . $dh_pubkey . '.value);
  3225. console.info("DiffieHellman: finished keygen process");
  3226. // secret_hash is used to verify that the server guesses the correct secret
  3227. var secret_hash = hex_sha1(secret);
  3228. // give the server our values
  3229. frm.' . $crypt_key . '.value = secret_hash;
  3230. ' . ( $dh_supported ? 'frm.' . $dh_client_pubkey . '.value = dh_pub;' : '' ) . '
  3231. // console.info("DiffieHellman: set public values");
  3232. // crypt_key is the actual AES key
  3233. var crypt_key = (hex_sha256(secret)).substr(0, (keySizeInBits / 4));
  3234. // Perform encryption
  3235. crypt_key = hexToByteArray(crypt_key);
  3236. var pass = frm.'.$pw_field.'.value;
  3237. pass = stringToByteArray(pass);
  3238. var cryptstring = rijndaelEncrypt(pass, crypt_key, \'ECB\');
  3239. if(!cryptstring)
  3240. {
  3241. return false;
  3242. }
  3243. cryptstring = byteArrayToHex(cryptstring);
  3244. console.info("DiffieHellman: finished AES. Result: " + cryptstring);
  3245. console.debug(frm);
  3246. frm.'.$crypt_data.'.value = cryptstring;
  3247. frm.'.$pw_field.'.value = \'\';
  3248. // console.info("DiffieHellman: ready to submit");
  3249. }
  3250. else if ( testpassed && !use_diffiehellman )
  3251. {
  3252. frm.'.$use_crypt.'.value = \'yes\';
  3253. var cryptkey = frm.'.$crypt_key.'.value;
  3254. frm.'.$crypt_key.'.value = hex_md5(cryptkey);
  3255. cryptkey = hexToByteArray(cryptkey);
  3256. if(!cryptkey || ( ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ) && cryptkey.length != keySizeInBits / 8 )
  3257. {
  3258. if ( frm._login ) frm._login.disabled = true;
  3259. len = ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ? \'\\nLen: \'+cryptkey.length : \'\';
  3260. alert(\'The key is messed up\\nType: \'+typeof(cryptkey)+len);
  3261. }
  3262. pass = frm.'.$pw_field.'.value;
  3263. chal = frm.'.$challenge.'.value;
  3264. challenge = hex_md5(pass + chal) + chal;
  3265. frm.'.$challenge.'.value = challenge;
  3266. pass = stringToByteArray(pass);
  3267. cryptstring = rijndaelEncrypt(pass, cryptkey, \'ECB\');
  3268. if(!cryptstring)
  3269. {
  3270. return false;
  3271. }
  3272. cryptstring = byteArrayToHex(cryptstring);
  3273. frm.'.$crypt_data.'.value = cryptstring;
  3274. frm.'.$pw_field.'.value = \'\';
  3275. }
  3276. }
  3277. </script>
  3278. ';
  3279. return $code;
  3280. }
  3281. /**
  3282. * Generates the HTML form elements required for an encrypted logon experience.
  3283. * @param reference Optional variable to fill with the server's public and private key. If IN_ENANO_INSTALL is defined, storing and retrieving the key
  3284. * is YOUR responsibility.
  3285. * @return string
  3286. */
  3287. function generate_aes_form(&$dh_store = array())
  3288. {
  3289. $aes_key = self::rijndael_genkey();
  3290. $dh_store = array('aes' => $aes_key, 'public' => '', 'private' => '');
  3291. $return = '<input type="hidden" name="use_crypt" value="no" />';
  3292. $return .= '<input type="hidden" name="crypt_key" value="' . $aes_key . '" />';
  3293. $return .= '<input type="hidden" name="crypt_data" value="" />';
  3294. $return .= '<input type="hidden" name="challenge_data" value="' . self::dss_rand() . '" />';
  3295. require_once(ENANO_ROOT . '/includes/math.php');
  3296. require_once(ENANO_ROOT . '/includes/diffiehellman.php');
  3297. global $dh_supported, $_math;
  3298. if ( $dh_supported )
  3299. {
  3300. $dh_key_priv = dh_gen_private();
  3301. $dh_key_pub = dh_gen_public($dh_key_priv);
  3302. $dh_key_priv = $_math->str($dh_key_priv);
  3303. $dh_key_pub = $_math->str($dh_key_pub);
  3304. // store the keys in the DB
  3305. $this->sql('INSERT INTO ' . table_prefix . "diffiehellman( public_key, private_key ) VALUES ( '$dh_key_pub', '$dh_key_priv' );");
  3306. // also give the key to the calling function
  3307. $dh_store['public'] = $dh_key_pub;
  3308. $dh_store['private'] = $dh_key_priv;
  3309. $return .= "<input type=\"hidden\" name=\"dh_supported\" value=\"true\" />
  3310. <input type=\"hidden\" name=\"dh_public_key\" value=\"$dh_key_pub\" />
  3311. <input type=\"hidden\" name=\"dh_client_public_key\" value=\"\" />";
  3312. }
  3313. else
  3314. {
  3315. $return .= "<input type=\"hidden\" name=\"dh_supported\" value=\"false\" />";
  3316. }
  3317. return $return;
  3318. }
  3319. /**
  3320. * Static version of generate_aes_form().
  3321. * @see sessionManager::generate_aes_form()
  3322. * @param reference
  3323. * @return string
  3324. */
  3325. static function generate_aes_form_static(&$dh_store = array())
  3326. {
  3327. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  3328. $aes_key = $aes->gen_readymade_key();
  3329. $dh_store = array('aes' => $aes_key, 'public' => '', 'private' => '');
  3330. $return = '<input type="hidden" name="use_crypt" value="no" />';
  3331. $return .= '<input type="hidden" name="crypt_key" value="' . $aes_key . '" />';
  3332. $return .= '<input type="hidden" name="crypt_data" value="" />';
  3333. $return .= '<input type="hidden" name="challenge_data" value="' . self::dss_rand() . '" />';
  3334. require_once(ENANO_ROOT . '/includes/math.php');
  3335. require_once(ENANO_ROOT . '/includes/diffiehellman.php');
  3336. global $dh_supported, $_math;
  3337. if ( $dh_supported )
  3338. {
  3339. $dh_key_priv = dh_gen_private();
  3340. $dh_key_pub = dh_gen_public($dh_key_priv);
  3341. $dh_key_priv = $_math->str($dh_key_priv);
  3342. $dh_key_pub = $_math->str($dh_key_pub);
  3343. // also give the key to the calling function
  3344. $dh_store['public'] = $dh_key_pub;
  3345. $dh_store['private'] = $dh_key_priv;
  3346. $return .= "<input type=\"hidden\" name=\"dh_supported\" value=\"true\" />
  3347. <input type=\"hidden\" name=\"dh_public_key\" value=\"$dh_key_pub\" />
  3348. <input type=\"hidden\" name=\"dh_client_public_key\" value=\"\" />";
  3349. }
  3350. else
  3351. {
  3352. $return .= "<input type=\"hidden\" name=\"dh_supported\" value=\"false\" />";
  3353. }
  3354. return $return;
  3355. }
  3356. /**
  3357. * If you used all the same form fields as the normal login interface, this will take care of DiffieHellman for you and return the key.
  3358. * @param string Password field name (defaults to "password")
  3359. * @param array Optional associative array with fields "public", "private", and "aes".
  3360. * @return string
  3361. */
  3362. static function get_aes_post($fieldname = 'password', $keys = false)
  3363. {
  3364. global $db, $session, $paths, $template, $plugins; // Common objects
  3365. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  3366. if ( $_POST['use_crypt'] == 'yes' )
  3367. {
  3368. $is_static = !( isset($this) && get_class($this) === __CLASS__ );
  3369. if ( $is_static && ( !is_array($keys) || (is_array($keys) && !isset($keys['aes'])) ) )
  3370. {
  3371. throw new Exception('ERR_STATIC_REQUIRES_KEY');
  3372. }
  3373. $crypt_key = $is_static ? $keys['aes'] : $this->fetch_public_key($_POST['crypt_key']);
  3374. if ( !$crypt_key )
  3375. {
  3376. throw new Exception($lang->get('user_err_key_not_found'));
  3377. }
  3378. $crypt_key = hexdecode($crypt_key);
  3379. $data = $aes->decrypt($_POST['crypt_data'], $crypt_key, ENC_HEX);
  3380. }
  3381. else if ( $_POST['use_crypt'] == 'yes_dh' )
  3382. {
  3383. require_once(ENANO_ROOT . '/includes/math.php');
  3384. require_once(ENANO_ROOT . '/includes/diffiehellman.php');
  3385. global $dh_supported, $_math;
  3386. if ( !$dh_supported )
  3387. {
  3388. throw new Exception('Server does not support DiffieHellman, denying request');
  3389. }
  3390. // Fetch private key
  3391. $dh_public = $_POST['dh_public_key'];
  3392. if ( !ctype_digit($dh_public) )
  3393. {
  3394. throw new Exception('ERR_DH_KEY_NOT_INTEGER');
  3395. }
  3396. if ( is_array($keys) && isset($keys['public']) && isset($keys['private']) )
  3397. {
  3398. if ( $keys['public'] !== $dh_public )
  3399. throw new Exception('ERR_DH_KEY_NOT_FOUND');
  3400. $dh_private = $keys['private'];
  3401. }
  3402. else
  3403. {
  3404. $q = $db->sql_query('SELECT private_key, key_id FROM ' . table_prefix . "diffiehellman WHERE public_key = '$dh_public';");
  3405. if ( !$q )
  3406. $db->die_json();
  3407. if ( $db->numrows() < 1 )
  3408. {
  3409. throw new Exception('ERR_DH_KEY_NOT_FOUND');
  3410. }
  3411. list($dh_private, $dh_key_id) = $db->fetchrow_num();
  3412. $db->free_result();
  3413. // We have the private key, now delete the key pair, we no longer need it
  3414. $q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE key_id = $dh_key_id;");
  3415. if ( !$q )
  3416. $db->die_json();
  3417. }
  3418. // Generate the shared secret
  3419. $dh_secret = dh_gen_shared_secret($dh_private, $_POST['dh_client_public_key']);
  3420. $dh_secret = $_math->str($dh_secret);
  3421. // Did we get all our math right?
  3422. $dh_secret_check = sha1($dh_secret);
  3423. $dh_hash = $_POST['crypt_key'];
  3424. if ( $dh_secret_check !== $dh_hash )
  3425. {
  3426. throw new Exception('ERR_DH_HASH_NO_MATCH');
  3427. }
  3428. // All good! Generate the AES key
  3429. $aes_key = substr(sha256($dh_secret), 0, ( AES_BITS / 4 ));
  3430. // decrypt user info
  3431. $aes_key = hexdecode($aes_key);
  3432. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  3433. $data = $aes->decrypt($_POST['crypt_data'], $aes_key, ENC_HEX);
  3434. }
  3435. else
  3436. {
  3437. $data = $_POST[$fieldname];
  3438. }
  3439. return $data;
  3440. }
  3441. /**
  3442. * Backend code for the JSON login interface. Basically a frontend to the session API that takes all parameters in one huge array.
  3443. * @param array LoginAPI request
  3444. * @return array LoginAPI response
  3445. */
  3446. function process_login_request($req)
  3447. {
  3448. global $db, $session, $paths, $template, $plugins; // Common objects
  3449. // Setup EnanoMath and Diffie-Hellman
  3450. global $dh_supported;
  3451. if ( !function_exists('dh_gen_private') )
  3452. {
  3453. require_once(ENANO_ROOT.'/includes/math.php');
  3454. $dh_supported = true;
  3455. try
  3456. {
  3457. require_once(ENANO_ROOT . '/includes/diffiehellman.php');
  3458. }
  3459. catch ( Exception $e )
  3460. {
  3461. $dh_supported = false;
  3462. }
  3463. }
  3464. global $_math;
  3465. // Check for the mode
  3466. if ( !isset($req['mode']) )
  3467. {
  3468. return $this->get_login_response('api_error', 'ERR_JSON_NO_MODE');
  3469. }
  3470. // Main processing switch
  3471. switch ( $req['mode'] )
  3472. {
  3473. default:
  3474. return $this->get_login_response('api_error', 'ERR_JSON_INVALID_MODE');
  3475. break;
  3476. case 'getkey':
  3477. $this->start();
  3478. return $this->get_login_response('initial');
  3479. break;
  3480. case 'login_dh':
  3481. // User is requesting a login and has sent Diffie-Hellman data.
  3482. //
  3483. // KEY RECONSTRUCTION
  3484. //
  3485. $userinfo_crypt = $req['userinfo'];
  3486. $dh_public = $req['dh_public_key'];
  3487. $dh_hash = $req['dh_secret_hash'];
  3488. // Check the key
  3489. if ( !ctype_digit($dh_public) || !ctype_digit($req['dh_client_key']) )
  3490. {
  3491. return $this->get_login_response('api_error', 'ERR_DH_KEY_NOT_NUMERIC');
  3492. }
  3493. // Fetch private key
  3494. $q = $db->sql_query('SELECT private_key, key_id FROM ' . table_prefix . "diffiehellman WHERE public_key = '$dh_public';");
  3495. if ( !$q )
  3496. $db->die_json();
  3497. if ( $db->numrows() < 1 )
  3498. {
  3499. return $this->get_login_response('api_error', 'ERR_DH_KEY_NOT_FOUND');
  3500. }
  3501. list($dh_private, $dh_key_id) = $db->fetchrow_num();
  3502. $db->free_result();
  3503. // We have the private key, now delete the key pair, we no longer need it
  3504. $q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE key_id = $dh_key_id;");
  3505. if ( !$q )
  3506. $db->die_json();
  3507. // Generate the shared secret
  3508. $dh_secret = dh_gen_shared_secret($dh_private, $req['dh_client_key']);
  3509. $dh_secret = $_math->str($dh_secret);
  3510. // Did we get all our math right?
  3511. $dh_secret_check = sha1($dh_secret);
  3512. if ( $dh_secret_check !== $dh_hash )
  3513. {
  3514. return $this->get_login_response('api_error', 'ERR_DH_HASH_NO_MATCH');
  3515. }
  3516. // All good! Generate the AES key
  3517. $aes_key = substr(sha256($dh_secret), 0, ( AES_BITS / 4 ));
  3518. case 'login_aes':
  3519. if ( $req['mode'] == 'login_aes' )
  3520. {
  3521. // login_aes-specific code
  3522. $aes_key = $this->fetch_public_key($req['key_aes']);
  3523. if ( !$aes_key )
  3524. {
  3525. return $this->get_login_response('api_error', 'ERR_AES_LOOKUP_FAILED');
  3526. }
  3527. $userinfo_crypt = $req['userinfo'];
  3528. }
  3529. // shared between the two systems from here on out
  3530. // decrypt user info
  3531. $aes_key = hexdecode($aes_key);
  3532. $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
  3533. // using "true" here disables caching of the decrypted login info (which includes the password)
  3534. $userinfo_json = $aes->decrypt($userinfo_crypt, $aes_key, ENC_HEX, true);
  3535. if ( !$userinfo_json )
  3536. {
  3537. return $this->get_login_response('api_error', 'ERR_AES_DECRYPT_FAILED');
  3538. }
  3539. // de-JSON user info
  3540. try
  3541. {
  3542. $userinfo = enano_json_decode($userinfo_json);
  3543. }
  3544. catch ( Exception $e )
  3545. {
  3546. return $this->get_login_response('api_error', 'ERR_USERINFO_DECODE_FAILED');
  3547. }
  3548. case 'login_pt':
  3549. // plaintext login
  3550. if ( $req['mode'] == 'login_pt' )
  3551. {
  3552. $userinfo = isset($req['userinfo']) ? $req['userinfo'] : array();
  3553. }
  3554. if ( !isset($userinfo['username']) || !isset($userinfo['password']) )
  3555. {
  3556. return $this->get_login_response('api_error', 'ERR_USERINFO_MISSING_VALUES');
  3557. }
  3558. $username =& $userinfo['username'];
  3559. $password =& $userinfo['password'];
  3560. // locked out? check captcha
  3561. $lockout_data = $this->get_lockout_info();
  3562. if ( $lockout_data['policy'] == 'captcha' && $lockout_data['active'] )
  3563. {
  3564. // policy is captcha -- check if it's correct, and if so, bypass lockout check
  3565. $real_code = $this->get_captcha($req['captcha_hash']);
  3566. if ( strtolower($real_code) !== strtolower($req['captcha_code']) )
  3567. {
  3568. // captcha is bad
  3569. return $this->get_login_response('login_failure', 'lockout_bad_captcha');
  3570. }
  3571. }
  3572. else if ( $lockout_data['policy'] == 'lockout' && $lockout_data['active'] )
  3573. {
  3574. // we're fully locked out
  3575. return $this->get_login_response('login_failure', 'lockout_request_denied');
  3576. }
  3577. // At this point if any extra info was injected into the login data packet, we need to let plugins process it
  3578. /**
  3579. * Called upon processing an incoming login request. If you added anything to the userinfo object during the jshook
  3580. * login_build_userinfo, that will be in the $userinfo array here. Expected return values are: true if your plugin has
  3581. * not only succeeded but ALSO issued a session key (bypass the whole Enano builtin login process) and an associative array
  3582. * with "mode" set to "error" and an error string in "error" to send an error back to the client. Any return value other
  3583. * than these will be treated as a pass-through, and the user's password will be validated through Enano's standard process.
  3584. * @hook login_process_userdata_json
  3585. */
  3586. $code = $plugins->setHook('login_process_userdata_json', true);
  3587. foreach ( $code as $cmd )
  3588. {
  3589. $result = eval($cmd);
  3590. if ( $result === true )
  3591. {
  3592. return $this->get_login_response('login_success', false, array(
  3593. 'key' => $this->sid_super,
  3594. 'user_id' => $this->user_id,
  3595. 'user_level' => $this->user_level,
  3596. 'reset' => false
  3597. ));
  3598. }
  3599. else if ( is_array($result) )
  3600. {
  3601. if ( isset($result['mode']) && $result['mode'] === 'error' && isset($result['error']) )
  3602. {
  3603. // Pass back any additional information from the error response
  3604. $append = $result;
  3605. unset($append['mode'], $append['error']);
  3606. $append['from_plugin'] = true;
  3607. return $this->get_login_response('login_failure', $result['error'], $append);
  3608. }
  3609. }
  3610. }
  3611. // attempt the login
  3612. $login_result = $this->login_without_crypto($username, $password, false, intval($req['level']), @$req['remember']);
  3613. if ( $login_result['success'] )
  3614. {
  3615. return $this->get_login_response('login_success', false, array(
  3616. 'key' => $this->sid_super,
  3617. 'user_id' => $this->user_id,
  3618. 'user_level' => $this->user_level,
  3619. ));
  3620. }
  3621. else if ( !$login_result['success'] && $login_result['error'] === 'valid_reset' )
  3622. {
  3623. return $this->get_login_response('reset_pass_used', false, array(
  3624. 'redirect_url' => $login_result['redirect_url']
  3625. ));
  3626. }
  3627. else
  3628. {
  3629. return $this->get_login_response('login_failure', 'invalid_credentials');
  3630. }
  3631. break;
  3632. case 'clean_key':
  3633. // Clean out a key, since it won't be used.
  3634. // This is called when the user clicks Cancel in the AJAX login interface.
  3635. if ( !empty($req['key_aes']) )
  3636. {
  3637. $this->fetch_public_key($req['key_aes']);
  3638. }
  3639. if ( !empty($req['key_dh']) )
  3640. {
  3641. $pk = $db->escape($req['key_dh']);
  3642. $q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE public_key = '$pk';");
  3643. if ( !$q )
  3644. $db->die_json();
  3645. }
  3646. return array(
  3647. 'mode' => 'noop'
  3648. );
  3649. break;
  3650. case 'respond_password_reset':
  3651. die(enano_json_encode(array(
  3652. 'mode' => 'login_success_reset',
  3653. 'user_id' => $req['user_id'],
  3654. 'temp_password' => $req['temp_password'],
  3655. 'respawn_info' => $this->process_login_request(array('mode' => 'getkey'))
  3656. )));
  3657. break;
  3658. case 'logout':
  3659. if ( !$this->started )
  3660. $this->start();
  3661. if ( !isset($req['csrf_token']) )
  3662. return array(
  3663. 'mode' => 'error',
  3664. 'error' => 'Invalid CSRF token'
  3665. );
  3666. if ( $req['csrf_token'] !== $this->csrf_token )
  3667. return array(
  3668. 'mode' => 'error',
  3669. 'error' => 'Invalid CSRF token'
  3670. );
  3671. $level = isset($req['level']) && is_int($req['level']) ? $req['level'] : USER_LEVEL_MEMBER;
  3672. if ( ($result = $this->logout($level)) === 'success' )
  3673. {
  3674. return array(
  3675. 'mode' => 'logout_success'
  3676. );
  3677. }
  3678. else
  3679. {
  3680. return array(
  3681. 'mode' => 'error',
  3682. 'error' => $result
  3683. );
  3684. }
  3685. break;
  3686. }
  3687. }
  3688. /**
  3689. * Generate a packet to send to the client for logins.
  3690. * @param string mode
  3691. * @param array
  3692. * @return array
  3693. */
  3694. function get_login_response($mode, $error = false, $base = array())
  3695. {
  3696. $this->start();
  3697. // init
  3698. $response = $base;
  3699. // modules in the packet
  3700. $response['mode'] = $mode;
  3701. $response['error'] = $error;
  3702. $response['crypto'] = $mode !== 'login_success' ? $this->get_login_crypto_packet() : false;
  3703. $response['lockout'] = $mode !== 'login_success' ? $this->get_lockout_info() : false;
  3704. $response['extended_time'] = intval(getConfig('session_remember_time', '30'));
  3705. $response['username'] = $this->user_logged_in ? $this->username : false;
  3706. return $response;
  3707. }
  3708. /**
  3709. * Get a packet of crypto flags for login.
  3710. * @return array
  3711. */
  3712. function get_login_crypto_packet()
  3713. {
  3714. global $dh_supported, $_math;
  3715. $response = array();
  3716. $response['dh_enable'] = $dh_supported;
  3717. $response['aes_key'] = $this->rijndael_genkey();
  3718. // Can we do Diffie-Hellman? If so, generate and stash a public/private key pair.
  3719. if ( $dh_supported )
  3720. {
  3721. $dh_key_priv = dh_gen_private();
  3722. $dh_key_pub = dh_gen_public($dh_key_priv);
  3723. $dh_key_priv = $_math->str($dh_key_priv);
  3724. $dh_key_pub = $_math->str($dh_key_pub);
  3725. $response['dh_public_key'] = $dh_key_pub;
  3726. // store the keys in the DB
  3727. $this->sql('INSERT INTO ' . table_prefix . "diffiehellman( public_key, private_key ) VALUES ( '$dh_key_pub', '$dh_key_priv' );");
  3728. }
  3729. return $response;
  3730. }
  3731. }
  3732. /**
  3733. * Class used to fetch permissions for a specific page. Used internally by SessionManager.
  3734. * @package Enano
  3735. * @subpackage Session manager
  3736. * @license http://www.gnu.org/copyleft/gpl.html
  3737. * @access private
  3738. */
  3739. class Session_ACLPageInfo {
  3740. /**
  3741. * The page ID of this ACL info package
  3742. * @var string
  3743. */
  3744. var $page_id;
  3745. /**
  3746. * The namespace of the page being checked
  3747. * @var string
  3748. */
  3749. var $namespace;
  3750. /**
  3751. * Our list of permission types.
  3752. * @access private
  3753. * @var array
  3754. */
  3755. var $acl_types = Array();
  3756. /**
  3757. * The list of descriptions for the permission types
  3758. * @var array
  3759. */
  3760. var $acl_descs = Array();
  3761. /**
  3762. * A list of dependencies for ACL types.
  3763. * @var array
  3764. */
  3765. var $acl_deps = Array();
  3766. /**
  3767. * Our tell-all list of permissions. Do not even try to change this.
  3768. * @access private
  3769. * @var array
  3770. */
  3771. var $perms = Array();
  3772. /**
  3773. * Array to track which default permissions are being used
  3774. * @var array
  3775. * @access private
  3776. */
  3777. var $acl_defaults_used = Array();
  3778. /**
  3779. * Tracks whether Wiki Mode is on for the page we're operating on.
  3780. * @var bool
  3781. */
  3782. var $wiki_mode = false;
  3783. /**
  3784. * Tracks where permissions were calculated using the ACL_INHERIT_* constants. Layout:
  3785. * array(
  3786. * [permission_name] => array(
  3787. * [src] => ACL_INHERIT_*
  3788. * [rule_id] => integer
  3789. * ),
  3790. * ...
  3791. * )
  3792. *
  3793. * @var array
  3794. */
  3795. var $perm_resolve_table = array();
  3796. #
  3797. # USER PARAMETERS
  3798. #
  3799. /**
  3800. * User ID
  3801. * @var int
  3802. */
  3803. var $user_id = 1;
  3804. /**
  3805. * Group membership associative array (group_id => group_name)
  3806. * @var array
  3807. */
  3808. var $groups = array();
  3809. /**
  3810. * Constructor.
  3811. * @param string $page_id The ID of the page to check
  3812. * @param string $namespace The namespace of the page to check.
  3813. * @param array $acl_types List of ACL types
  3814. * @param array $acl_descs List of human-readable descriptions for permissions (associative)
  3815. * @param array $acl_deps List of dependencies for permissions. For example, viewing history/diffs depends on the ability to read the page.
  3816. * @param array $base What to start with - this is an attempt to reduce the number of SQL queries.
  3817. * @param int|string $user_id_or_name Username or ID to search for, defaults to current user
  3818. * @param array $resolve_table Debugging info for tracking where rules came from, defaults to a blank array.
  3819. */
  3820. function __construct($page_id, $namespace, $acl_types, $acl_descs, $acl_deps, $base, $user_id = null, $groups = null, $resolve_table = array())
  3821. {
  3822. global $db, $session, $paths, $template, $plugins; // Common objects
  3823. // hack
  3824. if ( isset($base['__resolve_table']) )
  3825. {
  3826. unset($base['__resolve_table']);
  3827. }
  3828. foreach ( $acl_types as $perm_type => $_ )
  3829. {
  3830. if ( !$session->check_acl_scope($perm_type, $namespace) )
  3831. {
  3832. unset($acl_types[$perm_type]);
  3833. unset($acl_deps[$perm_type]);
  3834. unset($acl_descs[$perm_type]);
  3835. unset($base[$perm_type]);
  3836. }
  3837. }
  3838. $this->acl_deps = $acl_deps;
  3839. $this->acl_types = $acl_types;
  3840. $this->acl_descs = $acl_descs;
  3841. $this->perms = $acl_types;
  3842. $this->perms = $session->acl_merge_complete($this->perms, $base);
  3843. $this->perm_resolve_table = array();
  3844. if ( is_array($resolve_table) )
  3845. $this->perm_resolve_table = $resolve_table;
  3846. if ( is_int($user_id) && is_array($groups) )
  3847. {
  3848. $this->user_id = $user_id;
  3849. $this->groups = $groups;
  3850. }
  3851. else
  3852. {
  3853. $this->user_id = $session->user_id;
  3854. $this->groups = $session->groups;
  3855. }
  3856. $this->page_id = $page_id;
  3857. $this->namespace = $namespace;
  3858. $this->__calculate();
  3859. }
  3860. /**
  3861. * Performs the actual permission calculation.
  3862. * @access private
  3863. */
  3864. private function __calculate()
  3865. {
  3866. global $db, $session, $paths, $template, $plugins; // Common objects
  3867. $page_id =& $this->page_id;
  3868. $namespace =& $this->namespace;
  3869. // PAGE group info
  3870. $pg_list = $paths->get_page_groups($page_id, $namespace);
  3871. $pg_info = '';
  3872. foreach ( $pg_list as $g_id )
  3873. {
  3874. $pg_info .= ' ( page_id=\'' . $g_id . '\' AND namespace=\'__PageGroup\' ) OR';
  3875. }
  3876. // Build a query to grab ACL info
  3877. $bs = 'SELECT rules,target_type,target_id,page_id,namespace,rule_id,pg.pg_name,g.group_name FROM '.table_prefix."acl AS a\n"
  3878. . " LEFT JOIN " . table_prefix . "page_groups AS pg\n"
  3879. . " ON ( ( a.page_id = CAST(pg.pg_id AS char) AND a.namespace = '__PageGroup' ) OR ( a.namespace != '__PageGroup' ) )\n"
  3880. . " LEFT JOIN " . table_prefix . "groups AS g\n"
  3881. . " ON ( ( a.target_type = " . ACL_TYPE_GROUP . " AND a.target_id = g.group_id ) OR ( a.target_type != " . ACL_TYPE_GROUP . " ) )\n";
  3882. $bs .= ' WHERE ' . "\n"
  3883. . ' ( ';
  3884. $q = Array();
  3885. $q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
  3886. if(count($this->groups) > 0)
  3887. {
  3888. foreach($this->groups as $g_id => $g_name)
  3889. {
  3890. $q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
  3891. }
  3892. }
  3893. // 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
  3894. // permissions to override group permissions.
  3895. $bs .= implode(" OR\n ", $q) . ' ) AND (' . $pg_info . ' ( page_id=\''.$db->escape($page_id).'\' AND namespace=\''.$db->escape($namespace).'\' ) )
  3896. ORDER BY target_type ASC, page_id ASC, namespace ASC;';
  3897. $q = $session->sql($bs);
  3898. if ( $row = $db->fetchrow($q, true) )
  3899. {
  3900. do
  3901. {
  3902. $rules = $session->string_to_perm($row['rules']);
  3903. $is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
  3904. // log where this comes from
  3905. if ( $row['namespace'] == '__PageGroup' )
  3906. {
  3907. $src = ( $is_everyone ) ? ACL_INHERIT_PG_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_PG_GROUP : ACL_INHERIT_PG_USER );
  3908. $pg_name = $row['pg_name'];
  3909. }
  3910. else
  3911. {
  3912. $src = ( $is_everyone ) ? ACL_INHERIT_LOCAL_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_LOCAL_GROUP : ACL_INHERIT_LOCAL_USER );
  3913. }
  3914. if ( $row['group_name'] )
  3915. {
  3916. $group_name = $row['group_name'];
  3917. }
  3918. foreach ( $rules as $perm_type => $perm_value )
  3919. {
  3920. if ( !isset($this->perms[$perm_type]) )
  3921. continue;
  3922. if ( $this->perms[$perm_type] == AUTH_DENY )
  3923. continue;
  3924. if ( !$session->check_acl_scope($perm_type, $this->namespace) )
  3925. continue;
  3926. $this->perm_resolve_table[$perm_type] = array(
  3927. 'src' => $src,
  3928. 'rule_id' => $row['rule_id']
  3929. );
  3930. if ( isset($pg_name) )
  3931. {
  3932. $this->perm_resolve_table[$perm_type]['pg_name'] = $pg_name;
  3933. }
  3934. if ( isset($group_name) )
  3935. {
  3936. $this->perm_resolve_table[$perm_type]['group_name'] = $group_name;
  3937. }
  3938. }
  3939. $this->acl_merge_with_current($rules, $is_everyone);
  3940. } while ( $row = $db->fetchrow() );
  3941. }
  3942. $this->page_id = $page_id;
  3943. $this->namespace = $namespace;
  3944. $pathskey = $paths->nslist[$this->namespace].sanitize_page_id($this->page_id);
  3945. $ns = namespace_factory($this->page_id, $this->namespace);
  3946. $cdata = $ns->get_cdata();
  3947. $this->wiki_mode = false;
  3948. $wiki_mode_eligible = ($session->user_logged_in && getConfig('wiki_mode_require_login', 0) == 1) || getConfig('wiki_mode_require_login', 0) == 0;
  3949. $global_wiki_mode = getConfig('wiki_mode', 0) == 1;
  3950. if ( $wiki_mode_eligible && (($cdata['wiki_mode'] == 2 && $global_wiki_mode) || $cdata['wiki_mode'] == 1))
  3951. $this->wiki_mode = true;
  3952. }
  3953. /**
  3954. * Tells us whether permission $type is allowed or not based on the current rules.
  3955. * @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
  3956. * @param bool $no_deps If true, disables dependency checking
  3957. * @return bool True if allowed, false if denied or if an error occured
  3958. */
  3959. function get_permissions($type, $no_deps = false)
  3960. {
  3961. // echo '<pre>' . print_r($this->perms, true) . '</pre>';
  3962. global $db, $session, $paths, $template, $plugins; // Common objects
  3963. if ( isset( $this->perms[$type] ) )
  3964. {
  3965. if ( $this->perms[$type] == AUTH_DENY )
  3966. {
  3967. $ret = false;
  3968. }
  3969. else if ( $this->perms[$type] == AUTH_WIKIMODE && $this->wiki_mode )
  3970. {
  3971. $ret = true;
  3972. }
  3973. else if ( $this->perms[$type] == AUTH_WIKIMODE && !$this->wiki_mode )
  3974. {
  3975. $ret = false;
  3976. }
  3977. else if ( $this->perms[$type] == AUTH_ALLOW )
  3978. {
  3979. $ret = true;
  3980. }
  3981. else if ( $this->perms[$type] == AUTH_DISALLOW )
  3982. {
  3983. $ret = false;
  3984. }
  3985. }
  3986. else if(isset($this->acl_types[$type]))
  3987. {
  3988. if ( $this->acl_types[$type] == AUTH_DENY )
  3989. $ret = false;
  3990. else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
  3991. $ret = true;
  3992. else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
  3993. $ret = false;
  3994. else if ( $this->acl_types[$type] == AUTH_ALLOW )
  3995. $ret = true;
  3996. else if ( $this->acl_types[$type] == AUTH_DISALLOW )
  3997. $ret = false;
  3998. }
  3999. else
  4000. {
  4001. // ACL type is undefined
  4002. $caller = 'unknown';
  4003. if ( function_exists('debug_backtrace') )
  4004. {
  4005. if ( $bt = @debug_backtrace() )
  4006. {
  4007. foreach ( $bt as $trace )
  4008. {
  4009. $file = basename($trace['file']);
  4010. if ( $file != 'sessions.php' )
  4011. {
  4012. $caller = $file . ':' . $trace['line'];
  4013. break;
  4014. }
  4015. }
  4016. }
  4017. }
  4018. trigger_error('Unknown access type "' . $type . '", called from ' . $caller . '', E_USER_WARNING);
  4019. return false; // Be on the safe side and deny access
  4020. }
  4021. if ( !$no_deps )
  4022. {
  4023. if ( !$this->acl_check_deps($type) )
  4024. return false;
  4025. }
  4026. return $ret;
  4027. }
  4028. /**
  4029. * Tell us if the dependencies for a given permission are met.
  4030. * @param string The ACL permission ID
  4031. * @param bool If true, does not return a boolean value, but instead returns array of dependencies that fail
  4032. * @return bool
  4033. */
  4034. function acl_check_deps($type, $debug = false)
  4035. {
  4036. // This will only happen if the permissions table is hacked or improperly accessed
  4037. if(!isset($this->acl_deps[$type]))
  4038. return $debug ? array() : true;
  4039. // Permission has no dependencies?
  4040. if(sizeof($this->acl_deps[$type]) < 1)
  4041. return $debug ? array() : true;
  4042. // go through them all and build a flat list of dependencies
  4043. $deps = $this->acl_deps[$type];
  4044. while(true)
  4045. {
  4046. $j = sizeof($deps);
  4047. for ( $i = 0; $i < $j; $i++ )
  4048. {
  4049. $b = $deps;
  4050. if ( !isset($this->acl_deps[$deps[$i]]) )
  4051. {
  4052. // Action $type depends on action $deps[$i] which cannot be satisfied because $deps[$i] is out of scope.
  4053. trigger_error("acl_check_deps: $type depends on {$deps[$i]} which is not within scope of $this->namespace; this indicates a bug in ACL rule specification", E_USER_WARNING);
  4054. return false;
  4055. }
  4056. $deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
  4057. if( $b == $deps )
  4058. {
  4059. break 2;
  4060. }
  4061. $j = sizeof($deps);
  4062. }
  4063. }
  4064. $debugdata = array();
  4065. foreach($deps as $d)
  4066. {
  4067. // Our dependencies are fully resolved, so tell get_permissions() to not recursively call this function
  4068. if ( !$this->get_permissions($d, true) )
  4069. {
  4070. if ( $debug )
  4071. {
  4072. $debugdata[] = $d;
  4073. }
  4074. else
  4075. {
  4076. return false;
  4077. }
  4078. }
  4079. }
  4080. return $debug ? $debugdata : true;
  4081. }
  4082. /**
  4083. * Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
  4084. * @param array The array to merge into the master ACL list
  4085. * @param bool If true, $perm is treated as the "new default"
  4086. * @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
  4087. */
  4088. function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
  4089. {
  4090. foreach ( $this->perms as $i => $p )
  4091. {
  4092. if ( isset($perm[$i]) )
  4093. {
  4094. if ( $is_everyone && !@$this->acl_defaults_used[$i] )
  4095. continue;
  4096. // Decide precedence
  4097. if ( isset($this->acl_defaults_used[$i]) )
  4098. {
  4099. //echo "$i: default in use, overriding to: {$perm[$i]}<br />";
  4100. // Defaults are in use, override
  4101. $this->perms[$i] = $perm[$i];
  4102. $this->acl_defaults_used[$i] = ( $is_everyone );
  4103. }
  4104. else
  4105. {
  4106. //echo "$i: default NOT in use";
  4107. // Defaults are not in use, merge as normal
  4108. if ( $this->perms[$i] != AUTH_DENY )
  4109. {
  4110. //echo ", but overriding";
  4111. $this->perms[$i] = $perm[$i];
  4112. }
  4113. //echo "<br />";
  4114. }
  4115. }
  4116. }
  4117. }
  4118. }
  4119. /**
  4120. * Cron task - clears out the database of Diffie-Hellman keys
  4121. */
  4122. function cron_clean_login_cache()
  4123. {
  4124. global $db, $session, $paths, $template, $plugins; // Common objects
  4125. if ( !$db->sql_query('DELETE FROM ' . table_prefix . 'diffiehellman;') )
  4126. $db->_die();
  4127. setConfig('login_key_cache', '');
  4128. }
  4129. register_cron_task('cron_clean_login_cache', 72);
  4130. /**
  4131. * Cron task - clears out outdated high-auth session keys
  4132. */
  4133. function cron_clean_old_admin_keys()
  4134. {
  4135. global $db, $session, $paths, $template, $plugins; // Common objects
  4136. $threshold = time() - ( 15 * 60 );
  4137. $ul_member = USER_LEVEL_MEMBER;
  4138. if ( !$db->sql_query('DELETE FROM ' . table_prefix . "session_keys WHERE time < $threshold AND auth_level > $ul_member;") )
  4139. $db->_die();
  4140. }
  4141. // Once a week
  4142. register_cron_task('cron_clean_old_admin_keys', 168);
  4143. /**
  4144. * Cron task - regenerate cached user rank information
  4145. */
  4146. register_cron_task('generate_cache_userranks', 0.25);
  4147. ?>