PageRenderTime 56ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/include/functions.php

https://github.com/Dratone/EveBB
PHP | 2207 lines | 1454 code | 382 blank | 371 comment | 374 complexity | 373eb515493f9338fe1c15917bb8c171 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Copyright (C) 2008-2010 FluxBB
  4. * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
  5. * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
  6. */
  7. //
  8. // Return current timestamp (with microseconds) as a float
  9. //
  10. function get_microtime()
  11. {
  12. list($usec, $sec) = explode(' ', microtime());
  13. return ((float)$usec + (float)$sec);
  14. }
  15. //Real token generation.
  16. //This has been beefed up a little, by enhancing it's number of choices.
  17. //This takes it's "total number of possible combinations" from '751616304549', to '8.66106956337463e+24'
  18. //A brute force attack versus a server that will delay them is just not feasible at that stage.
  19. //It would be easier to break into the database.
  20. function gen_token() {
  21. $token = '';
  22. $chars = array(
  23. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  24. 'a', 'b', 'c', 'd', 'e', 'f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
  25. 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
  26. );
  27. for ($i = 0; $i < 32; $i++) {
  28. $token .= $chars[rand(0, count($chars)-1)];
  29. } //End 'i' for loop.
  30. return $token;
  31. } //End gen_token().
  32. //
  33. // Cookie stuff!
  34. //
  35. function check_cookie(&$pun_user)
  36. {
  37. global $db, $db_type, $pun_config, $cookie_seed;
  38. //Create a cookie name that can't clash in anyway, just to be one the safe side.
  39. //(Browsers *should* isolate the cookie per domain, but either way I don't want duplicate cookie names.)
  40. $cookie_name = str_replace('=', '', base64_encode($_SERVER['SERVER_NAME']));
  41. $now = gmmktime();
  42. $earlier = $now - $pun_config['session_length'];
  43. $much_earlier = $now - 2629743;
  44. $cookie = array();
  45. $matches = array();
  46. if (isset($_SERVER['HTTP_EVE_TRUSTED'])) {
  47. $_SESSION['igb'] = true;
  48. } else {
  49. $_SESSION['igb'] = false;
  50. } //End if - else.
  51. //Lets pull our session data out.
  52. if (isset($_COOKIE[$cookie_name]) && preg_match('/^(\d+)\:([0-9a-zA-Z]{32}):([0-9a-fA-F]{32})$/', $_COOKIE[$cookie_name], $matches)) {
  53. $cookie['user_id'] = intval($matches[1]);
  54. $cookie['token'] = $matches[2];
  55. $cookie['hash'] = $matches[3];
  56. $cookie['remember'] = 1;
  57. } else if (isset($_SESSION[$cookie_name]) && preg_match('/^(\d+)\:([0-9a-zA-Z]{32}):([0-9a-fA-F]{32})$/', $_SESSION[$cookie_name], $matches)) {
  58. $cookie['user_id'] = intval($matches[1]);
  59. $cookie['token'] = $matches[2];
  60. $cookie['hash'] = $matches[3];
  61. } //End if.
  62. if (!empty($cookie) && isset($cookie['user_id'])) {
  63. if (md5($cookie['user_id'].$cookie_seed.$cookie['token']) != $cookie['hash']) {
  64. if (defined('PUN_DEBUG')) {
  65. error('Hash mismatch.', __FILE__, __LINE__, $db->error());
  66. } //End if.
  67. unset($_SESSION[$cookie_name]);
  68. sleep(3);
  69. set_default_user();
  70. return; //The session has been messed with, abort!
  71. } //End if.
  72. $result = $db->query('
  73. SELECT
  74. sess.*,
  75. c.*,
  76. sc.*,
  77. u.*,
  78. g.*,
  79. o.logged,
  80. o.idle
  81. FROM
  82. '.$db->prefix.'session AS sess
  83. INNER JOIN
  84. '.$db->prefix.'users AS u
  85. ON
  86. sess.user_id=u.id
  87. INNER JOIN
  88. '.$db->prefix.'groups AS g
  89. ON
  90. u.group_id=g.g_id
  91. LEFT JOIN
  92. '.$db->prefix.'online AS o
  93. ON
  94. o.user_id=u.id
  95. LEFT JOIN
  96. '.$db->prefix.'api_selected_char AS sc
  97. ON
  98. u.id=sc.user_id
  99. LEFT JOIN
  100. '.$db->prefix.'api_characters AS c
  101. ON
  102. sc.character_id=c.character_id
  103. WHERE
  104. u.id='.intval($cookie['user_id']))
  105. or error('Unable to fetch user information', __FILE__, __LINE__, $db->error());
  106. if ($db->num_rows($result) != 1) {
  107. if (defined('PUN_DEBUG')) {
  108. error('No user found.', __FILE__, __LINE__, $db->error());
  109. } //End if.
  110. unset($_SESSION[$cookie_name]);
  111. set_default_user();
  112. sleep(3);
  113. return; //Chances are they have no active session.
  114. } //End if.
  115. $pun_user = $db->fetch_assoc($result);
  116. if ($pun_user['token'] != $cookie['token']) {
  117. if (defined('PUN_DEBUG')) {
  118. error('Token mismatch: '.$pun_user['token'].', '.$cookie['token'], __FILE__, __LINE__, $db->error());
  119. } //End if.
  120. //Even though this failed, because of the possibility of external tomfoolery, we won't remove the session.
  121. if (isset($cookie['remember'])) {
  122. $expire = $now + 31536000; // The cookie expires after a year
  123. forum_setcookie($cookie_name, pun_hash(uniqid(rand(), true)), $expire);
  124. } //End if.
  125. unset($_SESSION[$cookie_name]);
  126. set_default_user();
  127. sleep(3);
  128. return; //Trying to access from an old session, or they are evil!
  129. } //End if.
  130. //Is the stamp old or are they using a session cookie from a different IP?
  131. if ($now > ($pun_user['stamp'] + $pun_user['length']) || (($pun_user['ip'] != $_SERVER['REMOTE_ADDR']) && !isset($cookie['remember']))) {
  132. if (defined('PUN_DEBUG')) {
  133. error('IP or stamp mismatch.', __FILE__, __LINE__, $db->error());
  134. } //End if.
  135. $db->query("DELETE FROM ".$db->prefix."session WHERE user_id=".$pun_user['id']); //Get rid of the old session.
  136. if (isset($cookie['remember'])) {
  137. $expire = $now + 31536000; // The cookie expires after a year
  138. forum_setcookie($cookie_name, pun_hash(uniqid(rand(), true)), $expire);
  139. } //End if.
  140. unset($_SESSION[$cookie_name]);
  141. set_default_user();
  142. return;
  143. } //End if.
  144. //If they got this far, they provided a valid token with a valid user_id.
  145. $token = $pun_user['token'];
  146. //Lets update all our tracking bits.
  147. $db->query("UPDATE ".$db->prefix."session SET stamp=".$now.", length=".((isset($cookie['remember'])) ? 2629743 : $pun_config['session_length'])." WHERE user_id=".$pun_user['id']);
  148. if (isset($cookie['remember']) && !isset($_SESSION['remember']) && $pun_config['o_regen_token'] == '1') {
  149. //Let's generate a new token if they got here via a cookie login that doesn't have a session attached to it.
  150. $_SESSION['remember'] = 1;
  151. $token = gen_token();
  152. $pun_user['token'] = $token;
  153. $db->query("UPDATE ".$db->prefix."session SET token='".$token."' WHERE user_id=".$pun_user['id']);
  154. } else if (isset($cookie['remember'])) {
  155. $_SESSION['remember'] = 1;
  156. } //End if - else.
  157. // Send a new, updated cookie with a new expiration timestamp
  158. if (isset($cookie['remember'])) {
  159. forum_setcookie($cookie_name, $pun_user['id'].':'.$token.':'.md5($pun_user['id'].$cookie_seed.$token), $now+2629743); //Expire the cookie in 1 month.
  160. } //End if - else.
  161. //Update the PHP Session.
  162. $_SESSION[$cookie_name] = $pun_user['id'].':'.$token.':'.md5($pun_user['id'].$cookie_seed.$token);
  163. // Set a default language if the user selected language no longer exists
  164. if (!file_exists(PUN_ROOT.'lang/'.$pun_user['language']))
  165. $pun_user['language'] = $pun_config['o_default_lang'];
  166. // Set a default style if the user selected style no longer exists
  167. if (!file_exists(PUN_ROOT.'style/'.$pun_user['style'].'.css'))
  168. $pun_user['style'] = $pun_config['o_default_style'];
  169. if (!$pun_user['disp_topics'])
  170. $pun_user['disp_topics'] = $pun_config['o_disp_topics_default'];
  171. if (!$pun_user['disp_posts'])
  172. $pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
  173. // Define this if you want this visit to affect the online list and the users last visit data
  174. if (!defined('PUN_QUIET_VISIT'))
  175. {
  176. // Update the online list
  177. if (!$pun_user['logged'])
  178. {
  179. $pun_user['logged'] = $now;
  180. // With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
  181. switch ($db_type)
  182. {
  183. case 'mysql':
  184. case 'mysqli':
  185. case 'mysql_innodb':
  186. case 'mysqli_innodb':
  187. case 'sqlite':
  188. $db->query('REPLACE INTO '.$db->prefix.'online (user_id, ident, logged) VALUES('.$pun_user['id'].', \''.$db->escape($pun_user['username']).'\', '.$pun_user['logged'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
  189. break;
  190. default:
  191. $db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) SELECT '.$pun_user['id'].', \''.$db->escape($pun_user['username']).'\', '.$pun_user['logged'].' WHERE NOT EXISTS (SELECT 1 FROM '.$db->prefix.'online WHERE user_id='.$pun_user['id'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
  192. break;
  193. }
  194. // Reset tracked topics
  195. set_tracked_topics(null);
  196. }
  197. else
  198. {
  199. // Special case: We've timed out, but no other user has browsed the forums since we timed out
  200. if ($pun_user['logged'] < ($now-$pun_config['o_timeout_visit']))
  201. {
  202. $db->query('UPDATE '.$db->prefix.'users SET last_visit='.$pun_user['logged'].' WHERE id='.$pun_user['id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());
  203. $pun_user['last_visit'] = $pun_user['logged'];
  204. }
  205. $idle_sql = ($pun_user['idle'] == '1') ? ', idle=0' : '';
  206. $db->query('UPDATE '.$db->prefix.'online SET logged='.$now.$idle_sql.' WHERE user_id='.$pun_user['id']) or error('Unable to update online list', __FILE__, __LINE__, $db->error());
  207. // Update tracked topics with the current expire time
  208. if (isset($_COOKIE[$cookie_name.'_track']))
  209. forum_setcookie($cookie_name.'_track', $_COOKIE[$cookie_name.'_track'], $now + $pun_config['o_timeout_visit']);
  210. }
  211. }
  212. else
  213. {
  214. if (!$pun_user['logged'])
  215. $pun_user['logged'] = $pun_user['last_visit'];
  216. }
  217. $pun_user['is_guest'] = false;
  218. $pun_user['is_admmod'] = $pun_user['g_id'] == PUN_ADMIN || $pun_user['g_moderator'] == '1';
  219. /* EVE-BB Multi-group support.*/
  220. //We only look at their other groups if they aren't set as the purge group as primary.
  221. if ($pun_user['g_id'] != $pun_config['o_eve_restricted_group']) {
  222. $sql = "SELECT group_id FROM ".$db->prefix."groups_users WHERE user_id=".$pun_user['id'];
  223. $result = $db->query($sql) or error('Unable to fetch group list', __FILE__, __LINE__, $db->error());
  224. $pun_user['group_ids'] = array();
  225. while ($row = $db->fetch_assoc($result)) {
  226. $pun_user['group_ids'][] = $row['group_id'];
  227. if ($row['group_id'] == PUN_ADMIN) {
  228. $pun_user['is_admmod'] = true;
  229. $pun_user['g_id'] = PUN_ADMIN;
  230. } else if ($row['group_id'] == PUN_MOD) {
  231. $pun_user['is_admmod'] = true;
  232. } //End if - elseif.
  233. } //End while loop.
  234. } //End if.
  235. /* EVE-BB Multi-group support.*/
  236. } else {
  237. set_default_user();
  238. } //End if - else.
  239. }
  240. //
  241. // Converts the CDATA end sequence ]]> into ]]&gt;
  242. //
  243. function escape_cdata($str)
  244. {
  245. return str_replace(']]>', ']]&gt;', $str);
  246. }
  247. //
  248. // Authenticates the provided username and password against the user database
  249. // $user can be either a user ID (integer) or a username (string)
  250. // $password can be either a plaintext password or a password hash including salt ($password_is_hash must be set accordingly)
  251. //
  252. function authenticate_user($user, $password, $password_is_hash = false)
  253. {
  254. global $db, $pun_user;
  255. // Check if there's a user matching $user and $password
  256. $result = $db->query('SELECT u.*, g.*, o.logged, o.idle FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON g.g_id=u.group_id LEFT JOIN '.$db->prefix.'online AS o ON o.user_id=u.id WHERE '.(is_int($user) ? 'u.id='.intval($user) : 'u.username=\''.$db->escape($user).'\'')) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
  257. $pun_user = $db->fetch_assoc($result);
  258. if (!isset($pun_user['id']) ||
  259. ($password_is_hash && $password != $pun_user['password']) ||
  260. (!$password_is_hash && pun_hash($password) != $pun_user['password']))
  261. set_default_user();
  262. else
  263. $pun_user['is_guest'] = false;
  264. }
  265. //
  266. // Try to determine the current URL
  267. //
  268. function get_current_url($max_length = 0)
  269. {
  270. $protocol = get_current_protocol();
  271. $port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'] != '80' && $protocol == 'http') || ($_SERVER['SERVER_PORT'] != '443' && $protocol == 'https')) && strpos($_SERVER['HTTP_HOST'], ':') === false) ? ':'.$_SERVER['SERVER_PORT'] : '';
  272. $url = urldecode($protocol.'://'.$_SERVER['HTTP_HOST'].$port.$_SERVER['REQUEST_URI']);
  273. if (strlen($url) <= $max_length || $max_length == 0)
  274. return $url;
  275. // We can't find a short enough url
  276. return null;
  277. }
  278. //
  279. // Fetch the current protocol in use - http or https
  280. //
  281. function get_current_protocol()
  282. {
  283. $protocol = 'http';
  284. // Check if the server is claiming to using HTTPS
  285. if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off')
  286. $protocol = 'https';
  287. // If we are behind a reverse proxy try to decide which protocol it is using
  288. if (defined('FORUM_BEHIND_REVERSE_PROXY'))
  289. {
  290. // Check if we are behind a Microsoft based reverse proxy
  291. if (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) != 'off')
  292. $protocol = 'https';
  293. // Check if we're behind a "proper" reverse proxy, and what protocol it's using
  294. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
  295. $protocol = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']);
  296. }
  297. return $protocol;
  298. }
  299. //
  300. // Fetch the base_url, optionally support HTTPS and HTTP
  301. //
  302. function get_base_url($support_https = false)
  303. {
  304. global $pun_config;
  305. static $base_url;
  306. if (!$support_https)
  307. return $pun_config['o_base_url'];
  308. if (!isset($base_url))
  309. {
  310. // Make sure we are using the correct protocol
  311. $base_url = str_replace(array('http://', 'https://'), get_current_protocol().'://', $pun_config['o_base_url']);
  312. }
  313. return $base_url;
  314. }
  315. //
  316. // Fill $pun_user with default values (for guests)
  317. //
  318. function set_default_user()
  319. {
  320. global $db, $db_type, $pun_user, $pun_config;
  321. $remote_addr = get_remote_address();
  322. // Fetch guest user
  323. $result = $db->query('SELECT u.*, g.*, o.logged, o.last_post, o.last_search FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.ident=\''.$remote_addr.'\' WHERE u.id=1') or error('Unable to fetch guest information', __FILE__, __LINE__, $db->error());
  324. if (!$db->num_rows($result))
  325. exit('Unable to fetch guest information. The table \''.$db->prefix.'users\' must contain an entry with id = 1 that represents anonymous users.');
  326. $pun_user = $db->fetch_assoc($result);
  327. // Update online list
  328. if (!$pun_user['logged'])
  329. {
  330. $pun_user['logged'] = time();
  331. // With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
  332. switch ($db_type)
  333. {
  334. case 'mysql':
  335. case 'mysqli':
  336. case 'mysql_innodb':
  337. case 'mysqli_innodb':
  338. case 'sqlite':
  339. $db->query('REPLACE INTO '.$db->prefix.'online (user_id, ident, logged) VALUES(1, \''.$db->escape($remote_addr).'\', '.$pun_user['logged'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
  340. break;
  341. default:
  342. $db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) SELECT 1, \''.$db->escape($remote_addr).'\', '.$pun_user['logged'].' WHERE NOT EXISTS (SELECT 1 FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($remote_addr).'\')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
  343. break;
  344. }
  345. }
  346. else
  347. $db->query('UPDATE '.$db->prefix.'online SET logged='.time().' WHERE ident=\''.$db->escape($remote_addr).'\'') or error('Unable to update online list', __FILE__, __LINE__, $db->error());
  348. $pun_user['disp_topics'] = $pun_config['o_disp_topics_default'];
  349. $pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
  350. $pun_user['timezone'] = $pun_config['o_default_timezone'];
  351. $pun_user['dst'] = $pun_config['o_default_dst'];
  352. $pun_user['language'] = $pun_config['o_default_lang'];
  353. $pun_user['style'] = $pun_config['o_default_style'];
  354. $pun_user['is_guest'] = true;
  355. $pun_user['is_admmod'] = false;
  356. }
  357. //
  358. // SHA1 HMAC with PHP 4 fallback
  359. //
  360. function forum_hmac($data, $key, $raw_output = false)
  361. {
  362. if (function_exists('hash_hmac'))
  363. return hash_hmac('sha1', $data, $key, $raw_output);
  364. // If key size more than blocksize then we hash it once
  365. if (strlen($key) > 64)
  366. $key = pack('H*', sha1($key)); // we have to use raw output here to match the standard
  367. // Ensure we're padded to exactly one block boundary
  368. $key = str_pad($key, 64, chr(0x00));
  369. $hmac_opad = str_repeat(chr(0x5C), 64);
  370. $hmac_ipad = str_repeat(chr(0x36), 64);
  371. // Do inner and outer padding
  372. for ($i = 0;$i < 64;$i++) {
  373. $hmac_opad[$i] = $hmac_opad[$i] ^ $key[$i];
  374. $hmac_ipad[$i] = $hmac_ipad[$i] ^ $key[$i];
  375. }
  376. // Finally, calculate the HMAC
  377. $hash = sha1($hmac_opad.pack('H*', sha1($hmac_ipad.$data)));
  378. // If we want raw output then we need to pack the final result
  379. if ($raw_output)
  380. $hash = pack('H*', $hash);
  381. return $hash;
  382. }
  383. //
  384. // Set a cookie, FluxBB style!
  385. // Wrapper for forum_setcookie
  386. //
  387. function pun_setcookie($user_id, $password_hash, $expire)
  388. {
  389. global $cookie_seed;
  390. $cookie_name = base64_encode($_SERVER['SERVER_NAME']);
  391. forum_setcookie($cookie_name, $user_id.'|'.forum_hmac($password_hash, $cookie_seed.'_password_hash').'|'.$expire.'|'.forum_hmac($user_id.'|'.$expire, $cookie_seed.'_cookie_hash'), $expire);
  392. }
  393. //
  394. // Set a cookie, FluxBB style!
  395. //
  396. function forum_setcookie($name, $value, $expire)
  397. {
  398. global $cookie_path, $cookie_domain, $cookie_secure;
  399. // Enable sending of a P3P header
  400. header('P3P: CP="CUR ADM"');
  401. if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
  402. setcookie($name, $value, $expire, $cookie_path, $cookie_domain, $cookie_secure, true);
  403. } else {
  404. setcookie($name, $value, $expire, $cookie_path.'; HttpOnly', $cookie_domain, $cookie_secure);
  405. } //End if - else.
  406. }
  407. //
  408. // Check whether the connecting user is banned (and delete any expired bans while we're at it)
  409. //
  410. function check_bans()
  411. {
  412. global $db, $pun_config, $lang_common, $pun_user, $pun_bans;
  413. // Admins and moderators aren't affected
  414. if ($pun_user['is_admmod'] || !$pun_bans)
  415. return;
  416. // Add a dot or a colon (depending on IPv4/IPv6) at the end of the IP address to prevent banned address
  417. // 192.168.0.5 from matching e.g. 192.168.0.50
  418. $user_ip = get_remote_address();
  419. $user_ip .= (strpos($user_ip, '.') !== false) ? '.' : ':';
  420. $bans_altered = false;
  421. $is_banned = false;
  422. foreach ($pun_bans as $cur_ban)
  423. {
  424. // Has this ban expired?
  425. if ($cur_ban['expire'] != '' && $cur_ban['expire'] <= time())
  426. {
  427. $db->query('DELETE FROM '.$db->prefix.'bans WHERE id='.$cur_ban['id']) or error('Unable to delete expired ban', __FILE__, __LINE__, $db->error());
  428. $bans_altered = true;
  429. continue;
  430. }
  431. if ($cur_ban['username'] != '' && utf8_strtolower($pun_user['username']) == utf8_strtolower($cur_ban['username']))
  432. $is_banned = true;
  433. if ($cur_ban['ip'] != '')
  434. {
  435. $cur_ban_ips = explode(' ', $cur_ban['ip']);
  436. $num_ips = count($cur_ban_ips);
  437. for ($i = 0; $i < $num_ips; ++$i)
  438. {
  439. // Add the proper ending to the ban
  440. if (strpos($user_ip, '.') !== false)
  441. $cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
  442. else
  443. $cur_ban_ips[$i] = $cur_ban_ips[$i].':';
  444. if (substr($user_ip, 0, strlen($cur_ban_ips[$i])) == $cur_ban_ips[$i])
  445. {
  446. $is_banned = true;
  447. break;
  448. }
  449. }
  450. }
  451. if ($is_banned)
  452. {
  453. $db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($pun_user['username']).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
  454. message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
  455. }
  456. }
  457. // If we removed any expired bans during our run-through, we need to regenerate the bans cache
  458. if ($bans_altered)
  459. {
  460. if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
  461. require PUN_ROOT.'include/cache.php';
  462. generate_bans_cache();
  463. }
  464. }
  465. //
  466. // Check username
  467. //
  468. function check_username($username, $exclude_id = null)
  469. {
  470. global $db, $pun_config, $errors, $lang_prof_reg, $lang_register, $lang_common, $pun_bans;
  471. // Convert multiple whitespace characters into one (to prevent people from registering with indistinguishable usernames)
  472. $username = preg_replace('#\s+#s', ' ', $username);
  473. // Validate username
  474. if (pun_strlen($username) < 2)
  475. $errors[] = $lang_prof_reg['Username too short'];
  476. else if (pun_strlen($username) > 25) // This usually doesn't happen since the form element only accepts 25 characters
  477. $errors[] = $lang_prof_reg['Username too long'];
  478. else if (!strcasecmp($username, 'Guest') || !strcasecmp($username, $lang_common['Guest']))
  479. $errors[] = $lang_prof_reg['Username guest'];
  480. else if (preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $username) || preg_match('/((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))/', $username))
  481. $errors[] = $lang_prof_reg['Username IP'];
  482. else if ((strpos($username, '[') !== false || strpos($username, ']') !== false) && strpos($username, '\'') !== false && strpos($username, '"') !== false)
  483. $errors[] = $lang_prof_reg['Username reserved chars'];
  484. else if (preg_match('/(?:\[\/?(?:b|u|s|ins|del|em|i|h|colou?r|quote|code|img|url|email|list|\*)\]|\[(?:img|url|quote|list)=)/i', $username))
  485. $errors[] = $lang_prof_reg['Username BBCode'];
  486. // Check username for any censored words
  487. if ($pun_config['o_censoring'] == '1' && censor_words($username) != $username)
  488. $errors[] = $lang_register['Username censor'];
  489. // Check that the username (or a too similar username) is not already registered
  490. $query = ($exclude_id) ? ' AND id!='.$exclude_id : '';
  491. $result = $db->query('SELECT username FROM '.$db->prefix.'users WHERE (UPPER(username)=UPPER(\''.$db->escape($username).'\') OR UPPER(username)=UPPER(\''.$db->escape(ucp_preg_replace('/[^\p{L}\p{N}]/u', '', $username)).'\')) AND id>1'.$query) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
  492. if ($db->num_rows($result))
  493. {
  494. $busy = $db->result($result);
  495. $errors[] = $lang_register['Username dupe 1'].' '.pun_htmlspecialchars($busy).'. '.$lang_register['Username dupe 2'];
  496. }
  497. // Check username for any banned usernames
  498. foreach ($pun_bans as $cur_ban)
  499. {
  500. if ($cur_ban['username'] != '' && utf8_strtolower($username) == utf8_strtolower($cur_ban['username']))
  501. {
  502. $errors[] = $lang_prof_reg['Banned username'];
  503. break;
  504. }
  505. }
  506. }
  507. //
  508. // Update "Users online"
  509. //
  510. function update_users_online()
  511. {
  512. global $db, $pun_config;
  513. $now = time();
  514. // Fetch all online list entries that are older than "o_timeout_online"
  515. $result = $db->query('SELECT user_id, ident, logged, idle FROM '.$db->prefix.'online WHERE logged<'.($now-$pun_config['o_timeout_online'])) or error('Unable to fetch old entries from online list', __FILE__, __LINE__, $db->error());
  516. while ($cur_user = $db->fetch_assoc($result))
  517. {
  518. // If the entry is a guest, delete it
  519. if ($cur_user['user_id'] == '1')
  520. $db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($cur_user['ident']).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
  521. else
  522. {
  523. // If the entry is older than "o_timeout_visit", update last_visit for the user in question, then delete him/her from the online list
  524. if ($cur_user['logged'] < ($now-$pun_config['o_timeout_visit']))
  525. {
  526. $db->query('UPDATE '.$db->prefix.'users SET last_visit='.$cur_user['logged'].' WHERE id='.$cur_user['user_id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());
  527. $db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$cur_user['user_id']) or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
  528. }
  529. else if ($cur_user['idle'] == '0')
  530. $db->query('UPDATE '.$db->prefix.'online SET idle=1 WHERE user_id='.$cur_user['user_id']) or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
  531. }
  532. }
  533. }
  534. //
  535. // Display the profile navigation menu
  536. //
  537. function generate_profile_menu($page = '')
  538. {
  539. global $lang_profile, $pun_config, $pun_user, $id;
  540. ?>
  541. <div id="profile" class="block2col">
  542. <div class="blockmenu">
  543. <h2><span><?php echo $lang_profile['Profile menu'] ?></span></h2>
  544. <div class="box">
  545. <div class="inbox">
  546. <ul>
  547. <li<?php if ($page == 'essentials') echo ' class="isactive"'; ?>><a href="profile.php?section=essentials&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section essentials'] ?></a></li>
  548. <li<?php if ($page == 'characters') echo ' class="isactive"'; ?>><a href="profile.php?section=characters&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section characters'] ?></a></li>
  549. <li<?php if ($page == 'personal') echo ' class="isactive"'; ?>><a href="profile.php?section=personal&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section personal'] ?></a></li>
  550. <li<?php if ($page == 'messaging') echo ' class="isactive"'; ?>><a href="profile.php?section=messaging&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section messaging'] ?></a></li>
  551. <?php if ($pun_config['o_avatars'] == '1' || $pun_config['o_signatures'] == '1'): ?> <li<?php if ($page == 'personality') echo ' class="isactive"'; ?>><a href="profile.php?section=personality&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section personality'] ?></a></li>
  552. <?php endif; ?> <li<?php if ($page == 'display') echo ' class="isactive"'; ?>><a href="profile.php?section=display&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section display'] ?></a></li>
  553. <li<?php if ($page == 'privacy') echo ' class="isactive"'; ?>><a href="profile.php?section=privacy&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section privacy'] ?></a></li>
  554. <?php if ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_moderator'] == '1' && $pun_user['g_mod_ban_users'] == '1')): ?> <li<?php if ($page == 'admin') echo ' class="isactive"'; ?>><a href="profile.php?section=admin&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section admin'] ?></a></li>
  555. <?php endif; ?> </ul>
  556. </div>
  557. </div>
  558. </div>
  559. <?php
  560. }
  561. //
  562. // Outputs markup to display a user's avatar
  563. //
  564. function generate_avatar_markup($user_id)
  565. {
  566. global $pun_config;
  567. $filetypes = array('jpg', 'gif', 'png');
  568. $avatar_markup = '';
  569. foreach ($filetypes as $cur_type)
  570. {
  571. $path = $pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type;
  572. if (file_exists(PUN_ROOT.$path) && $img_size = getimagesize(PUN_ROOT.$path))
  573. {
  574. $avatar_markup = '<img src="'.pun_htmlspecialchars(get_base_url(true).'/'.$path.'?m='.filemtime(PUN_ROOT.$path)).'" '.$img_size[3].' alt="" />';
  575. break;
  576. }
  577. }
  578. return $avatar_markup;
  579. }
  580. //
  581. // Generate browser's title
  582. //
  583. function generate_page_title($page_title, $p = null)
  584. {
  585. global $pun_config, $lang_common;
  586. $page_title = array_reverse($page_title);
  587. if ($p != null)
  588. $page_title[0] .= ' ('.sprintf($lang_common['Page'], forum_number_format($p)).')';
  589. $crumbs = implode($lang_common['Title separator'], $page_title);
  590. return $crumbs;
  591. }
  592. //
  593. // Save array of tracked topics in cookie
  594. //
  595. function set_tracked_topics($tracked_topics)
  596. {
  597. global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $pun_config;
  598. $cookie_data = '';
  599. if (!empty($tracked_topics))
  600. {
  601. // Sort the arrays (latest read first)
  602. arsort($tracked_topics['topics'], SORT_NUMERIC);
  603. arsort($tracked_topics['forums'], SORT_NUMERIC);
  604. // Homebrew serialization (to avoid having to run unserialize() on cookie data)
  605. foreach ($tracked_topics['topics'] as $id => $timestamp)
  606. $cookie_data .= 't'.$id.'='.$timestamp.';';
  607. foreach ($tracked_topics['forums'] as $id => $timestamp)
  608. $cookie_data .= 'f'.$id.'='.$timestamp.';';
  609. // Enforce a byte size limit (4096 minus some space for the cookie name - defaults to 4048)
  610. if (strlen($cookie_data) > FORUM_MAX_COOKIE_SIZE)
  611. {
  612. $cookie_data = substr($cookie_data, 0, FORUM_MAX_COOKIE_SIZE);
  613. $cookie_data = substr($cookie_data, 0, strrpos($cookie_data, ';')).';';
  614. }
  615. }
  616. forum_setcookie($cookie_name.'_track', $cookie_data, time() + $pun_config['o_timeout_visit']);
  617. $_COOKIE[$cookie_name.'_track'] = $cookie_data; // Set it directly in $_COOKIE as well
  618. }
  619. //
  620. // Extract array of tracked topics from cookie
  621. //
  622. function get_tracked_topics()
  623. {
  624. global $cookie_name;
  625. $cookie_data = isset($_COOKIE[$cookie_name.'_track']) ? $_COOKIE[$cookie_name.'_track'] : false;
  626. if (!$cookie_data)
  627. return array('topics' => array(), 'forums' => array());
  628. if (strlen($cookie_data) > 4048)
  629. return array('topics' => array(), 'forums' => array());
  630. // Unserialize data from cookie
  631. $tracked_topics = array('topics' => array(), 'forums' => array());
  632. $temp = explode(';', $cookie_data);
  633. foreach ($temp as $t)
  634. {
  635. $type = substr($t, 0, 1) == 'f' ? 'forums' : 'topics';
  636. $id = intval(substr($t, 1));
  637. $timestamp = intval(substr($t, strpos($t, '=') + 1));
  638. if ($id > 0 && $timestamp > 0)
  639. $tracked_topics[$type][$id] = $timestamp;
  640. }
  641. return $tracked_topics;
  642. }
  643. //
  644. // Update posts, topics, last_post, last_post_id and last_poster for a forum
  645. //
  646. function update_forum($forum_id)
  647. {
  648. global $db;
  649. $result = $db->query('SELECT COUNT(id), SUM(num_replies) FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id) or error('Unable to fetch forum topic count', __FILE__, __LINE__, $db->error());
  650. list($num_topics, $num_posts) = $db->fetch_row($result);
  651. $num_posts = $num_posts + $num_topics; // $num_posts is only the sum of all replies (we have to add the topic posts)
  652. $result = $db->query('SELECT last_post, last_post_id, last_poster FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id.' AND moved_to IS NULL ORDER BY last_post DESC LIMIT 1') or error('Unable to fetch last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
  653. if ($db->num_rows($result)) // There are topics in the forum
  654. {
  655. list($last_post, $last_post_id, $last_poster) = $db->fetch_row($result);
  656. $db->query('UPDATE '.$db->prefix.'forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post='.$last_post.', last_post_id='.$last_post_id.', last_poster=\''.$db->escape($last_poster).'\' WHERE id='.$forum_id) or error('Unable to update last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
  657. }
  658. else // There are no topics
  659. $db->query('UPDATE '.$db->prefix.'forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post=NULL, last_post_id=NULL, last_poster=NULL WHERE id='.$forum_id) or error('Unable to update last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
  660. }
  661. //
  662. // Deletes any avatars owned by the specified user ID
  663. //
  664. function delete_avatar($user_id)
  665. {
  666. global $pun_config;
  667. $filetypes = array('jpg', 'gif', 'png');
  668. // Delete user avatar
  669. foreach ($filetypes as $cur_type)
  670. {
  671. if (file_exists(PUN_ROOT.$pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type))
  672. @unlink(PUN_ROOT.$pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type);
  673. }
  674. }
  675. //
  676. // Delete a topic and all of it's posts
  677. //
  678. function delete_topic($topic_id)
  679. {
  680. global $db;
  681. // Delete the topic and any redirect topics
  682. $db->query('DELETE FROM '.$db->prefix.'topics WHERE id='.$topic_id.' OR moved_to='.$topic_id) or error('Unable to delete topic', __FILE__, __LINE__, $db->error());
  683. // Create a list of the post IDs in this topic
  684. $post_ids = '';
  685. $result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to fetch posts', __FILE__, __LINE__, $db->error());
  686. while ($row = $db->fetch_row($result))
  687. $post_ids .= ($post_ids != '') ? ','.$row[0] : $row[0];
  688. // Make sure we have a list of post IDs
  689. if ($post_ids != '')
  690. {
  691. strip_search_index($post_ids);
  692. // Delete posts in topic
  693. $db->query('DELETE FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to delete posts', __FILE__, __LINE__, $db->error());
  694. }
  695. // Delete any subscriptions for this topic
  696. $db->query('DELETE FROM '.$db->prefix.'topic_subscriptions WHERE topic_id='.$topic_id) or error('Unable to delete subscriptions', __FILE__, __LINE__, $db->error());
  697. global $pun_user;
  698. require PUN_ROOT.'include/poll.php';
  699. poll_delete($topic_id);
  700. }
  701. //
  702. // Delete a single post
  703. //
  704. function delete_post($post_id, $topic_id)
  705. {
  706. global $db;
  707. $result = $db->query('SELECT id, poster, posted FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id.' ORDER BY id DESC LIMIT 2') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
  708. list($last_id, ,) = $db->fetch_row($result);
  709. list($second_last_id, $second_poster, $second_posted) = $db->fetch_row($result);
  710. // Delete the post
  711. $db->query('DELETE FROM '.$db->prefix.'posts WHERE id='.$post_id) or error('Unable to delete post', __FILE__, __LINE__, $db->error());
  712. strip_search_index($post_id);
  713. // Count number of replies in the topic
  714. $result = $db->query('SELECT COUNT(id) FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to fetch post count for topic', __FILE__, __LINE__, $db->error());
  715. $num_replies = $db->result($result, 0) - 1;
  716. // If the message we deleted is the most recent in the topic (at the end of the topic)
  717. if ($last_id == $post_id)
  718. {
  719. // If there is a $second_last_id there is more than 1 reply to the topic
  720. if (!empty($second_last_id))
  721. $db->query('UPDATE '.$db->prefix.'topics SET last_post='.$second_posted.', last_post_id='.$second_last_id.', last_poster=\''.$db->escape($second_poster).'\', num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
  722. else
  723. // We deleted the only reply, so now last_post/last_post_id/last_poster is posted/id/poster from the topic itself
  724. $db->query('UPDATE '.$db->prefix.'topics SET last_post=posted, last_post_id=id, last_poster=poster, num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
  725. }
  726. else
  727. // Otherwise we just decrement the reply counter
  728. $db->query('UPDATE '.$db->prefix.'topics SET num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
  729. }
  730. //
  731. // Delete every .php file in the forum's cache directory
  732. //
  733. function forum_clear_cache()
  734. {
  735. $d = dir(FORUM_CACHE_DIR);
  736. while (($entry = $d->read()) !== false)
  737. {
  738. if (substr($entry, -4) == '.php')
  739. @unlink(FORUM_CACHE_DIR.$entry);
  740. }
  741. $d->close();
  742. }
  743. //
  744. // Replace censored words in $text
  745. //
  746. function censor_words($text)
  747. {
  748. global $db;
  749. static $search_for, $replace_with;
  750. // If not already built in a previous call, build an array of censor words and their replacement text
  751. if (!isset($search_for))
  752. {
  753. if (file_exists(FORUM_CACHE_DIR.'cache_censoring.php'))
  754. include FORUM_CACHE_DIR.'cache_censoring.php';
  755. if (!defined('PUN_CENSOR_LOADED'))
  756. {
  757. if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
  758. require PUN_ROOT.'include/cache.php';
  759. generate_censoring_cache();
  760. require FORUM_CACHE_DIR.'cache_censoring.php';
  761. }
  762. }
  763. if (!empty($search_for))
  764. $text = substr(ucp_preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
  765. return $text;
  766. }
  767. //
  768. // Determines the correct title for $user
  769. // $user must contain the elements 'username', 'title', 'posts', 'g_id' and 'g_user_title'
  770. //
  771. function get_title($user)
  772. {
  773. global $db, $pun_config, $pun_bans, $lang_common;
  774. static $ban_list, $pun_ranks;
  775. // If not already built in a previous call, build an array of lowercase banned usernames
  776. if (empty($ban_list))
  777. {
  778. $ban_list = array();
  779. foreach ($pun_bans as $cur_ban)
  780. $ban_list[] = strtolower($cur_ban['username']);
  781. }
  782. // If not already loaded in a previous call, load the cached ranks
  783. if ($pun_config['o_ranks'] == '1' && !defined('PUN_RANKS_LOADED'))
  784. {
  785. if (file_exists(FORUM_CACHE_DIR.'cache_ranks.php'))
  786. include FORUM_CACHE_DIR.'cache_ranks.php';
  787. if (!defined('PUN_RANKS_LOADED'))
  788. {
  789. if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
  790. require PUN_ROOT.'include/cache.php';
  791. generate_ranks_cache();
  792. require FORUM_CACHE_DIR.'cache_ranks.php';
  793. }
  794. }
  795. // If the user has a custom title
  796. if ($user['title'] != '')
  797. $user_title = pun_htmlspecialchars($user['title']);
  798. // If the user is banned
  799. else if (in_array(strtolower($user['username']), $ban_list))
  800. $user_title = $lang_common['Banned'];
  801. // If the user group has a default user title
  802. else if ($user['g_user_title'] != '')
  803. $user_title = pun_htmlspecialchars($user['g_user_title']);
  804. // If the user is a guest
  805. else if ($user['g_id'] == PUN_GUEST)
  806. $user_title = $lang_common['Guest'];
  807. else
  808. {
  809. // Are there any ranks?
  810. if ($pun_config['o_ranks'] == '1' && !empty($pun_ranks))
  811. {
  812. foreach ($pun_ranks as $cur_rank)
  813. {
  814. if ($user['num_posts'] >= $cur_rank['min_posts'])
  815. $user_title = pun_htmlspecialchars($cur_rank['rank']);
  816. }
  817. }
  818. // If the user didn't "reach" any rank (or if ranks are disabled), we assign the default
  819. if (!isset($user_title))
  820. $user_title = $lang_common['Member'];
  821. }
  822. return $user_title;
  823. }
  824. //
  825. // Generate a string with numbered links (for multipage scripts)
  826. //
  827. function paginate($num_pages, $cur_page, $link)
  828. {
  829. global $lang_common;
  830. $pages = array();
  831. $link_to_all = false;
  832. // If $cur_page == -1, we link to all pages (used in viewforum.php)
  833. if ($cur_page == -1)
  834. {
  835. $cur_page = 1;
  836. $link_to_all = true;
  837. }
  838. if ($num_pages <= 1)
  839. $pages = array('<strong class="item1">1</strong>');
  840. else
  841. {
  842. // Add a previous page link
  843. if ($num_pages > 1 && $cur_page > 1)
  844. $pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.($cur_page - 1).'">'.$lang_common['Previous'].'</a>';
  845. if ($cur_page > 3)
  846. {
  847. $pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p=1">1</a>';
  848. if ($cur_page > 5)
  849. $pages[] = '<span class="spacer">'.$lang_common['Spacer'].'</span>';
  850. }
  851. // Don't ask me how the following works. It just does, OK? :-)
  852. for ($current = ($cur_page == 5) ? $cur_page - 3 : $cur_page - 2, $stop = ($cur_page + 4 == $num_pages) ? $cur_page + 4 : $cur_page + 3; $current < $stop; ++$current)
  853. {
  854. if ($current < 1 || $current > $num_pages)
  855. continue;
  856. else if ($current != $cur_page || $link_to_all)
  857. $pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.$current.'">'.forum_number_format($current).'</a>';
  858. else
  859. $pages[] = '<strong'.(empty($pages) ? ' class="item1"' : '').'>'.forum_number_format($current).'</strong>';
  860. }
  861. if ($cur_page <= ($num_pages-3))
  862. {
  863. if ($cur_page != ($num_pages-3) && $cur_page != ($num_pages-4))
  864. $pages[] = '<span class="spacer">'.$lang_common['Spacer'].'</span>';
  865. $pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.$num_pages.'">'.forum_number_format($num_pages).'</a>';
  866. }
  867. // Add a next page link
  868. if ($num_pages > 1 && !$link_to_all && $cur_page < $num_pages)
  869. $pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.($cur_page +1).'">'.$lang_common['Next'].'</a>';
  870. }
  871. return implode(' ', $pages);
  872. }
  873. //
  874. // Display a message
  875. //
  876. function message($message, $no_back_link = false)
  877. {
  878. global $db, $lang_common, $pun_config, $pun_start, $tpl_main, $pun_user;
  879. if (defined('EVEBB_AUTO_DEBUG')) {
  880. $xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
  881. $xml .= '<msg>'."\n";
  882. $xml .= '<text><![CDATA['.$message.']]></text>'."\n";
  883. $xml .= '</msg>'."\n";
  884. echo $xml;
  885. exit;
  886. } //End if.
  887. if (!defined('PUN_HEADER'))
  888. {
  889. $page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Info']);
  890. define('PUN_ACTIVE_PAGE', 'index');
  891. require PUN_ROOT.'header.php';
  892. }
  893. ?>
  894. <div id="msg" class="block">
  895. <h2><span><?php echo $lang_common['Info'] ?></span></h2>
  896. <div class="box">
  897. <div class="inbox">
  898. <p><?php echo $message ?></p>
  899. <?php if (!$no_back_link): ?> <p><a href="javascript: history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>
  900. <?php endif; ?> </div>
  901. </div>
  902. </div>
  903. <?php
  904. require PUN_ROOT.'footer.php';
  905. }
  906. //
  907. // Format a time string according to $time_format and time zones
  908. //
  909. function format_time($timestamp, $date_only = false, $date_format = null, $time_format = null, $time_only = false, $no_text = false)
  910. {
  911. global $pun_config, $lang_common, $pun_user, $forum_date_formats, $forum_time_formats;
  912. if ($timestamp == '')
  913. return $lang_common['Never'];
  914. $diff = ($pun_user['timezone'] + $pun_user['dst']) * 3600;
  915. $timestamp += $diff;
  916. $now = time();
  917. if($date_format == null)
  918. $date_format = $forum_date_formats[$pun_user['date_format']];
  919. if($time_format == null)
  920. $time_format = $forum_time_formats[$pun_user['time_format']];
  921. $date = gmdate($date_format, $timestamp);
  922. $today = gmdate($date_format, $now+$diff);
  923. $yesterday = gmdate($date_format, $now+$diff-86400);
  924. if(!$no_text)
  925. {
  926. if ($date == $today)
  927. $date = $lang_common['Today'];
  928. else if ($date == $yesterday)
  929. $date = $lang_common['Yesterday'];
  930. }
  931. if ($date_only)
  932. return $date;
  933. else if ($time_only)
  934. return gmdate($time_format, $timestamp);
  935. else
  936. return $date.' '.gmdate($time_format, $timestamp);
  937. }
  938. //
  939. // A wrapper for PHP's number_format function
  940. //
  941. function forum_number_format($number, $decimals = 0)
  942. {
  943. global $lang_common;
  944. return is_numeric($number) ? number_format($number, $decimals, $lang_common['lang_decimal_point'], $lang_common['lang_thousands_sep']) : $number;
  945. }
  946. //
  947. // Generate a random key of length $len
  948. //
  949. function random_key($len, $readable = false, $hash = false)
  950. {
  951. $key = '';
  952. if ($hash)
  953. $key = substr(pun_hash(uniqid(rand(), true)), 0, $len);
  954. else if ($readable)
  955. {
  956. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  957. for ($i = 0; $i < $len; ++$i)
  958. $key .= substr($chars, (mt_rand() % strlen($chars)), 1);
  959. }
  960. else
  961. {
  962. for ($i = 0; $i < $len; ++$i)
  963. $key .= chr(mt_rand(33, 126));
  964. }
  965. return $key;
  966. }
  967. //
  968. // Make sure that HTTP_REFERER matches base_url/script
  969. //
  970. function confirm_referrer($script, $error_msg = false)
  971. {
  972. global $pun_config, $lang_common;
  973. // There is no referrer
  974. if (empty($_SERVER['HTTP_REFERER']))
  975. message($error_msg ? $error_msg : $lang_common['Bad referrer']);
  976. $referrer = parse_url(strtolower($_SERVER['HTTP_REFERER']));
  977. // Remove www subdomain if it exists
  978. if (strpos($referrer['host'], 'www.') === 0)
  979. $referrer['host'] = substr($referrer['host'], 4);
  980. $valid = parse_url(strtolower(get_base_url().'/'.$script));
  981. // Remove www subdomain if it exists
  982. if (strpos($valid['host'], 'www.') === 0)
  983. $valid['host'] = substr($valid['host'], 4);
  984. // Check the host and path match. Ignore the scheme, port, etc.
  985. if ($referrer['host'] != $valid['host'] || $referrer['path'] != $valid['path'])
  986. message($error_msg ? $error_msg : $lang_common['Bad referrer']);
  987. }
  988. //
  989. // Generate a random password of length $len
  990. // Compatibility wrapper for random_key
  991. //
  992. function random_pass($len)
  993. {
  994. return random_key($len, true);
  995. }
  996. //
  997. // Compute a hash of $str
  998. //
  999. function pun_hash($str)
  1000. {
  1001. return sha1($str);
  1002. }
  1003. //
  1004. // Try to determine the correct remote IP-address
  1005. //
  1006. function get_remote_address()
  1007. {
  1008. $remote_addr = $_SERVER['REMOTE_ADDR'];
  1009. // If we are behind a reverse proxy try to find the real users IP
  1010. if (defined('FORUM_BEHIND_REVERSE_PROXY'))
  1011. {
  1012. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  1013. {
  1014. // The general format of the field is:
  1015. // X-Forwarded-For: client1, proxy1, proxy2
  1016. // where the value is a comma+space separated list of IP addresses, the left-most being the farthest downstream client,
  1017. // and each successive proxy that passed the request adding the IP address where it received the request from.
  1018. $remote_addr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1019. $remote_addr = trim($remote_addr[0]);
  1020. }
  1021. }
  1022. return $remote_addr;
  1023. }
  1024. //
  1025. // Calls htmlspecialchars with a few options already set
  1026. //
  1027. function pun_htmlspecialchars($str)
  1028. {
  1029. return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  1030. }
  1031. //
  1032. // Calls htmlspecialchars_decode with a few options already set
  1033. //
  1034. function pun_htmlspecialchars_decode($str)
  1035. {
  1036. if (function_exists('htmlspecialchars_decode'))
  1037. return htmlspecialchars_decode($str, ENT_QUOTES);
  1038. static $translations;
  1039. if (!isset($translations))
  1040. {
  1041. $translations = get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
  1042. $translations['&#039;'] = '\''; // get_html_translation_table doesn't include &#039; which is what htmlspecialchars translates ' to, but apparently that is okay?! http://bugs.php.net/bug.php?id=25927
  1043. $translations = array_flip($translations);
  1044. }
  1045. return strtr($str, $translations);
  1046. }
  1047. //
  1048. // A wrapper for utf8_strlen for compatibility
  1049. //
  1050. function pun_strlen($str)
  1051. {
  1052. return utf8_strlen($str);
  1053. }
  1054. //
  1055. // Convert \r\n and \r to \n
  1056. //
  1057. function pun_linebreaks($str)
  1058. {
  1059. return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
  1060. }
  1061. //
  1062. // A wrapper for utf8_trim for compatibility
  1063. //
  1064. function pun_trim($str, $charlist = false)
  1065. {
  1066. return utf8_trim($str, $charlist);
  1067. }
  1068. //
  1069. // Checks if a string is in all uppercase
  1070. //
  1071. function is_all_uppercase($string)
  1072. {
  1073. return utf8_strtoupper($string) == $string && utf8_strtolower($string) != $string;
  1074. }
  1075. //
  1076. // Inserts $element into $input at $offset
  1077. // $offset can be either a numerical offset to insert at (eg: 0 inserts at the beginning of the array)
  1078. // or a string, which is the key that the new element should be inserted before
  1079. // $key is optional: it's used when inserting a new key/value pair into an associative array
  1080. //
  1081. function array_insert(&$input, $offset, $element, $key = null)
  1082. {
  1083. if ($key == null)
  1084. $key = $offset;
  1085. // Determine the proper offset if we're using a string
  1086. if (!is_int($offset))
  1087. $offset = array_search($offset, array_keys($input), true);
  1088. // Out of bounds checks
  1089. if ($offset > count($input))
  1090. $offset = count($input);
  1091. else if ($offset < 0)
  1092. $offset = 0;
  1093. $input = array_merge(array_slice($input, 0, $offset), array($key => $element), array_slice($input, $offset));
  1094. }
  1095. //
  1096. // Display a message when board is in maintenance mode
  1097. //
  1098. function maintenance_message()
  1099. {
  1100. global $db, $pun_config, $lang_common, $pun_user;
  1101. // Send no-cache headers
  1102. header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
  1103. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  1104. header('Cache-Control: post-check=0, pre-check=0', false);
  1105. header('Pragma: no-cache'); // For HTTP/1.0 compatibility
  1106. // Send the Content-type header in case the web server is setup to send something else
  1107. header('Content-type: text/html; charset=utf-8');
  1108. // Deal with newlines, tabs and multiple spaces
  1109. $pattern = array("\t", ' ', ' ');
  1110. $replace = array('&#160; &#160; ', '&#160; ', ' &#160;');
  1111. $message = str_replace($pattern, $replace, $pun_config['o_maintenance_message']);
  1112. if (file_exists(PUN_ROOT.'style/'.$pun_user['style'].'/maintenance.tpl'))
  1113. {
  1114. $tpl_file = PUN_ROOT.'style/'.$pun_user['style'].'/maintenance.tpl';
  1115. $tpl_inc_dir = PUN_ROOT.'style/'.$pun_user['style'].'/';
  1116. }
  1117. else
  1118. {
  1119. $tpl_file = PUN_ROOT.'include/template/maintenance.tpl';
  1120. $tpl_inc_dir = PUN_ROOT.'include/user/';
  1121. }
  1122. $tpl_maint = file_get_contents($tpl_file);
  1123. // START SUBST - <pun_include "*">
  1124. preg_match_all('#<pun_include "([^/\\\\]*?)\.(php[45]?|inc|html?|txt)">#', $tpl_maint, $pun_includes, PREG_SET_ORDER);
  1125. foreach ($pun_includes as $cur_include)
  1126. {
  1127. ob_start();
  1128. // Allow for overriding user includes, too.
  1129. if (file_exists($tpl_inc_dir.$cur_include[1].'.'.$cur_include[2]))
  1130. require $tpl_inc_dir.$cur_include[1].'.'.$cur_include[2];
  1131. else if (file_exists(PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2]))
  1132. require PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2];
  1133. else
  1134. error(sprintf($lang_common['Pun include error'], htmlspecialchars($cur_include[0]), basename($tpl_file)));
  1135. $tpl_temp = ob_get_contents();
  1136. $tpl_maint = str_replace($cur_include[0], $tpl_temp, $tpl_maint);
  1137. ob_end_clean();
  1138. }
  1139. // END SUBST - <pun_include "*">
  1140. // START SUBST - <pun_language>
  1141. $tpl_maint = str_replace('<pun_language>', $lang_common['lang_identifier'], $tpl_maint);
  1142. // END SUBST - <pun_language>
  1143. // START SUBST - <pun_content_direction>
  1144. $tpl_maint = str_replace('<pun_content_direction>', $lang_common['lang_direction'], $tpl_maint);
  1145. // END SUBST - <pun_content_direction>
  1146. // START SUBST - <pun_head>
  1147. ob_start();
  1148. $page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Maintenance']);
  1149. ?>
  1150. <title><?php echo generate_page_title($page_title) ?></title>
  1151. <link rel="stylesheet" type="text/css" href="style/<?php echo $pun_user['style'].'.css' ?>" />
  1152. <?php
  1153. $tpl_temp = trim(ob_get_contents());
  1154. $tpl_maint = str_replace('<pun_head>', $tpl_temp, $tpl_maint);
  1155. ob_end_clean();
  1156. // END SUBST - <pun_head>
  1157. // START SUBST - <pun_maint_main…

Large files files are truncated, but you can click here to view the full file