PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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. }
  1155. //
  1156. // Display a simple error message
  1157. //
  1158. function error($message, $file = null, $line = null, $db_error = false)
  1159. {
  1160. global $pun_config, $lang_common;
  1161. // Set some default settings if the script failed before $pun_config could be populated
  1162. if (empty($pun_config))
  1163. {
  1164. $pun_config = array(
  1165. 'o_board_title' => 'FluxBB',
  1166. 'o_gzip' => '0'
  1167. );
  1168. }
  1169. // Set some default translations if the script failed before $lang_common could be populated
  1170. if (empty($lang_common))
  1171. {
  1172. $lang_common = array(
  1173. 'Title separator' => ' / ',
  1174. 'Page' => 'Page %s'
  1175. );
  1176. }
  1177. // Empty all output buffers and stop buffering
  1178. while (@ob_end_clean());
  1179. // "Restart" output buffering if we are using ob_gzhandler (since the gzip header is already sent)
  1180. if ($pun_config['o_gzip'] && extension_loaded('zlib'))
  1181. ob_start('ob_gzhandler');
  1182. // Send no-cache headers
  1183. header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
  1184. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  1185. header('Cache-Control: post-check=0, pre-check=0', false);
  1186. header('Pragma: no-cache'); // For HTTP/1.0 compatibility
  1187. // Send the Content-type header in case the web server is setup to send something else
  1188. header('Content-type: text/html; charset=utf-8');
  1189. ?>
  1190. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1191. <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
  1192. <head>
  1193. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  1194. <?php $page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), 'Error') ?>
  1195. <title><?php echo generate_page_title($page_title) ?></title>
  1196. <style type="text/css">
  1197. <!--
  1198. BODY {MARGIN: 10% 20% auto 20%; font: 10px Verdana, Arial, Helvetica, sans-serif}
  1199. #errorbox {BORDER: 1px solid #B84623}
  1200. H2 {MARGIN: 0; COLOR: #FFFFFF; BACKGROUND-COLOR: #B84623; FONT-SIZE: 1.1em; PADDING: 5px 4px}
  1201. #errorbox DIV {PADDING: 6px 5px; BACKGROUND-COLOR: #F1F1F1}
  1202. -->
  1203. </style>
  1204. </head>
  1205. <body>
  1206. <div id="errorbox">
  1207. <h2>An error was encountered</h2>
  1208. <div>
  1209. <?php
  1210. if (defined('PUN_DEBUG') && !is_null($file) && !is_null($line))
  1211. {
  1212. echo "\t\t".'<strong>File:</strong> '.$file.'<br />'."\n\t\t".'<strong>Line:</strong> '.$line.'<br /><br />'."\n\t\t".'<strong>FluxBB reported</strong>: '.$message."\n";
  1213. if ($db_error)
  1214. {
  1215. echo "\t\t".'<br /><br /><strong>Database reported:</strong> '.pun_htmlspecialchars($db_error['error_msg']).(($db_error['error_no']) ? ' (Errno: '.$db_error['error_no'].')' : '')."\n";
  1216. if ($db_error['error_sql'] != '')
  1217. echo "\t\t".'<br /><br /><strong>Failed query:</strong> '.pun_htmlspecialchars($db_error['error_sql'])."\n";
  1218. }
  1219. }
  1220. else
  1221. echo "\t\t".'Error: <strong>'.$message.'.</strong>'."\n";
  1222. ?>
  1223. </div>
  1224. </div>
  1225. </body>
  1226. </html>
  1227. <?php
  1228. // If a database connection was established (before this error) we close it
  1229. if ($db_error)
  1230. $GLOBALS['db']->close();
  1231. exit;
  1232. }
  1233. //
  1234. // Unset any variables instantiated as a result of register_globals being enabled
  1235. //
  1236. function forum_unregister_globals()
  1237. {
  1238. $register_globals = ini_get('register_globals');
  1239. if ($register_globals === '' || $register_globals === '0' || strtolower($register_globals) === 'off')
  1240. return;
  1241. // Prevent script.php?GLOBALS[foo]=bar
  1242. if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
  1243. exit('I\'ll have a steak sandwich and... a steak sandwich.');
  1244. // Variables that shouldn't be unset
  1245. $no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
  1246. // Remove elements in $GLOBALS that are present in any of the superglobals
  1247. $input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
  1248. foreach ($input as $k => $v)
  1249. {
  1250. if (!in_array($k, $no_unset) && isset($GLOBALS[$k]))
  1251. {
  1252. unset($GLOBALS[$k]);
  1253. unset($GLOBALS[$k]); // Double unset to circumvent the zend_hash_del_key_or_index hole in PHP <4.4.3 and <5.1.4
  1254. }
  1255. }
  1256. }
  1257. //
  1258. // Removes any "bad" characters (characters which mess with the display of a page, are invisible, etc) from user input
  1259. //
  1260. function forum_remove_bad_characters()
  1261. {
  1262. $_GET = remove_bad_characters($_GET);
  1263. $_POST = remove_bad_characters($_POST);
  1264. $_COOKIE = remove_bad_characters($_COOKIE);
  1265. $_REQUEST = remove_bad_characters($_REQUEST);
  1266. }
  1267. //
  1268. // Removes any "bad" characters (characters which mess with the display of a page, are invisible, etc) from the given string
  1269. // See: http://kb.mozillazine.org/Network.IDN.blacklist_chars
  1270. //
  1271. function remove_bad_characters($array)
  1272. {
  1273. static $bad_utf8_chars;
  1274. if (!isset($bad_utf8_chars))
  1275. {
  1276. $bad_utf8_chars = array(
  1277. "\xcc\xb7" => '', // COMBINING SHORT SOLIDUS OVERLAY 0337 *
  1278. "\xcc\xb8" => '', // COMBINING LONG SOLIDUS OVERLAY 0338 *
  1279. "\xe1\x85\x9F" => '', // HANGUL CHOSEONG FILLER 115F *
  1280. "\xe1\x85\xA0" => '', // HANGUL JUNGSEONG FILLER 1160 *
  1281. "\xe2\x80\x8b" => '', // ZERO WIDTH SPACE 200B *
  1282. "\xe2\x80\x8c" => '', // ZERO WIDTH NON-JOINER 200C
  1283. "\xe2\x80\x8d" => '', // ZERO WIDTH JOINER 200D
  1284. "\xe2\x80\x8e" => '', // LEFT-TO-RIGHT MARK 200E
  1285. "\xe2\x80\x8f" => '', // RIGHT-TO-LEFT MARK 200F
  1286. "\xe2\x80\xaa" => '', // LEFT-TO-RIGHT EMBEDDING 202A
  1287. "\xe2\x80\xab" => '', // RIGHT-TO-LEFT EMBEDDING 202B
  1288. "\xe2\x80\xac" => '', // POP DIRECTIONAL FORMATTING 202C
  1289. "\xe2\x80\xad" => '', // LEFT-TO-RIGHT OVERRIDE 202D
  1290. "\xe2\x80\xae" => '', // RIGHT-TO-LEFT OVERRIDE 202E
  1291. "\xe2\x80\xaf" => '', // NARROW NO-BREAK SPACE 202F *
  1292. "\xe2\x81\x9f" => '', // MEDIUM MATHEMATICAL SPACE 205F *
  1293. "\xe2\x81\xa0" => '', // WORD JOINER 2060
  1294. "\xe3\x85\xa4" => '', // HANGUL FILLER 3164 *
  1295. "\xef\xbb\xbf" => '', // ZERO WIDTH NO-BREAK SPACE FEFF
  1296. "\xef\xbe\xa0" => '', // HALFWIDTH HANGUL FILLER FFA0 *
  1297. "\xef\xbf\xb9" => '', // INTERLINEAR ANNOTATION ANCHOR FFF9 *
  1298. "\xef\xbf\xba" => '', // INTERLINEAR ANNOTATION SEPARATOR FFFA *
  1299. "\xef\xbf\xbb" => '', // INTERLINEAR ANNOTATION TERMINATOR FFFB *
  1300. "\xef\xbf\xbc" => '', // OBJECT REPLACEMENT CHARACTER FFFC *
  1301. "\xef\xbf\xbd" => '', // REPLACEMENT CHARACTER FFFD *
  1302. "\xe2\x80\x80" => ' ', // EN QUAD 2000 *
  1303. "\xe2\x80\x81" => ' ', // EM QUAD 2001 *
  1304. "\xe2\x80\x82" => ' ', // EN SPACE 2002 *
  1305. "\xe2\x80\x83" => ' ', // EM SPACE 2003 *
  1306. "\xe2\x80\x84" => ' ', // THREE-PER-EM SPACE 2004 *
  1307. "\xe2\x80\x85" => ' ', // FOUR-PER-EM SPACE 2005 *
  1308. "\xe2\x80\x86" => ' ', // SIX-PER-EM SPACE 2006 *
  1309. "\xe2\x80\x87" => ' ', // FIGURE SPACE 2007 *
  1310. "\xe2\x80\x88" => ' ', // PUNCTUATION SPACE 2008 *
  1311. "\xe2\x80\x89" => ' ', // THIN SPACE 2009 *
  1312. "\xe2\x80\x8a" => ' ', // HAIR SPACE 200A *
  1313. "\xE3\x80\x80" => ' ', // IDEOGRAPHIC SPACE 3000 *
  1314. );
  1315. }
  1316. if (is_array($array))
  1317. return array_map('remove_bad_characters', $array);
  1318. // Strip out any invalid characters
  1319. $array = utf8_bad_strip($array);
  1320. // Remove control characters
  1321. $array = preg_replace('%[\x00-\x08\x0b-\x0c\x0e-\x1f]%', '', $array);
  1322. // Replace some "bad" characters
  1323. $array = str_replace(array_keys($bad_utf8_chars), array_values($bad_utf8_chars), $array);
  1324. return $array;
  1325. }
  1326. //
  1327. // Converts the file size in bytes to a human readable file size
  1328. //
  1329. function file_size($size)
  1330. {
  1331. global $lang_common;
  1332. $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB');
  1333. for ($i = 0; $size > 1024; $i++)
  1334. $size /= 1024;
  1335. return sprintf($lang_common['Size unit '.$units[$i]], round($size, 2));
  1336. }
  1337. //
  1338. // Fetch a list of available styles
  1339. //
  1340. function forum_list_styles()
  1341. {
  1342. $styles = array();
  1343. $d = dir(PUN_ROOT.'style');
  1344. while (($entry = $d->read()) !== false)
  1345. {
  1346. if ($entry{0} == '.')
  1347. continue;
  1348. if (substr($entry, -4) == '.css')
  1349. $styles[] = substr($entry, 0, -4);
  1350. }
  1351. $d->close();
  1352. natcasesort($styles);
  1353. return $styles;
  1354. }
  1355. //
  1356. // Fetch a list of available language packs
  1357. //
  1358. function forum_list_langs()
  1359. {
  1360. $languages = array();
  1361. $d = dir(PUN_ROOT.'lang');
  1362. while (($entry = $d->read()) !== false)
  1363. {
  1364. if ($entry{0} == '.')
  1365. continue;
  1366. if (is_dir(PUN_ROOT.'lang/'.$entry) && file_exists(PUN_ROOT.'lang/'.$entry.'/common.php'))
  1367. $languages[] = $entry;
  1368. }
  1369. $d->close();
  1370. natcasesort($languages);
  1371. return $languages;
  1372. }
  1373. //
  1374. // Generate a cache ID based on the last modification time for all stopwords files
  1375. //
  1376. function generate_stopwords_cache_id()
  1377. {
  1378. $files = glob(PUN_ROOT.'lang/*/stopwords.txt');
  1379. if ($files === false)
  1380. return 'cache_id_error';
  1381. $hash = array();
  1382. foreach ($files as $file)
  1383. {
  1384. $hash[] = $file;
  1385. $hash[] = filemtime($file);
  1386. }
  1387. return sha1(implode('|', $hash));
  1388. }
  1389. //
  1390. // Fetch a list of available admin plugins
  1391. //
  1392. function forum_list_plugins($is_admin)
  1393. {
  1394. $plugins = array();
  1395. $d = dir(PUN_ROOT.'plugins');
  1396. while (($entry = $d->read()) !== false)
  1397. {
  1398. if ($entry{0} == '.')
  1399. continue;
  1400. $prefix = substr($entry, 0, strpos($entry, '_'));
  1401. $suffix = substr($entry, strlen($entry) - 4);
  1402. if ($suffix == '.php' && ((!$is_admin && $prefix == 'AMP') || ($is_admin && ($prefix == 'AP' || $prefix == 'AMP'))))
  1403. $plugins[$entry] = substr($entry, strpos($entry, '_') + 1, -4);
  1404. }
  1405. $d->close();
  1406. natcasesort($plugins);
  1407. return $plugins;
  1408. }
  1409. //
  1410. // Split text into chunks ($inside contains all text inside $start and $end, and $outside contains all text outside)
  1411. //
  1412. function split_text($text, $start, $end, $retab = true)
  1413. {
  1414. global $pun_config;
  1415. $result = array(0 => array(), 1 => array()); // 0 = inside, 1 = outside
  1416. // split the text into parts
  1417. $parts = preg_split('%'.preg_quote($start, '%').'(.*)'.preg_quote($end, '%').'%Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  1418. $num_parts = count($parts);
  1419. // preg_split results in outside parts having even indices, inside parts having odd
  1420. for ($i = 0;$i < $num_parts;$i++)
  1421. $result[1 - ($i % 2)][] = $parts[$i];
  1422. if ($pun_config['o_indent_num_spaces'] != 8 && $retab)
  1423. {
  1424. $spaces = str_repeat(' ', $pun_config['o_indent_num_spaces']);
  1425. $result[1] = str_replace("\t", $spaces, $result[1]);
  1426. }
  1427. return $result;
  1428. }
  1429. //
  1430. // Extract blocks from a text with a starting and ending string
  1431. // This function always matches the most outer block so nesting is possible
  1432. //
  1433. function extract_blocks($text, $start, $end, $retab = true)
  1434. {
  1435. global $pun_config;
  1436. $code = array();
  1437. $start_len = strlen($start);
  1438. $end_len = strlen($end);
  1439. $regex = '%(?:'.preg_quote($start, '%').'|'.preg_quote($end, '%').')%';
  1440. $matches = array();
  1441. if (preg_match_all($regex, $text, $matches))
  1442. {
  1443. $counter = $offset = 0;
  1444. $start_pos = $end_pos = false;
  1445. foreach ($matches[0] as $match)
  1446. {
  1447. if ($match == $start)
  1448. {
  1449. if ($counter == 0)
  1450. $start_pos = strpos($text, $start);
  1451. $counter++;
  1452. }
  1453. elseif ($match == $end)
  1454. {
  1455. $counter--;
  1456. if ($counter == 0)
  1457. $end_pos = strpos($text, $end, $offset + 1);
  1458. $offset = strpos($text, $end, $offset + 1);
  1459. }
  1460. if ($start_pos !== false && $end_pos !== false)
  1461. {
  1462. $code[] = substr($text, $start_pos + $start_len,
  1463. $end_pos - $start_pos - $start_len);
  1464. $text = substr_replace($text, "\1", $start_pos,
  1465. $end_pos - $start_pos + $end_len);
  1466. $start_pos = $end_pos = false;
  1467. $offset = 0;
  1468. }
  1469. }
  1470. }
  1471. if ($pun_config['o_indent_num_spaces'] != 8 && $retab)
  1472. {
  1473. $spaces = str_repeat(' ', $pun_config['o_indent_num_spaces']);
  1474. $text = str_replace("\t", $spaces, $text);
  1475. }
  1476. return array($code, $text);
  1477. }
  1478. //
  1479. // function url_valid($url) {
  1480. //
  1481. // Return associative array of valid URI components, or FALSE if $url is not
  1482. // RFC-3986 compliant. If the passed URL begins with: "www." or "ftp.", then
  1483. // "http://" or "ftp://" is prepended and the corrected full-url is stored in
  1484. // the return array with a key name "url". This value should be used by the caller.
  1485. //
  1486. // Return value: FALSE if $url is not valid, otherwise array of URI components:
  1487. // e.g.
  1488. // Given: "http://www.jmrware.com:80/articles?height=10&width=75#fragone"
  1489. // Array(
  1490. // [scheme] => http
  1491. // [authority] => www.jmrware.com:80
  1492. // [userinfo] =>
  1493. // [host] => www.jmrware.com
  1494. // [IP_literal] =>
  1495. // [IPV6address] =>
  1496. // [ls32] =>
  1497. // [IPvFuture] =>
  1498. // [IPv4address] =>
  1499. // [regname] => www.jmrware.com
  1500. // [port] => 80
  1501. // [path_abempty] => /articles
  1502. // [query] => height=10&width=75
  1503. // [fragment] => fragone
  1504. // [url] => http://www.jmrware.com:80/articles?height=10&width=75#fragone
  1505. // )
  1506. function url_valid($url)
  1507. {
  1508. if (strpos($url, 'www.') === 0) $url = 'http://'. $url;
  1509. if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;
  1510. if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
  1511. ^
  1512. (?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
  1513. (?P<authority>
  1514. (?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
  1515. (?P<host>
  1516. (?P<IP_literal>
  1517. \[
  1518. (?:
  1519. (?P<IPV6address>
  1520. (?: (?:[0-9A-Fa-f]{1,4}:){6}
  1521. | ::(?:[0-9A-Fa-f]{1,4}:){5}
  1522. | (?: [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
  1523. | (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
  1524. | (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
  1525. | (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}:
  1526. | (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
  1527. )
  1528. (?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
  1529. | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
  1530. (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
  1531. )
  1532. | (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?:: [0-9A-Fa-f]{1,4}
  1533. | (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
  1534. )
  1535. | (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
  1536. )
  1537. \]
  1538. )
  1539. | (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
  1540. (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
  1541. | (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
  1542. )
  1543. (?::(?P<port>[0-9]*))?
  1544. )
  1545. (?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
  1546. (?:\?(?P<query> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
  1547. (?:\#(?P<fragment> (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
  1548. $
  1549. /mx', $url, $m)) return FALSE;
  1550. switch ($m['scheme'])
  1551. {
  1552. case 'https':
  1553. case 'http':
  1554. if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.
  1555. break;
  1556. case 'ftps':
  1557. case 'ftp':
  1558. break;
  1559. default:
  1560. return FALSE; // Unrecognised URI scheme. Default to FALSE.
  1561. }
  1562. // Validate host name conforms to DNS "dot-separated-parts".
  1563. if ($m{'regname'}) // If host regname specified, check for DNS conformance.
  1564. {
  1565. if (!preg_match('/# HTTP DNS host name.
  1566. ^ # Anchor to beginning of string.
  1567. (?!.{256}) # Overall host length is less than 256 chars.
  1568. (?: # Group dot separated host part alternatives.
  1569. [0-9A-Za-z]\. # Either a single alphanum followed by dot
  1570. | # or... part has more than one char (63 chars max).
  1571. [0-9A-Za-z] # Part first char is alphanum (no dash).
  1572. [\-0-9A-Za-z]{0,61} # Internal chars are alphanum plus dash.
  1573. [0-9A-Za-z] # Part last char is alphanum (no dash).
  1574. \. # Each part followed by literal dot.
  1575. )* # One or more parts before top level domain.
  1576. (?: # Top level domains
  1577. [A-Za-z]{2,63}| # Country codes are exactly two alpha chars.
  1578. xn--[0-9A-Za-z]{4,59}) # Internationalized Domain Name (IDN)
  1579. $ # Anchor to end of string.
  1580. /ix', $m['host'])) return FALSE;
  1581. }
  1582. $m['url'] = $url;
  1583. for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);
  1584. return $m; // return TRUE == array of useful named $matches plus the valid $url.
  1585. }
  1586. //
  1587. // Replace string matching regular expression
  1588. //
  1589. // This function takes care of possibly disabled unicode properties in PCRE builds
  1590. //
  1591. function ucp_preg_replace($pattern, $replace, $subject, $callback = false)
  1592. {
  1593. if($callback)
  1594. $replaced = preg_replace_callback($pattern, create_function('$matches', 'return '.$replace.';'), $subject);
  1595. else
  1596. $replaced = preg_replace($pattern, $replace, $subject);
  1597. // If preg_replace() returns false, this probably means unicode support is not built-in, so we need to modify the pattern a little
  1598. if ($replaced === false)
  1599. {
  1600. if (is_array($pattern))
  1601. {
  1602. foreach ($pattern as $cur_key => $cur_pattern)
  1603. $pattern[$cur_key] = str_replace('\p{L}\p{N}', '\w', $cur_pattern);
  1604. $replaced = preg_replace($pattern, $replace, $subject);
  1605. }
  1606. else
  1607. $replaced = preg_replace(str_replace('\p{L}\p{N}', '\w', $pattern), $replace, $subject);
  1608. }
  1609. return $replaced;
  1610. }
  1611. //
  1612. // A wrapper for ucp_preg_replace
  1613. //
  1614. function ucp_preg_replace_callback($pattern, $replace, $subject)
  1615. {
  1616. return ucp_preg_replace($pattern, $replace, $subject, true);
  1617. }
  1618. //
  1619. // Replace four-byte characters with a question mark
  1620. //
  1621. // As MySQL cannot properly handle four-byte characters with the default utf-8
  1622. // charset up until version 5.5.3 (where a special charset has to be used), they
  1623. // need to be replaced, by question marks in this case.
  1624. //
  1625. function strip_bad_multibyte_chars($str)
  1626. {
  1627. $result = '';
  1628. $length = strlen($str);
  1629. for ($i = 0; $i < $length; $i++)
  1630. {
  1631. // Replace four-byte characters (11110www 10zzzzzz 10yyyyyy 10xxxxxx)
  1632. $ord = ord($str[$i]);
  1633. if ($ord >= 240 && $ord <= 244)
  1634. {
  1635. $result .= '?';
  1636. $i += 3;
  1637. }
  1638. else
  1639. {
  1640. $result .= $str[$i];
  1641. }
  1642. }
  1643. return $result;
  1644. }
  1645. //
  1646. // Check whether a file/folder is writable.
  1647. //
  1648. // This function also works on Windows Server where ACLs seem to be ignored.
  1649. //
  1650. function forum_is_writable($path)
  1651. {
  1652. if (is_dir($path))
  1653. {
  1654. $path = rtrim($path, '/').'/';
  1655. return forum_is_writable($path.uniqid(mt_rand()).'.tmp');
  1656. }
  1657. // Check temporary file for read/write capabilities
  1658. $rm = file_exists($path);
  1659. $f = @fopen($path, 'a');
  1660. if ($f === false)
  1661. return false;
  1662. fclose($f);
  1663. if (!$rm)
  1664. @unlink($path);
  1665. return true;
  1666. }
  1667. // DEBUG FUNCTIONS BELOW
  1668. //
  1669. // Display executed queries (if enabled)
  1670. //
  1671. function display_saved_queries()
  1672. {
  1673. global $db, $lang_common;
  1674. // Get the queries so that we can print them out
  1675. $saved_queries = $db->get_saved_queries();
  1676. ?>
  1677. <div id="debug" class="blocktable">
  1678. <h2><span><?php echo $lang_common['Debug table'] ?></span></h2>
  1679. <div class="box">
  1680. <div class="inbox">
  1681. <table>
  1682. <thead>
  1683. <tr>
  1684. <th class="tcl" scope="col"><?php echo $lang_common['Query times'] ?></th>
  1685. <th class="tcr" scope="col"><?php echo $lang_common['Query'] ?></th>
  1686. </tr>
  1687. </thead>
  1688. <tbody>
  1689. <?php
  1690. $query_time_total = 0.0;
  1691. foreach ($saved_queries as $cur_query)
  1692. {
  1693. $query_time_total += $cur_query[1];
  1694. ?>
  1695. <tr>
  1696. <td class="tcl"><?php echo ($cur_query[1] != 0) ? $cur_query[1] : '&#160;' ?></td>
  1697. <td class="tcr"><?php echo pun_htmlspecialchars($cur_query[0]) ?></td>
  1698. </tr>
  1699. <?php
  1700. }
  1701. ?>
  1702. <tr>
  1703. <td class="tcl" colspan="2"><?php printf($lang_common['Total query time'], $query_time_total.' s') ?></td>
  1704. </tr>
  1705. </tbody>
  1706. </table>
  1707. </div>
  1708. </div>
  1709. </div>
  1710. <?php
  1711. }
  1712. //
  1713. // Dump contents of variable(s)
  1714. //
  1715. function dump()
  1716. {
  1717. echo '<pre>';
  1718. $num_args = func_num_args();
  1719. for ($i = 0; $i < $num_args; ++$i)
  1720. {
  1721. print_r(func_get_arg($i));
  1722. echo "\n\n";
  1723. }
  1724. echo '</pre>';
  1725. exit;
  1726. }