PageRenderTime 63ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/forum/include/functions.php

https://github.com/patrickod/City-Blogger
PHP | 1114 lines | 677 code | 228 blank | 209 comment | 174 complexity | 93ddb4bcab13c208cbf9163cdf0f7085 MD5 | raw file
  1. <?php
  2. /***********************************************************************
  3. Copyright (C) 2002-2008 PunBB
  4. This file is part of PunBB.
  5. PunBB is free software; you can redistribute it and/or modify it
  6. under the terms of the GNU General Public License as published
  7. by the Free Software Foundation; either version 2 of the License,
  8. or (at your option) any later version.
  9. PunBB is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  16. MA 02111-1307 USA
  17. ************************************************************************/
  18. //
  19. // Cookie stuff!
  20. //
  21. function check_cookie(&$pun_user)
  22. {
  23. global $db, $db_type, $pun_config, $cookie_name, $cookie_seed;
  24. $now = time();
  25. $expire = $now + 31536000; // The cookie expires after a year
  26. // We assume it's a guest
  27. $cookie = array('user_id' => 1, 'password_hash' => 'Guest');
  28. // If a cookie is set, we get the user_id and password hash from it
  29. if (isset($_COOKIE[$cookie_name]))
  30. list($cookie['user_id'], $cookie['password_hash']) = @unserialize($_COOKIE[$cookie_name]);
  31. if ($cookie['user_id'] > 1)
  32. {
  33. // Check if there's a user with the user ID and password hash from the cookie
  34. $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());
  35. $pun_user = $db->fetch_assoc($result);
  36. // If user authorisation failed
  37. if (!isset($pun_user['id']) || md5($cookie_seed.$pun_user['password']) !== $cookie['password_hash'])
  38. {
  39. pun_setcookie(1, md5(uniqid(rand(), true)), $expire);
  40. set_default_user();
  41. return;
  42. }
  43. // Set a default language if the user selected language no longer exists
  44. if (!@file_exists(PUN_ROOT.'lang/'.$pun_user['language']))
  45. $pun_user['language'] = $pun_config['o_default_lang'];
  46. // Set a default style if the user selected style no longer exists
  47. if (!@file_exists(PUN_ROOT.'style/'.$pun_user['style'].'.css'))
  48. $pun_user['style'] = $pun_config['o_default_style'];
  49. if (!$pun_user['disp_topics'])
  50. $pun_user['disp_topics'] = $pun_config['o_disp_topics_default'];
  51. if (!$pun_user['disp_posts'])
  52. $pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
  53. if ($pun_user['save_pass'] == '0')
  54. $expire = 0;
  55. // Define this if you want this visit to affect the online list and the users last visit data
  56. if (!defined('PUN_QUIET_VISIT'))
  57. {
  58. // Update the online list
  59. if (!$pun_user['logged'])
  60. {
  61. $pun_user['logged'] = $now;
  62. // With MySQL/MySQLi, REPLACE INTO avoids a user having two rows in the online table
  63. switch ($db_type)
  64. {
  65. case 'mysql':
  66. case 'mysqli':
  67. $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());
  68. break;
  69. default:
  70. $db->query('INSERT 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());
  71. break;
  72. }
  73. }
  74. else
  75. {
  76. // Special case: We've timed out, but no other user has browsed the forums since we timed out
  77. if ($pun_user['logged'] < ($now-$pun_config['o_timeout_visit']))
  78. {
  79. $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());
  80. $pun_user['last_visit'] = $pun_user['logged'];
  81. }
  82. $idle_sql = ($pun_user['idle'] == '1') ? ', idle=0' : '';
  83. $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());
  84. }
  85. }
  86. $pun_user['is_guest'] = false;
  87. }
  88. else
  89. set_default_user();
  90. }
  91. //
  92. // Fill $pun_user with default values (for guests)
  93. //
  94. function set_default_user()
  95. {
  96. global $db, $db_type, $pun_user, $pun_config;
  97. $remote_addr = get_remote_address();
  98. // Fetch guest user
  99. $result = $db->query('SELECT u.*, g.*, o.logged FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.ident=\''.$remote_addr.'\' WHERE u.id=1') or error('Unable to fetch guest information', __FILE__, __LINE__, $db->error());
  100. if (!$db->num_rows($result))
  101. exit('Unable to fetch guest information. The table \''.$db->prefix.'users\' must contain an entry with id = 1 that represents anonymous users.');
  102. $pun_user = $db->fetch_assoc($result);
  103. // Update online list
  104. if (!$pun_user['logged'])
  105. {
  106. $pun_user['logged'] = time();
  107. // With MySQL/MySQLi, REPLACE INTO avoids a user having two rows in the online table
  108. switch ($db_type)
  109. {
  110. case 'mysql':
  111. case 'mysqli':
  112. $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());
  113. break;
  114. default:
  115. $db->query('INSERT 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());
  116. break;
  117. }
  118. }
  119. else
  120. $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());
  121. $pun_user['disp_topics'] = $pun_config['o_disp_topics_default'];
  122. $pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
  123. $pun_user['timezone'] = $pun_config['o_server_timezone'];
  124. $pun_user['language'] = $pun_config['o_default_lang'];
  125. $pun_user['style'] = $pun_config['o_default_style'];
  126. $pun_user['is_guest'] = true;
  127. }
  128. //
  129. // Set a cookie, PunBB style!
  130. //
  131. function pun_setcookie($user_id, $password_hash, $expire)
  132. {
  133. global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
  134. // Enable sending of a P3P header by removing // from the following line (try this if login is failing in IE6)
  135. // @header('P3P: CP="CUR ADM"');
  136. if (version_compare(PHP_VERSION, '5.2.0', '>='))
  137. setcookie($cookie_name, serialize(array($user_id, md5($cookie_seed.$password_hash))), $expire, $cookie_path, $cookie_domain, $cookie_secure, true);
  138. else
  139. setcookie($cookie_name, serialize(array($user_id, md5($cookie_seed.$password_hash))), $expire, $cookie_path.'; HttpOnly', $cookie_domain, $cookie_secure);
  140. }
  141. //
  142. // Check whether the connecting user is banned (and delete any expired bans while we're at it)
  143. //
  144. function check_bans()
  145. {
  146. global $db, $pun_config, $lang_common, $pun_user, $pun_bans;
  147. // Admins aren't affected
  148. if ($pun_user['g_id'] == PUN_ADMIN || !$pun_bans)
  149. return;
  150. // Add a dot at the end of the IP address to prevent banned address 192.168.0.5 from matching e.g. 192.168.0.50
  151. $user_ip = get_remote_address().'.';
  152. $bans_altered = false;
  153. foreach ($pun_bans as $cur_ban)
  154. {
  155. // Has this ban expired?
  156. if ($cur_ban['expire'] != '' && $cur_ban['expire'] <= time())
  157. {
  158. $db->query('DELETE FROM '.$db->prefix.'bans WHERE id='.$cur_ban['id']) or error('Unable to delete expired ban', __FILE__, __LINE__, $db->error());
  159. $bans_altered = true;
  160. continue;
  161. }
  162. if ($cur_ban['username'] != '' && !strcasecmp($pun_user['username'], $cur_ban['username']))
  163. {
  164. $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());
  165. message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
  166. }
  167. if ($cur_ban['ip'] != '')
  168. {
  169. $cur_ban_ips = explode(' ', $cur_ban['ip']);
  170. for ($i = 0; $i < count($cur_ban_ips); ++$i)
  171. {
  172. $cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
  173. if (substr($user_ip, 0, strlen($cur_ban_ips[$i])) == $cur_ban_ips[$i])
  174. {
  175. $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());
  176. message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
  177. }
  178. }
  179. }
  180. }
  181. // If we removed any expired bans during our run-through, we need to regenerate the bans cache
  182. if ($bans_altered)
  183. {
  184. require_once PUN_ROOT.'include/cache.php';
  185. generate_bans_cache();
  186. }
  187. }
  188. //
  189. // Update "Users online"
  190. //
  191. function update_users_online()
  192. {
  193. global $db, $pun_config, $pun_user;
  194. $now = time();
  195. // Fetch all online list entries that are older than "o_timeout_online"
  196. $result = $db->query('SELECT * 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());
  197. while ($cur_user = $db->fetch_assoc($result))
  198. {
  199. // If the entry is a guest, delete it
  200. if ($cur_user['user_id'] == '1')
  201. $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());
  202. else
  203. {
  204. // 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
  205. if ($cur_user['logged'] < ($now-$pun_config['o_timeout_visit']))
  206. {
  207. $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());
  208. $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());
  209. }
  210. else if ($cur_user['idle'] == '0')
  211. $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());
  212. }
  213. }
  214. }
  215. //
  216. // Generate the "navigator" that appears at the top of every page
  217. //
  218. function generate_navlinks()
  219. {
  220. global $pun_config, $lang_common, $pun_user;
  221. // Index and Userlist should always be displayed
  222. $links[] = '<li id="navindex"><a href="index.php">'.$lang_common['Index'].'</a>';
  223. $links[] = '<li id="navuserlist"><a href="userlist.php">'.$lang_common['User list'].'</a>';
  224. if ($pun_config['o_rules'] == '1')
  225. $links[] = '<li id="navrules"><a href="misc.php?action=rules">'.$lang_common['Rules'].'</a>';
  226. if ($pun_user['is_guest'])
  227. {
  228. if ($pun_user['g_search'] == '1')
  229. $links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
  230. $links[] = '<li id="navregister"><a href="register.php">'.$lang_common['Register'].'</a>';
  231. $links[] = '<li id="navlogin"><a href="login.php">'.$lang_common['Login'].'</a>';
  232. $info = $lang_common['Not logged in'];
  233. }
  234. else
  235. {
  236. if ($pun_user['g_id'] > PUN_MOD)
  237. {
  238. if ($pun_user['g_search'] == '1')
  239. $links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
  240. $links[] = '<li id="navprofile"><a href="profile.php?id='.$pun_user['id'].'">'.$lang_common['Profile'].'</a>';
  241. $links[] = '<li id="navlogout"><a href="login.php?action=out&amp;id='.$pun_user['id'].'&amp;csrf_token='.sha1($pun_user['id'].sha1(get_remote_address())).'">'.$lang_common['Logout'].'</a>';
  242. }
  243. else
  244. {
  245. $links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
  246. $links[] = '<li id="navprofile"><a href="profile.php?id='.$pun_user['id'].'">'.$lang_common['Profile'].'</a>';
  247. $links[] = '<li id="navadmin"><a href="admin_index.php">'.$lang_common['Admin'].'</a>';
  248. $links[] = '<li id="navlogout"><a href="login.php?action=out&amp;id='.$pun_user['id'].'&amp;csrf_token='.sha1($pun_user['id'].sha1(get_remote_address())).'">'.$lang_common['Logout'].'</a>';
  249. }
  250. }
  251. // Are there any additional navlinks we should insert into the array before imploding it?
  252. if ($pun_config['o_additional_navlinks'] != '')
  253. {
  254. if (preg_match_all('#([0-9]+)\s*=\s*(.*?)\n#s', $pun_config['o_additional_navlinks']."\n", $extra_links))
  255. {
  256. // Insert any additional links into the $links array (at the correct index)
  257. for ($i = 0; $i < count($extra_links[1]); ++$i)
  258. array_splice($links, $extra_links[1][$i], 0, array('<li id="navextra'.($i + 1).'">'.$extra_links[2][$i]));
  259. }
  260. }
  261. return '<ul>'."\n\t\t\t\t".implode($lang_common['Link separator'].'</li>'."\n\t\t\t\t", $links).'</li>'."\n\t\t\t".'</ul>';
  262. }
  263. //
  264. // Display the profile navigation menu
  265. //
  266. function generate_profile_menu($page = '')
  267. {
  268. global $lang_profile, $pun_config, $pun_user, $id;
  269. ?>
  270. <div id="profile" class="block2col">
  271. <div class="blockmenu">
  272. <h2><span><?php echo $lang_profile['Profile menu'] ?></span></h2>
  273. <div class="box">
  274. <div class="inbox">
  275. <ul>
  276. <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>
  277. <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>
  278. <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>
  279. <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>
  280. <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>
  281. <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>
  282. <?php if ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_id'] == PUN_MOD && $pun_config['p_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>
  283. <?php endif; ?> </ul>
  284. </div>
  285. </div>
  286. </div>
  287. <?php
  288. }
  289. //
  290. // Update posts, topics, last_post, last_post_id and last_poster for a forum
  291. //
  292. function update_forum($forum_id)
  293. {
  294. global $db;
  295. $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());
  296. list($num_topics, $num_posts) = $db->fetch_row($result);
  297. $num_posts = $num_posts + $num_topics; // $num_posts is only the sum of all replies (we have to add the topic posts)
  298. $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());
  299. if ($db->num_rows($result)) // There are topics in the forum
  300. {
  301. list($last_post, $last_post_id, $last_poster) = $db->fetch_row($result);
  302. $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());
  303. }
  304. else // There are no topics
  305. $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());
  306. }
  307. //
  308. // Delete a topic and all of it's posts
  309. //
  310. function delete_topic($topic_id)
  311. {
  312. global $db;
  313. // Delete the topic and any redirect topics
  314. $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());
  315. // Create a list of the post ID's in this topic
  316. $post_ids = '';
  317. $result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to fetch posts', __FILE__, __LINE__, $db->error());
  318. while ($row = $db->fetch_row($result))
  319. $post_ids .= ($post_ids != '') ? ','.$row[0] : $row[0];
  320. // Make sure we have a list of post ID's
  321. if ($post_ids != '')
  322. {
  323. strip_search_index($post_ids);
  324. // Delete posts in topic
  325. $db->query('DELETE FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to delete posts', __FILE__, __LINE__, $db->error());
  326. }
  327. // Delete any subscriptions for this topic
  328. $db->query('DELETE FROM '.$db->prefix.'subscriptions WHERE topic_id='.$topic_id) or error('Unable to delete subscriptions', __FILE__, __LINE__, $db->error());
  329. }
  330. //
  331. // Delete a single post
  332. //
  333. function delete_post($post_id, $topic_id)
  334. {
  335. global $db;
  336. $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());
  337. list($last_id, ,) = $db->fetch_row($result);
  338. list($second_last_id, $second_poster, $second_posted) = $db->fetch_row($result);
  339. // Delete the post
  340. $db->query('DELETE FROM '.$db->prefix.'posts WHERE id='.$post_id) or error('Unable to delete post', __FILE__, __LINE__, $db->error());
  341. strip_search_index($post_id);
  342. // Count number of replies in the topic
  343. $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());
  344. $num_replies = $db->result($result, 0) - 1;
  345. // If the message we deleted is the most recent in the topic (at the end of the topic)
  346. if ($last_id == $post_id)
  347. {
  348. // If there is a $second_last_id there is more than 1 reply to the topic
  349. if (!empty($second_last_id))
  350. $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());
  351. else
  352. // We deleted the only reply, so now last_post/last_post_id/last_poster is posted/id/poster from the topic itself
  353. $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());
  354. }
  355. else
  356. // Otherwise we just decrement the reply counter
  357. $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());
  358. }
  359. //
  360. // Replace censored words in $text
  361. //
  362. function censor_words($text)
  363. {
  364. global $db;
  365. static $search_for, $replace_with;
  366. // If not already built in a previous call, build an array of censor words and their replacement text
  367. if (!isset($search_for))
  368. {
  369. $result = $db->query('SELECT search_for, replace_with FROM '.$db->prefix.'censoring') or error('Unable to fetch censor word list', __FILE__, __LINE__, $db->error());
  370. $num_words = $db->num_rows($result);
  371. $search_for = array();
  372. for ($i = 0; $i < $num_words; ++$i)
  373. {
  374. list($search_for[$i], $replace_with[$i]) = $db->fetch_row($result);
  375. $search_for[$i] = '/\b('.str_replace('\*', '\w*?', preg_quote($search_for[$i], '/')).')\b/i';
  376. }
  377. }
  378. if (!empty($search_for))
  379. $text = substr(preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
  380. return $text;
  381. }
  382. //
  383. // Determines the correct title for $user
  384. // $user must contain the elements 'username', 'title', 'posts', 'g_id' and 'g_user_title'
  385. //
  386. function get_title($user)
  387. {
  388. global $db, $pun_config, $pun_bans, $lang_common;
  389. static $ban_list, $pun_ranks;
  390. // If not already built in a previous call, build an array of lowercase banned usernames
  391. if (empty($ban_list))
  392. {
  393. $ban_list = array();
  394. foreach ($pun_bans as $cur_ban)
  395. $ban_list[] = strtolower($cur_ban['username']);
  396. }
  397. // If not already loaded in a previous call, load the cached ranks
  398. if ($pun_config['o_ranks'] == '1' && empty($pun_ranks))
  399. {
  400. @include PUN_ROOT.'cache/cache_ranks.php';
  401. if (!defined('PUN_RANKS_LOADED'))
  402. {
  403. require_once PUN_ROOT.'include/cache.php';
  404. generate_ranks_cache();
  405. require PUN_ROOT.'cache/cache_ranks.php';
  406. }
  407. }
  408. // If the user has a custom title
  409. if ($user['title'] != '')
  410. $user_title = pun_htmlspecialchars($user['title']);
  411. // If the user is banned
  412. else if (in_array(strtolower($user['username']), $ban_list))
  413. $user_title = $lang_common['Banned'];
  414. // If the user group has a default user title
  415. else if ($user['g_user_title'] != '')
  416. $user_title = pun_htmlspecialchars($user['g_user_title']);
  417. // If the user is a guest
  418. else if ($user['g_id'] == PUN_GUEST)
  419. $user_title = $lang_common['Guest'];
  420. else
  421. {
  422. // Are there any ranks?
  423. if ($pun_config['o_ranks'] == '1' && !empty($pun_ranks))
  424. {
  425. @reset($pun_ranks);
  426. while (list(, $cur_rank) = @each($pun_ranks))
  427. {
  428. if (intval($user['num_posts']) >= $cur_rank['min_posts'])
  429. $user_title = pun_htmlspecialchars($cur_rank['rank']);
  430. }
  431. }
  432. // If the user didn't "reach" any rank (or if ranks are disabled), we assign the default
  433. if (!isset($user_title))
  434. $user_title = $lang_common['Member'];
  435. }
  436. return $user_title;
  437. }
  438. //
  439. // Generate a string with numbered links (for multipage scripts)
  440. //
  441. function paginate($num_pages, $cur_page, $link_to)
  442. {
  443. $pages = array();
  444. $link_to_all = false;
  445. // If $cur_page == -1, we link to all pages (used in viewforum.php)
  446. if ($cur_page == -1)
  447. {
  448. $cur_page = 1;
  449. $link_to_all = true;
  450. }
  451. if ($num_pages <= 1)
  452. $pages = array('<strong>1</strong>');
  453. else
  454. {
  455. if ($cur_page > 3)
  456. {
  457. $pages[] = '<a href="'.$link_to.'&amp;p=1">1</a>';
  458. if ($cur_page != 4)
  459. $pages[] = '&hellip;';
  460. }
  461. // Don't ask me how the following works. It just does, OK? :-)
  462. for ($current = $cur_page - 2, $stop = $cur_page + 3; $current < $stop; ++$current)
  463. {
  464. if ($current < 1 || $current > $num_pages)
  465. continue;
  466. else if ($current != $cur_page || $link_to_all)
  467. $pages[] = '<a href="'.$link_to.'&amp;p='.$current.'">'.$current.'</a>';
  468. else
  469. $pages[] = '<strong>'.$current.'</strong>';
  470. }
  471. if ($cur_page <= ($num_pages-3))
  472. {
  473. if ($cur_page != ($num_pages-3))
  474. $pages[] = '&hellip;';
  475. $pages[] = '<a href="'.$link_to.'&amp;p='.$num_pages.'">'.$num_pages.'</a>';
  476. }
  477. }
  478. return implode('&nbsp;', $pages);
  479. }
  480. //
  481. // Display a message
  482. //
  483. function message($message, $no_back_link = false)
  484. {
  485. global $db, $lang_common, $pun_config, $pun_start, $tpl_main;
  486. if (!defined('PUN_HEADER'))
  487. {
  488. global $pun_user;
  489. $page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Info'];
  490. require PUN_ROOT.'header.php';
  491. }
  492. ?>
  493. <div id="msg" class="block">
  494. <h2><span><?php echo $lang_common['Info'] ?></span></h2>
  495. <div class="box">
  496. <div class="inbox">
  497. <p><?php echo $message ?></p>
  498. <?php if (!$no_back_link): ?> <p><a href="javascript: history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>
  499. <?php endif; ?> </div>
  500. </div>
  501. </div>
  502. <?php
  503. require PUN_ROOT.'footer.php';
  504. }
  505. //
  506. // Format a time string according to $time_format and timezones
  507. //
  508. function format_time($timestamp, $date_only = false)
  509. {
  510. global $pun_config, $lang_common, $pun_user;
  511. if ($timestamp == '')
  512. return $lang_common['Never'];
  513. $diff = ($pun_user['timezone'] - $pun_config['o_server_timezone']) * 3600;
  514. $timestamp += $diff;
  515. $now = time();
  516. $date = date($pun_config['o_date_format'], $timestamp);
  517. $today = date($pun_config['o_date_format'], $now+$diff);
  518. $yesterday = date($pun_config['o_date_format'], $now+$diff-86400);
  519. if ($date == $today)
  520. $date = $lang_common['Today'];
  521. else if ($date == $yesterday)
  522. $date = $lang_common['Yesterday'];
  523. if (!$date_only)
  524. return $date.' '.date($pun_config['o_time_format'], $timestamp);
  525. else
  526. return $date;
  527. }
  528. //
  529. // If we are running pre PHP 4.3.0, we add our own implementation of file_get_contents
  530. //
  531. if (!function_exists('file_get_contents'))
  532. {
  533. function file_get_contents($filename, $use_include_path = 0)
  534. {
  535. $data = '';
  536. if ($fh = fopen($filename, 'rb', $use_include_path))
  537. {
  538. $data = fread($fh, filesize($filename));
  539. fclose($fh);
  540. }
  541. return $data;
  542. }
  543. }
  544. //
  545. // Make sure that HTTP_REFERER matches $pun_config['o_base_url']/$script
  546. //
  547. function confirm_referrer($script)
  548. {
  549. global $pun_config, $lang_common;
  550. if (!preg_match('#^'.preg_quote(str_replace('www.', '', $pun_config['o_base_url']).'/'.$script, '#').'#i', str_replace('www.', '', (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''))))
  551. message($lang_common['Bad referrer']);
  552. }
  553. //
  554. // Generate a random password of length $len
  555. //
  556. function random_pass($len)
  557. {
  558. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  559. $password = '';
  560. for ($i = 0; $i < $len; ++$i)
  561. $password .= substr($chars, (mt_rand() % strlen($chars)), 1);
  562. return $password;
  563. }
  564. //
  565. // Compute a hash of $str
  566. // Uses sha1() if available. If not, SHA1 through mhash() if available. If not, fall back on md5().
  567. //
  568. function pun_hash($str)
  569. {
  570. if (function_exists('sha1')) // Only in PHP 4.3.0+
  571. return sha1($str);
  572. else if (function_exists('mhash')) // Only if Mhash library is loaded
  573. return bin2hex(mhash(MHASH_SHA1, $str));
  574. else
  575. return md5($str);
  576. }
  577. //
  578. // Try to determine the correct remote IP-address
  579. //
  580. function get_remote_address()
  581. {
  582. return $_SERVER['REMOTE_ADDR'];
  583. }
  584. //
  585. // Equivalent to htmlspecialchars(), but allows &#[0-9]+ (for unicode)
  586. //
  587. function pun_htmlspecialchars($str)
  588. {
  589. $str = preg_replace('/&(?!#[0-9]+;)/s', '&amp;', $str);
  590. $str = str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $str);
  591. return $str;
  592. }
  593. //
  594. // Equivalent to strlen(), but counts &#[0-9]+ as one character (for unicode)
  595. //
  596. function pun_strlen($str)
  597. {
  598. return strlen(preg_replace('/&#([0-9]+);/', '!', $str));
  599. }
  600. //
  601. // Convert \r\n and \r to \n
  602. //
  603. function pun_linebreaks($str)
  604. {
  605. return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
  606. }
  607. //
  608. // A more aggressive version of trim()
  609. //
  610. function pun_trim($str)
  611. {
  612. global $lang_common;
  613. if (strpos($lang_common['lang_encoding'], '8859') !== false)
  614. {
  615. $fishy_chars = array(chr(0x81), chr(0x8D), chr(0x8F), chr(0x90), chr(0x9D), chr(0xA0));
  616. return trim(str_replace($fishy_chars, ' ', $str));
  617. }
  618. else
  619. return trim($str);
  620. }
  621. //
  622. // Display a message when board is in maintenance mode
  623. //
  624. function maintenance_message()
  625. {
  626. global $db, $pun_config, $lang_common, $pun_user;
  627. // Deal with newlines, tabs and multiple spaces
  628. $pattern = array("\t", ' ', ' ');
  629. $replace = array('&nbsp; &nbsp; ', '&nbsp; ', ' &nbsp;');
  630. $message = str_replace($pattern, $replace, $pun_config['o_maintenance_message']);
  631. // Load the maintenance template
  632. $tpl_maint = trim(file_get_contents(PUN_ROOT.'include/template/maintenance.tpl'));
  633. // START SUBST - <pun_include "*">
  634. while (preg_match('#<pun_include "([^/\\\\]*?)\.(php[45]?|inc|html?|txt)">#', $tpl_maint, $cur_include))
  635. {
  636. if (!file_exists(PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2]))
  637. error('Unable to process user include '.htmlspecialchars($cur_include[0]).' from template maintenance.tpl. There is no such file in folder /include/user/');
  638. ob_start();
  639. include PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2];
  640. $tpl_temp = ob_get_contents();
  641. $tpl_maint = str_replace($cur_include[0], $tpl_temp, $tpl_maint);
  642. ob_end_clean();
  643. }
  644. // END SUBST - <pun_include "*">
  645. // START SUBST - <pun_content_direction>
  646. $tpl_maint = str_replace('<pun_content_direction>', $lang_common['lang_direction'], $tpl_maint);
  647. // END SUBST - <pun_content_direction>
  648. // START SUBST - <pun_char_encoding>
  649. $tpl_maint = str_replace('<pun_char_encoding>', $lang_common['lang_encoding'], $tpl_maint);
  650. // END SUBST - <pun_char_encoding>
  651. // START SUBST - <pun_head>
  652. ob_start();
  653. ?>
  654. <title><?php echo pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Maintenance'] ?></title>
  655. <link rel="stylesheet" type="text/css" href="style/<?php echo $pun_user['style'].'.css' ?>" />
  656. <?php
  657. $tpl_temp = trim(ob_get_contents());
  658. $tpl_maint = str_replace('<pun_head>', $tpl_temp, $tpl_maint);
  659. ob_end_clean();
  660. // END SUBST - <pun_head>
  661. // START SUBST - <pun_maint_heading>
  662. $tpl_maint = str_replace('<pun_maint_heading>', $lang_common['Maintenance'], $tpl_maint);
  663. // END SUBST - <pun_maint_heading>
  664. // START SUBST - <pun_maint_message>
  665. $tpl_maint = str_replace('<pun_maint_message>', $message, $tpl_maint);
  666. // END SUBST - <pun_maint_message>
  667. // End the transaction
  668. $db->end_transaction();
  669. // Close the db connection (and free up any result data)
  670. $db->close();
  671. exit($tpl_maint);
  672. }
  673. //
  674. // Display $message and redirect user to $destination_url
  675. //
  676. function redirect($destination_url, $message)
  677. {
  678. global $db, $pun_config, $lang_common, $pun_user;
  679. // Prefix with o_base_url (unless there's already a valid URI)
  680. if (strpos($destination_url, 'http://') !== 0 && strpos($destination_url, 'https://') !== 0 && strpos($destination_url, '/') !== 0)
  681. $destination_url = $pun_config['o_base_url'].'/'.$destination_url;
  682. // Do a little spring cleaning
  683. $destination_url = preg_replace('/([\r\n])|(%0[ad])|(;[\s]*data[\s]*:)/i', '', $destination_url);
  684. // If the delay is 0 seconds, we might as well skip the redirect all together
  685. if ($pun_config['o_redirect_delay'] == '0')
  686. header('Location: '.str_replace('&amp;', '&', $destination_url));
  687. // Load the redirect template
  688. $tpl_redir = trim(file_get_contents(PUN_ROOT.'include/template/redirect.tpl'));
  689. // START SUBST - <pun_include "*">
  690. while (preg_match('#<pun_include "([^/\\\\]*?)\.(php[45]?|inc|html?|txt)">#', $tpl_redir, $cur_include))
  691. {
  692. if (!file_exists(PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2]))
  693. error('Unable to process user include '.htmlspecialchars($cur_include[0]).' from template redirect.tpl. There is no such file in folder /include/user/');
  694. ob_start();
  695. include PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2];
  696. $tpl_temp = ob_get_contents();
  697. $tpl_redir = str_replace($cur_include[0], $tpl_temp, $tpl_redir);
  698. ob_end_clean();
  699. }
  700. // END SUBST - <pun_include "*">
  701. // START SUBST - <pun_content_direction>
  702. $tpl_redir = str_replace('<pun_content_direction>', $lang_common['lang_direction'], $tpl_redir);
  703. // END SUBST - <pun_content_direction>
  704. // START SUBST - <pun_char_encoding>
  705. $tpl_redir = str_replace('<pun_char_encoding>', $lang_common['lang_encoding'], $tpl_redir);
  706. // END SUBST - <pun_char_encoding>
  707. // START SUBST - <pun_head>
  708. ob_start();
  709. ?>
  710. <meta http-equiv="refresh" content="<?php echo $pun_config['o_redirect_delay'] ?>;URL=<?php echo str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $destination_url) ?>" />
  711. <title><?php echo pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Redirecting'] ?></title>
  712. <link rel="stylesheet" type="text/css" href="style/<?php echo $pun_user['style'].'.css' ?>" />
  713. <?php
  714. $tpl_temp = trim(ob_get_contents());
  715. $tpl_redir = str_replace('<pun_head>', $tpl_temp, $tpl_redir);
  716. ob_end_clean();
  717. // END SUBST - <pun_head>
  718. // START SUBST - <pun_redir_heading>
  719. $tpl_redir = str_replace('<pun_redir_heading>', $lang_common['Redirecting'], $tpl_redir);
  720. // END SUBST - <pun_redir_heading>
  721. // START SUBST - <pun_redir_text>
  722. $tpl_temp = $message.'<br /><br />'.'<a href="'.$destination_url.'">'.$lang_common['Click redirect'].'</a>';
  723. $tpl_redir = str_replace('<pun_redir_text>', $tpl_temp, $tpl_redir);
  724. // END SUBST - <pun_redir_text>
  725. // START SUBST - <pun_footer>
  726. ob_start();
  727. // End the transaction
  728. $db->end_transaction();
  729. // Display executed queries (if enabled)
  730. if (defined('PUN_SHOW_QUERIES'))
  731. display_saved_queries();
  732. $tpl_temp = trim(ob_get_contents());
  733. $tpl_redir = str_replace('<pun_footer>', $tpl_temp, $tpl_redir);
  734. ob_end_clean();
  735. // END SUBST - <pun_footer>
  736. // Close the db connection (and free up any result data)
  737. $db->close();
  738. exit($tpl_redir);
  739. }
  740. //
  741. // Display a simple error message
  742. //
  743. function error($message, $file, $line, $db_error = false)
  744. {
  745. global $pun_config;
  746. // Set a default title if the script failed before $pun_config could be populated
  747. if (empty($pun_config))
  748. $pun_config['o_board_title'] = 'PunBB';
  749. // Empty output buffer and stop buffering
  750. @ob_end_clean();
  751. // "Restart" output buffering if we are using ob_gzhandler (since the gzip header is already sent)
  752. if (!empty($pun_config['o_gzip']) && extension_loaded('zlib') && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== false))
  753. ob_start('ob_gzhandler');
  754. ?>
  755. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  756. <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
  757. <head>
  758. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  759. <title><?php echo pun_htmlspecialchars($pun_config['o_board_title']) ?> / Error</title>
  760. <style type="text/css">
  761. <!--
  762. BODY {MARGIN: 10% 20% auto 20%; font: 10px Verdana, Arial, Helvetica, sans-serif}
  763. #errorbox {BORDER: 1px solid #B84623}
  764. H2 {MARGIN: 0; COLOR: #FFFFFF; BACKGROUND-COLOR: #B84623; FONT-SIZE: 1.1em; PADDING: 5px 4px}
  765. #errorbox DIV {PADDING: 6px 5px; BACKGROUND-COLOR: #F1F1F1}
  766. -->
  767. </style>
  768. </head>
  769. <body>
  770. <div id="errorbox">
  771. <h2>An error was encountered</h2>
  772. <div>
  773. <?php
  774. if (defined('PUN_DEBUG'))
  775. {
  776. echo "\t\t".'<strong>File:</strong> '.$file.'<br />'."\n\t\t".'<strong>Line:</strong> '.$line.'<br /><br />'."\n\t\t".'<strong>PunBB reported</strong>: '.$message."\n";
  777. if ($db_error)
  778. {
  779. 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";
  780. if ($db_error['error_sql'] != '')
  781. echo "\t\t".'<br /><br /><strong>Failed query:</strong> '.pun_htmlspecialchars($db_error['error_sql'])."\n";
  782. }
  783. }
  784. else
  785. echo "\t\t".'Error: <strong>'.$message.'.</strong>'."\n";
  786. ?>
  787. </div>
  788. </div>
  789. </body>
  790. </html>
  791. <?php
  792. // If a database connection was established (before this error) we close it
  793. if ($db_error)
  794. $GLOBALS['db']->close();
  795. exit;
  796. }
  797. // DEBUG FUNCTIONS BELOW
  798. //
  799. // Display executed queries (if enabled)
  800. //
  801. function display_saved_queries()
  802. {
  803. global $db, $lang_common;
  804. // Get the queries so that we can print them out
  805. $saved_queries = $db->get_saved_queries();
  806. ?>
  807. <div id="debug" class="blocktable">
  808. <h2><span><?php echo $lang_common['Debug table'] ?></span></h2>
  809. <div class="box">
  810. <div class="inbox">
  811. <table cellspacing="0">
  812. <thead>
  813. <tr>
  814. <th class="tcl" scope="col">Time (s)</th>
  815. <th class="tcr" scope="col">Query</th>
  816. </tr>
  817. </thead>
  818. <tbody>
  819. <?php
  820. $query_time_total = 0.0;
  821. while (list(, $cur_query) = @each($saved_queries))
  822. {
  823. $query_time_total += $cur_query[1];
  824. ?>
  825. <tr>
  826. <td class="tcl"><?php echo ($cur_query[1] != 0) ? $cur_query[1] : '&nbsp;' ?></td>
  827. <td class="tcr"><?php echo pun_htmlspecialchars($cur_query[0]) ?></td>
  828. </tr>
  829. <?php
  830. }
  831. ?>
  832. <tr>
  833. <td class="tcl" colspan="2">Total query time: <?php echo $query_time_total ?> s</td>
  834. </tr>
  835. </tbody>
  836. </table>
  837. </div>
  838. </div>
  839. </div>
  840. <?php
  841. }
  842. //
  843. // Unset any variables instantiated as a result of register_globals being enabled
  844. //
  845. function unregister_globals()
  846. {
  847. $register_globals = @ini_get('register_globals');
  848. if ($register_globals === "" || $register_globals === "0" || strtolower($register_globals) === "off")
  849. return;
  850. // Prevent script.php?GLOBALS[foo]=bar
  851. if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
  852. exit('I\'ll have a steak sandwich and... a steak sandwich.');
  853. // Variables that shouldn't be unset
  854. $no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
  855. // Remove elements in $GLOBALS that are present in any of the superglobals
  856. $input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
  857. foreach ($input as $k => $v)
  858. {
  859. if (!in_array($k, $no_unset) && isset($GLOBALS[$k]))
  860. {
  861. unset($GLOBALS[$k]);
  862. unset($GLOBALS[$k]); // Double unset to circumvent the zend_hash_del_key_or_index hole in PHP <4.4.3 and <5.1.4
  863. }
  864. }
  865. }
  866. //
  867. // Dump contents of variable(s)
  868. //
  869. function dump()
  870. {
  871. echo '<pre>';
  872. $num_args = func_num_args();
  873. for ($i = 0; $i < $num_args; ++$i)
  874. {
  875. print_r(func_get_arg($i));
  876. echo "\n\n";
  877. }
  878. echo '</pre>';
  879. exit;
  880. }