add some properties
[phpbb.git] / phpBB / includes / functions.php
blobbdd175e9dab10fa98f33b91d08a7928c9ce5ff07
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 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 // Common global functions
21 /**
22 * Wrapper function of phpbb_request::variable which exists for backwards compatability.
23 * See {@link phpbb_request::variable phpbb_request::variable} for documentation of this function's use.
25 * @param string|array $var_name The form variable's name from which data shall be retrieved.
26 * If the value is an array this may be an array of indizes which will give
27 * direct access to a value at any depth. E.g. if the value of "var" is array(1 => "a")
28 * then specifying array("var", 1) as the name will return "a".
29 * @param mixed $default A default value that is returned if the variable was not set.
30 * This function will always return a value of the same type as the default.
31 * @param bool $multibyte If $default is a string this paramater has to be true if the variable may contain any UTF-8 characters
32 * Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks
33 * @param bool $cookie This param is mapped to phpbb_request::COOKIE as the last param for phpbb_request::variable for backwards compatability reasons.
35 * @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the
36 * the same as that of $default. If the variable is not set $default is returned.
38 function request_var($var_name, $default, $multibyte = false, $cookie = false)
40 return phpbb_request::variable($var_name, $default, $multibyte, ($cookie) ? phpbb_request::COOKIE : phpbb_request::REQUEST);
43 /**
44 * Set config value.
45 * Creates missing config entry if update did not succeed and phpbb::$config for this entry empty.
47 * @param string $config_name The configuration keys name
48 * @param string $config_value The configuration value
49 * @param bool $is_dynamic True if the configuration entry is not cached
51 function set_config($config_name, $config_value, $is_dynamic = false)
53 $sql = 'UPDATE ' . CONFIG_TABLE . "
54 SET config_value = '" . phpbb::$db->sql_escape($config_value) . "'
55 WHERE config_name = '" . phpbb::$db->sql_escape($config_name) . "'";
56 phpbb::$db->sql_query($sql);
58 if (!phpbb::$db->sql_affectedrows() && !isset(phpbb::$config[$config_name]))
60 $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', array(
61 'config_name' => (string) $config_name,
62 'config_value' => (string) $config_value,
63 'is_dynamic' => (int) $is_dynamic,
64 ));
65 phpbb::$db->sql_query($sql);
68 phpbb::$config[$config_name] = $config_value;
70 if (!$is_dynamic)
72 phpbb::$acm->destroy('#config');
76 /**
77 * Return formatted string for filesizes
79 function get_formatted_filesize($bytes, $add_size_lang = true)
81 if ($bytes >= pow(2, 20))
83 return ($add_size_lang) ? round($bytes / 1024 / 1024, 2) . ' ' . phpbb::$user->lang['MIB'] : round($bytes / 1024 / 1024, 2);
86 if ($bytes >= pow(2, 10))
88 return ($add_size_lang) ? round($bytes / 1024, 2) . ' ' . phpbb::$user->lang['KIB'] : round($bytes / 1024, 2);
91 return ($add_size_lang) ? ($bytes) . ' ' . phpbb::$user->lang['BYTES'] : ($bytes);
94 /**
95 * Determine whether we are approaching the maximum execution time. Should be called once
96 * at the beginning of the script in which it's used.
97 * @return bool Either true if the maximum execution time is nearly reached, or false
98 * if some time is still left.
100 function still_on_time($extra_time = 15)
102 static $max_execution_time, $start_time;
104 $time = explode(' ', microtime());
105 $current_time = $time[0] + $time[1];
107 if (empty($max_execution_time))
109 $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
111 // If zero, then set to something higher to not let the user catch the ten seconds barrier.
112 if ($max_execution_time === 0)
114 $max_execution_time = 50 + $extra_time;
117 $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
119 // For debugging purposes
120 // $max_execution_time = 10;
122 global $starttime;
123 $start_time = (empty($starttime)) ? $current_time : $starttime;
126 return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
131 * Add a secret hash for use in links/GET requests
132 * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
133 * @return string the hash
136 @todo should use our hashing instead of a "custom" one
138 function generate_link_hash($link_name)
140 if (!isset(phpbb::$user->data["hash_$link_name"]))
142 phpbb::$user->data["hash_$link_name"] = substr(sha1(phpbb::$user->data['user_form_salt'] . $link_name), 0, 8);
145 return phpbb::$user->data["hash_$link_name"];
150 * checks a link hash - for GET requests
151 * @param string $token the submitted token
152 * @param string $link_name The name of the link
153 * @return boolean true if all is fine
156 function check_link_hash($token, $link_name)
158 return $token === generate_link_hash($link_name);
161 // functions used for building option fields
164 * Pick a language, any language ...
166 function language_select($default = '')
168 $sql = 'SELECT lang_iso, lang_local_name
169 FROM ' . LANG_TABLE . '
170 ORDER BY lang_english_name';
171 $result = phpbb::$db->sql_query($sql);
173 $lang_options = '';
174 while ($row = phpbb::$db->sql_fetchrow($result))
176 $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
177 $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
179 phpbb::$db->sql_freeresult($result);
181 return $lang_options;
185 * Pick a template/theme combo,
187 function style_select($default = '', $all = false)
189 $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
190 $sql = 'SELECT style_id, style_name
191 FROM ' . STYLES_TABLE . "
192 $sql_where
193 ORDER BY style_name";
194 $result = phpbb::$db->sql_query($sql);
196 $style_options = '';
197 while ($row = phpbb::$db->sql_fetchrow($result))
199 $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
200 $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
202 phpbb::$db->sql_freeresult($result);
204 return $style_options;
208 * Pick a timezone
210 function tz_select($default = '', $truncate = false)
212 $tz_select = '';
213 foreach (phpbb::$user->lang['tz_zones'] as $offset => $zone)
215 if ($truncate)
217 $zone_trunc = truncate_string($zone, 50, 255, false, '...');
219 else
221 $zone_trunc = $zone;
224 if (is_numeric($offset))
226 $selected = ($offset == $default) ? ' selected="selected"' : '';
227 $tz_select .= '<option title="'.$zone.'" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
231 return $tz_select;
234 // Functions handling topic/post tracking/marking
237 * Marks a topic/forum as read
238 * Marks a topic as posted to
240 * @param int $user_id can only be used with $mode == 'post'
242 function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
244 if ($mode == 'all')
246 if ($forum_id === false || !sizeof($forum_id))
248 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
250 // Mark all forums read (index page)
251 phpbb::$db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . ' WHERE user_id = ' . phpbb::$user->data['user_id']);
252 phpbb::$db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . ' WHERE user_id = ' . phpbb::$user->data['user_id']);
253 phpbb::$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . ' WHERE user_id = ' . phpbb::$user->data['user_id']);
255 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
257 $tracking_topics = phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE);
258 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
260 unset($tracking_topics['tf']);
261 unset($tracking_topics['t']);
262 unset($tracking_topics['f']);
263 $tracking_topics['l'] = base_convert(time() - phpbb::$config['board_startdate'], 10, 36);
265 phpbb::$user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
266 phpbb_request::overwrite(phpbb::$config['cookie_name'] . '_track', tracking_serialize($tracking_topics), phpbb_request::COOKIE);
268 unset($tracking_topics);
270 if (phpbb::$user->data['is_registered'])
272 phpbb::$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . ' WHERE user_id = ' . phpbb::$user->data['user_id']);
277 return;
279 else if ($mode == 'topics')
281 // Mark all topics in forums read
282 if (!is_array($forum_id))
284 $forum_id = array($forum_id);
287 // Add 0 to forums array to mark global announcements correctly
288 $forum_id[] = 0;
290 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
292 $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . '
293 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
294 AND ' . phpbb::$db->sql_in_set('forum_id', $forum_id);
295 phpbb::$db->sql_query($sql);
297 $sql = 'SELECT forum_id
298 FROM ' . FORUMS_TRACK_TABLE . '
299 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
300 AND ' . phpbb::$db->sql_in_set('forum_id', $forum_id);
301 $result = phpbb::$db->sql_query($sql);
303 $sql_update = array();
304 while ($row = phpbb::$db->sql_fetchrow($result))
306 $sql_update[] = $row['forum_id'];
308 phpbb::$db->sql_freeresult($result);
310 if (sizeof($sql_update))
312 $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
313 SET mark_time = ' . time() . '
314 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
315 AND ' . phpbb::$db->sql_in_set('forum_id', $sql_update);
316 phpbb::$db->sql_query($sql);
319 if ($sql_insert = array_diff($forum_id, $sql_update))
321 $sql_ary = array();
322 foreach ($sql_insert as $f_id)
324 $sql_ary[] = array(
325 'user_id' => (int) phpbb::$user->data['user_id'],
326 'forum_id' => (int) $f_id,
327 'mark_time' => time()
331 phpbb::$db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
334 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
336 $tracking = phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE);
337 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
339 foreach ($forum_id as $f_id)
341 $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
343 if (isset($tracking['tf'][$f_id]))
345 unset($tracking['tf'][$f_id]);
348 foreach ($topic_ids36 as $topic_id36)
350 unset($tracking['t'][$topic_id36]);
353 if (isset($tracking['f'][$f_id]))
355 unset($tracking['f'][$f_id]);
358 $tracking['f'][$f_id] = base_convert(time() - phpbb::$config['board_startdate'], 10, 36);
361 if (isset($tracking['tf']) && empty($tracking['tf']))
363 unset($tracking['tf']);
366 phpbb::$user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
367 phpbb_request::overwrite(phpbb::$config['cookie_name'] . '_track', tracking_serialize($tracking), phpbb_request::COOKIE);
369 unset($tracking);
372 return;
374 else if ($mode == 'topic')
376 if ($topic_id === false || $forum_id === false)
378 return;
381 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
383 $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
384 SET mark_time = ' . (($post_time) ? $post_time : time()) . '
385 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
386 AND topic_id = ' . $topic_id;
387 phpbb::$db->sql_query($sql);
389 // insert row
390 if (!phpbb::$db->sql_affectedrows())
392 phpbb::$db->sql_return_on_error(true);
394 $sql_ary = array(
395 'user_id' => (int) phpbb::$user->data['user_id'],
396 'topic_id' => (int) $topic_id,
397 'forum_id' => (int) $forum_id,
398 'mark_time' => ($post_time) ? (int) $post_time : time(),
401 phpbb::$db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary));
403 phpbb::$db->sql_return_on_error(false);
406 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
408 $tracking = phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE);
409 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
411 $topic_id36 = base_convert($topic_id, 10, 36);
413 if (!isset($tracking['t'][$topic_id36]))
415 $tracking['tf'][$forum_id][$topic_id36] = true;
418 $post_time = ($post_time) ? $post_time : time();
419 $tracking['t'][$topic_id36] = base_convert($post_time - phpbb::$config['board_startdate'], 10, 36);
421 // If the cookie grows larger than 10000 characters we will remove the smallest value
422 // This can result in old topics being unread - but most of the time it should be accurate...
423 if (strlen(phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE)) > 10000)
425 //echo 'Cookie grown too large' . print_r($tracking, true);
427 // We get the ten most minimum stored time offsets and its associated topic ids
428 $time_keys = array();
429 for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
431 $min_value = min($tracking['t']);
432 $m_tkey = array_search($min_value, $tracking['t']);
433 unset($tracking['t'][$m_tkey]);
435 $time_keys[$m_tkey] = $min_value;
438 // Now remove the topic ids from the array...
439 foreach ($tracking['tf'] as $f_id => $topic_id_ary)
441 foreach ($time_keys as $m_tkey => $min_value)
443 if (isset($topic_id_ary[$m_tkey]))
445 $tracking['f'][$f_id] = $min_value;
446 unset($tracking['tf'][$f_id][$m_tkey]);
451 if (phpbb::$user->data['is_registered'])
453 phpbb::$user->data['user_lastmark'] = intval(base_convert(max($time_keys) + phpbb::$config['board_startdate'], 36, 10));
454 phpbb::$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . phpbb::$user->data['user_lastmark'] . ' WHERE user_id = ' . phpbb::$user->data['user_id']);
456 else
458 $tracking['l'] = max($time_keys);
462 phpbb::$user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
463 phpbb_request::overwrite(phpbb::$config['cookie_name'] . '_track', tracking_serialize($tracking));
466 return;
468 else if ($mode == 'post')
470 if ($topic_id === false)
472 return;
475 $use_user_id = (!$user_id) ? phpbb::$user->data['user_id'] : $user_id;
477 if (phpbb::$config['load_db_track'] && $use_user_id != ANONYMOUS)
479 phpbb::$db->sql_return_on_error(true);
481 $sql_ary = array(
482 'user_id' => (int) $use_user_id,
483 'topic_id' => (int) $topic_id,
484 'topic_posted' => 1
487 phpbb::$db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary));
489 phpbb::$db->sql_return_on_error(false);
492 return;
497 * Get topic tracking info by using already fetched info
499 function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
501 $last_read = array();
503 if (!is_array($topic_ids))
505 $topic_ids = array($topic_ids);
508 foreach ($topic_ids as $topic_id)
510 if (!empty($rowset[$topic_id]['mark_time']))
512 $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
516 $topic_ids = array_diff($topic_ids, array_keys($last_read));
518 if (sizeof($topic_ids))
520 $mark_time = array();
522 // Get global announcement info
523 if ($global_announce_list && sizeof($global_announce_list))
525 if (!isset($forum_mark_time[0]))
527 $sql = 'SELECT mark_time
528 FROM ' . FORUMS_TRACK_TABLE . '
529 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
530 AND forum_id = 0';
531 $result = phpbb::$db->sql_query($sql);
532 $row = phpbb::$db->sql_fetchrow($result);
533 phpbb::$db->sql_freeresult($result);
535 if ($row)
537 $mark_time[0] = $row['mark_time'];
540 else
542 if ($forum_mark_time[0] !== false)
544 $mark_time[0] = $forum_mark_time[0];
549 if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
551 $mark_time[$forum_id] = $forum_mark_time[$forum_id];
554 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : phpbb::$user->data['user_lastmark'];
556 foreach ($topic_ids as $topic_id)
558 if ($global_announce_list && isset($global_announce_list[$topic_id]))
560 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
562 else
564 $last_read[$topic_id] = $user_lastmark;
569 return $last_read;
573 * Get topic tracking info from db (for cookie based tracking only this function is used)
575 function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
577 $last_read = array();
579 if (!is_array($topic_ids))
581 $topic_ids = array($topic_ids);
584 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
586 $sql = 'SELECT topic_id, mark_time
587 FROM ' . TOPICS_TRACK_TABLE . '
588 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
589 AND ' . phpbb::$db->sql_in_set('topic_id', $topic_ids);
590 $result = phpbb::$db->sql_query($sql);
592 while ($row = phpbb::$db->sql_fetchrow($result))
594 $last_read[$row['topic_id']] = $row['mark_time'];
596 phpbb::$db->sql_freeresult($result);
598 $topic_ids = array_diff($topic_ids, array_keys($last_read));
600 if (sizeof($topic_ids))
602 $sql = 'SELECT forum_id, mark_time
603 FROM ' . FORUMS_TRACK_TABLE . '
604 WHERE user_id = ' . phpbb::$user->data['user_id'] . '
605 AND forum_id ' .
606 (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
607 $result = phpbb::$db->sql_query($sql);
609 $mark_time = array();
610 while ($row = phpbb::$db->sql_fetchrow($result))
612 $mark_time[$row['forum_id']] = $row['mark_time'];
614 phpbb::$db->sql_freeresult($result);
616 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : phpbb::$user->data['user_lastmark'];
618 foreach ($topic_ids as $topic_id)
620 if ($global_announce_list && isset($global_announce_list[$topic_id]))
622 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
624 else
626 $last_read[$topic_id] = $user_lastmark;
631 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
633 global $tracking_topics;
635 if (!isset($tracking_topics) || !sizeof($tracking_topics))
637 $tracking_topics = phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE);
638 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
641 if (!phpbb::$user->data['is_registered'])
643 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + phpbb::$config['board_startdate'] : 0;
645 else
647 $user_lastmark = phpbb::$user->data['user_lastmark'];
650 foreach ($topic_ids as $topic_id)
652 $topic_id36 = base_convert($topic_id, 10, 36);
654 if (isset($tracking_topics['t'][$topic_id36]))
656 $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + phpbb::$config['board_startdate'];
660 $topic_ids = array_diff($topic_ids, array_keys($last_read));
662 if (sizeof($topic_ids))
664 $mark_time = array();
665 if ($global_announce_list && sizeof($global_announce_list))
667 if (isset($tracking_topics['f'][0]))
669 $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + phpbb::$config['board_startdate'];
673 if (isset($tracking_topics['f'][$forum_id]))
675 $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + phpbb::$config['board_startdate'];
678 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
680 foreach ($topic_ids as $topic_id)
682 if ($global_announce_list && isset($global_announce_list[$topic_id]))
684 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
686 else
688 $last_read[$topic_id] = $user_lastmark;
694 return $last_read;
698 * Check for read forums and update topic tracking info accordingly
700 * @param int $forum_id the forum id to check
701 * @param int $forum_last_post_time the forums last post time
702 * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
703 * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
705 * @return true if complete forum got marked read, else false.
707 function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
709 global $tracking_topics;
711 // Determine the users last forum mark time if not given.
712 if ($mark_time_forum === false)
714 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
716 $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : phpbb::$user->data['user_lastmark'];
718 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
720 $tracking_topics = phpbb_request::variable(phpbb::$config['cookie_name'] . '_track', '', false, phpbb_request::COOKIE);
721 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
723 if (!phpbb::$user->data['is_registered'])
725 phpbb::$user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + phpbb::$config['board_startdate']) : 0;
728 $mark_time_forum = (isset($tracking_topics['f'][$forum_id])) ? (int) (base_convert($tracking_topics['f'][$forum_id], 36, 10) + phpbb::$config['board_startdate']) : phpbb::$user->data['user_lastmark'];
732 // Check the forum for any left unread topics.
733 // If there are none, we mark the forum as read.
734 if (phpbb::$config['load_db_lastread'] && phpbb::$user->data['is_registered'])
736 if ($mark_time_forum >= $forum_last_post_time)
738 // We do not need to mark read, this happened before. Therefore setting this to true
739 $row = true;
741 else
743 $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
744 LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . phpbb::$user->data['user_id'] . ')
745 WHERE t.forum_id = ' . $forum_id . '
746 AND t.topic_last_post_time > ' . $mark_time_forum . '
747 AND t.topic_moved_id = 0
748 AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
749 GROUP BY t.forum_id';
750 $result = phpbb::$db->sql_query_limit($sql, 1);
751 $row = phpbb::$db->sql_fetchrow($result);
752 phpbb::$db->sql_freeresult($result);
755 else if (phpbb::$config['load_anon_lastread'] || phpbb::$user->data['is_registered'])
757 // Get information from cookie
758 $row = false;
760 if (!isset($tracking_topics['tf'][$forum_id]))
762 // We do not need to mark read, this happened before. Therefore setting this to true
763 $row = true;
765 else
767 $sql = 'SELECT topic_id
768 FROM ' . TOPICS_TABLE . '
769 WHERE forum_id = ' . $forum_id . '
770 AND topic_last_post_time > ' . $mark_time_forum . '
771 AND topic_moved_id = 0';
772 $result = phpbb::$db->sql_query($sql);
774 $check_forum = $tracking_topics['tf'][$forum_id];
775 $unread = false;
777 while ($row = phpbb::$db->sql_fetchrow($result))
779 if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
781 $unread = true;
782 break;
785 phpbb::$db->sql_freeresult($result);
787 $row = $unread;
790 else
792 $row = true;
795 if (!$row)
797 markread('topics', $forum_id);
798 return true;
801 return false;
805 * Transform an array into a serialized format
807 function tracking_serialize($input)
809 $out = '';
810 foreach ($input as $key => $value)
812 if (is_array($value))
814 $out .= $key . ':(' . tracking_serialize($value) . ');';
816 else
818 $out .= $key . ':' . $value . ';';
821 return $out;
825 * Transform a serialized array into an actual array
827 function tracking_unserialize($string, $max_depth = 3)
829 $n = strlen($string);
830 if ($n > 10010)
832 die('Invalid data supplied');
834 $data = $stack = array();
835 $key = '';
836 $mode = 0;
837 $level = &$data;
838 for ($i = 0; $i < $n; ++$i)
840 switch ($mode)
842 case 0:
843 switch ($string[$i])
845 case ':':
846 $level[$key] = 0;
847 $mode = 1;
848 break;
849 case ')':
850 unset($level);
851 $level = array_pop($stack);
852 $mode = 3;
853 break;
854 default:
855 $key .= $string[$i];
857 break;
859 case 1:
860 switch ($string[$i])
862 case '(':
863 if (sizeof($stack) >= $max_depth)
865 die('Invalid data supplied');
867 $stack[] = &$level;
868 $level[$key] = array();
869 $level = &$level[$key];
870 $key = '';
871 $mode = 0;
872 break;
873 default:
874 $level[$key] = $string[$i];
875 $mode = 2;
876 break;
878 break;
880 case 2:
881 switch ($string[$i])
883 case ')':
884 unset($level);
885 $level = array_pop($stack);
886 $mode = 3;
887 break;
888 case ';':
889 $key = '';
890 $mode = 0;
891 break;
892 default:
893 $level[$key] .= $string[$i];
894 break;
896 break;
898 case 3:
899 switch ($string[$i])
901 case ')':
902 unset($level);
903 $level = array_pop($stack);
904 break;
905 case ';':
906 $key = '';
907 $mode = 0;
908 break;
909 default:
910 die('Invalid data supplied');
911 break;
913 break;
917 if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
919 die('Invalid data supplied');
922 return $level;
925 // Pagination functions
928 * Pagination routine, generates page number sequence
929 * tpl_prefix is for using different pagination blocks at one page
931 function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
933 global $template;
935 // Make sure $per_page is a valid value
936 $per_page = ($per_page <= 0) ? 1 : $per_page;
938 $seperator = '<span class="page-sep">' . phpbb::$user->lang['COMMA_SEPARATOR'] . '</span>';
939 $total_pages = ceil($num_items / $per_page);
941 if ($total_pages == 1 || !$num_items)
943 return false;
946 $on_page = floor($start_item / $per_page) + 1;
947 $url_delim = (strpos($base_url, '?') === false) ? '?' : '&amp;';
949 $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
951 if ($total_pages > 5)
953 $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
954 $end_cnt = max(min($total_pages, $on_page + 4), 6);
956 $page_string .= ($start_cnt > 1) ? ' ... ' : $seperator;
958 for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
960 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
961 if ($i < $end_cnt - 1)
963 $page_string .= $seperator;
967 $page_string .= ($end_cnt < $total_pages) ? ' ... ' : $seperator;
969 else
971 $page_string .= $seperator;
973 for ($i = 2; $i < $total_pages; $i++)
975 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
976 if ($i < $total_pages)
978 $page_string .= $seperator;
983 $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>';
985 if ($add_prevnext_text)
987 if ($on_page != 1)
989 $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . phpbb::$user->lang['PREVIOUS'] . '</a>&nbsp;&nbsp;' . $page_string;
992 if ($on_page != $total_pages)
994 $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . phpbb::$user->lang['NEXT'] . '</a>';
998 $template->assign_vars(array(
999 $tpl_prefix . 'BASE_URL' => $base_url,
1000 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
1001 $tpl_prefix . 'PER_PAGE' => $per_page,
1003 $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
1004 $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
1005 $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
1008 return $page_string;
1012 * Return current page (pagination)
1014 function on_page($num_items, $per_page, $start)
1016 global $template;
1018 // Make sure $per_page is a valid value
1019 $per_page = ($per_page <= 0) ? 1 : $per_page;
1021 $on_page = floor($start / $per_page) + 1;
1023 $template->assign_vars(array(
1024 'ON_PAGE' => $on_page)
1027 return phpbb::$user->lang('PAGE_OF', $on_page, max(ceil($num_items / $per_page), 1));
1031 //Form validation
1036 * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
1037 * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
1039 function add_form_key($form_name)
1041 global $template;
1043 $now = time();
1044 $token_sid = (phpbb::$user->data['user_id'] == ANONYMOUS && !empty(phpbb::$config['form_token_sid_guests'])) ? phpbb::$user->session_id : '';
1045 $token = sha1($now . phpbb::$user->data['user_form_salt'] . $form_name . $token_sid);
1047 $s_fields = build_hidden_fields(array(
1048 'creation_time' => $now,
1049 'form_token' => $token,
1052 $template->assign_vars(array(
1053 'S_FORM_TOKEN' => $s_fields,
1058 * Check the form key. Required for all altering actions not secured by confirm_box
1059 * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
1060 * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
1061 * @param string $return_page The address for the return link
1062 * @param bool $trigger If true, the function will triger an error when encountering an invalid form
1064 function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
1066 if ($timespan === false)
1068 // we enforce a minimum value of half a minute here.
1069 $timespan = (phpbb::$config['form_token_lifetime'] == -1) ? -1 : max(30, phpbb::$config['form_token_lifetime']);
1072 if (phpbb_request::is_set_post('creation_time') && phpbb_request::is_set_post('form_token'))
1074 $creation_time = abs(request_var('creation_time', 0));
1075 $token = request_var('form_token', '');
1077 $diff = time() - $creation_time;
1079 // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
1080 if ($diff && ($diff <= $timespan || $timespan === -1))
1082 $token_sid = (phpbb::$user->data['user_id'] == ANONYMOUS && !empty(phpbb::$config['form_token_sid_guests'])) ? phpbb::$user->session_id : '';
1083 $key = sha1($creation_time . phpbb::$user->data['user_form_salt'] . $form_name . $token_sid);
1085 if ($key === $token)
1087 return true;
1092 if ($trigger)
1094 trigger_error(phpbb::$user->lang['FORM_INVALID'] . $return_page);
1097 return false;
1100 // Message/Login boxes
1103 * Build Confirm box
1104 * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
1105 * @param string $title Title/Message used for confirm box.
1106 * message text is _CONFIRM appended to title.
1107 * If title cannot be found in user->lang a default one is displayed
1108 * If title_CONFIRM cannot be found in user->lang the text given is used.
1109 * @param string $hidden Hidden variables
1110 * @param string $html_body Template used for confirm box
1111 * @param string $u_action Custom form action
1113 function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
1115 global $template;
1117 if (phpbb_request::is_set_post('cancel'))
1119 return false;
1122 $confirm = false;
1123 if (phpbb_request::is_set_post('confirm'))
1125 // language frontier
1126 if (request_var('confirm', '') === phpbb::$user->lang['YES'])
1128 $confirm = true;
1132 if ($check && $confirm)
1134 $user_id = request_var('user_id', 0);
1135 $session_id = request_var('sess', '');
1136 $confirm_key = request_var('confirm_key', '');
1138 if ($user_id != phpbb::$user->data['user_id'] || $session_id != phpbb::$user->session_id || !$confirm_key || !phpbb::$user->data['user_last_confirm_key'] || $confirm_key != phpbb::$user->data['user_last_confirm_key'])
1140 return false;
1143 // Reset user_last_confirm_key
1144 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
1145 WHERE user_id = " . phpbb::$user->data['user_id'];
1146 phpbb::$db->sql_query($sql);
1148 return true;
1150 else if ($check)
1152 return false;
1155 $s_hidden_fields = build_hidden_fields(array(
1156 'user_id' => phpbb::$user->data['user_id'],
1157 'sess' => phpbb::$user->session_id,
1158 'sid' => phpbb::$user->session_id,
1161 // generate activation key
1162 $confirm_key = gen_rand_string(10);
1164 page_header((!isset(phpbb::$user->lang[$title])) ? phpbb::$user->lang['CONFIRM'] : phpbb::$user->lang[$title]);
1166 $template->set_filenames(array(
1167 'body' => $html_body)
1170 // If activation key already exist, we better do not re-use the key (something very strange is going on...)
1171 if (request_var('confirm_key', ''))
1173 // This should not occur, therefore we cancel the operation to safe the user
1174 return false;
1177 // re-add sid / transform & to &amp; for user->page (user->page is always using &)
1178 $use_page = ($u_action) ? PHPBB_ROOT_PATH . $u_action : PHPBB_ROOT_PATH . str_replace('&', '&amp;', phpbb::$user->page['page']);
1179 $u_action = reapply_sid($use_page);
1180 $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&amp;') . 'confirm_key=' . $confirm_key;
1182 $template->assign_vars(array(
1183 'MESSAGE_TITLE' => (!isset(phpbb::$user->lang[$title])) ? phpbb::$user->lang['CONFIRM'] : phpbb::$user->lang[$title],
1184 'MESSAGE_TEXT' => (!isset(phpbb::$user->lang[$title . '_CONFIRM'])) ? $title : phpbb::$user->lang[$title . '_CONFIRM'],
1186 'YES_VALUE' => phpbb::$user->lang['YES'],
1187 'S_CONFIRM_ACTION' => $u_action,
1188 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
1191 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . phpbb::$db->sql_escape($confirm_key) . "'
1192 WHERE user_id = " . phpbb::$user->data['user_id'];
1193 phpbb::$db->sql_query($sql);
1195 page_footer();
1199 * Generate login box or verify password
1201 function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
1203 $err = '';
1205 // Make sure user->setup() has been called
1206 if (empty(phpbb::$user->lang))
1208 phpbb::$user->setup();
1211 // Print out error if user tries to authenticate as an administrator without having the privileges...
1212 if ($admin && !phpbb::$acl->acl_get('a_'))
1214 // Not authd
1215 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
1216 if (phpbb::$user->is_registered)
1218 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
1221 $admin = false;
1224 if (phpbb_request::is_set_post('login'))
1226 // Get credential
1227 if ($admin)
1229 $credential = request_var('credential', '');
1231 if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
1233 if (phpbb::$user->is_registered)
1235 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
1238 trigger_error('NO_AUTH_ADMIN');
1241 $password = request_var('password_' . $credential, '', true);
1243 else
1245 $password = request_var('password', '', true);
1248 $username = request_var('username', '', true);
1249 $autologin = phpbb_request::variable('autologin', false, false, phpbb_request::POST);
1250 $viewonline = (phpbb_request::variable('viewonline', false, false, phpbb_request::POST)) ? 0 : 1;
1251 $admin = ($admin) ? 1 : 0;
1252 $viewonline = ($admin) ? phpbb::$user->data['session_viewonline'] : $viewonline;
1254 // Check if the supplied username is equal to the one stored within the database if re-authenticating
1255 if ($admin && utf8_clean_string($username) != utf8_clean_string(phpbb::$user->data['username']))
1257 // We log the attempt to use a different username...
1258 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
1259 trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
1262 // If authentication is successful we redirect user to previous page
1263 $result = phpbb::$user->login($username, $password, $autologin, $viewonline, $admin);
1265 // If admin authentication and login, we will log if it was a success or not...
1266 // We also break the operation on the first non-success login - it could be argued that the user already knows
1267 if ($admin)
1269 if ($result['status'] == LOGIN_SUCCESS)
1271 add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
1273 else
1275 // Only log the failed attempt if a real user tried to.
1276 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
1277 if (phpbb::$user->is_registered)
1279 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
1284 // The result parameter is always an array, holding the relevant information...
1285 if ($result['status'] == LOGIN_SUCCESS)
1287 $redirect = request_var('redirect', phpbb::$user->page['page']);
1289 $message = ($l_success) ? $l_success : phpbb::$user->lang['LOGIN_REDIRECT'];
1290 $l_redirect = ($admin) ? phpbb::$user->lang['PROCEED_TO_ACP'] : (($redirect === PHPBB_ROOT_PATH . 'index.' . PHP_EXT || $redirect === 'index.' . PHP_EXT) ? phpbb::$user->lang['RETURN_INDEX'] : phpbb::$user->lang['RETURN_PAGE']);
1292 // append/replace SID (may change during the session for AOL users)
1293 $redirect = phpbb::$url->reapply_sid($redirect);
1295 // Special case... the user is effectively banned, but we allow founders to login
1296 if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != phpbb::USER_FOUNDER)
1298 return;
1301 // $redirect = phpbb::$url->meta_refresh(3, $redirect);
1302 trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
1305 // Something failed, determine what...
1306 if ($result['status'] == LOGIN_BREAK)
1308 trigger_error($result['error_msg']);
1311 // Special cases... determine
1312 switch ($result['status'])
1314 case LOGIN_ERROR_ATTEMPTS:
1316 $captcha = phpbb_captcha_factory::get_instance(phpbb::$config['captcha_plugin']);
1317 $captcha->init(CONFIRM_LOGIN);
1318 $captcha->reset();
1320 $template->assign_vars(array(
1321 'S_CONFIRM_CODE' => true,
1322 'CONFIRM' => $captcha->get_template(''),
1325 $err = phpbb::$user->lang[$result['error_msg']];
1327 break;
1329 case LOGIN_ERROR_PASSWORD_CONVERT:
1330 $err = sprintf(
1331 phpbb::$user->lang[$result['error_msg']],
1332 (phpbb::$config['email_enable']) ? '<a href="' . append_sid('ucp', 'mode=sendpassword') . '">' : '',
1333 (phpbb::$config['email_enable']) ? '</a>' : '',
1334 (phpbb::$config['board_contact']) ? '<a href="mailto:' . utf8_htmlspecialchars(phpbb::$config['board_contact']) . '">' : '',
1335 (phpbb::$config['board_contact']) ? '</a>' : ''
1337 break;
1339 // Username, password, etc...
1340 default:
1341 $err = phpbb::$user->lang[$result['error_msg']];
1343 // Assign admin contact to some error messages
1344 if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
1346 $err = (!phpbb::$config['board_contact']) ? sprintf(phpbb::$user->lang[$result['error_msg']], '', '') : sprintf(phpbb::$user->lang[$result['error_msg']], '<a href="mailto:' . utf8_htmlspecialchars(phpbb::$config['board_contact']) . '">', '</a>');
1349 break;
1353 if (!$redirect)
1355 // We just use what the session code determined...
1356 // If we are not within the admin directory we use the page dir...
1357 $redirect = '';
1359 if (!$admin && !defined('ADMIN_START'))
1361 $redirect .= (phpbb::$user->page['page_dir']) ? phpbb::$user->page['page_dir'] . '/' : '';
1364 $redirect .= phpbb::$user->page['page_name'] . ((phpbb::$user->page['query_string']) ? '?' . utf8_htmlspecialchars(phpbb::$user->page['query_string']) : '');
1367 // Assign credential for username/password pair
1368 $credential = ($admin) ? md5(phpbb::$security->unique_id()) : false;
1370 $s_hidden_fields = array(
1371 'redirect' => $redirect,
1372 'sid' => phpbb::$user->session_id,
1375 if ($admin)
1377 $s_hidden_fields['credential'] = $credential;
1380 $s_hidden_fields = build_hidden_fields($s_hidden_fields);
1382 phpbb::$template->assign_vars(array(
1383 'LOGIN_ERROR' => $err,
1384 'LOGIN_EXPLAIN' => $l_explain,
1386 'U_SEND_PASSWORD' => (phpbb::$config['email_enable']) ? phpbb::$url->append_sid('ucp', 'mode=sendpassword') : '',
1387 'U_RESEND_ACTIVATION' => (phpbb::$config['require_activation'] != USER_ACTIVATION_NONE && phpbb::$config['email_enable']) ? phpbb::$url->append_sid('ucp', 'mode=resend_act') : '',
1388 'U_TERMS_USE' => phpbb::$url->append_sid('ucp', 'mode=terms'),
1389 'U_PRIVACY' => phpbb::$url->append_sid('ucp', 'mode=privacy'),
1391 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
1392 'S_LOGIN_ACTION' => (!$admin && !defined('ADMIN_START')) ? phpbb::$url->append_sid('ucp', 'mode=login') : phpbb::$url->append_sid(PHPBB_ADMIN_PATH . 'index.' . PHP_EXT, false, true, phpbb::$user->session_id),
1393 'S_HIDDEN_FIELDS' => $s_hidden_fields,
1395 'S_ADMIN_AUTH' => $admin,
1396 'S_ACP_LOGIN' => defined('ADMIN_START'),
1397 'USERNAME' => ($admin) ? phpbb::$user->data['username'] : '',
1399 'USERNAME_CREDENTIAL' => 'username',
1400 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
1403 phpbb::$template->set_filenames(array(
1404 'body' => 'login_body.html')
1407 page_header(phpbb::$user->lang['LOGIN'], false);
1408 make_jumpbox('viewforum');
1410 page_footer();
1414 * Generate forum login box
1416 function login_forum_box($forum_data)
1418 global $template;
1420 $password = request_var('password', '', true);
1422 $sql = 'SELECT forum_id
1423 FROM ' . FORUMS_ACCESS_TABLE . '
1424 WHERE forum_id = ' . $forum_data['forum_id'] . '
1425 AND user_id = ' . phpbb::$user->data['user_id'] . "
1426 AND session_id = '" . phpbb::$db->sql_escape(phpbb::$user->session_id) . "'";
1427 $result = phpbb::$db->sql_query($sql);
1428 $row = phpbb::$db->sql_fetchrow($result);
1429 phpbb::$db->sql_freeresult($result);
1431 if ($row)
1433 return true;
1436 if ($password)
1438 // Remove expired authorised sessions
1439 $sql = 'SELECT f.session_id
1440 FROM ' . FORUMS_ACCESS_TABLE . ' f
1441 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
1442 WHERE s.session_id IS NULL';
1443 $result = phpbb::$db->sql_query($sql);
1445 if ($row = phpbb::$db->sql_fetchrow($result))
1447 $sql_in = array();
1450 $sql_in[] = (string) $row['session_id'];
1452 while ($row = phpbb::$db->sql_fetchrow($result));
1454 // Remove expired sessions
1455 $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
1456 WHERE ' . phpbb::$db->sql_in_set('session_id', $sql_in);
1457 phpbb::$db->sql_query($sql);
1459 phpbb::$db->sql_freeresult($result);
1461 if (phpbb_check_hash($password, $forum_data['forum_password']))
1463 $sql_ary = array(
1464 'forum_id' => (int) $forum_data['forum_id'],
1465 'user_id' => (int) phpbb::$user->data['user_id'],
1466 'session_id' => (string) phpbb::$user->session_id,
1469 phpbb::$db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary));
1471 return true;
1474 $template->assign_var('LOGIN_ERROR', phpbb::$user->lang['WRONG_PASSWORD']);
1477 page_header(phpbb::$user->lang['LOGIN']);
1479 $template->assign_vars(array(
1480 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
1483 $template->set_filenames(array(
1484 'body' => 'login_forum.html')
1487 page_footer();
1490 // Little helpers
1493 * Little helper for the build_hidden_fields function
1495 function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
1497 $hidden_fields = '';
1499 if (!is_array($value))
1501 $value = ($stripslashes) ? stripslashes($value) : $value;
1502 $value = ($specialchar) ? utf8_htmlspecialchars($value) : $value;
1504 $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
1506 else
1508 foreach ($value as $_key => $_value)
1510 $_key = ($stripslashes) ? stripslashes($_key) : $_key;
1511 $_key = ($specialchar) ? utf8_htmlspecialchars($_key) : $_key;
1513 $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
1517 return $hidden_fields;
1521 * Build simple hidden fields from array
1523 * @param array $field_ary an array of values to build the hidden field from
1524 * @param bool $specialchar if true, keys and values get specialchared
1525 * @param bool $stripslashes if true, keys and values get stripslashed
1527 * @return string the hidden fields
1529 function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
1531 $s_hidden_fields = '';
1533 foreach ($field_ary as $name => $vars)
1535 $name = ($stripslashes) ? stripslashes($name) : $name;
1536 $name = ($specialchar) ? utf8_htmlspecialchars($name) : $name;
1538 $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
1541 return $s_hidden_fields;
1545 * Parse cfg file
1547 function parse_cfg_file($filename, $lines = false)
1549 $parsed_items = array();
1551 if ($lines === false)
1553 $lines = file($filename);
1556 foreach ($lines as $line)
1558 $line = trim($line);
1560 if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
1562 continue;
1565 // Determine first occurrence, since in values the equal sign is allowed
1566 $key = strtolower(trim(substr($line, 0, $delim_pos)));
1567 $value = trim(substr($line, $delim_pos + 1));
1569 if (in_array($value, array('off', 'false', '0')))
1571 $value = false;
1573 else if (in_array($value, array('on', 'true', '1')))
1575 $value = true;
1577 else if (!trim($value))
1579 $value = '';
1581 else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
1583 $value = substr($value, 1, sizeof($value)-2);
1586 $parsed_items[$key] = $value;
1589 return $parsed_items;
1593 * Add log event
1595 function add_log()
1597 $args = func_get_args();
1599 $mode = array_shift($args);
1600 $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
1601 $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
1602 $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
1603 $action = array_shift($args);
1604 $data = (!sizeof($args)) ? '' : serialize($args);
1606 $sql_ary = array(
1607 'user_id' => (empty(phpbb::$user->data)) ? ANONYMOUS : phpbb::$user->data['user_id'],
1608 'log_ip' => phpbb::$user->ip,
1609 'log_time' => time(),
1610 'log_operation' => $action,
1611 'log_data' => $data,
1614 switch ($mode)
1616 case 'admin':
1617 $sql_ary['log_type'] = LOG_ADMIN;
1618 break;
1620 case 'mod':
1621 $sql_ary += array(
1622 'log_type' => LOG_MOD,
1623 'forum_id' => $forum_id,
1624 'topic_id' => $topic_id
1626 break;
1628 case 'user':
1629 $sql_ary += array(
1630 'log_type' => LOG_USERS,
1631 'reportee_id' => $reportee_id
1633 break;
1635 case 'critical':
1636 $sql_ary['log_type'] = LOG_CRITICAL;
1637 break;
1639 default:
1640 return false;
1643 phpbb::$db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . phpbb::$db->sql_build_array('INSERT', $sql_ary));
1645 return phpbb::$db->sql_nextid();
1649 * Return a nicely formatted backtrace (parts from the php manual by diz at ysagoon dot com)
1651 function get_backtrace()
1653 $output = '<div style="font-family: monospace;">';
1654 $backtrace = debug_backtrace();
1655 $path = phpbb::$url->realpath(PHPBB_ROOT_PATH);
1657 foreach ($backtrace as $number => $trace)
1659 // We skip the first one, because it only shows this file/function
1660 if ($number == 0)
1662 continue;
1665 if (empty($trace['file']) && empty($trace['line']))
1667 continue;
1670 // Strip the current directory from path
1671 if (empty($trace['file']))
1673 $trace['file'] = '';
1675 else
1677 $trace['file'] = str_replace(array($path, '\\'), array('', '/'), $trace['file']);
1678 $trace['file'] = substr($trace['file'], 1);
1680 $args = array();
1682 // If include/require/include_once is not called, do not show arguments - they may contain sensible information
1683 if (!in_array($trace['function'], array('include', 'require', 'include_once')))
1685 unset($trace['args']);
1687 else
1689 // Path...
1690 if (!empty($trace['args'][0]))
1692 $argument = htmlspecialchars($trace['args'][0]);
1693 $argument = str_replace(array($path, '\\'), array('', '/'), $argument);
1694 $argument = substr($argument, 1);
1695 $args[] = "'{$argument}'";
1699 $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
1700 $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
1702 $output .= '<br />';
1703 $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
1704 $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
1706 $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '(' . ((sizeof($args)) ? implode(', ', $args) : '') . ')<br />';
1708 $output .= '</div>';
1709 return $output;
1713 * This function returns a regular expression pattern for commonly used expressions
1714 * Use with / as delimiter for email mode and # for url modes
1715 * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
1717 function get_preg_expression($mode)
1719 switch ($mode)
1721 case 'email':
1722 return '(?:[a-z0-9\'\.\-_\+\|]++|&amp;)+@[a-z0-9\-]+\.(?:[a-z0-9\-]+\.)*[a-z]+';
1723 break;
1725 case 'bbcode_htm':
1726 return array(
1727 '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
1728 '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
1729 '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
1730 '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
1731 '#<!\-\- .*? \-\->#s',
1732 '#<.*?>#s',
1734 break;
1736 // Whoa these look impressive!
1737 // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
1738 // can be found in the develop directory
1739 case 'ipv4':
1740 return '#^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$#';
1741 break;
1743 case 'ipv6':
1744 return '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){5}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:))$#i';
1745 break;
1747 case 'url':
1748 case 'url_inline':
1749 $inline = ($mode == 'url') ? ')' : '';
1750 $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
1751 // generated with regex generation file in the develop folder
1752 return "[a-z]$scheme*:/{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})*)?";
1753 break;
1755 case 'www_url':
1756 case 'www_url_inline':
1757 $inline = ($mode == 'www_url') ? ')' : '';
1758 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})*)?";
1759 break;
1761 case 'relative_url':
1762 case 'relative_url_inline':
1763 $inline = ($mode == 'relative_url') ? ')' : '';
1764 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})*)?";
1765 break;
1768 return '';
1772 * Returns the first block of the specified IPv6 address and as many additional
1773 * ones as specified in the length paramater.
1774 * If length is zero, then an empty string is returned.
1775 * If length is greater than 3 the complete IP will be returned
1777 function short_ipv6($ip, $length)
1779 if ($length < 1)
1781 return '';
1784 // extend IPv6 addresses
1785 $blocks = substr_count($ip, ':') + 1;
1786 if ($blocks < 9)
1788 $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
1790 if ($ip[0] == ':')
1792 $ip = '0000' . $ip;
1794 if ($length < 4)
1796 $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
1799 return $ip;
1803 * Wrapper for php's checkdnsrr function.
1805 * The windows failover is from the php manual
1806 * Please make sure to check the return value for === true and === false, since NULL could
1807 * be returned too.
1809 * @return true if entry found, false if not, NULL if this function is not supported by this environment
1811 function phpbb_checkdnsrr($host, $type = '')
1813 $type = (!$type) ? 'MX' : $type;
1815 if (DIRECTORY_SEPARATOR == '\\')
1817 if (!function_exists('exec'))
1819 return NULL;
1822 // @exec('nslookup -retry=1 -timout=1 -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
1823 @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host) . '.', $output);
1825 // If output is empty, the nslookup failed
1826 if (empty($output))
1828 return NULL;
1831 foreach ($output as $line)
1833 if (!trim($line))
1835 continue;
1838 // Valid records begin with host name:
1839 if (strpos($line, $host) === 0)
1841 return true;
1845 return false;
1847 else if (function_exists('checkdnsrr'))
1849 // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
1850 return (checkdnsrr($host . '.', $type)) ? true : false;
1853 return NULL;
1856 // Handler, header and footer
1859 * Error and message handler, call with trigger_error if reqd
1861 function msg_handler($errno, $msg_text, $errfile, $errline)
1863 global $msg_title, $msg_long_text;
1865 // Message handler is stripping text. In case we need it, we are able to define long text...
1866 if (isset($msg_long_text) && $msg_long_text && !$msg_text)
1868 $msg_text = $msg_long_text;
1871 // Store information for later use
1872 phpbb::$last_notice = array(
1873 'file' => $errfile,
1874 'line' => $errline,
1875 'message' => $msg_text,
1876 'php_error' => (!empty($php_errormsg)) ? $php_errormsg : '',
1877 'errno' => $errno,
1880 // Do not display notices if we suppress them via @
1881 if (error_reporting() == 0)
1883 return;
1886 switch ($errno)
1888 case E_NOTICE:
1889 case E_WARNING:
1890 case E_STRICT:
1892 // Check the error reporting level and return if the error level does not match
1893 // If DEBUG is defined the default level is E_ALL
1894 if (($errno & ((phpbb::$base_config['debug']) ? E_ALL | E_STRICT : error_reporting())) == 0)
1896 return;
1899 // if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
1900 // {
1901 // flush the content, else we get a white page if output buffering is on
1902 if ((int) @ini_get('output_buffering') === 1 || strtolower(@ini_get('output_buffering')) === 'on')
1904 @ob_flush();
1907 // Another quick fix for those having gzip compression enabled, but do not flush if the coder wants to catch "something". ;)
1908 if (!empty(phpbb::$config['gzip_compress']))
1910 if (@extension_loaded('zlib') && !headers_sent() && !ob_get_level())
1912 @ob_flush();
1916 // remove complete path to installation, with the risk of changing backslashes meant to be there
1917 if (phpbb::registered('url'))
1919 $errfile = str_replace(array(phpbb::$url->realpath(PHPBB_ROOT_PATH), '\\'), array('', '/'), $errfile);
1920 $msg_text = str_replace(array(phpbb::$url->realpath(PHPBB_ROOT_PATH), '\\'), array('', '/'), $msg_text);
1923 echo '<b>[phpBB Debug] PHP Notice</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
1924 // }
1926 return;
1928 break;
1930 case E_RECOVERABLE_ERROR:
1931 case E_USER_ERROR:
1933 if (phpbb::registered('user'))
1935 // Setup language
1936 if (empty(phpbb::$user->lang))
1938 phpbb::$user->setup();
1941 $msg_text = (!empty(phpbb::$user->lang[$msg_text])) ? phpbb::$user->lang[$msg_text] : $msg_text;
1942 $msg_title = (!isset($msg_title)) ? phpbb::$user->lang['GENERAL_ERROR'] : ((!empty(phpbb::$user->lang[$msg_title])) ? phpbb::$user->lang[$msg_title] : $msg_title);
1944 $l_return_index = phpbb::$user->lang('RETURN_INDEX', '<a href="' . PHPBB_ROOT_PATH . '">', '</a>');
1945 $l_notify = '';
1947 if (!empty(phpbb::$config['board_contact']))
1949 $l_notify = '<p>' . phpbb::$user->lang('NOTIFY_ADMIN_EMAIL', phpbb::$config['board_contact']) . '</p>';
1952 else
1954 $msg_title = 'General Error';
1955 $l_return_index = '<a href="' . PHPBB_ROOT_PATH . '">Return to index page</a>';
1956 $l_notify = '';
1958 if (!empty(phpbb::$config['board_contact']))
1960 $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . phpbb::$config['board_contact'] . '">' . phpbb::$config['board_contact'] . '</a></p>';
1964 garbage_collection();
1966 // Try to not call the adm page data...
1967 // @todo put into failover template file
1969 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
1970 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
1971 echo '<head>';
1972 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
1973 echo '<title>' . $msg_title . '</title>';
1974 echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
1975 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; } ';
1976 echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
1977 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; } ';
1978 echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
1979 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; } ';
1980 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; } ';
1981 echo "\n" . '/* ]]> */' . "\n";
1982 echo '</style>';
1983 echo '</head>';
1984 echo '<body id="errorpage">';
1985 echo '<div id="wrap">';
1986 echo ' <div id="page-header">';
1987 echo ' ' . $l_return_index;
1988 echo ' </div>';
1989 echo ' <div id="acp">';
1990 echo ' <div class="panel">';
1991 echo ' <div id="content">';
1992 echo ' <h1>' . $msg_title . '</h1>';
1994 echo ' <div>' . $msg_text;
1996 if ((phpbb::registered('acl') && phpbb::$acl->acl_get('a_')) || defined('IN_INSTALL') || phpbb::$base_config['debug_extra'])
1998 echo ($backtrace = get_backtrace()) ? '<br /><br />BACKTRACE' . $backtrace : '';
2000 echo '</div>';
2002 echo $l_notify;
2004 echo ' </div>';
2005 echo ' </div>';
2006 echo ' </div>';
2007 echo ' <div id="page-footer">';
2008 echo ' Powered by phpBB &copy; 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>';
2009 echo ' </div>';
2010 echo '</div>';
2011 echo '</body>';
2012 echo '</html>';
2014 exit_handler();
2016 // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
2017 exit;
2018 break;
2020 case E_USER_WARNING:
2021 case E_USER_NOTICE:
2023 define('IN_ERROR_HANDLER', true);
2025 if (empty(phpbb::$user->data))
2027 phpbb::$user->session_begin();
2030 // We re-init the auth array to get correct results on login/logout
2031 phpbb::$acl->init(phpbb::$user->data);
2033 if (empty(phpbb::$user->lang))
2035 phpbb::$user->setup();
2038 $msg_text = (!empty(phpbb::$user->lang[$msg_text])) ? phpbb::$user->lang[$msg_text] : $msg_text;
2039 $msg_title = (!isset($msg_title)) ? phpbb::$user->lang['INFORMATION'] : ((!empty(phpbb::$user->lang[$msg_title])) ? phpbb::$user->lang[$msg_title] : $msg_title);
2041 if (!defined('HEADER_INC'))
2043 page_header($msg_title);
2046 phpbb::$template->set_filenames(array(
2047 'body' => 'message_body.html')
2050 phpbb::$template->assign_vars(array(
2051 'MESSAGE_TITLE' => $msg_title,
2052 'MESSAGE_TEXT' => $msg_text,
2053 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
2054 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
2057 // We do not want the cron script to be called on error messages
2058 define('IN_CRON', true);
2060 page_footer();
2062 exit_handler();
2063 break;
2066 // If we notice an error not handled here we pass this back to PHP by returning false
2067 // This may not work for all php versions
2068 return false;
2072 * Generate page header
2073 * @plugin-support override, default, return
2075 function page_header($page_title = '', $display_online_list = true)
2077 if (phpbb::$plugins->function_override(__FUNCTION__)) return phpbb::$plugins->call_override(__FUNCTION__, $page_title, $display_online_list);
2079 if (defined('HEADER_INC'))
2081 return;
2084 define('HEADER_INC', true);
2086 // gzip_compression
2087 if (phpbb::$config['gzip_compress'])
2089 if (@extension_loaded('zlib') && !headers_sent())
2091 ob_start('ob_gzhandler');
2095 if (phpbb::$plugins->function_inject(__FUNCTION__)) phpbb::$plugins->call_inject(__FUNCTION__, array('default', &$page_title, &$display_online_list));
2097 // Generate logged in/logged out status
2098 if (phpbb::$user->data['user_id'] != ANONYMOUS)
2100 $u_login_logout = phpbb::$url->append_sid('ucp', 'mode=logout', true, phpbb::$user->session_id);
2101 $l_login_logout = sprintf(phpbb::$user->lang['LOGOUT_USER'], phpbb::$user->data['username']);
2103 else
2105 $u_login_logout = phpbb::$url->append_sid('ucp', 'mode=login');
2106 $l_login_logout = phpbb::$user->lang['LOGIN'];
2109 // Last visit date/time
2110 $s_last_visit = (phpbb::$user->data['user_id'] != ANONYMOUS) ? phpbb::$user->format_date(phpbb::$user->data['session_last_visit']) : '';
2112 // Get users online list ... if required
2113 $online_userlist = array();
2114 $l_online_users = $l_online_record = '';
2115 $forum = request_var('f', 0);
2117 if (phpbb::$config['load_online'] && phpbb::$config['load_online_time'] && $display_online_list)
2119 $logged_visible_online = $logged_hidden_online = $guests_online = $prev_user_id = 0;
2120 $prev_session_ip = $reading_sql = '';
2122 if ($forum)
2124 $reading_sql = ' AND s.session_forum_id = ' . $forum;
2127 // Get number of online guests
2128 if (!phpbb::$config['load_online_guests'])
2130 if (phpbb::$db->features['count_distinct'])
2132 $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
2133 FROM ' . SESSIONS_TABLE . ' s
2134 WHERE s.session_user_id = ' . ANONYMOUS . '
2135 AND s.session_time >= ' . (time() - (phpbb::$config['load_online_time'] * 60)) .
2136 $reading_sql;
2138 else
2140 $sql = 'SELECT COUNT(session_ip) as num_guests
2141 FROM (
2142 SELECT DISTINCT s.session_ip
2143 FROM ' . SESSIONS_TABLE . ' s
2144 WHERE s.session_user_id = ' . ANONYMOUS . '
2145 AND s.session_time >= ' . (time() - (phpbb::$config['load_online_time'] * 60)) .
2146 $reading_sql .
2147 ')';
2149 $result = phpbb::$db->sql_query($sql);
2150 $guests_online = (int) phpbb::$db->sql_fetchfield('num_guests');
2151 phpbb::$db->sql_freeresult($result);
2154 $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
2155 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_TABLE . ' s
2156 WHERE s.session_time >= ' . (time() - (intval(phpbb::$config['load_online_time']) * 60)) .
2157 $reading_sql .
2158 ((!phpbb::$config['load_online_guests']) ? ' AND s.session_user_id <> ' . ANONYMOUS : '') . '
2159 AND u.user_id = s.session_user_id
2160 ORDER BY u.username_clean ASC, s.session_ip ASC';
2161 $result = phpbb::$db->sql_query($sql);
2163 $prev_user_id = false;
2165 while ($row = phpbb::$db->sql_fetchrow($result))
2167 // User is logged in and therefore not a guest
2168 if ($row['user_id'] != ANONYMOUS)
2170 // Skip multiple sessions for one user
2171 if ($row['user_id'] != $prev_user_id)
2173 if ($row['session_viewonline'])
2175 $logged_visible_online++;
2177 else
2179 $row['username'] = '<em>' . $row['username'] . '</em>';
2180 $logged_hidden_online++;
2183 if (($row['session_viewonline']) || phpbb::$acl->acl_get('u_viewonline'))
2185 $user_online_link = get_username_string(($row['user_type'] <> phpbb::USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
2186 $online_userlist[] = $user_online_link;
2190 $prev_user_id = $row['user_id'];
2192 else
2194 // Skip multiple sessions for one user
2195 if ($row['session_ip'] != $prev_session_ip)
2197 $guests_online++;
2201 $prev_session_ip = $row['session_ip'];
2203 phpbb::$db->sql_freeresult($result);
2205 if (!sizeof($online_userlist))
2207 $online_userlist = phpbb::$user->lang['NO_ONLINE_USERS'];
2209 else
2211 $online_userlist = implode(', ', $online_userlist);
2214 if (!$forum)
2216 $online_userlist = phpbb::$user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
2218 else
2220 $online_userlist = phpbb::$user->lang('BROWSING_FORUM_GUESTS', $online_userlist, $guests_online);
2223 $total_online_users = $logged_visible_online + $logged_hidden_online + $guests_online;
2225 if ($total_online_users > phpbb::$config['record_online_users'])
2227 set_config('record_online_users', $total_online_users, true);
2228 set_config('record_online_date', time(), true);
2231 $l_online_users = phpbb::$user->lang('ONLINE_USER_COUNT', $total_online_users);
2232 $l_online_users .= phpbb::$user->lang('REG_USER_COUNT', $logged_visible_online);
2233 $l_online_users .= phpbb::$user->lang('HIDDEN_USER_COUNT', $logged_hidden_online);
2234 $l_online_users .= phpbb::$user->lang('GUEST_USER_COUNT', $guests_online);
2236 $l_online_record = phpbb::$user->lang('RECORD_ONLINE_USERS', phpbb::$config['record_online_users'], phpbb::$user->format_date(phpbb::$config['record_online_date']));
2237 $l_online_time = phpbb::$user->lang('VIEW_ONLINE_TIME', phpbb::$config['load_online_time']);
2239 else
2241 $l_online_time = '';
2244 $l_privmsgs_text = $l_privmsgs_text_unread = '';
2245 $s_privmsg_new = false;
2247 // Obtain number of new private messages if user is logged in
2248 if (!empty(phpbb::$user->data['is_registered']))
2250 if (phpbb::$user->data['user_new_privmsg'])
2252 $l_privmsgs_text = phpbb::$user->lang('NEW_PM', phpbb::$user->data['user_new_privmsg']);
2254 if (!phpbb::$user->data['user_last_privmsg'] || phpbb::$user->data['user_last_privmsg'] > phpbb::$user->data['session_last_visit'])
2256 $sql = 'UPDATE ' . USERS_TABLE . '
2257 SET user_last_privmsg = ' . phpbb::$user->data['session_last_visit'] . '
2258 WHERE user_id = ' . phpbb::$user->data['user_id'];
2259 phpbb::$db->sql_query($sql);
2261 $s_privmsg_new = true;
2263 else
2265 $s_privmsg_new = false;
2268 else
2270 $l_privmsgs_text = phpbb::$user->lang['NO_NEW_PM'];
2271 $s_privmsg_new = false;
2274 $l_privmsgs_text_unread = '';
2276 if (phpbb::$user->data['user_unread_privmsg'] && phpbb::$user->data['user_unread_privmsg'] != phpbb::$user->data['user_new_privmsg'])
2278 $l_privmsgs_text_unread = phpbb::$user->lang('UNREAD_PM', phpbb::$user->data['user_unread_privmsg']);
2282 // Which timezone?
2283 $tz = (phpbb::$user->data['user_id'] != ANONYMOUS) ? strval(doubleval(phpbb::$user->data['user_timezone'])) : strval(doubleval(phpbb::$config['board_timezone']));
2285 // Send a proper content-language to the output
2286 $user_lang = phpbb::$user->lang['USER_LANG'];
2287 if (strpos($user_lang, '-x-') !== false)
2289 $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
2292 // The following assigns all _common_ variables that may be used at any point in a template.
2293 phpbb::$template->assign_vars(array(
2294 'SITENAME' => phpbb::$config['sitename'],
2295 'SITE_DESCRIPTION' => phpbb::$config['site_desc'],
2296 'PAGE_TITLE' => $page_title,
2297 'SCRIPT_NAME' => str_replace('.' . PHP_EXT, '', phpbb::$user->page['page_name']),
2298 'LAST_VISIT_DATE' => phpbb::$user->lang('YOU_LAST_VISIT', $s_last_visit),
2299 'LAST_VISIT_YOU' => $s_last_visit,
2300 'CURRENT_TIME' => phpbb::$user->lang('CURRENT_TIME', phpbb::$user->format_date(time(), false, true)),
2301 'TOTAL_USERS_ONLINE' => $l_online_users,
2302 'LOGGED_IN_USER_LIST' => $online_userlist,
2303 'RECORD_USERS' => $l_online_record,
2304 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
2305 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
2307 'S_USER_NEW_PRIVMSG' => phpbb::$user->data['user_new_privmsg'],
2308 'S_USER_UNREAD_PRIVMSG' => phpbb::$user->data['user_unread_privmsg'],
2310 'SESSION_ID' => phpbb::$user->session_id,
2311 'ROOT_PATH' => PHPBB_ROOT_PATH,
2313 'L_LOGIN_LOGOUT' => $l_login_logout,
2314 'L_INDEX' => phpbb::$user->lang['FORUM_INDEX'],
2315 'L_ONLINE_EXPLAIN' => $l_online_time,
2317 'U_PRIVATEMSGS' => phpbb::$url->append_sid('ucp', 'i=pm&amp;folder=inbox'),
2318 'U_RETURN_INBOX' => phpbb::$url->append_sid('ucp', 'i=pm&amp;folder=inbox'),
2319 'U_POPUP_PM' => phpbb::$url->append_sid('ucp', 'i=pm&amp;mode=popup'),
2320 'UA_POPUP_PM' => addslashes(phpbb::$url->append_sid('ucp', 'i=pm&amp;mode=popup')),
2321 'U_MEMBERLIST' => phpbb::$url->append_sid('memberlist'),
2322 'U_VIEWONLINE' => (phpbb::$acl->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? phpbb::$url->append_sid('viewonline') : '',
2323 'U_LOGIN_LOGOUT' => $u_login_logout,
2324 'U_INDEX' => phpbb::$url->append_sid('index'),
2325 'U_SEARCH' => phpbb::$url->append_sid('search'),
2326 'U_REGISTER' => phpbb::$url->append_sid('ucp', 'mode=register'),
2327 'U_PROFILE' => phpbb::$url->append_sid('ucp'),
2328 'U_MODCP' => phpbb::$url->append_sid('mcp', false, true, phpbb::$user->session_id),
2329 'U_FAQ' => phpbb::$url->append_sid('faq'),
2330 'U_SEARCH_SELF' => phpbb::$url->append_sid('search', 'search_id=egosearch'),
2331 'U_SEARCH_NEW' => phpbb::$url->append_sid('search', 'search_id=newposts'),
2332 'U_SEARCH_UNANSWERED' => phpbb::$url->append_sid('search', 'search_id=unanswered'),
2333 'U_SEARCH_ACTIVE_TOPICS'=> phpbb::$url->append_sid('search', 'search_id=active_topics'),
2334 'U_DELETE_COOKIES' => phpbb::$url->append_sid('ucp', 'mode=delete_cookies'),
2335 'U_TEAM' => (phpbb::$user->data['user_id'] != ANONYMOUS && !phpbb::$acl->acl_get('u_viewprofile')) ? '' : phpbb::$url->append_sid('memberlist', 'mode=leaders'),
2336 'U_RESTORE_PERMISSIONS' => (phpbb::$user->data['user_perm_from'] && phpbb::$acl->acl_get('a_switchperm')) ? phpbb::$url->append_sid('ucp', 'mode=restore_perm') : '',
2338 'S_USER_LOGGED_IN' => (phpbb::$user->data['user_id'] != ANONYMOUS) ? true : false,
2339 'S_AUTOLOGIN_ENABLED' => (phpbb::$config['allow_autologin']) ? true : false,
2340 'S_BOARD_DISABLED' => (phpbb::$config['board_disable']) ? true : false,
2341 'S_REGISTERED_USER' => (!empty(phpbb::$user->is_registered)) ? true : false,
2342 'S_IS_BOT' => (!empty(phpbb::$user->is_bot)) ? true : false,
2343 'S_USER_PM_POPUP' => phpbb::$user->optionget('popuppm'),
2344 'S_USER_LANG' => $user_lang,
2345 'S_USER_BROWSER' => (isset(phpbb::$user->data['session_browser'])) ? phpbb::$user->data['session_browser'] : phpbb::$user->lang['UNKNOWN_BROWSER'],
2346 'S_USERNAME' => phpbb::$user->data['username'],
2347 'S_CONTENT_DIRECTION' => phpbb::$user->lang['DIRECTION'],
2348 'S_CONTENT_FLOW_BEGIN' => (phpbb::$user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
2349 'S_CONTENT_FLOW_END' => (phpbb::$user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
2350 'S_CONTENT_ENCODING' => 'UTF-8',
2351 'S_TIMEZONE' => (phpbb::$user->data['user_dst'] || (phpbb::$user->data['user_id'] == ANONYMOUS && phpbb::$config['board_dst'])) ? sprintf(phpbb::$user->lang['ALL_TIMES'], phpbb::$user->lang['tz'][$tz], phpbb::$user->lang['tz']['dst']) : sprintf(phpbb::$user->lang['ALL_TIMES'], phpbb::$user->lang['tz'][$tz], ''),
2352 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
2353 'S_DISPLAY_SEARCH' => (!phpbb::$config['load_search']) ? 0 : (phpbb::$acl->acl_get('u_search') && phpbb::$acl->acl_getf_global('f_search')),
2354 'S_DISPLAY_PM' => (phpbb::$config['allow_privmsg'] && !empty(phpbb::$user->data['is_registered']) && (phpbb::$acl->acl_get('u_readpm') || phpbb::$acl->acl_get('u_sendpm'))) ? true : false,
2355 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? phpbb::$acl->acl_get('u_viewprofile') : 0,
2356 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
2357 'S_REGISTER_ENABLED' => (phpbb::$config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
2359 'T_THEME_PATH' => PHPBB_ROOT_PATH . 'styles/' . phpbb::$user->theme['theme_path'] . '/theme',
2360 'T_TEMPLATE_PATH' => PHPBB_ROOT_PATH . 'styles/' . phpbb::$user->theme['template_path'] . '/template',
2361 'T_IMAGESET_PATH' => PHPBB_ROOT_PATH . 'styles/' . phpbb::$user->theme['imageset_path'] . '/imageset',
2362 'T_IMAGESET_LANG_PATH' => PHPBB_ROOT_PATH . 'styles/' . phpbb::$user->theme['imageset_path'] . '/imageset/' . phpbb::$user->data['user_lang'],
2363 'T_IMAGES_PATH' => PHPBB_ROOT_PATH . 'images/',
2364 'T_SMILIES_PATH' => PHPBB_ROOT_PATH . phpbb::$config['smilies_path'] . '/',
2365 'T_AVATAR_PATH' => PHPBB_ROOT_PATH . phpbb::$config['avatar_path'] . '/',
2366 'T_AVATAR_GALLERY_PATH' => PHPBB_ROOT_PATH . phpbb::$config['avatar_gallery_path'] . '/',
2367 'T_ICONS_PATH' => PHPBB_ROOT_PATH . phpbb::$config['icons_path'] . '/',
2368 'T_RANKS_PATH' => PHPBB_ROOT_PATH . phpbb::$config['ranks_path'] . '/',
2369 'T_UPLOAD_PATH' => PHPBB_ROOT_PATH . phpbb::$config['upload_path'] . '/',
2370 'T_STYLESHEET_LINK' => (!phpbb::$user->theme['theme_storedb']) ? PHPBB_ROOT_PATH . 'styles/' . phpbb::$user->theme['theme_path'] . '/theme/stylesheet.css' : phpbb::$url->get(PHPBB_ROOT_PATH . 'style.' . PHP_EXT . '?id=' . phpbb::$user->theme['style_id'] . '&amp;lang=' . phpbb::$user->data['user_lang']), //PHPBB_ROOT_PATH . "store/{$user->theme['theme_id']}_{$user->theme['imageset_id']}_{$user->lang_name}.css"
2371 'T_STYLESHEET_NAME' => phpbb::$user->theme['theme_name'],
2373 'SITE_LOGO_IMG' => phpbb::$user->img('site_logo'),
2375 'A_COOKIE_SETTINGS' => addslashes('; path=' . phpbb::$config['cookie_path'] . ((!phpbb::$config['cookie_domain'] || phpbb::$config['cookie_domain'] == 'localhost' || phpbb::$config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . phpbb::$config['cookie_domain']) . ((!phpbb::$config['cookie_secure']) ? '' : '; secure')),
2378 // application/xhtml+xml not used because of IE
2379 header('Content-type: text/html; charset=UTF-8');
2381 header('Cache-Control: private, no-cache="set-cookie"');
2382 header('Expires: 0');
2383 header('Pragma: no-cache');
2385 if (phpbb::$plugins->function_inject(__FUNCTION__, 'return')) return phpbb::$plugins->call_inject(__FUNCTION__, 'return');
2389 * Generate page footer
2391 function page_footer($run_cron = true)
2393 global $starttime;
2395 // Output page creation time
2396 if (phpbb::$base_config['debug'])
2398 $mtime = explode(' ', microtime());
2399 $totaltime = $mtime[0] + $mtime[1] - $starttime;
2401 if (phpbb_request::variable('explain', false) && /*phpbb::$acl->acl_get('a_') &&*/ phpbb::$base_config['debug_extra'] && method_exists(phpbb::$db, 'sql_report'))
2403 phpbb::$db->sql_report('display');
2406 $debug_output = sprintf('Time : %.3fs | ' . phpbb::$db->sql_num_queries() . ' Queries | GZIP : ' . ((phpbb::$config['gzip_compress']) ? 'On' : 'Off') . ((phpbb::$user->system['load']) ? ' | Load : ' . phpbb::$user->system['load'] : ''), $totaltime);
2408 if (/*phpbb::$acl->acl_get('a_') &&*/ phpbb::$base_config['debug_extra'])
2410 if (function_exists('memory_get_usage'))
2412 if ($memory_usage = memory_get_usage())
2414 $memory_usage -= phpbb::$base_config['memory_usage'];
2415 $memory_usage = get_formatted_filesize($memory_usage);
2417 $debug_output .= ' | Memory Usage: ' . $memory_usage;
2421 $debug_output .= ' | <a href="' . phpbb::$url->build_url() . '&amp;explain=1">Explain</a>';
2425 phpbb::$template->assign_vars(array(
2426 'DEBUG_OUTPUT' => (phpbb::$base_config['debug']) ? $debug_output : '',
2427 'TRANSLATION_INFO' => (!empty(phpbb::$user->lang['TRANSLATION_INFO'])) ? phpbb::$user->lang['TRANSLATION_INFO'] : '',
2429 'U_ACP' => (phpbb::$acl->acl_get('a_') && !empty(phpbb::$user->is_registered)) ? phpbb::$url->append_sid(phpbb::$base_config['admin_folder'] . '/index', false, true, phpbb::$user->session_id) : '',
2432 // Call cron-type script
2433 if (!defined('IN_CRON') && $run_cron && !phpbb::$config['board_disable'])
2435 $cron_type = '';
2437 if (time() - phpbb::$config['queue_interval'] > phpbb::$config['last_queue_run'] && !defined('IN_ADMIN') && file_exists(PHPBB_ROOT_PATH . 'cache/queue.' . PHP_EXT))
2439 // Process email queue
2440 $cron_type = 'queue';
2442 else if (method_exists(phpbb::$acm, 'tidy') && time() - phpbb::$config['cache_gc'] > phpbb::$config['cache_last_gc'])
2444 // Tidy the cache
2445 $cron_type = 'tidy_cache';
2447 else if (time() - phpbb::$config['warnings_gc'] > phpbb::$config['warnings_last_gc'])
2449 $cron_type = 'tidy_warnings';
2451 else if (time() - phpbb::$config['database_gc'] > phpbb::$config['database_last_gc'])
2453 // Tidy the database
2454 $cron_type = 'tidy_database';
2456 else if (time() - phpbb::$config['search_gc'] > phpbb::$config['search_last_gc'])
2458 // Tidy the search
2459 $cron_type = 'tidy_search';
2461 else if (time() - phpbb::$config['session_gc'] > phpbb::$config['session_last_gc'])
2463 $cron_type = 'tidy_sessions';
2466 if ($cron_type)
2468 phpbb::$template->assign_var('RUN_CRON_TASK', '<img src="' . phpbb::$url->append_sid('cron', 'cron_type=' . $cron_type) . '" width="1" height="1" alt="cron" />');
2472 phpbb::$template->display('body');
2474 garbage_collection();
2475 exit_handler();
2479 * Closing the cache object and the database
2480 * Cool function name, eh? We might want to add operations to it later
2482 function garbage_collection()
2484 // Unload cache, must be done before the DB connection if closed
2485 if (phpbb::registered('acm'))
2487 phpbb::$acm->unload();
2490 // Close our DB connection.
2491 if (phpbb::registered('db'))
2493 phpbb::$db->sql_close();
2498 * Handler for exit calls in phpBB.
2499 * This function supports hooks.
2501 * Note: This function is called after the template has been outputted.
2503 function exit_handler()
2505 // needs to be run prior to the hook
2506 if (phpbb_request::super_globals_disabled())
2508 phpbb_request::enable_super_globals();
2511 // As a pre-caution... some setups display a blank page if the flush() is not there.
2512 (empty(phpbb::$config['gzip_compress'])) ? @flush() : @ob_flush();
2514 exit;