PageRenderTime 62ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/include/functions.php

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

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