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