View file includes/functions.php

File size: 26.36Kb
<?php
/***************************************************************************
 *                               functions.php
 *                            -------------------
 *      Разработка: phpBB Group.
 *      Оптимизация под WAP: Гутник Игорь ( чел ).
 *          2008 год
 ***************************************************************************/
function detect_mobile_device()
{
       if (stristr(@$_SERVER['HTTP_USER_AGENT'],'windows') && !stristr(@$_SERVER['HTTP_USER_AGENT'], 'windows ce')) 
       {
              return false;
       }       
       if (eregi('up.browser|up. link |windows ce|iemobile|mini|mmp|symbian|midp|wap|phone|pocket|mobile|pda|psp', @$_SERVER['HTTP_USER_AGENT']))
       {
              return true;
       }       
       if (isset($_SERVER['HTTP_ACCEPT'])&&(stristr($_SERVER['HTTP_ACCEPT'], 'text/vnd.wap.wml') || stristr($_SERVER['HTTP_ACCEPT'], 'application/vnd.wap.xhtml xml')))
       {
              return true;   
       }       
       if (isset($_SERVER['HTTP_X_WAP_PROFILE'])|| isset($_SERVER['HTTP_PROFILE'] ) || isset($_SERVER['X-OperaMini-Features']) || isset($_SERVER['UA-pixels']))
       {
              return true;
       }       
       
       $a = array ('acs-','alav','alca','amoi','audi','aste','avan','benq','bird','blac','bla z','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno','ipaq','java', 'jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mi ts','mmef','mobi','mot-','moto','mwbp','nec-','newt','noki','opwv','palm','pana' ,'pant','pdxg','phil','play','pluc','port','prox','qtek','qwap','sage','sams','s any','sch-','sec-','send','seri','sgh-','shar','sie-','siem','smal','smar','sony ','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda',' w3c ','wap-','wapa','wapi','wapp','wapr','webc','winw','winw','xda','xda-');
      
       if (isset($a[ substr (@$_SERVER['HTTP_USER_AGENT'], 0, 4)])) 
       {
              return true;
       }       
}

function add_sobytie($link_id, $link_type, $count, $to_user_id, $to_username, $user_id, $username, $subject, $text, $time)
{
	global $db;

	$sql = "INSERT INTO ".SOBYTIE_TABLE." (link_id, link_type, count, to_user_id, to_username, user_id, username, subject, text, time)
		VALUES ('$link_id', '" . str_replace("\'", "''", $link_type) . "', '$count', '$to_user_id', '" . $to_username . "', '$user_id', '" . str_replace("\'", "''", $username) . "', '" . str_replace("\'", "''", $subject) . "', '" . str_replace("\'", "''", $text) . "', '$time')";
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'No insert into', '', __LINE__, __FILE__, $sql);
	}
}         
    
function avatar_img($user_avatar_type, $user_allowavatar, $user_avatar, &$avatar_img, &$avatar_mini)
{
	global $phpEx, $lang, $board_config;
	
        $avatar_img = '<img src="images/nothumbnail.jpg" alt="' . $lang['Avatar'] . '" />';
        $avatar_mini = '<img src="images.php?file=images/nothumbnail.jpg" alt="' . $lang['Avatar'] . '" />';
        if ( $user_avatar_type && $user_allowavatar )
        {
	       switch( $user_avatar_type )
	       {
		   case USER_AVATAR_UPLOAD:
			$avatar_img = ( $board_config['allow_avatar_upload'] ) ? '<img src="' . $board_config['avatar_path'] . '/' . $user_avatar . '" alt="" />' : '';
			$avatar_mini = '<img src="images.php?file=' . $board_config['avatar_path'] . '/' . $user_avatar . '" alt="" />';
			break;
		   case USER_AVATAR_REMOTE:		        
			$avatar_img = ( $board_config['allow_avatar_remote'] ) ? '<img src="images.php?w=100&amp;h=100&amp;file=' . $user_avatar . '" alt="" />' : '';
			$avatar_mini = '<img src="images.php?file=' . $user_avatar . '" alt="" />';
			break;
		   case USER_AVATAR_GALLERY:
		        if ( intval($user_avatar) )
		        {
		               $user_avatar_img = append_sid("album_pic.$phpEx?thumb=1&amp;pic_id=" . $user_avatar);
		               $user_avatar_mini = append_sid("album_pic.$phpEx?thumb=2&amp;pic_id=" . $user_avatar);
		        }
		        else
		        {
		               $user_avatar_img = $board_config['avatar_gallery_path'] . '/' . $user_avatar;
		               $user_avatar_mini = 'images.php?file=' . $board_config['avatar_gallery_path'] . '/' . $user_avatar;
		        }       
			$avatar_img = ( $board_config['allow_avatar_local'] ) ? '<img src="' . $user_avatar_img . '" alt="" />' : '';
			$avatar_mini = '<img src="' . $user_avatar_mini . '" alt="" />';			
			break;
	       }
        }
        return;
} 

function get_db_stat($mode)
{
	global $db;

	switch( $mode )
	{
		case 'usercount':
			$sql = "SELECT COUNT(user_id) AS total
				FROM " . USERS_TABLE . "
				WHERE user_id <> " . ANONYMOUS;
			break;

		case 'newestuser':
			$sql = "SELECT user_id, username
				FROM " . USERS_TABLE . "
				WHERE user_id <> " . ANONYMOUS . "
				ORDER BY user_id DESC
				LIMIT 1";
			break;

		case 'postcount':
		case 'topiccount':
			$sql = "SELECT SUM(forum_topics) AS topic_total, SUM(forum_posts) AS post_total
				FROM " . FORUMS_TABLE;
			break;
		case 'attachcount':
			$sql = "SELECT count(*) AS total FROM " . ATTACHMENTS_DESC_TABLE;
			break;
	}

	if ( !($result = $db->sql_query($sql)) )
	{
		return false;
	}

	$row = $db->sql_fetchrow($result);

	switch ( $mode )
	{
		case 'usercount':
			return $row['total'];
			break;
		case 'newestuser':
			return $row;
			break;
		case 'postcount':
			return $row['post_total'];
			break;
		case 'topiccount':
			return $row['topic_total'];
			break;
		case 'attachcount':
			return $row['total'];
			break;
	}

	return false;
}

function check_unread($forum_id)
{
        global $new_topic_data, $tracking_topics, $tracking_forums, $HTTP_COOKIE_VARS, $board_config;
        if ( !empty($new_topic_data[$forum_id]) )
        {
              $forum_last_post_time = 0;

              while( list($check_topic_id, $check_post_time) = @each($new_topic_data[$forum_id]) )
              {
                      if ( empty($tracking_topics[$check_topic_id]) )
                      {
                               $unread_topics = true;
                               $forum_last_post_time = max($check_post_time, $forum_last_post_time);

                      }
                      else
                      {
                               if ( $tracking_topics[$check_topic_id] < $check_post_time )
                               {
                                       $unread_topics = true;
                                       $forum_last_post_time = max($check_post_time, $forum_last_post_time);
                               }
                      }
               }

               if ( !empty($tracking_forums[$forum_id]) )
               {
                      if ( $tracking_forums[$forum_id] > $forum_last_post_time )
                      {
                               $unread_topics = false;
                      }
               }

               if ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f_all']) )
               {
                      if ( $HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f_all'] > $forum_last_post_time )
                      {
                              $unread_topics = false;
                      }
               }

        }
        return $unread_topics;
} 

function phpbb_clean_username($username)
{
	$username = substr(htmlspecialchars(str_replace("\'", "'", trim($username))), 0, 25);
	$username = phpbb_rtrim($username, "\\");
	$username = str_replace("'", "\'", $username);

	return $username;
}

function phpbb_clean_email($email)
{
        $email = substr(htmlspecialchars(str_replace("\'", "'", trim($email))), 0, 255);
        $email = phpbb_rtrim($email, "\\");
        $email = str_replace("'", "\'", $email);

        return $email;
} 

function phpbb_ltrim($str, $charlist = false)
{
	if ($charlist === false)
	{
		return ltrim($str);
	}
	
	$php_version = explode('.', PHP_VERSION);

	if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
	{
		while ($str{0} == $charlist)
		{
			$str = substr($str, 1);
		}
	}
	else
	{
		$str = ltrim($str, $charlist);
	}

	return $str;
}

function phpbb_rtrim($str, $charlist = false)
{
	if ($charlist === false)
	{
		return rtrim($str);
	}
	
	$php_version = explode('.', PHP_VERSION);

	if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
	{
		while ($str{strlen($str)-1} == $charlist)
		{
			$str = substr($str, 0, strlen($str)-1);
		}
	}
	else
	{
		$str = rtrim($str, $charlist);
	}

	return $str;
}

function dss_rand()
{
	global $db, $board_config, $dss_seeded;

	$val = $board_config['rand_seed'] . microtime();
	$val = md5($val);
	$board_config['rand_seed'] = md5($board_config['rand_seed'] . $val . 'a');
   
	if($dss_seeded !== true)
	{
		$sql = "UPDATE " . CONFIG_TABLE . " SET
			config_value = '" . $board_config['rand_seed'] . "'
			WHERE config_name = 'rand_seed'";
		
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "Unable to reseed PRNG", "", __LINE__, __FILE__, $sql);
		}

		$dss_seeded = true;
	}

	return substr($val, 4, 16);
}

function get_userdata($user, $force_str = false)
{
	global $db;

	if (!is_numeric($user) || $force_str)
	{
		$user = phpbb_clean_username($user);
	}
	else
	{
		$user = intval($user);
	}

	$sql = "SELECT *
		FROM " . USERS_TABLE . " 
		WHERE ";
	$sql .= ( ( is_integer($user) ) ? "user_id = $user" : "username = '" .  str_replace("\'", "''", $user) . "'" ) . " AND user_id <> " . ANONYMOUS;
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Tried obtaining data for a non-existent user', '', __LINE__, __FILE__, $sql);
	}

	return ( $row = $db->sql_fetchrow($result) ) ? $row : false;
}

function init_userprefs($userdata)
{
	global $board_config;
	global $template, $template_name, $lang, $phpEx, $phpbb_root_path, $db;

	if ( $userdata['user_id'] != ANONYMOUS )
	{
		if ( !empty($userdata['user_lang']))
		{
			$default_lang = phpbb_ltrim(basename(phpbb_rtrim($userdata['user_lang'])), "'");
		}

		if ( !empty($userdata['user_dateformat']) )
		{
			$board_config['default_dateformat'] = $userdata['user_dateformat'];
		}

		if ( isset($userdata['user_timezone']) )
		{
			$board_config['board_timezone'] = $userdata['user_timezone'];
		}
		if ( isset($userdata['user_topics_per_page']) )
		{
			$board_config['topics_per_page'] = $userdata['user_topics_per_page'];
		}
		if ( isset($userdata['user_posts_per_page']) )
		{
			$board_config['posts_per_page'] = $userdata['user_posts_per_page'];
		}
	}
	else
	{
		$default_lang = phpbb_ltrim(basename(phpbb_rtrim($board_config['default_lang'])), "'");
	}

	if ( !file_exists(@phpbb_realpath($phpbb_root_path . 'language/lang_' . $default_lang . '/lang_main.'.$phpEx)) )
	{
		if ( $userdata['user_id'] != ANONYMOUS )
		{
			$default_lang = phpbb_ltrim(basename(phpbb_rtrim($board_config['default_lang'])), "'");
		}
		else
		{

			$default_lang = 'russian';
		}
		if ( !file_exists(@phpbb_realpath($phpbb_root_path . 'language/lang_' . $default_lang . '/lang_main.'.$phpEx)) )
		{
			message_die(CRITICAL_ERROR, 'Could not locate valid language pack');
		}
	}

	if ( $userdata['user_id'] != ANONYMOUS && $userdata['user_lang'] !== $default_lang )
	{
		$sql = 'UPDATE ' . USERS_TABLE . "
			SET user_lang = '" . $default_lang . "'
			WHERE user_lang = '" . $userdata['user_lang'] . "'";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, 'Could not update user language info');
		}

		$userdata['user_lang'] = $default_lang;
	}
	elseif ( $userdata['user_id'] == ANONYMOUS && $board_config['default_lang'] !== $default_lang )
	{
		$sql = 'UPDATE ' . CONFIG_TABLE . "
			SET config_value = '" . $default_lang . "'
			WHERE config_name = 'default_lang'";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, 'Could not update user language info');
		}
	}

	$board_config['default_lang'] = $default_lang;
	
	include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_main.' . $phpEx);
	
	if(file_exists($phpbb_root_path . "language/lang_".$board_config['default_lang'] . "/lang_book.php"))
	{
		@include($phpbb_root_path . "language/lang_".$board_config['default_lang'] . "/lang_book.php");
	}
	elseif(file_exists($phpbb_root_path . "language/lang_russian/lang_book.php"))
	{
		@include($phpbb_root_path . "language/lang_russian/lang_book.php");
	}		

	if ( defined('IN_ADMIN') )
	{
		if( !file_exists(@phpbb_realpath($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_admin.'.$phpEx)) )
		{
			$board_config['default_lang'] = 'russian';
		}

		include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_admin.' . $phpEx);
	}
	include_attach_lang();

	if ( $userdata['user_id'] != ANONYMOUS )
	{
	        $template_name = $userdata['theme'];
	}
        if ($template_name == '')
        {
                $template_name = (detect_mobile_device()) ? 'wap' : 'web';                   
        }	              	         	                        				      	
 	if ( defined('IN_ADMIN') ) 
 	{        
	        $template_name = '';
        }	
        
 	$template_path = 'templates/' ;	
 	$template = new Template($phpbb_root_path . $template_path . $template_name);
	return;
}

function encode_ip($dotquad_ip)
{
	$ip_sep = explode('.', $dotquad_ip);
	return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
	$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
	return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}

function create_date($format, $gmepoch, $tz)
{
	global $board_config, $lang;
	static $translate;

	if ( empty($translate) && $board_config['default_lang'] = 'russian' )
	{
		@reset($lang['datetime']);
		while ( list($match, $replace) = @each($lang['datetime']) )
		{
			$translate[$match] = $replace;
		}
	}

	return ( !empty($translate) ) ? strtr(@gmdate($format, $gmepoch + (3600 * $tz)), $translate) : @gmdate($format, $gmepoch + (3600 * $tz));
}

function get_page($num_items, $per_page, $start_item) 
{ 

        $total_pages = ceil($num_items/$per_page); 

        if ( $total_pages == 1 ) 
        { 
              return '1'; 
              exit; 
        } 
        $on_page = floor($start_item / $per_page) + 1; 
        $page_string = ''; 

        for($i = 0; $i < $total_pages + 1; $i++) 
        { 
               if( $i == $on_page ) 
               { 
                      $page_string = $i; 
               }
        } 
        return $page_string; 
}

function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE)
{
	global $lang;

	$total_pages = ceil($num_items/$per_page);

	if ( $total_pages == 1 )
	{
		return '';
	}

	$on_page = floor($start_item / $per_page) + 1;

	$page_string = '';
	if ( $on_page == 1 )
	{
		$page_string = '';
	}
        if ( $on_page == $total_pages )
	{
		$page_string = '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $on_page - 2 ) * $per_page ) ) . '" class="buttom">' . $lang['Previous'] . '</a>&nbsp;';
	}
	if ( $total_pages > 10 )
	{
		$init_page_max = ( $total_pages > 3 ) ? 3 : $total_pages;

		for($i = 1; $i < $init_page_max + 1; $i++)
		{
			$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '" class="buttom">' . $i . '</a>';
			if ( $i <  $init_page_max )
			{
				$page_string .= ",";
			}
		}

		if ( $total_pages > 3 )
		{
			if ( $on_page > 1  && $on_page < $total_pages )
			{
				$page_string .= ( $on_page > 5 ) ? '...' : ',';

				$init_page_min = ( $on_page > 4 ) ? $on_page : 5;
				$init_page_max = ( $on_page < $total_pages - 4 ) ? $on_page : $total_pages - 4;

				for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
				{
					$page_string .= ($i == $on_page) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '" class="buttom">' . $i . '</a>';
					if ( $i <  $init_page_max + 1 )
					{
						$page_string .= ',';
					}
				}

				$page_string .= ( $on_page < $total_pages - 4 ) ? '...' : ',';
			}
			else
			{
				$page_string .= '...';
			}

			for($i = $total_pages - 2; $i < $total_pages + 1; $i++)
			{
				$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>'  : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '" class="buttom">' . $i . '</a>';
				if( $i <  $total_pages )
				{
					$page_string .= ",";
				}
			}
		}
	}
	else
	{
		for($i = 1; $i < $total_pages + 1; $i++)
		{
			$page_string .= ( $i == $on_page ) ? '<b>' . $i . '</b>' : '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $i - 1 ) * $per_page ) ) . '" class="buttom">' . $i . '</a>';
			if ( $i <  $total_pages )
			{
				$page_string .= ',';
			}
		}
	}
	if ( $on_page == 1 )
	{
		$page_string .= '&nbsp;<a href="' . append_sid($base_url . "&amp;start=" . ( $on_page * $per_page ) ) . '" class="buttom">' . $lang['Next'] . '</a>';
	}
        if ( $on_page == $total_pages )
	{
		$page_string .= '';
	}
	if ( $add_prevnext_text )
	{
		if ( $on_page > 1  && $on_page < $total_pages )
		{
			$page_string = '<a href="' . append_sid($base_url . "&amp;start=" . ( ( $on_page - 2 ) * $per_page ) ) . '" class="buttom">' . $lang['Previous'] . '</a>&nbsp;' . $page_string . '&nbsp;<a href="' . append_sid($base_url . "&amp;start=" . ( $on_page * $per_page ) ) . '" class="buttom">' . $lang['Next'] . '</a>';
		}

		if ( $on_page < $total_pages )
		{
			$page_string .= '';
		}
	}

	return $page_string;
}

function phpbb_preg_quote($str, $delimiter)
{
	$text = preg_quote($str);
	$text = str_replace($delimiter, '\\' . $delimiter, $text);
	
	return $text;
}

function obtain_word_list(&$orig_word, &$replacement_word)
{
	global $db;

	$sql = "SELECT word, replacement
		FROM  " . WORDS_TABLE;
	if( !($result = $db->sql_query($sql)) )
	{
		message_die(GENERAL_ERROR, 'Could not get censored words from database', '', __LINE__, __FILE__, $sql);
	}

	if ( $row = $db->sql_fetchrow($result) )
	{
		do 
		{
			
			$orig_word[] = $row['word'];
			$replacement_word[] = $row['replacement'];
		}
		while ( $row = $db->sql_fetchrow($result) );
	}

	return true;
}

function message_die($msg_code, $msg_text = '', $msg_title = '', $err_line = '', $err_file = '', $sql = '')
{
	global $db, $template, $board_config, $lang, $phpEx, $phpbb_root_path, $gen_simple_header, $opera_mini, $tmp_name;
	global $userdata, $user_ip, $session_length;
	global $starttime;

	$sql_store = $sql;

	if ( DEBUG && ( $msg_code == GENERAL_ERROR || $msg_code == CRITICAL_ERROR ) )
	{
		$sql_error = $db->sql_error();

		$debug_text = '';

		if ( $sql_error['message'] != '' )
		{
			$debug_text .= '<br />SQL Error: ' . $sql_error['code'] . ' ' . $sql_error['message'];
		}

		if ( $sql_store != '' )
		{
			$debug_text .= "<br /><br />$sql_store";
		}

		if ( $err_line != '' && $err_file != '' )
		{
			$debug_text .= '<br />Line: ' . $err_line . '<br />File : ' . basename($err_file);
		}
	}

	if( empty($userdata) && ( $msg_code == GENERAL_MESSAGE || $msg_code == GENERAL_ERROR ) )
	{
		$userdata = session_pagestart($user_ip, PAGE_INDEX);
		init_userprefs($userdata);
	}

	if ( !defined('HEADER_INC') && $msg_code != CRITICAL_ERROR )
	{
		if ( empty($lang) )
		{
			if ( !empty($board_config['default_lang']) )
			{
				include($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/lang_main.'.$phpEx);
			}
			else
			{
				include($phpbb_root_path . 'language/lang_russian/lang_main.'.$phpEx);
			}
		}

		$page_title = $lang['Information'];

		if ( !defined('IN_ADMIN') )
		{			
			include($phpbb_root_path . 'includes/page_header.'.$phpEx);
		}
		else
		{
			include($phpbb_root_path . 'admin/page_header_admin.'.$phpEx);
		}
	}

	switch($msg_code)
	{
		case GENERAL_MESSAGE:
			if ( $msg_title == '' )
			{
				$msg_title = $lang['Information'];
			}
			break;

		case CRITICAL_MESSAGE:
			if ( $msg_title == '' )
			{
				$msg_title = $lang['Critical_Information'];
			}
			break;

		case GENERAL_ERROR:
			if ( $msg_text == '' )
			{
				$msg_text = $lang['An_error_occured'];
			}

			if ( $msg_title == '' )
			{
				$msg_title = $lang['General_Error'];
			}
			break;

		case CRITICAL_ERROR:

			include($phpbb_root_path . 'language/lang_russian/lang_main.'.$phpEx);

			if ( $msg_text == '' )
			{
				$msg_text = $lang['A_critical_error'];
			}

			if ( $msg_title == '' )
			{
				$msg_title = $lang['Critical_Error'];
			}
			break;
	}

	if ( DEBUG && ( $msg_code == GENERAL_ERROR || $msg_code == CRITICAL_ERROR ) )
	{
		if ( $debug_text != '' )
		{
			$msg_text = $msg_text . '<br /><b><u>DEBUG MODE</u></b>' . $debug_text;
		}
	}

	if ( $msg_code != CRITICAL_ERROR )
	{
		if ( !empty($lang[$msg_text]) )
		{
			$msg_text = $lang[$msg_text];
		}

		if ( !defined('IN_ADMIN') )
		{
			$template->set_filenames(array(
				'message_body' => 'message_body.tpl')
			);
		}
		else
		{
			$template->set_filenames(array(
				'message_body' => 'admin/admin_message_body.tpl')
			);
		}

		$template->assign_vars(array(
			'MESSAGE_TITLE' => $msg_title,
			'MESSAGE_TEXT' => $msg_text)
		);
		$template->pparse('message_body');

		if ( !defined('IN_ADMIN') )
		{
			include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
		}
		else
		{
			include($phpbb_root_path . 'admin/page_footer_admin.'.$phpEx);
		}
	}
	else
	{
		echo "<html>\n<body>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title>" . $msg_title . "</title>\n";
	        echo "</head>\n<br /><br />" . $msg_text . "\n</body>\n</html>";
	}
	exit;
}

function phpbb_realpath($path)
{
	global $phpbb_root_path, $phpEx;

	return (!@function_exists('realpath') || !@realpath($phpbb_root_path . 'includes/functions.'.$phpEx)) ? $path : @realpath($path);
}

function redirect($url)
{
	global $db, $board_config;

	if (!empty($db))
	{
		$db->sql_close();
	}

	if (strstr(urldecode($url), "\n") || strstr(urldecode($url), "\r") || strstr(urldecode($url), ';url'))
	{
		message_die(GENERAL_ERROR, 'Tried to redirect to potentially insecure url.');
	}

	$server_protocol = ($board_config['cookie_secure']) ? 'https://' : 'http://';
	$server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['server_name']));
	$server_port = ($board_config['server_port'] <> 80) ? ':' . trim($board_config['server_port']) : '';
	$script_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($board_config['script_path']));
	$script_name = ($script_name == '') ? $script_name : '/' . $script_name;
	$url = preg_replace('#^\/?(.*?)\/?$#', '/\1', trim($url));

	if (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')))
	{
		header('Refresh: 0; URL=' . $server_protocol . $server_name . $server_port . $script_name . $url);
		echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><meta http-equiv="refresh" content="0; url=' . $server_protocol . $server_name . $server_port . $script_name . $url . '"><title>Redirect</title></head><body><div align="center">If your browser does not support meta redirection please click <a href="' . $server_protocol . $server_name . $server_port . $script_name . $url . '">HERE</a> to be redirected</div></body></html>';
		exit;
	}

	header('Location: ' . $server_protocol . $server_name . $server_port . $script_name . $url);
	exit;
}

function db_query($sql)
{
	global $db;

	$sql = preg_replace_callback('#{(\w+)}#', 'const_subst', $sql); 

	if (func_num_args() > 1)
	{
		$args = func_get_args();
		$args = array_map('addslashes', $args);
		$args[0] = $sql;
		$sql = call_user_func_array('sprintf', $args);
	}

	if ($result = $db->sql_query($sql))
	{
		return $result;
	}
	else
	{
		message_die(GENERAL_ERROR, 'SQL query failed', '', __LINE__, __FILE__, $sql);
	}
}

function const_subst($match)
{
	return constant($match[1]);
}

function db_transaction($command)
{
	global $db;

	$db->sql_query('SELECT 0', $command);
}


function mkrealdate($day,$month,$birth_year)
{
	if ($month<1 || $month>12) return "error";
	switch ($month)
	{
		case 1: if ($day>31) return "error";break;
		case 2: if ($day>29) return "error";
			$epoch=$epoch+31;break;
		case 3: if ($day>31) return "error";
			$epoch=$epoch+59;break;
		case 4: if ($day>30) return "error" ;
			$epoch=$epoch+90;break;
		case 5: if ($day>31) return "error";
			$epoch=$epoch+120;break;
		case 6: if ($day>30) return "error";
			$epoch=$epoch+151;break;
		case 7: if ($day>31) return "error";
			$epoch=$epoch+181;break;
		case 8: if ($day>31) return "error";
			$epoch=$epoch+212;break;
		case 9: if ($day>30) return "error";
			$epoch=$epoch+243;break;
		case 10: if ($day>31) return "error";
			$epoch=$epoch+273;break;
		case 11: if ($day>30) return "error";
			$epoch=$epoch+304;break;
		case 12: if ($day>31) return "error";
			$epoch=$epoch+334;break;
	}
	$epoch=$epoch+$day;
	$epoch_Y=sqrt(($birth_year-1970)*($birth_year-1970));
	$leapyear=round((($epoch_Y+2) / 4)-.5);
	if (($epoch_Y+2)%4==0)
	{
		$leapyear--;
		if ($birth_year >1970 && $month>=3) $epoch=$epoch+1;
		if ($birth_year <1970 && $month<3) $epoch=$epoch-1;
	} else if ($month==2 && $day>28) return "error";
	if ($birth_year>1970)
		$epoch=$epoch+$epoch_Y*365-1+$leapyear;
	else
		$epoch=$epoch-$epoch_Y*365-1-$leapyear;
	return $epoch;
}

function realdate($date_syntax="Ymd",$date=0)
{
	global $lang;
	$i=2;
	if ($date>=0)
	{
	 	return create_date($date_syntax,$date*86400+1,0);
	} else
	{
		$year= -(date%1461);
		$days = $date + $year*1461;
		while ($days<0)
		{
			$year--;
			$days+=365;
			if ($i++==3)
			{
				$i=0;
				$days++;
			}
		}
	}
	$leap_year = ($i==0) ? TRUE : FALSE;
	$months_array = ($i==0) ?
		array (0,31,60,91,121,152,182,213,244,274,305,335,366) :
		array (0,31,59,90,120,151,181,212,243,273,304,334,365);
	for ($month=1;$month<12;$month++)
	{
		if ($days<$months_array[$month]) break;
	}

	$day=$days-$months_array[$month-1]+1;
	return strtr ($date_syntax, array(
		'a' => '',
		'A' => '',
		'\\d' => 'd',
		'd' => ($day>9) ? $day : '0'.$day,
		'\\D' => 'D',
		'D' => $lang['day_short'][($date-3)%7],
		'\\F' => 'F',
		'F' => $lang['month_long'][$month-1],
		'g' => '',
		'G' => '',
		'H' => '',
		'h' => '',
		'i' => '',
		'I' => '',
		'\\j' => 'j',
		'j' => $day,
		'\\l' => 'l',
		'l' => $lang['day_long'][($date-3)%7],
		'\\L' => 'L',
		'L' => $leap_year,
		'\\m' => 'm',
		'm' => ($month>9) ? $month : '0'.$month,
		'\\M' => 'M',
		'M' => $lang['month_short'][$month-1],
		'\\n' => 'n',
		'n' => $month,
		'O' => '',
		's' => '',
		'S' => '',
		'\\t' => 't',
		't' => $months_array[$month]-$months_array[$month-1],
		'w' => '',
		'\\y' => 'y',
		'y' => ($year>29) ? $year-30 : $year+70,
		'\\Y' => 'Y',
		'Y' => $year+1970,
		'\\z' => 'z',
		'z' => $days,
		'\\W' => '',
		'W' => '') );
}

?>