<?php
/* PageCookery Framework
*
* Author: Explon
*
* Copyright (C) 2009 Explon <explon@gmail.com>
*/

require(COOKERY_FRAMEWORK_DIR . 'lib/functions_html.php');

function load_template($file)
{
	global $template_files;
	
	if (file_exists('template/' . $file . '.html'))
	{
	    $file_content = file_get_contents('template/' . $file . '.html');
	    
	    $file_content = preg_replace("/\{template (.+?)\}/e", "load_template('\\1')", $file_content);
	    
	    if (DEBUG == true AND !Helper::IsBrowser('ie'))
	    {
	    	$file_content = "\n<!-- " . $file . ".html Start -->\n" . $file_content;
	    }
	
	    if (DEBUG == true)
	    {
	    	$file_content .= "\n<!-- " . $file . ".html End -->\n";
	    }
	    
	    $template_files .= "\n" . $file . '.html';
	}
	else
	{
	    exit('Template file: ' . $file . '.html not exists.');
	}
	
	return $file_content;
}

function draw_array_select($array, $name, $selected, $zero = '', $onchange = '')
{
	if (!$selected)
	{
		$selected = '___zero';
	}

	if ($onchange)
	{
		$html = '<select name="' . $name . '" id="' . $name . '" onchange="' . $onchange . '">';
	}
	else
	{
		$html = '<select name="' . $name . '" id="' . $name . '">';
	}

	if ($zero)
	{
		if ($selected == '___zero')
		{
			$html .= '<option value="0" selected="selected">' . $zero . '</option>';
		}
		else
		{
			$html .= '<option value="0">' . $zero . '</option>';
		}
	}

	foreach ($array AS $key => $name)
	{
		if ($key == $selected)
		{
			$html .= '<option value="' . $key . '" selected="selected">' . $name . '</option>';
		}
		else
		{
			$html .= '<option value="' . $key . '">' . $name . '</option>';
		}
	}

	$html .= '</select>';

	return $html;
}

function output_debug()
{
	global $runtime, $template_files, $db_driver;
	
	echo "\r\n\r\n<!-- 页面生成耗时: " . $runtime->Match() . ' 秒, 数据库扩展: ' . $db_driver . ' -->';

	if (DEBUG == TRUE)
	{		
		$get_request = print_r($_GET, true);
		$post_request = print_r($_POST, true);
		$cookie_request = print_r($_COOKIE, true);
		
		echo "\n<!-- Templates: " . $template_files . ' -->';
		
		if (sizeof($_GET) > 0)
		{
			echo "\n<!-- GET Request: " . $get_request . ' -->';
		}
		
		if (sizeof($_POST) > 0)
		{
			echo "\n<!-- POST Request: " . $post_request . ' -->';
		}
		
		if (sizeof($_COOKIE) > 0)
		{
			echo "\n<!-- COOKIE Request: " . $cookie_request . ' -->';
		}
		
		if ($_SERVER['HTTP_REFERER'])
		{
			echo "\n<!-- Referer: " . $_SERVER['HTTP_REFERER'] . ' -->';
		}
		
		echo "\n<!-- Script: " . basename($_SERVER['PHP_SELF']) . '?' . $_SERVER['QUERY_STRING'] . ' -->';
		echo "\n<!-- Request URI: " . $_SERVER['REQUEST_URI'] . ' -->';
		echo "\n<!-- User-Agent: " . Helper::UserAgent() . ' -->';
	}
}

function cjk_strlen($string, $charset = 'UTF-8')
{
    if (function_exists('mb_strlen'))
    {
    	return mb_strlen($string, $charset);
    }
    else if (function_exists('iconv_strlen'))
    {
    	return iconv_strlen($string, $charset);
    }
	
	if ($charset == 'UTF-8')
	{
    	return strlen(utf8_decode($string));
	}
	else
	{
		return false;
	}
}

function cjk_substr($string, $start, $length = NULL, $charset = 'UTF-8')
{
    if (function_exists('mb_substr'))
    {
    	return mb_substr($string, $start, $length, $charset);
    }
    else if (function_exists('iconv_substr'))
    {
    	return iconv_substr($string, $start, $length, $charset);
    }

	if ($charset == 'UTF-8')
	{
    	preg_match_all("/./u", $string, $array);

    	if (func_num_args() >= 3)
    	{
    		$end = func_get_arg(2);
			
    		return join('', array_slice($array[0], $start, $end));
    	}
    	else
    	{
    		return join('', array_slice($array[0], $start));
    	}
	}
	else
	{
		return false;
	}
}

function charset_convert($string, $input = 'GBK', $output = 'UTF-8')
{
    if (function_exists('mb_convert_encoding'))
    {
    	$output = mb_convert_encoding($string, $output, $input);
    }
    else if (function_exists('iconv'))
    {
    	$output = iconv($input, $output, $string);
    }
    else
    {
    	exit('charset_convert() needs mb_convert_encoding or iconv function support.');
    }

    return $output;
}

// #############################################################################
/**
* 非英文字符 ISO 编码, 防乱码
* @author	explon
* @param	string	待处理的模板代码
*
* @return	string	最后生成的 HTML 代码
*/

function iso_encode($str)
{
    if (!Helper::IsSearchBot())
    {
    	$str = mb_convert_encoding($str, 'UTF-16', 'UTF-8');
    	
    	for ($i = 0; $i < strlen($str); $i++, $i++)
    	{ 
    		$code = ord($str{$i}) * 256 + ord($str{$i + 1}); 
    		
    		if ($code < 128)
    		{ 
    			$output .= chr($code); 
    		}
    		else if ($code != 65279)
    		{ 
    			$output .= '&#' . $code . ';'; 
    		}
    	}
    }
    else
    {
    	$output = $str;
    }
    
    return $output; 
}

function jquery_json_encode($json = array(), $callback = 'jsoncallback')
{
	if ($_GET[$callback])
	{
		return $_GET[$callback] . '(' . json_encode($json) . ')';
	}
	
	return json_encode($json);
}

/**
* Determines if the current version of PHP is greater then the supplied value
*
* Since there are a few places where we conditionally test for PHP > 5
* we'll set a static variable.
*
* @access	public
* @param	string
* @return	bool
*/
function is_php($version = '5.1.0')
{
	static $_is_php;
	
	$version = (string)$version;
	
	if ( ! isset($_is_php[$version]))
	{
		$_is_php[$version] = (version_compare(PHP_VERSION, $version) < 0) ? FALSE : TRUE;
	}

	return $_is_php[$version];
}

// ------------------------------------------------------------------------

/**
 * Tests for file writability
 *
 * is_writable() returns TRUE on Windows servers when you really can't write to 
 * the file, based on the read-only attribute.  is_writable() is also unreliable
 * on Unix servers if safe_mode is on. 
 *
 * @return	void
 */
function is_really_writable($file)
{	
	// If we're on a Unix server with safe_mode off we call is_writable
	if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
	{
		return is_writable($file);
	}

	// For windows servers and safe_mode "on" installations we'll actually
	// write a file then read it.  Bah...
	if (is_dir($file))
	{
		$file = rtrim($file, '/') . '/' . md5(rand(1,100));

		if (!file_put_contents($file, 'PageCookery is_really_writable() test.'))
		{
			return FALSE;
		}
		else
		{
			@unlink($file);
		}
		
		return TRUE;
	}
	else if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
	{
		return FALSE;
	}
	
	return TRUE;
}

/**
 * Set HTTP Status Header
 *
 * @access	public
 * @param	int 	the status code
 * @param	string	
 * @return	void
 */
function set_status_header($code = 200, $text = '')
{
	$stati = array(
						200	=> 'OK',
						201	=> 'Created',
						202	=> 'Accepted',
						203	=> 'Non-Authoritative Information',
						204	=> 'No Content',
						205	=> 'Reset Content',
						206	=> 'Partial Content',

						300	=> 'Multiple Choices',
						301	=> 'Moved Permanently',
						302	=> 'Found',
						304	=> 'Not Modified',
						305	=> 'Use Proxy',
						307	=> 'Temporary Redirect',

						400	=> 'Bad Request',
						401	=> 'Unauthorized',
						403	=> 'Forbidden',
						404	=> 'Not Found',
						405	=> 'Method Not Allowed',
						406	=> 'Not Acceptable',
						407	=> 'Proxy Authentication Required',
						408	=> 'Request Timeout',
						409	=> 'Conflict',
						410	=> 'Gone',
						411	=> 'Length Required',
						412	=> 'Precondition Failed',
						413	=> 'Request Entity Too Large',
						414	=> 'Request-URI Too Long',
						415	=> 'Unsupported Media Type',
						416	=> 'Requested Range Not Satisfiable',
						417	=> 'Expectation Failed',

						500	=> 'Internal Server Error',
						501	=> 'Not Implemented',
						502	=> 'Bad Gateway',
						503	=> 'Service Unavailable',
						504	=> 'Gateway Timeout',
						505	=> 'HTTP Version Not Supported'
					);

	if ($code == '' OR ! is_numeric($code))
	{
		exit('function set_status_header() error: Status codes must be numeric');
	}

	if (isset($stati[$code]) AND $text == '')
	{				
		$text = $stati[$code];
	}
	
	if ($text == '')
	{
		exit('function set_status_header() error: No status text available.  Please check your status code number or supply your own message text.');
	}
	
	$server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : FALSE;

	if (substr(php_sapi_name(), 0, 3) == 'cgi')
	{
		header("Status: {$code} {$text}", TRUE);
	}
	elseif ($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0')
	{
		header($server_protocol." {$code} {$text}", TRUE, $code);
	}
	else
	{
		header("HTTP/1.1 {$code} {$text}", TRUE, $code);
	}
}

function redirect($uri = '', $method = 'location', $http_response_code = 302)
{	
	switch ($method)
	{
		case 'refresh':
				header("Refresh:0;url=" . $uri);
		break;
		
		default:
			header("Location: " . $uri, TRUE, $http_response_code);
		break;
	}
	
	exit;
}

function format_result_array_key(&$result_array, $master_key)
{
	$new_result_array = array();
	
	foreach ($result_array AS $key => $item)
	{
		$new_result_array[$item[$master_key]] = $item;
	}
	
	return $new_result_array;
}