we included a check for getimagesize() existance... now we again can suppress notices...
[phpbb.git] / phpBB / includes / functions.php
blobfee5f49cc1fc65c9b4beadf21b8073be9215ab00
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 // Common global functions
13 /**
14 * set_var
16 * Set variable, used by {@link request_var the request_var function}
18 * @access private
20 function set_var(&$result, $var, $type, $multibyte = false)
22 settype($var, $type);
23 $result = $var;
25 if ($type == 'string')
27 $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result), ENT_COMPAT, 'UTF-8'));
29 if (!empty($result))
31 // Make sure multibyte characters are wellformed
32 if ($multibyte)
34 if (!preg_match('/^./u', $result))
36 $result = '';
39 else
41 // no multibyte, allow only ASCII (0-127)
42 $result = preg_replace('/[\x80-\xFF]/', '?', $result);
46 $result = (STRIP) ? stripslashes($result) : $result;
50 /**
51 * request_var
53 * Used to get passed variable
55 function request_var($var_name, $default, $multibyte = false, $cookie = false)
57 if (!$cookie && isset($_COOKIE[$var_name]))
59 if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))
61 return (is_array($default)) ? array() : $default;
63 $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];
66 if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name])))
68 return (is_array($default)) ? array() : $default;
71 $var = $_REQUEST[$var_name];
72 if (!is_array($default))
74 $type = gettype($default);
76 else
78 list($key_type, $type) = each($default);
79 $type = gettype($type);
80 $key_type = gettype($key_type);
83 if (is_array($var))
85 $_var = $var;
86 $var = array();
88 foreach ($_var as $k => $v)
90 if (is_array($v))
92 foreach ($v as $_k => $_v)
94 set_var($k, $k, $key_type);
95 set_var($_k, $_k, $key_type);
96 set_var($var[$k][$_k], $_v, $type, $multibyte);
99 else
101 set_var($k, $k, $key_type);
102 set_var($var[$k], $v, $type, $multibyte);
106 else
108 set_var($var, $var, $type, $multibyte);
111 return $var;
115 * Set config value. Creates missing config entry.
117 function set_config($config_name, $config_value, $is_dynamic = false)
119 global $db, $cache, $config;
121 $sql = 'UPDATE ' . CONFIG_TABLE . "
122 SET config_value = '" . $db->sql_escape($config_value) . "'
123 WHERE config_name = '" . $db->sql_escape($config_name) . "'";
124 $db->sql_query($sql);
126 if (!$db->sql_affectedrows() && !isset($config[$config_name]))
128 $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
129 'config_name' => $config_name,
130 'config_value' => $config_value,
131 'is_dynamic' => ($is_dynamic) ? 1 : 0));
132 $db->sql_query($sql);
135 $config[$config_name] = $config_value;
137 if (!$is_dynamic)
139 $cache->destroy('config');
144 * Generates an alphanumeric random string of given length
146 function gen_rand_string($num_chars = 8)
148 $rand_str = unique_id();
149 $rand_str = str_replace('0', 'Z', strtoupper(base_convert($rand_str, 16, 35)));
151 return substr($rand_str, 0, $num_chars);
155 * Return unique id
156 * @param string $extra additional entropy
158 function unique_id($extra = 'c')
160 static $dss_seeded = false;
161 global $config;
163 $val = $config['rand_seed'] . microtime();
164 $val = md5($val);
165 $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
167 if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
169 set_config('rand_seed', $config['rand_seed'], true);
170 set_config('rand_seed_last_update', time(), true);
171 $dss_seeded = true;
174 return substr($val, 4, 16);
178 * Determine whether we are approaching the maximum execution time. Should be called once
179 * at the beginning of the script in which it's used.
180 * @return bool Either true if the maximum execution time is nearly reached, or false
181 * if some time is still left.
183 function still_on_time($extra_time = 15)
185 static $max_execution_time, $start_time;
187 $time = explode(' ', microtime());
188 $current_time = $time[0] + $time[1];
190 if (empty($max_execution_time))
192 $max_execution_time = (function_exists('ini_get')) ? (int) ini_get('max_execution_time') : (int) get_cfg_var('max_execution_time');
194 // If zero, then set to something higher to not let the user catch the ten seconds barrier.
195 if ($max_execution_time === 0)
197 $max_execution_time = 50 + $extra_time;
200 $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
202 // For debugging purposes
203 // $max_execution_time = 10;
205 global $starttime;
206 $start_time = (empty($starttime)) ? $current_time : $starttime;
209 return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
213 * Generate sort selection fields
215 function gen_sort_selects(&$limit_days, &$sort_by_text, &$sort_days, &$sort_key, &$sort_dir, &$s_limit_days, &$s_sort_key, &$s_sort_dir, &$u_sort_param)
217 global $user;
219 $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
221 // Check if the key is selectable. If not, we reset to the first key found.
222 // This ensures the values are always valid.
223 if (!isset($limit_days[$sort_days]))
225 @reset($limit_days);
226 $sort_days = key($limit_days);
229 if (!isset($sort_by_text[$sort_key]))
231 @reset($sort_by_text);
232 $sort_key = key($sort_by_text);
235 if (!isset($sort_dir_text[$sort_dir]))
237 @reset($sort_dir_text);
238 $sort_dir = key($sort_dir_text);
241 $s_limit_days = '<select name="st">';
242 foreach ($limit_days as $day => $text)
244 $selected = ($sort_days == $day) ? ' selected="selected"' : '';
245 $s_limit_days .= '<option value="' . $day . '"' . $selected . '>' . $text . '</option>';
247 $s_limit_days .= '</select>';
249 $s_sort_key = '<select name="sk">';
250 foreach ($sort_by_text as $key => $text)
252 $selected = ($sort_key == $key) ? ' selected="selected"' : '';
253 $s_sort_key .= '<option value="' . $key . '"' . $selected . '>' . $text . '</option>';
255 $s_sort_key .= '</select>';
257 $s_sort_dir = '<select name="sd">';
258 foreach ($sort_dir_text as $key => $value)
260 $selected = ($sort_dir == $key) ? ' selected="selected"' : '';
261 $s_sort_dir .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
263 $s_sort_dir .= '</select>';
265 $u_sort_param = "st=$sort_days&amp;sk=$sort_key&amp;sd=$sort_dir";
267 return;
271 * Generate Jumpbox
273 function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false)
275 global $config, $auth, $template, $user, $db;
277 if (!$config['load_jumpbox'])
279 return;
282 $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
283 FROM ' . FORUMS_TABLE . '
284 ORDER BY left_id ASC';
285 $result = $db->sql_query($sql, 600);
287 $right = $padding = 0;
288 $padding_store = array('0' => 0);
289 $display_jumpbox = false;
290 $iteration = 0;
292 // Sometimes it could happen that forums will be displayed here not be displayed within the index page
293 // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
294 // If this happens, the padding could be "broken"
296 while ($row = $db->sql_fetchrow($result))
298 if ($row['left_id'] < $right)
300 $padding++;
301 $padding_store[$row['parent_id']] = $padding;
303 else if ($row['left_id'] > $right + 1)
305 // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
306 // @todo digging deep to find out "how" this can happen.
307 $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
310 $right = $row['right_id'];
312 if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
314 // Non-postable forum with no subforums, don't display
315 continue;
318 if (!$auth->acl_get('f_list', $row['forum_id']))
320 // if the user does not have permissions to list this forum skip
321 continue;
324 if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
326 continue;
329 if (!$display_jumpbox)
331 $template->assign_block_vars('jumpbox_forums', array(
332 'FORUM_ID' => ($select_all) ? 0 : -1,
333 'FORUM_NAME' => ($select_all) ? $user->lang['ALL_FORUMS'] : $user->lang['SELECT_FORUM'],
334 'S_FORUM_COUNT' => $iteration)
337 $iteration++;
338 $display_jumpbox = true;
341 $template->assign_block_vars('jumpbox_forums', array(
342 'FORUM_ID' => $row['forum_id'],
343 'FORUM_NAME' => $row['forum_name'],
344 'SELECTED' => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
345 'S_FORUM_COUNT' => $iteration,
346 'S_IS_CAT' => ($row['forum_type'] == FORUM_CAT) ? true : false,
347 'S_IS_LINK' => ($row['forum_type'] == FORUM_LINK) ? true : false,
348 'S_IS_POST' => ($row['forum_type'] == FORUM_POST) ? true : false)
351 for ($i = 0; $i < $padding; $i++)
353 $template->assign_block_vars('jumpbox_forums.level', array());
355 $iteration++;
357 $db->sql_freeresult($result);
358 unset($padding_store);
360 $template->assign_vars(array(
361 'S_DISPLAY_JUMPBOX' => $display_jumpbox,
362 'S_JUMPBOX_ACTION' => $action)
365 return;
369 // Compatibility functions
371 if (!function_exists('array_combine'))
374 * A wrapper for the PHP5 function array_combine()
375 * @param array $keys contains keys for the resulting array
376 * @param array $values contains values for the resulting array
378 * @return Returns an array by using the values from the keys array as keys and the
379 * values from the values array as the corresponding values. Returns false if the
380 * number of elements for each array isn't equal or if the arrays are empty.
382 function array_combine($keys, $values)
384 $keys = array_values($keys);
385 $values = array_values($values);
387 $n = sizeof($keys);
388 $m = sizeof($values);
389 if (!$n || !$m || ($n != $m))
391 return false;
394 $combined = array();
395 for ($i = 0; $i < $n; $i++)
397 $combined[$keys[$i]] = $values[$i];
399 return $combined;
403 if (!function_exists('str_split'))
406 * A wrapper for the PHP5 function str_split()
407 * @param array $string contains the string to be converted
408 * @param array $split_length contains the length of each chunk
410 * @return Converts a string to an array. If the optional split_length parameter is specified,
411 * the returned array will be broken down into chunks with each being split_length in length,
412 * otherwise each chunk will be one character in length. FALSE is returned if split_length is
413 * less than 1. If the split_length length exceeds the length of string, the entire string is
414 * returned as the first (and only) array element.
416 function str_split($string, $split_length = 1)
418 if ($split_length < 1)
420 return false;
422 else if ($split_length >= strlen($string))
424 return array($string);
426 else
428 preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
429 return $matches[0];
434 if (!function_exists('stripos'))
437 * A wrapper for the PHP5 function stripos
438 * Find position of first occurrence of a case-insensitive string
440 * @param string $haystack is the string to search in
441 * @param string $needle is the string to search for
443 * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
444 * Note that the needle may be a string of one or more characters.
445 * If needle is not found, stripos() will return boolean FALSE.
447 function stripos($haystack, $needle)
449 if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
451 return strpos($haystack, $m[0]);
454 return false;
458 if (!function_exists('realpath'))
460 if (substr(PHP_OS, 0, 3) != 'WIN' && !(bool) ini_get('safe_mode') && function_exists('shell_exec') && trim(`realpath .`))
463 * @author Chris Smith <chris@project-minerva.org>
464 * @copyright 2006 Project Minerva Team
465 * @param string $path The path which we should attempt to resolve.
466 * @return mixed
467 * @ignore
469 function phpbb_realpath($path)
471 $arg = escapeshellarg($path);
472 return trim(`realpath '$arg'`);
475 else
478 * Checks if a path ($path) is absolute or relative
480 * @param string $path Path to check absoluteness of
481 * @return boolean
483 function is_absolute($path)
485 return ($path[0] == '/' || (substr(PHP_OS, 0, 3) == 'WIN' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
489 * @author Chris Smith <chris@project-minerva.org>
490 * @copyright 2006 Project Minerva Team
491 * @param string $path The path which we should attempt to resolve.
492 * @return mixed
494 function phpbb_realpath($path)
496 // Now to perform funky shizzle
498 // Switch to use UNIX slashes
499 $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
500 $path_prefix = '';
502 // Determine what sort of path we have
503 if (is_absolute($path))
505 $absolute = true;
507 if ($path[0] == '/')
509 // Absolute path, *NIX style
510 $path_prefix = '';
512 else
514 // Absolute path, Windows style
515 // Remove the drive letter and colon
516 $path_prefix = $path[0] . ':';
517 $path = substr($path, 2);
520 else
522 // Relative Path
523 // Prepend the current working directory
524 if (function_exists('getcwd'))
526 // This is the best method, hopefully it is enabled!
527 $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
528 $absolute = true;
529 if (preg_match('#^[a-z]:#i', $path))
531 $path_prefix = $path[0] . ':';
532 $path = substr($path, 2);
534 else
536 $path_prefix = '';
539 else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
541 // Warning: If chdir() has been used this will lie!
542 // Warning: This has some problems sometime (CLI can create them easily)
543 $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
544 $absolute = true;
545 $path_prefix = '';
547 else
549 // We have no way of getting the absolute path, just run on using relative ones.
550 $absolute = false;
551 $path_prefix = '.';
555 // Remove any repeated slashes
556 $path = preg_replace('#/{2,}#', '/', $path);
558 // Remove the slashes from the start and end of the path
559 $path = trim($path, '/');
561 // Break the string into little bits for us to nibble on
562 $bits = explode('/', $path);
564 // Remove any . in the path, renumber array for the loop below
565 $bits = array_keys(array_diff($bits, array('.')));
567 // Lets get looping, run over and resolve any .. (up directory)
568 for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
570 // @todo Optimise
571 if ($bits[$i] == '..' )
573 if (isset($bits[$i - 1]))
575 if ($bits[$i - 1] != '..')
577 // We found a .. and we are able to traverse upwards, lets do it!
578 unset($bits[$i]);
579 unset($bits[$i - 1]);
580 $i -= 2;
581 $max -= 2;
582 $bits = array_values($bits);
585 else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
587 // We have an absolute path trying to descend above the root of the filesystem
588 // ... Error!
589 return false;
594 // Prepend the path prefix
595 array_unshift($bits, $path_prefix);
597 $resolved = '';
599 $max = sizeof($bits) - 1;
601 // Check if we are able to resolve symlinks, Windows cannot.
602 $symlink_resolve = (function_exists('readlink')) ? true : false;
604 foreach ($bits as $i => $bit)
606 if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
608 // Path Exists
609 if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
611 // Resolved a symlink.
612 $resolved = $link . (($i == $max) ? '' : '/');
613 continue;
616 else
618 // Something doesn't exist here!
619 // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
620 // return false;
622 $resolved .= $bit . (($i == $max) ? '' : '/');
625 // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
626 // because we must be inside that basedir, the question is where...
627 // @internal The slash in is_dir() gets around an open_basedir restriction
628 if (!@file_exists($resolved) || (!is_dir($resolved . '/') && !is_file($resolved)))
630 return false;
633 // Put the slashes back to the native operating systems slashes
634 $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
636 return $resolved; // We got here, in the end!
640 else
643 * A wrapper for realpath
644 * @ignore
646 function phpbb_realpath($path)
648 return realpath($path);
652 if (!function_exists('htmlspecialchars_decode'))
655 * A wrapper for htmlspecialchars_decode
656 * @ignore
658 function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
660 return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
664 // functions used for building option fields
667 * Pick a language, any language ...
669 function language_select($default = '')
671 global $db;
673 $sql = 'SELECT lang_iso, lang_local_name
674 FROM ' . LANG_TABLE . '
675 ORDER BY lang_english_name';
676 $result = $db->sql_query($sql);
678 $lang_options = '';
679 while ($row = $db->sql_fetchrow($result))
681 $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
682 $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
684 $db->sql_freeresult($result);
686 return $lang_options;
689 /**
690 * Pick a template/theme combo,
692 function style_select($default = '', $all = false)
694 global $db;
696 $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
697 $sql = 'SELECT style_id, style_name
698 FROM ' . STYLES_TABLE . "
699 $sql_where
700 ORDER BY style_name";
701 $result = $db->sql_query($sql);
703 $style_options = '';
704 while ($row = $db->sql_fetchrow($result))
706 $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
707 $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
709 $db->sql_freeresult($result);
711 return $style_options;
715 * Pick a timezone
717 function tz_select($default = '', $truncate = false)
719 global $user;
721 $tz_select = '';
722 foreach ($user->lang['tz_zones'] as $offset => $zone)
724 if ($truncate)
726 $zone_trunc = truncate_string($zone, 50, false, '...');
728 else
730 $zone_trunc = $zone;
733 if (is_numeric($offset))
735 $selected = ($offset == $default) ? ' selected="selected"' : '';
736 $tz_select .= '<option title="'.$zone.'" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
740 return $tz_select;
743 // Functions handling topic/post tracking/marking
746 * Marks a topic/forum as read
747 * Marks a topic as posted to
749 * @param int $user_id can only be used with $mode == 'post'
751 function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
753 global $db, $user, $config;
755 if ($mode == 'all')
757 if ($forum_id === false || !sizeof($forum_id))
759 if ($config['load_db_lastread'] && $user->data['is_registered'])
761 // Mark all forums read (index page)
762 $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
763 $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
764 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
766 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
768 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
769 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
771 unset($tracking_topics['tf']);
772 unset($tracking_topics['t']);
773 unset($tracking_topics['f']);
774 $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
776 $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
777 unset($tracking_topics);
779 if ($user->data['is_registered'])
781 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
786 return;
788 else if ($mode == 'topics')
790 // Mark all topics in forums read
791 if (!is_array($forum_id))
793 $forum_id = array($forum_id);
796 // Add 0 to forums array to mark global announcements correctly
797 $forum_id[] = 0;
799 if ($config['load_db_lastread'] && $user->data['is_registered'])
801 $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
802 WHERE user_id = {$user->data['user_id']}
803 AND " . $db->sql_in_set('forum_id', $forum_id);
804 $db->sql_query($sql);
806 $sql = 'SELECT forum_id
807 FROM ' . FORUMS_TRACK_TABLE . "
808 WHERE user_id = {$user->data['user_id']}
809 AND " . $db->sql_in_set('forum_id', $forum_id);
810 $result = $db->sql_query($sql);
812 $sql_update = array();
813 while ($row = $db->sql_fetchrow($result))
815 $sql_update[] = $row['forum_id'];
817 $db->sql_freeresult($result);
819 if (sizeof($sql_update))
821 $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
822 SET mark_time = ' . time() . "
823 WHERE user_id = {$user->data['user_id']}
824 AND " . $db->sql_in_set('forum_id', $sql_update);
825 $db->sql_query($sql);
828 if ($sql_insert = array_diff($forum_id, $sql_update))
830 $sql_ary = array();
831 foreach ($sql_insert as $f_id)
833 $sql_ary[] = array(
834 'user_id' => $user->data['user_id'],
835 'forum_id' => $f_id,
836 'mark_time' => time()
840 $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
843 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
845 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
846 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
848 foreach ($forum_id as $f_id)
850 $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
852 if (isset($tracking['tf'][$f_id]))
854 unset($tracking['tf'][$f_id]);
857 foreach ($topic_ids36 as $topic_id36)
859 unset($tracking['t'][$topic_id36]);
862 if (isset($tracking['f'][$f_id]))
864 unset($tracking['f'][$f_id]);
867 $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
870 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
871 unset($tracking);
874 return;
876 else if ($mode == 'topic')
878 if ($topic_id === false || $forum_id === false)
880 return;
883 if ($config['load_db_lastread'] && $user->data['is_registered'])
885 $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
886 SET mark_time = ' . (($post_time) ? $post_time : time()) . "
887 WHERE user_id = {$user->data['user_id']}
888 AND topic_id = $topic_id";
889 $db->sql_query($sql);
891 // insert row
892 if (!$db->sql_affectedrows())
894 $db->sql_return_on_error(true);
896 $sql_ary = array(
897 'user_id' => $user->data['user_id'],
898 'topic_id' => $topic_id,
899 'forum_id' => (int) $forum_id,
900 'mark_time' => ($post_time) ? $post_time : time(),
903 $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
905 $db->sql_return_on_error(false);
908 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
910 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
911 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
913 $topic_id36 = base_convert($topic_id, 10, 36);
915 if (!isset($tracking['t'][$topic_id36]))
917 $tracking['tf'][$forum_id][$topic_id36] = true;
920 $post_time = ($post_time) ? $post_time : time();
921 $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
923 // If the cookie grows larger than 10000 characters we will remove the smallest value
924 // This can result in old topics being unread - but most of the time it should be accurate...
925 if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
927 //echo 'Cookie grown too large' . print_r($tracking, true);
929 // We get the ten most minimum stored time offsets and its associated topic ids
930 $time_keys = array();
931 for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
933 $min_value = min($tracking['t']);
934 $m_tkey = array_search($min_value, $tracking['t']);
935 unset($tracking['t'][$m_tkey]);
937 $time_keys[$m_tkey] = $min_value;
940 // Now remove the topic ids from the array...
941 foreach ($tracking['tf'] as $f_id => $topic_id_ary)
943 foreach ($time_keys as $m_tkey => $min_value)
945 if (isset($topic_id_ary[$m_tkey]))
947 $tracking['f'][$f_id] = $min_value;
948 unset($tracking['tf'][$f_id][$m_tkey]);
953 if ($user->data['is_registered'])
955 $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
956 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
958 else
960 $tracking['l'] = max($time_keys);
964 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
967 return;
969 else if ($mode == 'post')
971 if ($topic_id === false)
973 return;
976 $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
978 if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
980 $db->sql_return_on_error(true);
982 $sql_ary = array(
983 'user_id' => $use_user_id,
984 'topic_id' => $topic_id,
985 'topic_posted' => 1
988 $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
990 $db->sql_return_on_error(false);
993 return;
998 * Get topic tracking info by using already fetched info
1000 function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
1002 global $config, $user;
1004 $last_read = array();
1006 if (!is_array($topic_ids))
1008 $topic_ids = array($topic_ids);
1011 foreach ($topic_ids as $topic_id)
1013 if (!empty($rowset[$topic_id]['mark_time']))
1015 $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
1019 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1021 if (sizeof($topic_ids))
1023 $mark_time = array();
1025 // Get global announcement info
1026 if ($global_announce_list && sizeof($global_announce_list))
1028 if (!isset($forum_mark_time[0]))
1030 global $db;
1032 $sql = 'SELECT mark_time
1033 FROM ' . FORUMS_TRACK_TABLE . "
1034 WHERE user_id = {$user->data['user_id']}
1035 AND forum_id = 0";
1036 $result = $db->sql_query($sql);
1037 $row = $db->sql_fetchrow($result);
1038 $db->sql_freeresult($result);
1040 if ($row)
1042 $mark_time[0] = $row['mark_time'];
1045 else
1047 if ($forum_mark_time[0] !== false)
1049 $mark_time[0] = $forum_mark_time[0];
1054 if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
1056 $mark_time[$forum_id] = $forum_mark_time[$forum_id];
1059 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1061 foreach ($topic_ids as $topic_id)
1063 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1065 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1067 else
1069 $last_read[$topic_id] = $user_lastmark;
1074 return $last_read;
1078 * Get topic tracking info from db (for cookie based tracking only this function is used)
1080 function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
1082 global $config, $user;
1084 $last_read = array();
1086 if (!is_array($topic_ids))
1088 $topic_ids = array($topic_ids);
1091 if ($config['load_db_lastread'] && $user->data['is_registered'])
1093 global $db;
1095 $sql = 'SELECT topic_id, mark_time
1096 FROM ' . TOPICS_TRACK_TABLE . "
1097 WHERE user_id = {$user->data['user_id']}
1098 AND " . $db->sql_in_set('topic_id', $topic_ids);
1099 $result = $db->sql_query($sql);
1101 while ($row = $db->sql_fetchrow($result))
1103 $last_read[$row['topic_id']] = $row['mark_time'];
1105 $db->sql_freeresult($result);
1107 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1109 if (sizeof($topic_ids))
1111 $sql = 'SELECT forum_id, mark_time
1112 FROM ' . FORUMS_TRACK_TABLE . "
1113 WHERE user_id = {$user->data['user_id']}
1114 AND forum_id " .
1115 (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
1116 $result = $db->sql_query($sql);
1118 $mark_time = array();
1119 while ($row = $db->sql_fetchrow($result))
1121 $mark_time[$row['forum_id']] = $row['mark_time'];
1123 $db->sql_freeresult($result);
1125 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1127 foreach ($topic_ids as $topic_id)
1129 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1131 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1133 else
1135 $last_read[$topic_id] = $user_lastmark;
1140 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1142 global $tracking_topics;
1144 if (!isset($tracking_topics) || !sizeof($tracking_topics))
1146 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1147 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1150 if (!$user->data['is_registered'])
1152 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1154 else
1156 $user_lastmark = $user->data['user_lastmark'];
1159 foreach ($topic_ids as $topic_id)
1161 $topic_id36 = base_convert($topic_id, 10, 36);
1163 if (isset($tracking_topics['t'][$topic_id36]))
1165 $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1169 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1171 if (sizeof($topic_ids))
1173 $mark_time = array();
1174 if ($global_announce_list && sizeof($global_announce_list))
1176 if (isset($tracking_topics['f'][0]))
1178 $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
1182 if (isset($tracking_topics['f'][$forum_id]))
1184 $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1187 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
1189 foreach ($topic_ids as $topic_id)
1191 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1193 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1195 else
1197 $last_read[$topic_id] = $user_lastmark;
1203 return $last_read;
1207 * Check for read forums and update topic tracking info accordingly
1209 * @param int $forum_id the forum id to check
1210 * @param int $forum_last_post_time the forums last post time
1211 * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
1212 * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
1214 * @return true if complete forum got marked read, else false.
1216 function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
1218 global $db, $tracking_topics, $user, $config;
1220 // Determine the users last forum mark time if not given.
1221 if ($mark_time_forum === false)
1223 if ($config['load_db_lastread'] && $user->data['is_registered'])
1225 $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
1227 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1229 if (!isset($tracking_topics) || !sizeof($tracking_topics))
1231 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1232 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1235 if (!$user->data['is_registered'])
1237 $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
1240 $mark_time_forum = (isset($tracking_topics['f'][$forum_id])) ? (int) (base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate']) : $user->data['user_lastmark'];
1244 // Check the forum for any left unread topics.
1245 // If there are none, we mark the forum as read.
1246 if ($config['load_db_lastread'] && $user->data['is_registered'])
1248 if ($mark_time_forum >= $forum_last_post_time)
1250 // We do not need to mark read, this happened before. Therefore setting this to true
1251 $row = true;
1253 else
1255 $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
1256 LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
1257 WHERE t.forum_id = ' . $forum_id . '
1258 AND t.topic_last_post_time > ' . $mark_time_forum . '
1259 AND t.topic_moved_id = 0
1260 AND tt.topic_id IS NULL
1261 GROUP BY t.forum_id';
1262 $result = $db->sql_query_limit($sql, 1);
1263 $row = $db->sql_fetchrow($result);
1264 $db->sql_freeresult($result);
1267 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1269 // Get information from cookie
1270 $row = false;
1272 if (!isset($tracking_topics['tf'][$forum_id]))
1274 // We do not need to mark read, this happened before. Therefore setting this to true
1275 $row = true;
1277 else
1279 $sql = 'SELECT topic_id
1280 FROM ' . TOPICS_TABLE . '
1281 WHERE forum_id = ' . $forum_id . '
1282 AND topic_last_post_time > ' . $mark_time_forum . '
1283 AND topic_moved_id = 0';
1284 $result = $db->sql_query($sql);
1286 $check_forum = $tracking_topics['tf'][$forum_id];
1287 $unread = false;
1288 while ($row = $db->sql_fetchrow($result))
1290 if (!in_array(base_convert($row['topic_id'], 10, 36), array_keys($check_forum)))
1292 $unread = true;
1293 break;
1296 $db->sql_freeresult($result);
1298 $row = $unread;
1301 else
1303 $row = true;
1306 if (!$row)
1308 markread('topics', $forum_id);
1309 return true;
1312 return false;
1316 * Transform an array into a serialized format
1318 function tracking_serialize($input)
1320 $out = '';
1321 foreach ($input as $key => $value)
1323 if (is_array($value))
1325 $out .= $key . ':(' . tracking_serialize($value) . ');';
1327 else
1329 $out .= $key . ':' . $value . ';';
1332 return $out;
1336 * Transform a serialized array into an actual array
1338 function tracking_unserialize($string, $max_depth = 3)
1340 $n = strlen($string);
1341 if ($n > 10010)
1343 die('Invalid data supplied');
1345 $data = $stack = array();
1346 $key = '';
1347 $mode = 0;
1348 $level = &$data;
1349 for ($i = 0; $i < $n; ++$i)
1351 switch ($mode)
1353 case 0:
1354 switch ($string[$i])
1356 case ':':
1357 $level[$key] = 0;
1358 $mode = 1;
1359 break;
1360 case ')':
1361 unset($level);
1362 $level = array_pop($stack);
1363 $mode = 3;
1364 break;
1365 default:
1366 $key .= $string[$i];
1368 break;
1370 case 1:
1371 switch ($string[$i])
1373 case '(':
1374 if (sizeof($stack) >= $max_depth)
1376 die('Invalid data supplied');
1378 $stack[] = &$level;
1379 $level[$key] = array();
1380 $level = &$level[$key];
1381 $key = '';
1382 $mode = 0;
1383 break;
1384 default:
1385 $level[$key] = $string[$i];
1386 $mode = 2;
1387 break;
1389 break;
1391 case 2:
1392 switch ($string[$i])
1394 case ')':
1395 unset($level);
1396 $level = array_pop($stack);
1397 $mode = 3;
1398 break;
1399 case ';':
1400 $key = '';
1401 $mode = 0;
1402 break;
1403 default:
1404 $level[$key] .= $string[$i];
1405 break;
1407 break;
1409 case 3:
1410 switch ($string[$i])
1412 case ')':
1413 unset($level);
1414 $level = array_pop($stack);
1415 break;
1416 case ';':
1417 $key = '';
1418 $mode = 0;
1419 break;
1420 default:
1421 die('Invalid data supplied');
1422 break;
1424 break;
1428 if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
1430 die('Invalid data supplied');
1433 return $level;
1436 // Pagination functions
1439 * Pagination routine, generates page number sequence
1440 * tpl_prefix is for using different pagination blocks at one page
1442 function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
1444 global $template, $user;
1446 // Make sure $per_page is a valid value
1447 $per_page = ($per_page <= 0) ? 1 : $per_page;
1449 $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
1450 $total_pages = ceil($num_items / $per_page);
1452 if ($total_pages == 1 || !$num_items)
1454 return false;
1457 $on_page = floor($start_item / $per_page) + 1;
1458 $url_delim = (strpos($base_url, '?') === false) ? '?' : '&amp;';
1460 $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
1462 if ($total_pages > 5)
1464 $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
1465 $end_cnt = max(min($total_pages, $on_page + 4), 6);
1467 $page_string .= ($start_cnt > 1) ? ' ... ' : $seperator;
1469 for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
1471 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
1472 if ($i < $end_cnt - 1)
1474 $page_string .= $seperator;
1478 $page_string .= ($end_cnt < $total_pages) ? ' ... ' : $seperator;
1480 else
1482 $page_string .= $seperator;
1484 for ($i = 2; $i < $total_pages; $i++)
1486 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
1487 if ($i < $total_pages)
1489 $page_string .= $seperator;
1494 $page_string .= ($on_page == $total_pages) ? '<strong>' . $total_pages . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($total_pages - 1) * $per_page) . '">' . $total_pages . '</a>';
1496 if ($add_prevnext_text)
1498 if ($on_page != 1)
1500 $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a>&nbsp;&nbsp;' . $page_string;
1503 if ($on_page != $total_pages)
1505 $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
1509 $template->assign_vars(array(
1510 $tpl_prefix . 'BASE_URL' => $base_url,
1511 $tpl_prefix . 'PER_PAGE' => $per_page,
1513 $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
1514 $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
1515 $tpl_prefix . 'TOTAL_PAGES' => $total_pages)
1518 return $page_string;
1522 * Return current page (pagination)
1524 function on_page($num_items, $per_page, $start)
1526 global $template, $user;
1528 // Make sure $per_page is a valid value
1529 $per_page = ($per_page <= 0) ? 1 : $per_page;
1531 $on_page = floor($start / $per_page) + 1;
1533 $template->assign_vars(array(
1534 'ON_PAGE' => $on_page)
1537 return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
1540 // Server functions (building urls, redirecting...)
1543 * Append session id to url
1545 * @param string $url The url the session id needs to be appended to (can have params)
1546 * @param mixed $params String or array of additional url parameters
1547 * @param bool $is_amp Is url using &amp; (true) or & (false)
1548 * @param string $session_id Possibility to use a custom session id instead of the global one
1550 * Examples:
1551 * <code>
1552 * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&amp;f=2");
1553 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
1554 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
1555 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
1556 * </code>
1558 function append_sid($url, $params = false, $is_amp = true, $session_id = false)
1560 global $_SID, $_EXTRA_URL;
1562 // Assign sid if session id is not specified
1563 if ($session_id === false)
1565 $session_id = $_SID;
1568 $amp_delim = ($is_amp) ? '&amp;' : '&';
1569 $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
1571 // Appending custom url parameter?
1572 $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
1574 // Use the short variant if possible ;)
1575 if ($params === false)
1577 // Append session id
1578 return (!$session_id) ? $url . (($append_url) ? $url_delim . $append_url : '') : $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id;
1581 // Build string if parameters are specified as array
1582 if (is_array($params))
1584 $output = array();
1586 foreach ($params as $key => $item)
1588 if ($item === NULL)
1590 continue;
1593 $output[] = $key . '=' . $item;
1596 $params = implode($amp_delim, $output);
1599 // Append session id and parameters (even if they are empty)
1600 // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
1601 return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id);
1605 * Generate board url (example: http://www.foo.bar/phpBB)
1606 * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.foo.bar)
1608 function generate_board_url($without_script_path = false)
1610 global $config, $user;
1612 $server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
1613 $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
1615 // Forcing server vars is the only way to specify/override the protocol
1616 if ($config['force_server_vars'] || !$server_name)
1618 $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
1619 $server_name = $config['server_name'];
1620 $server_port = (int) $config['server_port'];
1621 $script_path = $config['script_path'];
1623 $url = $server_protocol . $server_name;
1625 else
1627 // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
1628 $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
1629 $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
1631 $script_path = $user->page['root_script_path'];
1634 if ($server_port && (($config['cookie_secure'] && $server_port <> 443) || (!$config['cookie_secure'] && $server_port <> 80)))
1636 $url .= ':' . $server_port;
1639 if (!$without_script_path)
1641 $url .= $script_path;
1644 // Strip / from the end
1645 if (substr($url, -1, 1) == '/')
1647 $url = substr($url, 0, -1);
1650 return $url;
1654 * Redirects the user to another page then exits the script nicely
1656 function redirect($url, $return = false)
1658 global $db, $cache, $config, $user, $phpbb_root_path;
1660 if (empty($user->lang))
1662 $user->add_lang('common');
1665 if (!$return)
1667 garbage_collection();
1670 // Make sure no &amp;'s are in, this will break the redirect
1671 $url = str_replace('&amp;', '&', $url);
1673 // Determine which type of redirect we need to handle...
1674 $url_parts = parse_url($url);
1676 if ($url_parts === false)
1678 // Malformed url, redirect to current page...
1679 $url = generate_board_url() . '/' . $user->page['page'];
1681 else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
1683 // Full URL
1685 else if ($url[0] == '/')
1687 // Absolute uri, prepend direct url...
1688 $url = generate_board_url(true) . $url;
1690 else
1692 // Relative uri
1693 $pathinfo = pathinfo($url);
1695 // Is the uri pointing to the current directory?
1696 if ($pathinfo['dirname'] == '.')
1698 $url = str_replace('./', '', $url);
1700 // Strip / from the beginning
1701 if ($url && substr($url, 0, 1) == '/')
1703 $url = substr($url, 1);
1706 if ($user->page['page_dir'])
1708 $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
1710 else
1712 $url = generate_board_url() . '/' . $url;
1715 else
1717 // Used ./ before, but $phpbb_root_path is working better with urls within another root path
1718 $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
1719 $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
1720 $intersection = array_intersect_assoc($root_dirs, $page_dirs);
1722 $root_dirs = array_diff_assoc($root_dirs, $intersection);
1723 $page_dirs = array_diff_assoc($page_dirs, $intersection);
1725 $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
1727 // Strip / from the end
1728 if ($dir && substr($dir, -1, 1) == '/')
1730 $dir = substr($dir, 0, -1);
1733 // Strip / from the beginning
1734 if ($dir && substr($dir, 0, 1) == '/')
1736 $dir = substr($dir, 1);
1739 $url = str_replace($pathinfo['dirname'] . '/', '', $url);
1741 // Strip / from the beginning
1742 if (substr($url, 0, 1) == '/')
1744 $url = substr($url, 1);
1747 $url = $dir . '/' . $url;
1748 $url = generate_board_url() . '/' . $url;
1752 // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
1753 if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
1755 trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
1758 if ($return)
1760 return $url;
1763 // Redirect via an HTML form for PITA webservers
1764 if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
1766 header('Refresh: 0; URL=' . $url);
1768 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
1769 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
1770 echo '<head>';
1771 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
1772 echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
1773 echo '<title>' . $user->lang['REDIRECT'] . '</title>';
1774 echo '</head>';
1775 echo '<body>';
1776 echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&amp;', $url) . '">', '</a>') . '</div>';
1777 echo '</body>';
1778 echo '</html>';
1780 exit;
1783 // Behave as per HTTP/1.1 spec for others
1784 header('Location: ' . $url);
1785 exit;
1789 * Re-Apply session id after page reloads
1791 function reapply_sid($url)
1793 global $phpEx, $phpbb_root_path;
1795 if ($url === "index.$phpEx")
1797 return append_sid("index.$phpEx");
1799 else if ($url === "{$phpbb_root_path}index.$phpEx")
1801 return append_sid("{$phpbb_root_path}index.$phpEx");
1804 // Remove previously added sid
1805 if (strpos($url, '?sid=') !== false)
1807 $url = preg_replace('/(\?)sid=[a-z0-9]+(&amp;|&)?/', '\1', $url);
1809 else if (strpos($url, '&sid=') !== false)
1811 $url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
1813 else if (strpos($url, '&amp;sid=') !== false)
1815 $url = preg_replace('/&amp;sid=[a-z0-9]+(&amp;)?/', '\1', $url);
1818 return append_sid($url);
1822 * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
1824 function build_url($strip_vars = false)
1826 global $user, $phpbb_root_path;
1828 // Append SID
1829 $redirect = (($user->page['page_dir']) ? $user->page['page_dir'] . '/' : '') . $user->page['page_name'] . (($user->page['query_string']) ? "?{$user->page['query_string']}" : '');
1830 $redirect = append_sid($redirect, false, false);
1832 // Add delimiter if not there...
1833 if (strpos($redirect, '?') === false)
1835 $redirect .= '?';
1838 // Strip vars...
1839 if ($strip_vars !== false && strpos($redirect, '?') !== false)
1841 if (!is_array($strip_vars))
1843 $strip_vars = array($strip_vars);
1846 $query = $_query = array();
1848 $args = substr($redirect, strpos($redirect, '?') + 1);
1849 $args = ($args) ? explode('&', $args) : array();
1850 $redirect = substr($redirect, 0, strpos($redirect, '?'));
1852 foreach ($args as $argument)
1854 $arguments = explode('=', $argument);
1855 $key = $arguments[0];
1856 unset($arguments[0]);
1858 $query[$key] = implode('=', $arguments);
1861 // Strip the vars off
1862 foreach ($strip_vars as $strip)
1864 if (isset($query[$strip]))
1866 unset($query[$strip]);
1870 // Glue the remaining parts together... already urlencoded
1871 foreach ($query as $key => $value)
1873 $_query[] = $key . '=' . $value;
1875 $query = implode('&', $_query);
1877 $redirect .= ($query) ? '?' . $query : '';
1880 return $phpbb_root_path . str_replace('&', '&amp;', $redirect);
1884 * Meta refresh assignment
1886 function meta_refresh($time, $url)
1888 global $template;
1890 $url = redirect($url, true);
1892 // For XHTML compatibility we change back & to &amp;
1893 $template->assign_vars(array(
1894 'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . str_replace('&', '&amp;', $url) . '" />')
1898 // Message/Login boxes
1901 * Build Confirm box
1902 * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
1903 * @param string $title Title/Message used for confirm box.
1904 * message text is _CONFIRM appended to title.
1905 * If title can not be found in user->lang a default one is displayed
1906 * If title_CONFIRM can not be found in user->lang the text given is used.
1907 * @param string $hidden Hidden variables
1908 * @param string $html_body Template used for confirm box
1909 * @param string $u_action Custom form action
1911 function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
1913 global $user, $template, $db;
1914 global $phpEx, $phpbb_root_path;
1916 if (isset($_POST['cancel']))
1918 return false;
1921 $confirm = false;
1922 if (isset($_POST['confirm']))
1924 // language frontier
1925 if ($_POST['confirm'] == $user->lang['YES'])
1927 $confirm = true;
1931 if ($check && $confirm)
1933 $user_id = request_var('user_id', 0);
1934 $session_id = request_var('sess', '');
1935 $confirm_key = request_var('confirm_key', '');
1937 if ($user_id != $user->data['user_id'] || $session_id != $user->session_id || !$confirm_key || !$user->data['user_last_confirm_key'] || $confirm_key != $user->data['user_last_confirm_key'])
1939 return false;
1942 // Reset user_last_confirm_key
1943 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
1944 WHERE user_id = " . $user->data['user_id'];
1945 $db->sql_query($sql);
1947 return true;
1949 else if ($check)
1951 return false;
1954 $s_hidden_fields = build_hidden_fields(array(
1955 'user_id' => $user->data['user_id'],
1956 'sess' => $user->session_id,
1957 'sid' => $user->session_id)
1960 // generate activation key
1961 $confirm_key = gen_rand_string(10);
1963 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
1965 adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
1967 else
1969 page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
1972 $template->set_filenames(array(
1973 'body' => $html_body)
1976 // If activation key already exist, we better do not re-use the key (something very strange is going on...)
1977 if (request_var('confirm_key', ''))
1979 // This should not occur, therefore we cancel the operation to safe the user
1980 return false;
1983 // re-add sid / transform & to &amp; for user->page (user->page is always using &)
1984 $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&amp;', $user->page['page']);
1985 $u_action = reapply_sid($use_page);
1986 $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&amp;') . 'confirm_key=' . $confirm_key;
1988 $template->assign_vars(array(
1989 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
1990 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
1992 'YES_VALUE' => $user->lang['YES'],
1993 'S_CONFIRM_ACTION' => $u_action,
1994 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
1997 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
1998 WHERE user_id = " . $user->data['user_id'];
1999 $db->sql_query($sql);
2001 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2003 adm_page_footer();
2005 else
2007 page_footer();
2012 * Generate login box or verify password
2014 function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
2016 global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
2018 $err = '';
2020 // Make sure user->setup() has been called
2021 if (empty($user->lang))
2023 $user->setup();
2026 // Print out error if user tries to authenticate as an administrator without having the privileges...
2027 if ($admin && !$auth->acl_get('a_'))
2029 // Not authd
2030 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2031 if ($user->data['is_registered'])
2033 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2035 trigger_error('NO_AUTH_ADMIN');
2038 if (isset($_POST['login']))
2040 $username = request_var('username', '', true);
2041 $password = request_var('password', '', true);
2042 $autologin = (!empty($_POST['autologin'])) ? true : false;
2043 $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
2044 $admin = ($admin) ? 1 : 0;
2045 $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
2047 // Check if the supplied username is equal to the one stored within the database if re-authenticating
2048 if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
2050 // We log the attempt to use a different username...
2051 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2052 trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
2055 // do not allow empty password
2056 if (!$password)
2058 trigger_error('NO_PASSWORD_SUPPLIED');
2061 // If authentication is successful we redirect user to previous page
2062 $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
2064 // If admin authentication and login, we will log if it was a success or not...
2065 // We also break the operation on the first non-success login - it could be argued that the user already knows
2066 if ($admin)
2068 if ($result['status'] == LOGIN_SUCCESS)
2070 add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
2072 else
2074 // Only log the failed attempt if a real user tried to.
2075 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2076 if ($user->data['is_registered'])
2078 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2083 // The result parameter is always an array, holding the relevant information...
2084 if ($result['status'] == LOGIN_SUCCESS)
2086 $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
2087 $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
2088 $l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
2090 // append/replace SID (may change during the session for AOL users)
2091 $redirect = reapply_sid($redirect);
2093 // Make sure the user is able to hide his session
2094 if (!$viewonline)
2096 $check_auth = new auth();
2097 $check_auth->acl($user->data);
2099 // Reset online status if not allowed to hide the session...
2100 if (!$check_auth->acl_get('u_hideonline'))
2102 $sql = 'UPDATE ' . SESSIONS_TABLE . '
2103 SET session_viewonline = 1
2104 WHERE session_user_id = ' . $user->data['user_id'];
2105 $db->sql_query($sql);
2108 unset($check_auth);
2111 // Special case... the user is effectively banned, but we allow founders to login
2112 if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
2114 return;
2117 meta_refresh(3, $redirect);
2118 trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
2121 // Something failed, determine what...
2122 if ($result['status'] == LOGIN_BREAK)
2124 trigger_error($result['error_msg'], E_USER_ERROR);
2127 // Special cases... determine
2128 switch ($result['status'])
2130 case LOGIN_ERROR_ATTEMPTS:
2132 // Show confirm image
2133 $sql = 'DELETE FROM ' . CONFIRM_TABLE . "
2134 WHERE session_id = '" . $db->sql_escape($user->session_id) . "'
2135 AND confirm_type = " . CONFIRM_LOGIN;
2136 $db->sql_query($sql);
2138 // Generate code
2139 $code = gen_rand_string(mt_rand(5, 8));
2140 $confirm_id = md5(unique_id($user->ip));
2141 $seed = hexdec(substr(unique_id(), 4, 10));
2143 // compute $seed % 0x7fffffff
2144 $seed -= 0x7fffffff * floor($seed / 0x7fffffff);
2146 $sql = 'INSERT INTO ' . CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array(
2147 'confirm_id' => (string) $confirm_id,
2148 'session_id' => (string) $user->session_id,
2149 'confirm_type' => (int) CONFIRM_LOGIN,
2150 'code' => (string) $code,
2151 'seed' => (int) $seed)
2153 $db->sql_query($sql);
2155 $template->assign_vars(array(
2156 'S_CONFIRM_CODE' => true,
2157 'CONFIRM_ID' => $confirm_id,
2158 'CONFIRM_IMAGE' => '<img src="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=confirm&amp;id=' . $confirm_id . '&amp;type=' . CONFIRM_LOGIN) . '" alt="" title="" />',
2159 'L_LOGIN_CONFIRM_EXPLAIN' => sprintf($user->lang['LOGIN_CONFIRM_EXPLAIN'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>'),
2162 $err = $user->lang[$result['error_msg']];
2164 break;
2166 case LOGIN_ERROR_PASSWORD_CONVERT:
2167 $err = sprintf(
2168 $user->lang[$result['error_msg']],
2169 ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
2170 ($config['email_enable']) ? '</a>' : '',
2171 ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
2172 ($config['board_contact']) ? '</a>' : ''
2174 break;
2176 // Username, password, etc...
2177 default:
2178 $err = $user->lang[$result['error_msg']];
2180 // Assign admin contact to some error messages
2181 if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
2183 $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
2186 break;
2190 if (!$redirect)
2192 // We just use what the session code determined...
2193 // If we are not within the admin directory we use the page dir...
2194 $redirect = '';
2196 if (!$admin)
2198 $redirect .= ($user->page['page_dir']) ? $user->page['page_dir'] . '/' : '';
2201 $redirect .= $user->page['page_name'] . (($user->page['query_string']) ? '?' . htmlspecialchars($user->page['query_string']) : '');
2204 $s_hidden_fields = build_hidden_fields(array('redirect' => $redirect, 'sid' => $user->session_id));
2206 $template->assign_vars(array(
2207 'LOGIN_ERROR' => $err,
2208 'LOGIN_EXPLAIN' => $l_explain,
2210 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
2211 'U_RESEND_ACTIVATION' => ($config['require_activation'] != USER_ACTIVATION_NONE && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
2212 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
2213 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
2215 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
2216 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
2217 'S_LOGIN_ACTION' => (!$admin) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id), // Needs to stay index.$phpEx because we are within the admin directory
2218 'S_HIDDEN_FIELDS' => $s_hidden_fields,
2220 'S_ADMIN_AUTH' => $admin,
2221 'USERNAME' => ($admin) ? $user->data['username'] : '')
2224 page_header($user->lang['LOGIN']);
2226 $template->set_filenames(array(
2227 'body' => 'login_body.html')
2229 make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
2231 page_footer();
2235 * Generate forum login box
2237 function login_forum_box($forum_data)
2239 global $db, $config, $user, $template, $phpEx;
2241 $password = request_var('password', '', true);
2243 $sql = 'SELECT forum_id
2244 FROM ' . FORUMS_ACCESS_TABLE . '
2245 WHERE forum_id = ' . $forum_data['forum_id'] . '
2246 AND user_id = ' . $user->data['user_id'] . "
2247 AND session_id = '" . $db->sql_escape($user->session_id) . "'";
2248 $result = $db->sql_query($sql);
2249 $row = $db->sql_fetchrow($result);
2250 $db->sql_freeresult($result);
2252 if ($row)
2254 return true;
2257 if ($password)
2259 // Remove expired authorised sessions
2260 $sql = 'SELECT session_id
2261 FROM ' . SESSIONS_TABLE;
2262 $result = $db->sql_query($sql);
2264 if ($row = $db->sql_fetchrow($result))
2266 $sql_in = array();
2269 $sql_in[] = (string) $row['session_id'];
2271 while ($row = $db->sql_fetchrow($result));
2273 // Remove expired sessions
2274 $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
2275 WHERE ' . $db->sql_in_set('session_id', $sql_in, true);
2276 $db->sql_query($sql);
2278 $db->sql_freeresult($result);
2280 if ($password == $forum_data['forum_password'])
2282 $sql_ary = array(
2283 'forum_id' => (int) $forum_data['forum_id'],
2284 'user_id' => (int) $user->data['user_id'],
2285 'session_id' => (string) $user->session_id,
2288 $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
2290 return true;
2293 $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
2296 page_header($user->lang['LOGIN']);
2298 $template->assign_vars(array(
2299 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
2302 $template->set_filenames(array(
2303 'body' => 'login_forum.html')
2306 page_footer();
2309 // Content related functions
2312 * Bump Topic Check - used by posting and viewtopic
2314 function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
2316 global $config, $auth, $user;
2318 // Check permission and make sure the last post was not already bumped
2319 if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
2321 return false;
2324 // Check bump time range, is the user really allowed to bump the topic at this time?
2325 $bump_time = ($config['bump_type'] == 'm') ? $config['bump_interval'] * 60 : (($config['bump_type'] == 'h') ? $config['bump_interval'] * 3600 : $config['bump_interval'] * 86400);
2327 // Check bump time
2328 if ($last_post_time + $bump_time > time())
2330 return false;
2333 // Check bumper, only topic poster and last poster are allowed to bump
2334 if ($topic_poster != $user->data['user_id'] && $last_topic_poster != $user->data['user_id'])
2336 return false;
2339 // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
2340 return $bump_time;
2344 * Generates a text with approx. the specified length which contains the specified words and their context
2346 * @param string $text The full text from which context shall be extracted
2347 * @param string $words An array of words which should be contained in the result, has to be a valid part of a PCRE pattern (escape with preg_quote!)
2348 * @param int $length The desired length of the resulting text, however the result might be shorter or longer than this value
2350 * @return string Context of the specified words separated by "..."
2352 function get_context($text, $words, $length = 400)
2354 // first replace all whitespaces with single spaces
2355 $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", ' '), $text);
2357 $word_indizes = array();
2358 if (sizeof($words))
2360 $match = '';
2361 // find the starting indizes of all words
2362 foreach ($words as $word)
2364 if ($word)
2366 if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
2368 $pos = strpos($text, $match[1]);
2369 if ($pos !== false)
2371 $word_indizes[] = $pos;
2376 unset($match);
2378 if (sizeof($word_indizes))
2380 $word_indizes = array_unique($word_indizes);
2381 sort($word_indizes);
2383 $wordnum = sizeof($word_indizes);
2384 // number of characters on the right and left side of each word
2385 $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
2386 $final_text = '';
2387 $word = $j = 0;
2388 $final_text_index = -1;
2390 // cycle through every character in the original text
2391 for ($i = $word_indizes[$word], $n = strlen($text); $i < $n; $i++)
2393 // if the current position is the start of one of the words then append $sequence_length characters to the final text
2394 if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
2396 if ($final_text_index < $i - $sequence_length - 1)
2398 $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', substr($text, $i - $sequence_length, $sequence_length));
2400 else
2402 // if the final text is already nearer to the current word than $sequence_length we only append the text
2403 // from its current index on and distribute the unused length to all other sequenes
2404 $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
2405 $final_text .= substr($text, $final_text_index + 1, $i - $final_text_index - 1);
2407 $final_text_index = $i - 1;
2409 // add the following characters to the final text (see below)
2410 $word++;
2411 $j = 1;
2414 if ($j > 0)
2416 // add the character to the final text and increment the sequence counter
2417 $final_text .= $text[$i];
2418 $final_text_index++;
2419 $j++;
2421 // if this is a whitespace then check whether we are done with this sequence
2422 if ($text[$i] == ' ')
2424 // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
2425 if ($i + 4 < $n)
2427 if (($j > $sequence_length && $word >= $wordnum) || strlen($final_text) > $length)
2429 $final_text .= ' ...';
2430 break;
2433 else
2435 // make sure the text really reaches the end
2436 $j -= 4;
2439 // stop context generation and wait for the next word
2440 if ($j > $sequence_length)
2442 $j = 0;
2447 return $final_text;
2451 if (!sizeof($words) || !sizeof($word_indizes))
2453 return (strlen($text) >= $length + 3) ? substr($text, 0, $length) . '...' : $text;
2458 * Decode text whereby text is coming from the db and expected to be pre-parsed content
2459 * We are placing this outside of the message parser because we are often in need of it...
2461 function decode_message(&$message, $bbcode_uid = '')
2463 global $config;
2465 if ($bbcode_uid)
2467 $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
2468 $replace = array("\n", '', '', '', '');
2470 else
2472 $match = array('<br />');
2473 $replace = array("\n");
2476 $message = str_replace($match, $replace, $message);
2478 $match = get_preg_expression('bbcode_htm');
2479 $replace = array('\1', '\1', '\2', '\1', '', '');
2481 $message = preg_replace($match, $replace, $message);
2485 * Strips all bbcode from a text and returns the plain content
2487 function strip_bbcode(&$text, $uid = '')
2489 if (!$uid)
2491 $uid = '[0-9a-z]{5,}';
2494 $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=.*?)?(?::[a-z])?(\:?$uid)\]#", ' ', $text);
2496 $match = get_preg_expression('bbcode_htm');
2497 $replace = array('\1', '\1', '\2', '\1', '', '');
2499 $text = preg_replace($match, $replace, $text);
2503 * For display of custom parsed text on user-facing pages
2504 * Expects $text to be the value directly from the database (stored value)
2506 function generate_text_for_display($text, $uid, $bitfield, $flags)
2508 static $bbcode;
2510 if (!$text)
2512 return '';
2515 $text = censor_text($text);
2517 // Parse bbcode if bbcode uid stored and bbcode enabled
2518 if ($uid && ($flags & OPTION_FLAG_BBCODE))
2520 if (!class_exists('bbcode'))
2522 global $phpbb_root_path, $phpEx;
2523 include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
2526 if (empty($bbcode))
2528 $bbcode = new bbcode($bitfield);
2530 else
2532 $bbcode->bbcode($bitfield);
2535 $bbcode->bbcode_second_pass($text, $uid);
2538 $text = str_replace("\n", '<br />', $text);
2540 $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
2542 return $text;
2546 * For parsing custom parsed text to be stored within the database.
2547 * This function additionally returns the uid and bitfield that needs to be stored.
2548 * Expects $text to be the value directly from request_var() and in it's non-parsed form
2550 function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false)
2552 global $phpbb_root_path, $phpEx;
2554 $uid = $bitfield = '';
2556 if (!$text)
2558 return;
2561 if (!class_exists('parse_message'))
2563 include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
2566 $message_parser = new parse_message($text);
2567 $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies);
2569 $text = $message_parser->message;
2570 $uid = $message_parser->bbcode_uid;
2572 // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
2573 if (!$message_parser->bbcode_bitfield)
2575 $uid = '';
2578 $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
2579 $bitfield = $message_parser->bbcode_bitfield;
2581 return;
2585 * For decoding custom parsed text for edits as well as extracting the flags
2586 * Expects $text to be the value directly from the database (pre-parsed content)
2588 function generate_text_for_edit($text, $uid, $flags)
2590 global $phpbb_root_path, $phpEx;
2592 decode_message($text, $uid);
2594 return array(
2595 'allow_bbcode' => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
2596 'allow_smilies' => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
2597 'allow_urls' => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
2598 'text' => $text
2603 * A subroutine of make_clickable used with preg_replace
2604 * It places correct HTML around an url, shortens the displayed text
2605 * and makes sure no entities are inside URLs
2607 function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
2609 $append = '';
2610 $url = htmlspecialchars_decode($url);
2611 $relative_url = htmlspecialchars_decode($relative_url);
2613 // make sure no HTML entities were matched
2614 $chars = array('<', '>', '"');
2615 $split = false;
2616 foreach ($chars as $char)
2618 $next_split = strpos($url, $char);
2619 if ($next_split !== false)
2621 $split = ($split !== false) ? min($split, $next_split) : $next_split;
2625 if ($split !== false)
2627 // an HTML entity was found, so the URL has to end before it
2628 $append = substr($url, $split) . $relative_url;
2629 $url = substr($url, 0, $split);
2630 $relative_url = '';
2632 else if ($relative_url)
2634 // same for $relative_url
2635 $split = false;
2636 foreach ($chars as $char)
2638 $next_split = strpos($relative_url, $char);
2639 if ($next_split !== false)
2641 $split = ($split !== false) ? min($split, $next_split) : $next_split;
2645 if ($split !== false)
2647 $append = substr($relative_url, $split);
2648 $relative_url = substr($relative_url, 0, $split);
2652 // if the last character of the url is a punctuation mark, exclude it from the url
2653 $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
2655 switch ($last_char)
2657 case '.':
2658 case '?':
2659 case '!':
2660 case ':':
2661 case ',':
2662 $append = $last_char;
2663 if ($relative_url)
2665 $relative_url = substr($relative_url, 0, -1);
2667 else
2669 $url = substr($url, 0, -1);
2673 switch ($type)
2675 case MAGIC_URL_LOCAL:
2676 $tag = 'l';
2677 $relative_url = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
2678 $url = $url . '/' . $relative_url;
2679 $text = ($relative_url) ? $relative_url : $url . '/';
2680 break;
2682 case MAGIC_URL_FULL:
2683 $tag = 'm';
2684 $text = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
2685 break;
2687 case MAGIC_URL_WWW:
2688 $tag = 'w';
2689 $url = 'http://' . $url;
2690 $text = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
2691 break;
2693 case MAGIC_URL_EMAIL:
2694 $tag = 'e';
2695 $url = 'mailto:' . $url;
2696 $text = (strlen($url) > 55) ? substr($url, 0, 39) . ' ... ' . substr($url, -10) : $url;
2697 break;
2700 $url = htmlspecialchars($url);
2701 $text = htmlspecialchars($text);
2702 $append = htmlspecialchars($append);
2704 $html = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
2706 return $html;
2710 * make_clickable function
2712 * Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
2713 * Cuts down displayed size of link if over 50 chars, turns absolute links
2714 * into relative versions when the server/script path matches the link
2716 function make_clickable($text, $server_url = false, $class = 'postlink')
2718 if ($server_url === false)
2720 $server_url = generate_board_url();
2723 static $magic_url_match;
2724 static $magic_url_replace;
2725 static $static_class;
2727 if (!is_array($magic_url_match) || $static_class != $class)
2729 $static_class = $class;
2730 $class = ($static_class) ? ' class="' . $static_class . '"' : '';
2731 $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
2733 $magic_url_match = $magic_url_replace = array();
2734 // Be sure to not let the matches cross over. ;)
2736 // relative urls for this board
2737 $magic_url_match[] = '#(^|[\n\t (>\]])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#ie';
2738 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_LOCAL, '\$1', '\$2', '\$3', '$local_class')";
2740 // matches a xxxx://aaaaa.bbb.cccc. ...
2741 $magic_url_match[] = '#(^|[\n\t (>\]])(' . get_preg_expression('url_inline') . ')#ie';
2742 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_FULL, '\$1', '\$2', '', '$class')";
2744 // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
2745 $magic_url_match[] = '#(^|[\n\t (>\]])(' . get_preg_expression('www_url_inline') . ')#ie';
2746 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_WWW, '\$1', '\$2', '', '$class')";
2748 // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
2749 $magic_url_match[] = '/(^|[\n\t (>\]])(' . get_preg_expression('email') . ')/ie';
2750 $magic_url_replace[] = "make_clickable_callback(MAGIC_URL_EMAIL, '\$1', '\$2', '', '')";
2753 return preg_replace($magic_url_match, $magic_url_replace, $text);
2757 * Censoring
2759 function censor_text($text)
2761 static $censors;
2762 global $cache;
2764 if (!isset($censors) || !is_array($censors))
2766 // obtain_word_list is taking care of the users censor option and the board-wide option
2767 $censors = $cache->obtain_word_list();
2770 if (sizeof($censors))
2772 return preg_replace($censors['match'], $censors['replace'], $text);
2775 return $text;
2779 * Smiley processing
2781 function smiley_text($text, $force_option = false)
2783 global $config, $user, $phpbb_root_path;
2785 if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
2787 return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
2789 else
2791 return str_replace('<img src="{SMILIES_PATH}', '<img src="' . $phpbb_root_path . $config['smilies_path'], $text);
2796 * General attachment parsing
2798 * @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
2799 * @param string &$message The post/private message
2800 * @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
2801 * @param array &$update_count The attachment counts to be updated - will be filled
2802 * @param bool $preview If set to true the attachments are parsed for preview. Within preview mode the comments are fetched from the given $attachments array and not fetched from the database.
2804 function parse_attachments($forum_id, &$message, &$attachments, &$update_count, $preview = false)
2806 if (!sizeof($attachments))
2808 return;
2811 global $template, $cache, $user;
2812 global $extensions, $config, $phpbb_root_path, $phpEx;
2815 $compiled_attachments = array();
2817 if (!isset($template->filename['attachment_tpl']))
2819 $template->set_filenames(array(
2820 'attachment_tpl' => 'attachment.html')
2824 if (empty($extensions) || !is_array($extensions))
2826 $extensions = $cache->obtain_attach_extensions($forum_id);
2829 // Look for missing attachment information...
2830 $attach_ids = array();
2831 foreach ($attachments as $pos => $attachment)
2833 // If is_orphan is set, we need to retrieve the attachments again...
2834 if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
2836 $attach_ids[(int) $attachment['attach_id']] = $pos;
2840 // Grab attachments (security precaution)
2841 if (sizeof($attach_ids))
2843 global $db;
2845 $new_attachment_data = array();
2847 $sql = 'SELECT *
2848 FROM ' . ATTACHMENTS_TABLE . '
2849 WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
2850 $result = $db->sql_query($sql);
2852 while ($row = $db->sql_fetchrow($result))
2854 if (!isset($attach_ids[$row['attach_id']]))
2856 continue;
2859 // If we preview attachments we will set some retrieved values here
2860 if ($preview)
2862 $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
2865 $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
2867 $db->sql_freeresult($result);
2869 $attachments = $new_attachment_data;
2870 unset($new_attachment_data);
2873 // Sort correctly
2874 if ($config['display_order'])
2876 // Ascending sort
2877 krsort($attachments);
2879 else
2881 // Descending sort
2882 ksort($attachments);
2885 foreach ($attachments as $attachment)
2887 if (!sizeof($attachment))
2889 continue;
2892 // We need to reset/empty the _file block var, because this function might be called more than once
2893 $template->destroy_block_vars('_file');
2895 $block_array = array();
2897 // Some basics...
2898 $attachment['extension'] = strtolower(trim($attachment['extension']));
2899 $filename = $phpbb_root_path . $config['upload_path'] . '/' . basename($attachment['physical_filename']);
2900 $thumbnail_filename = $phpbb_root_path . $config['upload_path'] . '/thumb_' . basename($attachment['physical_filename']);
2902 $upload_icon = '';
2904 if (isset($extensions[$attachment['extension']]))
2906 if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
2908 $upload_icon = $user->img('icon_topic_attach', '');
2910 else if ($extensions[$attachment['extension']]['upload_icon'])
2912 $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
2916 $filesize = $attachment['filesize'];
2917 $size_lang = ($filesize >= 1048576) ? $user->lang['MB'] : ( ($filesize >= 1024) ? $user->lang['KB'] : $user->lang['BYTES'] );
2918 $filesize = ($filesize >= 1048576) ? round((round($filesize / 1048576 * 100) / 100), 2) : (($filesize >= 1024) ? round((round($filesize / 1024 * 100) / 100), 2) : $filesize);
2920 $comment = str_replace("\n", '<br />', censor_text($attachment['attach_comment']));
2922 $block_array += array(
2923 'UPLOAD_ICON' => $upload_icon,
2924 'FILESIZE' => $filesize,
2925 'SIZE_LANG' => $size_lang,
2926 'DOWNLOAD_NAME' => basename($attachment['real_filename']),
2927 'COMMENT' => $comment,
2930 $denied = false;
2932 if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
2934 $denied = true;
2936 $block_array += array(
2937 'S_DENIED' => true,
2938 'DENIED_MESSAGE' => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
2942 if (!$denied)
2944 $l_downloaded_viewed = $download_link = '';
2945 $display_cat = $extensions[$attachment['extension']]['display_cat'];
2947 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE)
2949 if ($attachment['thumbnail'])
2951 $display_cat = ATTACHMENT_CATEGORY_THUMB;
2953 else
2955 if ($config['img_display_inlined'])
2957 if ($config['img_link_width'] || $config['img_link_height'])
2959 $dimension = @getimagesize($filename);
2961 // If the dimensions could not be determined or the image being 0x0 we display it as a link for safety purposes
2962 if ($dimension === false || empty($dimension[0]) || empty($dimension[1]))
2964 $display_cat = ATTACHMENT_CATEGORY_NONE;
2966 else
2968 $display_cat = ($dimension[0] <= $config['img_link_width'] && $dimension[1] <= $config['img_link_height']) ? ATTACHMENT_CATEGORY_IMAGE : ATTACHMENT_CATEGORY_NONE;
2972 else
2974 $display_cat = ATTACHMENT_CATEGORY_NONE;
2979 // Make some descisions based on user options being set.
2980 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
2982 $display_cat = ATTACHMENT_CATEGORY_NONE;
2985 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
2987 $display_cat = ATTACHMENT_CATEGORY_NONE;
2990 $download_link = append_sid("{$phpbb_root_path}download.$phpEx", 'id=' . $attachment['attach_id']);
2992 switch ($display_cat)
2994 // Images
2995 case ATTACHMENT_CATEGORY_IMAGE:
2996 $l_downloaded_viewed = 'VIEWED_COUNT';
2997 $inline_link = append_sid("{$phpbb_root_path}download.$phpEx", 'id=' . $attachment['attach_id']);
2998 $download_link .= '&amp;mode=view';
3000 $block_array += array(
3001 'S_IMAGE' => true,
3002 'U_INLINE_LINK' => $inline_link,
3005 $update_count[] = $attachment['attach_id'];
3006 break;
3008 // Images, but display Thumbnail
3009 case ATTACHMENT_CATEGORY_THUMB:
3010 $l_downloaded_viewed = 'VIEWED_COUNT';
3011 $thumbnail_link = append_sid("{$phpbb_root_path}download.$phpEx", 'id=' . $attachment['attach_id'] . '&amp;t=1');
3012 $download_link .= '&amp;mode=view';
3014 $block_array += array(
3015 'S_THUMBNAIL' => true,
3016 'THUMB_IMAGE' => $thumbnail_link,
3018 break;
3020 // Windows Media Streams
3021 case ATTACHMENT_CATEGORY_WM:
3022 $l_downloaded_viewed = 'VIEWED_COUNT';
3024 // Giving the filename directly because within the wm object all variables are in local context making it impossible
3025 // to validate against a valid session (all params can differ)
3026 // $download_link = $filename;
3028 $block_array += array(
3029 'U_FORUM' => generate_board_url(),
3030 'ATTACH_ID' => $attachment['attach_id'],
3031 'S_WM_FILE' => true,
3034 // Viewed/Heared File ... update the download count
3035 $update_count[] = $attachment['attach_id'];
3036 break;
3038 // Real Media Streams
3039 case ATTACHMENT_CATEGORY_RM:
3040 case ATTACHMENT_CATEGORY_QUICKTIME:
3041 $l_downloaded_viewed = 'VIEWED_COUNT';
3043 $block_array += array(
3044 'S_RM_FILE' => ($display_cat == ATTACHMENT_CATEGORY_RM) ? true : false,
3045 'S_QUICKTIME_FILE' => ($display_cat == ATTACHMENT_CATEGORY_QUICKTIME) ? true : false,
3046 'U_FORUM' => generate_board_url(),
3047 'ATTACH_ID' => $attachment['attach_id'],
3050 // Viewed/Heared File ... update the download count
3051 $update_count[] = $attachment['attach_id'];
3052 break;
3054 // Macromedia Flash Files
3055 case ATTACHMENT_CATEGORY_FLASH:
3056 list($width, $height) = @getimagesize($filename);
3058 $l_downloaded_viewed = 'VIEWED_COUNT';
3060 $block_array += array(
3061 'S_FLASH_FILE' => true,
3062 'WIDTH' => $width,
3063 'HEIGHT' => $height,
3066 // Viewed/Heared File ... update the download count
3067 $update_count[] = $attachment['attach_id'];
3068 break;
3070 default:
3071 $l_downloaded_viewed = 'DOWNLOAD_COUNT';
3073 $block_array += array(
3074 'S_FILE' => true,
3076 break;
3079 $l_download_count = (!isset($attachment['download_count']) || $attachment['download_count'] == 0) ? $user->lang[$l_downloaded_viewed . '_NONE'] : (($attachment['download_count'] == 1) ? sprintf($user->lang[$l_downloaded_viewed], $attachment['download_count']) : sprintf($user->lang[$l_downloaded_viewed . 'S'], $attachment['download_count']));
3081 $block_array += array(
3082 'U_DOWNLOAD_LINK' => $download_link,
3083 'L_DOWNLOAD_COUNT' => $l_download_count
3087 $template->assign_block_vars('_file', $block_array);
3089 $compiled_attachments[] = $template->assign_display('attachment_tpl');
3092 $attachments = $compiled_attachments;
3093 unset($compiled_attachments);
3095 $tpl_size = sizeof($attachments);
3097 $unset_tpl = array();
3099 preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
3101 $replace = array();
3102 foreach ($matches[0] as $num => $capture)
3104 // Flip index if we are displaying the reverse way
3105 $index = ($config['display_order']) ? ($tpl_size-($matches[1][$num] + 1)) : $matches[1][$num];
3107 $replace['from'][] = $matches[0][$num];
3108 $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
3110 $unset_tpl[] = $index;
3113 if (isset($replace['from']))
3115 $message = str_replace($replace['from'], $replace['to'], $message);
3118 $unset_tpl = array_unique($unset_tpl);
3120 // Needed to let not display the inlined attachments at the end of the post again
3121 foreach ($unset_tpl as $index)
3123 unset($attachments[$index]);
3128 * Check if extension is allowed to be posted.
3130 * @param mixed $forum_id The forum id to check or false if private message
3131 * @param string $extension The extension to check, for example zip.
3132 * @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
3134 * @return bool False if the extension is not allowed to be posted, else true.
3136 function extension_allowed($forum_id, $extension, &$extensions)
3138 if (empty($extensions))
3140 global $cache;
3141 $extensions = $cache->obtain_attach_extensions($forum_id);
3144 return (!isset($extensions['_allowed_'][$extension])) ? false : true;
3147 // Little helpers
3150 * Little helper for the build_hidden_fields function
3152 function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
3154 $hidden_fields = '';
3156 if (!is_array($value))
3158 $value = ($stripslashes) ? stripslashes($value) : $value;
3159 $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
3161 $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
3163 else
3165 foreach ($value as $_key => $_value)
3167 $_key = ($stripslashes) ? stripslashes($_key) : $_key;
3168 $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
3170 $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
3174 return $hidden_fields;
3178 * Build simple hidden fields from array
3180 * @param array $field_ary an array of values to build the hidden field from
3181 * @param bool $specialchar if true, keys and values get specialchared
3182 * @param bool $stripslashes if true, keys and values get stripslashed
3184 * @return string the hidden fields
3186 function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
3188 $s_hidden_fields = '';
3190 foreach ($field_ary as $name => $vars)
3192 $name = ($stripslashes) ? stripslashes($name) : $name;
3193 $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
3195 $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
3198 return $s_hidden_fields;
3202 * Parse cfg file
3204 function parse_cfg_file($filename, $lines = false)
3206 $parsed_items = array();
3208 if ($lines === false)
3210 $lines = file($filename);
3213 foreach ($lines as $line)
3215 $line = trim($line);
3217 if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
3219 continue;
3222 // Determine first occurrence, since in values the equal sign is allowed
3223 $key = strtolower(trim(substr($line, 0, $delim_pos)));
3224 $value = trim(substr($line, $delim_pos + 1));
3226 if (in_array($value, array('off', 'false', '0')))
3228 $value = false;
3230 else if (in_array($value, array('on', 'true', '1')))
3232 $value = true;
3234 else if (!trim($value))
3236 $value = '';
3238 else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
3240 $value = substr($value, 1, sizeof($value)-2);
3243 $parsed_items[$key] = $value;
3246 return $parsed_items;
3250 * Add log event
3252 function add_log()
3254 global $db, $user;
3256 $args = func_get_args();
3258 $mode = array_shift($args);
3259 $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
3260 $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3261 $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3262 $action = array_shift($args);
3263 $data = (!sizeof($args)) ? '' : serialize($args);
3265 $sql_ary = array(
3266 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
3267 'log_ip' => $user->ip,
3268 'log_time' => time(),
3269 'log_operation' => $action,
3270 'log_data' => $data,
3273 switch ($mode)
3275 case 'admin':
3276 $sql_ary['log_type'] = LOG_ADMIN;
3277 break;
3279 case 'mod':
3280 $sql_ary += array(
3281 'log_type' => LOG_MOD,
3282 'forum_id' => $forum_id,
3283 'topic_id' => $topic_id
3285 break;
3287 case 'user':
3288 $sql_ary += array(
3289 'log_type' => LOG_USERS,
3290 'reportee_id' => $reportee_id
3292 break;
3294 case 'critical':
3295 $sql_ary['log_type'] = LOG_CRITICAL;
3296 break;
3298 default:
3299 return false;
3302 $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
3304 return $db->sql_nextid();
3308 * Return a nicely formatted backtrace (parts from the php manual by diz at ysagoon dot com)
3310 function get_backtrace()
3312 global $phpbb_root_path;
3314 $output = '<div style="font-family: monospace;">';
3315 $backtrace = debug_backtrace();
3316 $path = phpbb_realpath($phpbb_root_path);
3318 foreach ($backtrace as $number => $trace)
3320 // We skip the first one, because it only shows this file/function
3321 if ($number == 0)
3323 continue;
3326 // Strip the current directory from path
3327 if (empty($trace['file']))
3329 $trace['file'] = '';
3331 else
3333 $trace['file'] = str_replace(array($path, '\\'), array('', '/'), $trace['file']);
3334 $trace['file'] = substr($trace['file'], 1);
3336 $args = array();
3338 // If include/require/include_once is not called, do not show arguments - they may contain sensible information
3339 if (!in_array($trace['function'], array('include', 'require', 'include_once')))
3341 unset($trace['args']);
3343 else
3345 // Path...
3346 if (!empty($trace['args'][0]))
3348 $argument = htmlspecialchars($trace['args'][0]);
3349 $argument = str_replace(array($path, '\\'), array('', '/'), $argument);
3350 $argument = substr($argument, 1);
3351 $args[] = "'{$argument}'";
3355 $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
3356 $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
3358 $output .= '<br />';
3359 $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
3360 $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
3362 $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '(' . ((sizeof($args)) ? implode(', ', $args) : '') . ')<br />';
3364 $output .= '</div>';
3365 return $output;
3369 * This function returns a regular expression pattern for commonly used expressions
3370 * Use with / as delimiter for email mode and # for url modes
3371 * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline
3373 function get_preg_expression($mode)
3375 switch ($mode)
3377 case 'email':
3378 return '[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*[a-z]+';
3379 break;
3381 case 'bbcode_htm':
3382 return array(
3383 '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
3384 '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
3385 '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
3386 '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
3387 '#<!\-\- .*? \-\->#s',
3388 '#<.*?>#s',
3390 break;
3392 case 'url':
3393 case 'url_inline':
3394 $inline = ($mode == 'url') ? ')' : '';
3395 // generated with regex generation file in the develop folder
3396 return "[a-z][a-z\d+\-.]*:/{2}(?:(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+|[0-9.]+|\[[a-z0-9.]+:[a-z0-9.]+:[a-z0-9.:]+\])(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3397 break;
3399 case 'www_url':
3400 case 'www_url_inline':
3401 $inline = ($mode == 'www_url') ? ')' : '';
3402 return "www\.(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3403 break;
3405 case 'relative_url':
3406 case 'relative_url_inline':
3407 $inline = ($mode == 'relative_url') ? ')' : '';
3408 return "(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3409 break;
3412 return '';
3416 * Returns the first block of the specified IPv6 address and as many additional
3417 * ones as specified in the length paramater.
3418 * If length is zero, then an empty string is returned.
3419 * If length is greater than 3 the complete IP will be returned
3421 function short_ipv6($ip, $length)
3423 if ($length < 1)
3425 return '';
3428 // extend IPv6 addresses
3429 $blocks = substr_count($ip, ':') + 1;
3430 if ($blocks < 9)
3432 $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
3434 if ($ip[0] == ':')
3436 $ip = '0000' . $ip;
3438 if ($length < 4)
3440 $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
3443 return $ip;
3447 * Truncates string while retaining special characters if going over the max length
3448 * The default max length is 60 at the moment
3450 function truncate_string($string, $max_length = 60, $allow_reply = true, $append = '')
3452 $chars = array();
3454 $strip_reply = false;
3455 $stripped = false;
3456 if ($allow_reply && strpos($string, 'Re: ') === 0)
3458 $strip_reply = true;
3459 $string = substr($string, 4);
3462 $_chars = utf8_str_split(htmlspecialchars_decode($string));
3463 $chars = array_map('htmlspecialchars', $_chars);
3465 // Now check the length ;)
3466 if (sizeof($chars) > $max_length)
3468 // Cut off the last elements from the array
3469 $string = implode('', array_slice($chars, 0, $max_length));
3470 $stripped = true;
3473 if ($strip_reply)
3475 $string = 'Re: ' . $string;
3478 if ($append != '' && $stripped)
3480 $string = $string . $append;
3483 return $string;
3487 * Get username details for placing into templates.
3489 * @param string $mode Can be profile (for getting an url to the profile), username (for obtaining the username), colour (for obtaining the user colour) or full (for obtaining a html string representing a coloured link to the users profile).
3490 * @param int $user_id The users id
3491 * @param string $username The users name
3492 * @param string $username_colour The users colour
3493 * @param string $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
3494 * @param string $custom_profile_url optional parameter to specify a profile url. The user id get appended to this url as &amp;u={user_id}
3496 * @return string A string consisting of what is wanted based on $mode.
3498 function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
3500 global $phpbb_root_path, $phpEx, $user, $auth;
3502 $profile_url = '';
3503 $username_colour = ($username_colour) ? '#' . $username_colour : '';
3505 if ($guest_username === false)
3507 $username = ($username) ? $username : $user->lang['GUEST'];
3509 else
3511 $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
3514 // Only show the link if not anonymous
3515 if ($user_id && $user_id != ANONYMOUS)
3517 // Do not show the link if the user is already logged in but do not have u_viewprofile permissions (relevant for bots mostly).
3518 // For all others the link leads to a login page or the profile.
3519 if ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile'))
3521 $profile_url = '';
3523 else
3525 $profile_url = ($custom_profile_url !== false) ? $custom_profile_url : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile');
3526 $profile_url .= '&amp;u=' . (int) $user_id;
3529 else
3531 $profile_url = '';
3534 switch ($mode)
3536 case 'profile':
3537 return $profile_url;
3538 break;
3540 case 'username':
3541 return $username;
3542 break;
3544 case 'colour':
3545 return $username_colour;
3546 break;
3548 case 'full':
3549 default:
3551 $tpl = '';
3552 if (!$profile_url && !$username_colour)
3554 $tpl = '{USERNAME}';
3556 else if (!$profile_url && $username_colour)
3558 $tpl = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
3560 else if ($profile_url && !$username_colour)
3562 $tpl = '<a href="{PROFILE_URL}">{USERNAME}</a>';
3564 else if ($profile_url && $username_colour)
3566 $tpl = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
3569 return str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), $tpl);
3570 break;
3575 * Wrapper for php's checkdnsrr function.
3577 * The windows failover is from the php manual
3578 * Please make sure to check the return value for === true and === false, since NULL could
3579 * be returned too.
3581 * @return true if entry found, false if not, NULL if this function is not supported by this environment
3583 function phpbb_checkdnsrr($host, $type = '')
3585 $type = (!$type) ? 'MX' : $type;
3587 if (strpos(PHP_OS, 'WIN') !== false)
3589 if (!function_exists('exec'))
3591 return NULL;
3594 @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
3596 // If output is empty, the nslookup failed
3597 if (empty($output))
3599 return NULL;
3602 foreach ($output as $line)
3604 if (!trim($line))
3606 continue;
3609 // Valid records begin with host name:
3610 if (strpos($line, $host) === 0)
3612 return true;
3616 return false;
3618 else if (function_exists('checkdnsrr'))
3620 return (checkdnsrr($host, $type)) ? true : false;
3623 return NULL;
3626 // Handler, header and footer
3629 * Error and message handler, call with trigger_error if reqd
3631 function msg_handler($errno, $msg_text, $errfile, $errline)
3633 global $cache, $db, $auth, $template, $config, $user;
3634 global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
3636 // Message handler is stripping text. In case we need it, we are possible to define long text...
3637 if (isset($msg_long_text) && $msg_long_text && !$msg_text)
3639 $msg_text = $msg_long_text;
3642 switch ($errno)
3644 case E_NOTICE:
3645 case E_WARNING:
3647 // Check the error reporting level and return if the error level does not match
3648 // Additionally do not display notices if we suppress them via @
3649 // If DEBUG is defined the default level is E_ALL
3650 if (($errno & ((defined('DEBUG') && error_reporting()) ? E_ALL : error_reporting())) == 0)
3652 return;
3655 if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
3657 // remove complete path to installation, with the risk of changing backslashes meant to be there
3658 $errfile = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $errfile);
3659 $msg_text = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $msg_text);
3661 echo '<b>[phpBB Debug] PHP Notice</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
3664 return;
3666 break;
3668 case E_USER_ERROR:
3670 if (!empty($user) && !empty($user->lang))
3672 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3673 $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3675 $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
3676 $l_notify = '';
3678 if (!empty($config['board_contact']))
3680 $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
3683 else
3685 $msg_title = 'General Error';
3686 $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
3687 $l_notify = '';
3689 if (!empty($config['board_contact']))
3691 $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
3695 garbage_collection();
3697 // Try to not call the adm page data...
3699 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
3700 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
3701 echo '<head>';
3702 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
3703 echo '<title>' . $msg_title . '</title>';
3704 echo '<style type="text/css">' . "\n" . '<!--' . "\n";
3705 echo '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; } ';
3706 echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
3707 echo '#wrap { padding: 0 20px 15px 20px; min-width: 615px; } #page-header { text-align: right; height: 40px; } #page-footer { clear: both; font-size: 1em; text-align: center; } ';
3708 echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
3709 echo '#errorpage #page-header a { font-weight: bold; line-height: 6em; } #errorpage #content { padding: 10px; } #errorpage #content h1 { line-height: 1.2em; margin-bottom: 0; color: #DF075C; } ';
3710 echo '#errorpage #content div { margin-top: 20px; margin-bottom: 5px; border-bottom: 1px solid #CCCCCC; padding-bottom: 5px; color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; line-height: 120%; text-align: left; } ';
3711 echo "\n" . '//-->' . "\n";
3712 echo '</style>';
3713 echo '</head>';
3714 echo '<body id="errorpage">';
3715 echo '<div id="wrap">';
3716 echo ' <div id="page-header">';
3717 echo ' ' . $l_return_index;
3718 echo ' </div>';
3719 echo ' <div id="acp">';
3720 echo ' <div class="panel">';
3721 echo ' <div id="content">';
3722 echo ' <h1>' . $msg_title . '</h1>';
3724 echo ' <div>' . $msg_text . '</div>';
3726 echo $l_notify;
3728 echo ' </div>';
3729 echo ' </div>';
3730 echo ' </div>';
3731 echo ' <div id="page-footer">';
3732 echo ' Powered by phpBB &copy; 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>';
3733 echo ' </div>';
3734 echo '</div>';
3735 echo '</body>';
3736 echo '</html>';
3738 exit;
3739 break;
3741 case E_USER_WARNING:
3742 case E_USER_NOTICE:
3744 define('IN_ERROR_HANDLER', true);
3746 if (empty($user->data))
3748 $user->session_begin();
3751 // We re-init the auth array to get correct results on login/logout
3752 $auth->acl($user->data);
3754 if (empty($user->lang))
3756 $user->setup();
3759 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3760 $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3762 if (!defined('HEADER_INC'))
3764 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3766 adm_page_header($msg_title);
3768 else
3770 page_header($msg_title);
3774 $template->set_filenames(array(
3775 'body' => 'message_body.html')
3778 $template->assign_vars(array(
3779 'MESSAGE_TITLE' => $msg_title,
3780 'MESSAGE_TEXT' => $msg_text,
3781 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
3782 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
3785 // We do not want the cron script to be called on error messages
3786 define('IN_CRON', true);
3788 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3790 adm_page_footer();
3792 else
3794 page_footer();
3797 exit;
3798 break;
3801 // If we notice an error not handled here we pass this back to PHP by returning false
3802 // This may not work for all php versions
3803 return false;
3807 * Generate page header
3809 function page_header($page_title = '', $display_online_list = true)
3811 global $db, $config, $template, $SID, $_SID, $user, $auth, $phpEx, $phpbb_root_path;
3813 if (defined('HEADER_INC'))
3815 return;
3818 define('HEADER_INC', true);
3820 // gzip_compression
3821 if ($config['gzip_compress'])
3823 if (@extension_loaded('zlib') && !headers_sent())
3825 ob_start('ob_gzhandler');
3829 // Generate logged in/logged out status
3830 if ($user->data['user_id'] != ANONYMOUS)
3832 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
3833 $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
3835 else
3837 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
3838 $l_login_logout = $user->lang['LOGIN'];
3841 // Last visit date/time
3842 $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
3844 // Get users online list ... if required
3845 $l_online_users = $online_userlist = $l_online_record = '';
3847 if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
3849 $logged_visible_online = $logged_hidden_online = $guests_online = $prev_user_id = 0;
3850 $prev_session_ip = $reading_sql = '';
3852 if (!empty($_REQUEST['f']))
3854 $f = request_var('f', 0);
3856 // Do not change this (it is defined as _f_={forum_id}x within session.php)
3857 $reading_sql = " AND s.session_page LIKE '%\_f\_={$f}x%'";
3859 // Specify escape character for MSSQL
3860 if ($db->sql_layer == 'mssql' || $db->sql_layer == 'mssql_odbc')
3862 $reading_sql .= " ESCAPE '\\' ";
3866 // Get number of online guests
3867 if (!$config['load_online_guests'])
3869 if ($db->sql_layer === 'sqlite')
3871 $sql = 'SELECT COUNT(session_ip) as num_guests
3872 FROM (
3873 SELECT DISTINCT s.session_ip
3874 FROM ' . SESSIONS_TABLE . ' s
3875 WHERE s.session_user_id = ' . ANONYMOUS . '
3876 AND s.session_time >= ' . (time() - ($config['load_online_time'] * 60)) .
3877 $reading_sql .
3878 ')';
3880 else
3882 $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
3883 FROM ' . SESSIONS_TABLE . ' s
3884 WHERE s.session_user_id = ' . ANONYMOUS . '
3885 AND s.session_time >= ' . (time() - ($config['load_online_time'] * 60)) .
3886 $reading_sql;
3888 $result = $db->sql_query($sql);
3889 $guests_online = (int) $db->sql_fetchfield('num_guests');
3890 $db->sql_freeresult($result);
3893 $sql = 'SELECT u.username, u.username_clean, u.user_id, u.user_type, u.user_allow_viewonline, u.user_colour, s.session_ip, s.session_viewonline
3894 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_TABLE . ' s
3895 WHERE s.session_time >= ' . (time() - (intval($config['load_online_time']) * 60)) .
3896 $reading_sql .
3897 ((!$config['load_online_guests']) ? ' AND s.session_user_id <> ' . ANONYMOUS : '') . '
3898 AND u.user_id = s.session_user_id
3899 ORDER BY u.username_clean ASC, s.session_ip ASC';
3900 $result = $db->sql_query($sql);
3902 while ($row = $db->sql_fetchrow($result))
3904 // User is logged in and therefore not a guest
3905 if ($row['user_id'] != ANONYMOUS)
3907 // Skip multiple sessions for one user
3908 if ($row['user_id'] != $prev_user_id)
3910 if ($row['user_colour'])
3912 $user_colour = ' style="color:#' . $row['user_colour'] . '"';
3913 $row['username'] = '<strong>' . $row['username'] . '</strong>';
3915 else
3917 $user_colour = '';
3920 if ($row['user_allow_viewonline'] && $row['session_viewonline'])
3922 $user_online_link = $row['username'];
3923 $logged_visible_online++;
3925 else
3927 $user_online_link = '<em>' . $row['username'] . '</em>';
3928 $logged_hidden_online++;
3931 if (($row['user_allow_viewonline'] && $row['session_viewonline']) || $auth->acl_get('u_viewonline'))
3933 if ($row['user_type'] <> USER_IGNORE)
3935 $user_online_link = '<a href="' . append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u=' . $row['user_id']) . '"' . $user_colour . '>' . $user_online_link . '</a>';
3937 else
3939 $user_online_link = ($user_colour) ? '<span' . $user_colour . '>' . $user_online_link . '</span>' : $user_online_link;
3942 $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
3946 $prev_user_id = $row['user_id'];
3948 else
3950 // Skip multiple sessions for one user
3951 if ($row['session_ip'] != $prev_session_ip)
3953 $guests_online++;
3957 $prev_session_ip = $row['session_ip'];
3959 $db->sql_freeresult($result);
3961 if (!$online_userlist)
3963 $online_userlist = $user->lang['NO_ONLINE_USERS'];
3966 if (empty($_REQUEST['f']))
3968 $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
3970 else
3972 $l_online = ($guests_online == 1) ? $user->lang['BROWSING_FORUM_GUEST'] : $user->lang['BROWSING_FORUM_GUESTS'];
3973 $online_userlist = sprintf($l_online, $online_userlist, $guests_online);
3976 $total_online_users = $logged_visible_online + $logged_hidden_online + $guests_online;
3978 if ($total_online_users > $config['record_online_users'])
3980 set_config('record_online_users', $total_online_users, true);
3981 set_config('record_online_date', time(), true);
3984 // Build online listing
3985 $vars_online = array(
3986 'ONLINE' => array('total_online_users', 'l_t_user_s'),
3987 'REG' => array('logged_visible_online', 'l_r_user_s'),
3988 'HIDDEN' => array('logged_hidden_online', 'l_h_user_s'),
3989 'GUEST' => array('guests_online', 'l_g_user_s')
3992 foreach ($vars_online as $l_prefix => $var_ary)
3994 switch (${$var_ary[0]})
3996 case 0:
3997 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL'];
3998 break;
4000 case 1:
4001 ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL'];
4002 break;
4004 default:
4005 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL'];
4006 break;
4009 unset($vars_online);
4011 $l_online_users = sprintf($l_t_user_s, $total_online_users);
4012 $l_online_users .= sprintf($l_r_user_s, $logged_visible_online);
4013 $l_online_users .= sprintf($l_h_user_s, $logged_hidden_online);
4014 $l_online_users .= sprintf($l_g_user_s, $guests_online);
4016 $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date']));
4018 $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
4019 $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
4021 else
4023 $l_online_time = '';
4026 $l_privmsgs_text = $l_privmsgs_text_unread = '';
4027 $s_privmsg_new = false;
4029 // Obtain number of new private messages if user is logged in
4030 if (isset($user->data['is_registered']) && $user->data['is_registered'])
4032 if ($user->data['user_new_privmsg'])
4034 $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
4035 $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
4037 if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
4039 $sql = 'UPDATE ' . USERS_TABLE . '
4040 SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
4041 WHERE user_id = ' . $user->data['user_id'];
4042 $db->sql_query($sql);
4044 $s_privmsg_new = true;
4046 else
4048 $s_privmsg_new = false;
4051 else
4053 $l_privmsgs_text = $user->lang['NO_NEW_PM'];
4054 $s_privmsg_new = false;
4057 $l_privmsgs_text_unread = '';
4059 if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
4061 $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
4062 $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
4066 // Which timezone?
4067 $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
4069 // The following assigns all _common_ variables that may be used at any point in a template.
4070 $template->assign_vars(array(
4071 'SITENAME' => $config['sitename'],
4072 'SITE_DESCRIPTION' => $config['site_desc'],
4073 'PAGE_TITLE' => $page_title,
4074 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
4075 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
4076 'LAST_VISIT_YOU' => $s_last_visit,
4077 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
4078 'TOTAL_USERS_ONLINE' => $l_online_users,
4079 'LOGGED_IN_USER_LIST' => $online_userlist,
4080 'RECORD_USERS' => $l_online_record,
4081 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
4082 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
4084 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
4085 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
4087 'SID' => $SID,
4088 '_SID' => $_SID,
4089 'SESSION_ID' => $user->session_id,
4090 'ROOT_PATH' => $phpbb_root_path,
4092 'L_LOGIN_LOGOUT' => $l_login_logout,
4093 'L_INDEX' => $user->lang['FORUM_INDEX'],
4094 'L_ONLINE_EXPLAIN' => $l_online_time,
4096 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
4097 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
4098 'UA_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox', false),
4099 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup'),
4100 'UA_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup', false),
4101 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
4102 'U_MEMBERSLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
4103 'U_VIEWONLINE' => append_sid("{$phpbb_root_path}viewonline.$phpEx"),
4104 'U_LOGIN_LOGOUT' => $u_login_logout,
4105 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
4106 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
4107 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
4108 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
4109 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
4110 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
4111 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
4112 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
4113 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
4114 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
4115 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
4116 'U_TEAM' => append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
4117 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
4119 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
4120 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
4121 'S_REGISTERED_USER' => $user->data['is_registered'],
4122 'S_IS_BOT' => $user->data['is_bot'],
4123 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
4124 'S_USER_LANG' => $user->lang['USER_LANG'],
4125 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
4126 'S_USERNAME' => $user->data['username'],
4127 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
4128 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
4129 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
4130 'S_CONTENT_ENCODING' => 'UTF-8',
4131 'S_TIMEZONE' => ($user->data['user_dst'] || ($user->data['user_id'] == ANONYMOUS && $config['board_dst'])) ? sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], $user->lang['tz']['dst']) : sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], ''),
4132 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
4133 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
4134 'S_DISPLAY_PM' => ($config['allow_privmsg'] && $user->data['is_registered'] && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
4135 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
4136 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
4138 'T_THEME_PATH' => "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme',
4139 'T_TEMPLATE_PATH' => "{$phpbb_root_path}styles/" . $user->theme['template_path'] . '/template',
4140 'T_IMAGESET_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset',
4141 'T_IMAGESET_LANG_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->data['user_lang'],
4142 'T_IMAGES_PATH' => "{$phpbb_root_path}images/",
4143 'T_SMILIES_PATH' => "{$phpbb_root_path}{$config['smilies_path']}/",
4144 'T_AVATAR_PATH' => "{$phpbb_root_path}{$config['avatar_path']}/",
4145 'T_AVATAR_GALLERY_PATH' => "{$phpbb_root_path}{$config['avatar_gallery_path']}/",
4146 'T_ICONS_PATH' => "{$phpbb_root_path}{$config['icons_path']}/",
4147 'T_RANKS_PATH' => "{$phpbb_root_path}{$config['ranks_path']}/",
4148 'T_UPLOAD_PATH' => "{$phpbb_root_path}{$config['upload_path']}/",
4149 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : "{$phpbb_root_path}style.$phpEx?sid=$user->session_id&amp;id=" . $user->theme['style_id'] . '&amp;lang=' . $user->data['user_lang'],
4150 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
4152 'SITE_LOGO_IMG' => $user->img('site_logo'))
4155 // Once used, we do not want to have the whole theme data twice in memory...
4156 if ($user->theme['theme_storedb'])
4158 // Parse Theme Data
4159 $replace = array(
4160 '{T_THEME_PATH}' => "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme',
4161 '{T_TEMPLATE_PATH}' => "{$phpbb_root_path}styles/" . $user->theme['template_path'] . '/template',
4162 '{T_IMAGESET_PATH}' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset',
4163 '{T_IMAGESET_LANG_PATH}' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->data['user_lang'],
4164 '{T_STYLESHEET_NAME}' => $user->theme['theme_name'],
4165 '{S_USER_LANG}' => $user->data['user_lang']
4168 $user->theme['theme_data'] = str_replace(array_keys($replace), array_values($replace), $user->theme['theme_data']);
4170 $matches = array();
4171 if (strpos($user->theme['theme_data'], '{IMG_') !== false)
4173 preg_match_all('#\{IMG_([A-Za-z0-9_]*?)_(WIDTH|HEIGHT|SRC)\}#', $user->theme['theme_data'], $matches);
4175 $imgs = $find = $replace = array();
4176 if (isset($matches[0]) && sizeof($matches[0]))
4178 foreach ($matches[1] as $i => $img)
4180 $img = strtolower($img);
4181 if (!isset($img_array[$img]))
4183 continue;
4186 if (!isset($imgs[$img]))
4188 $img_data = &$img_array[$img];
4189 $imgsrc = ($img_data['image_lang'] ? $img_data['image_lang'] . '/' : '') . $img_data['image_filename'];
4190 $imgs[$img] = array(
4191 'src' => $phpbb_root_path . 'styles/' . $user->theme['imageset_path'] . '/imageset/' . $imgsrc,
4192 'width' => $img_data['image_width'],
4193 'height' => $img_data['image_height'],
4197 switch ($matches[2][$i])
4199 case 'SRC':
4200 $replace[] = $imgs[$img]['src'];
4201 break;
4203 case 'WIDTH':
4204 $replace[] = $imgs[$img]['width'];
4205 break;
4207 case 'HEIGHT':
4208 $replace[] = $imgs[$img]['height'];
4209 break;
4211 default:
4212 continue;
4214 $find[] = $matches[0][$i];
4217 if (sizeof($find))
4219 $user->theme['theme_data'] = str_replace($find, $replace, $user->theme['theme_data']);
4224 $template->assign_var('T_THEME_DATA', $user->theme['theme_data']);
4225 $user->theme['theme_data'] = '';
4228 // application/xhtml+xml not used because of IE
4229 header('Content-type: text/html; charset=UTF-8');
4231 header('Cache-Control: private, no-cache="set-cookie"');
4232 header('Expires: 0');
4233 header('Pragma: no-cache');
4235 return;
4239 * Generate page footer
4241 function page_footer($run_cron = true)
4243 global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
4245 // Output page creation time
4246 if (defined('DEBUG'))
4248 $mtime = explode(' ', microtime());
4249 $totaltime = $mtime[0] + $mtime[1] - $starttime;
4251 if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
4253 $db->sql_report('display');
4256 $debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress']) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
4258 if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
4260 if (function_exists('memory_get_usage'))
4262 if ($memory_usage = memory_get_usage())
4264 global $base_memory_usage;
4265 $memory_usage -= $base_memory_usage;
4266 $memory_usage = ($memory_usage >= 1048576) ? round((round($memory_usage / 1048576 * 100) / 100), 2) . ' ' . $user->lang['MB'] : (($memory_usage >= 1024) ? round((round($memory_usage / 1024 * 100) / 100), 2) . ' ' . $user->lang['KB'] : $memory_usage . ' ' . $user->lang['BYTES']);
4268 $debug_output .= ' | Memory Usage: ' . $memory_usage;
4272 $debug_output .= ' | <a href="' . build_url() . '&amp;explain=1">Explain</a>';
4276 $template->assign_vars(array(
4277 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
4278 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
4280 'U_ACP' => ($auth->acl_get('a_') && $user->data['is_registered']) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", '', true, $user->session_id) : '')
4283 // Call cron-type script
4284 if (!defined('IN_CRON') && $run_cron)
4286 $cron_type = '';
4288 if (time() - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
4290 // Process email queue
4291 $cron_type = 'queue';
4293 else if (method_exists($cache, 'tidy') && time() - $config['cache_gc'] > $config['cache_last_gc'])
4295 // Tidy the cache
4296 $cron_type = 'tidy_cache';
4298 else if (time() - $config['warnings_gc'] > $config['warnings_last_gc'])
4300 $cron_type = 'tidy_warnings';
4302 else if (time() - $config['database_gc'] > $config['database_last_gc'])
4304 // Tidy the database
4305 $cron_type = 'tidy_database';
4307 else if (time() - $config['search_gc'] > $config['search_last_gc'])
4309 // Tidy the search
4310 $cron_type = 'tidy_search';
4312 else if (time() - $config['session_gc'] > $config['session_last_gc'])
4314 $cron_type = 'tidy_sessions';
4317 if ($cron_type)
4319 $template->assign_var('RUN_CRON_TASK', '<img src="' . append_sid($phpbb_root_path . 'cron.' . $phpEx, 'cron_type=' . $cron_type) . '" width="1" height="1" alt="cron" />');
4323 $template->display('body');
4325 garbage_collection();
4327 exit;
4331 * Closing the cache object and the database
4332 * Cool function name, eh? We might want to add operations to it later
4334 function garbage_collection()
4336 global $cache, $db;
4338 // Unload cache, must be done before the DB connection if closed
4339 if (!empty($cache))
4341 $cache->unload();
4344 // Close our DB connection.
4345 if (!empty($db))
4347 $db->sql_close();
4352 * @package phpBB3
4354 class bitfield
4356 var $data;
4358 function bitfield($bitfield = '')
4360 $this->data = base64_decode($bitfield);
4365 function get($n)
4367 // Get the ($n / 8)th char
4368 $byte = $n >> 3;
4370 if (strlen($this->data) >= $byte + 1)
4372 $c = $this->data[$byte];
4374 // Lookup the ($n % 8)th bit of the byte
4375 $bit = 7 - ($n & 7);
4376 return (bool) (ord($c) & (1 << $bit));
4378 else
4380 return false;
4384 function set($n)
4386 $byte = $n >> 3;
4387 $bit = 7 - ($n & 7);
4389 if (strlen($this->data) >= $byte + 1)
4391 $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
4393 else
4395 $this->data .= str_repeat("\0", $byte - strlen($this->data));
4396 $this->data .= chr(1 << $bit);
4400 function clear($n)
4402 $byte = $n >> 3;
4404 if (strlen($this->data) >= $byte + 1)
4406 $bit = 7 - ($n & 7);
4407 $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
4411 function get_blob()
4413 return $this->data;
4416 function get_base64()
4418 return base64_encode($this->data);
4421 function get_bin()
4423 $bin = '';
4424 $len = strlen($this->data);
4426 for ($i = 0; $i < $len; ++$i)
4428 $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
4431 return $bin;
4434 function get_all_set()
4436 return array_keys(array_filter(str_split($this->get_bin())));
4439 function merge($bitfield)
4441 $this->data = $this->data | $bitfield->get_blob();