<?php
if( !defined('ISDVBBS') ){
	//header('HTTP/1.0 401 Unauthorized');
	header('HTTP/1.0 400 Bad Request');
	exit;
}

//Start modify by @20061102
	if (!defined('FH_DEFAULT_WRITABLE_DIR')) {
        if (defined('UPLOAD_BASEDIR')) {
            define('FH_DEFAULT_WRITABLE_DIR', str_replace('\\', '/', realpath(UPLOAD_BASEDIR.'tempimage')));
        } else {
            !isset($fsetting) AND isset($GLOBALS['fsetting']) AND ($fsetting =& $GLOBALS['fsetting']);
            if (empty($fsetting) AND @is_file(CACHE_PATH.'forum_setting.php')) {
                require_once CACHE_PATH.'forum_setting.php';
                $fsetting =& $_DCACHE['settings'];
            }
            (!isset($fsetting['forumuploadname']) OR empty($fsetting['forumuploadname'])) AND ($fsetting['forumuploadname'] = 'uploadfile/');
            define('FH_DEFAULT_WRITABLE_DIR', str_replace('\\', '/', realpath(basename($fsetting['forumuploadname']).'/tempimage')));
        }
	}
//End modify by xiaodu@20061102

/**
* 此类用于解决系统自带的文件操作函数在安全模式下受限制的问题。
* 只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
* 为了保证操作的可靠性，建议您在处理文件时，传递完整的文件名，包括其完整的路径，可使用系统函数 realpath()获取完整文件名。
*
*
* @package 		dvphp
* @author		@dv
* @version		$Revision: 1.0 beta $
* @date 		$Date: 2006/07/27 $
* @copyright 	http://p.dvbbs.net/license.html
*
*/
class FileHandler
{
	var $_errinfo = array('errno'=>null, 'errstr'=>null, 'errfile'=>null, 'errline'=>null, 'is_safe_mode_restriction'=>false, 'invoke_method'=>null, 'myuid'=>null, 'dest_file'=>null, 'dest_file_owner'=>null);
	function FileHandler()
	{
	}//end function FileHandler

	function &create_instance($writabledir = '') // 静态方法，用于创建此类的唯一实例
	{
		static $instance;
		if (!isset($instance)) {
			$instance = new FileHandler();
		}
		if (!empty($writabledir)) {
			FileHandler::find_writable_dir($writabledir);
		}
		$instance->_initialize();
		return $instance;
	}//end function create_instance

	/**
	 * Description 检测目标目录是否可写。（此函数没有考虑安全模式的因素）
	 * @author @dv
	 * @param string 要检测的目录
	 * @return mixed 如果目录目录可写，返回 TRUE ，否则返回 FALSE 。
	 */
	function _dir_is_writable($testdir)
	{
		if (!is_dir($testdir)) {
			return false;
		} elseif (false AND function_exists('version_compare') AND version_compare(PHP_VERSION, '4.4.2') >= 0 AND is_writable($testdir)) {
			return true;
		} else {
			$testfile = "{$testdir}/".md5(uniqid(rand(), true));
			if (@touch($testfile)) {
				@unlink($testfile);
				return true;
			}
		}
		return false;
	}//end function dir_is_writable

	function _dispose()
	{
		$this->_initialize();
	}//end function _dispose

	function _error_handler($errno, $errstr, $errfile, $errline)
	{
		$match = array();
		$errinfo = array('errno'=>$errno, 'errstr'=>$errstr, 'errfile'=>$errfile, 'errline'=>$errline, 'is_safe_mode_restriction'=>false, 'invoke_method'=>null, 'myuid'=>null, 'dest_file'=>null, 'dest_file_owner'=>null);
		$matchresult = preg_match('#.*?(.+?(?=\()).*?SAFE.*?MODE.*?Restriction.*?(?:uid\s+is).*?([0-9]+)\s+is\s+not\s+allowed\s+to\s+access\s+(.+?)\s+owned\s+by\s+uid\s+([0-9]+).*?#i', $errstr, $matchs);
		if (1 == $matchresult AND !empty($matchs)) {
			$errinfo['is_safe_mode_restriction'] = true;
			$errinfo['invoke_method'] = $matchs[1];
			$errinfo['myuid'] = $matchs[2];
			$errinfo['dest_file'] = $matchs[3];
			$errinfo['dest_file_owner'] = $matchs[4];
		} else {
			if (0 == preg_match('#tempnam\(#i', $errstr)) {
				trigger_error("{$errstr} in {$errfile} on line {$errline}.", E_USER_WARNING);
			}
		}
		$this->_errinfo =& $errinfo;
	}//end function _errorHandler

	function _write2TmpFile(&$content)
	{
		$tmp_str = strval($content);
		if ('' === $tmp_str) {
			return false;
		}

		$writable_dir = FileHandler::find_writable_dir();
		if (empty($writable_dir)) {
			return false;
		}

		static $st_tmp_name;
		empty($st_tmp_name) AND ($st_tmp_name = strtolower(substr(base64_encode(md5(uniqid(time(),true))),20,8)).'.php');

		$fwrited = false;
		$path_name = $writable_dir.'/__dvtmpfile__'.$st_tmp_name;
		if ($fp = fopen($path_name, 'wb')) {
			@flock($fp, 2);
			$fwrited = fwrite($fp, $tmp_str, strlen($tmp_str));
			fclose($fp);
		}
		if (false === $fwrited) {
			return false;
		}

		return $path_name;
	}//end function _write2TmpFile

	/**
	 * Description 此函数用于解决相关文件操作函数，在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 在临时文件中要执行的PHP代码
	 * @return mixed 如果发生错误，返回 FALSE，否则返回PHP代码的执行结果。
	 */
	function _exec(&$operation_code)
	{
		static $st_url_token_id;
		empty($st_url_token_id) AND ($st_url_token_id = md5(uniqid(rand(), true)));
		$php_code = "<?php\n";
		$php_code .= <<<EOT
		error_reporting(E_ALL);
		function error_handler(\$errno, \$errstr, \$errfile, \$errline)
		{
			restore_error_handler();
			\$errfile = basename(dirname(\$errfile)).'/'.basename(\$errfile);
			if (\$errno == E_USER_ERROR) {
				print "Fatal: {\$errstr} in {\$errfile} on line {\$errline}";
			} else {
				print "Warning: {\$errstr} in {\$errfile} on line {\$errline}";
			}
			exit;
		}//end function 
		set_error_handler('error_handler');
		if (isset(\$_GET)) {
			\$httpget =& \$_GET;
		} elseif(isset(\$HTTP_GET_VARS)) {
			\$httpget =& \$HTTP_GET_VARS;
		} else {
			trigger_error('URL argument error!', E_USER_ERROR);
			exit;
		}
		if (empty(\$httpget)) {
			trigger_error('URL argument error!', E_USER_ERROR);
			exit;
		}
		if (\$httpget['urltokenid'] !== '{$st_url_token_id}') {
			trigger_error('URL token id error!', E_USER_ERROR);
			exit;
		}//*/
		//------------------ Start user define code------------------
		\n{$operation_code}\n
		//------------------ End user define code------------------
		exit;
EOT;
		$php_code .= "\n?>";

		$path_name = FileHandler::_write2TmpFile($php_code);
		if (false === $path_name OR false === @realpath($path_name)) {
			return false;
		}

		static $st_filehandler_settings;
		if (!isset($st_filehandler_settings)) {
			$st_filehandler_settings = array(0=>$_SERVER['HTTP_HOST'], 1=>NULL, 2=>NULL);
			
			global $gFileHandlerSettings;
			@is_file(CACHE_PATH.'filehandler_settings.php') AND @require_once(CACHE_PATH.'filehandler_settings.php');

			if (!empty($gFileHandlerSettings)) {
				$st_filehandler_settings = $gFileHandlerSettings;
				empty($st_filehandler_settings[2]) AND ($st_filehandler_settings[2] = dirname(FileHandler::getScriptName()));
				$st_filehandler_settings[2] = str_replace(array('\\', '//'), '/', $st_filehandler_settings[2]);
				('/' !== substr($st_filehandler_settings[2], -1)) AND ($st_filehandler_settings[2] .= '/');
			}
		}

		$document_root = FileHandler::realpath(FileHandler::getDocumentRoot(true));
		if (empty($st_filehandler_settings[2])) {
			$script_path = str_replace($document_root, '', $path_name);
		} else {
			$script_path = $st_filehandler_settings[2].str_replace($document_root.'/', '', $path_name);
		}
		if (defined('USER_DOMAIN_NAME') AND defined('MAIN_DOMAIN_NAME')) {
			$st_filehandler_settings[1] = USER_DOMAIN_NAME.MAIN_DOMAIN_NAME;
		}

		$exec_result =& FileHandler::getHttpContents("http://{$st_filehandler_settings[0]}:{$_SERVER['SERVER_PORT']}{$script_path}?urltokenid={$st_url_token_id}", empty($st_filehandler_settings[1]) ? NULL : $st_filehandler_settings[1]);
		
		unlink($path_name);
		return $exec_result;
	}//end function _exec

	function buildConfigureFile($siteVirtualRootPath)
	{
		if (!defined('CACHE_PATH')) {
			return false;
		}

		settype($siteVirtualRootPath, 'string');
		if ('' === $siteVirtualRootPath) {
			return false;
		}
		('/' !== substr($siteVirtualRootPath, -1)) AND ($siteVirtualRootPath .= '/');
		$siteVirtualRootPath = str_replace(array('\\', '//'), '/', $siteVirtualRootPath);

		$content = "<?php\r\n";
		$content .= "print 'OK';";
		$content .= "\r\n?>";
		$path_name = FileHandler::_write2TmpFile($content);
		if (false === $path_name OR false === @realpath($path_name)) {
			return false;
		}

		global $_SERVER;
		$document_root = FileHandler::realpath(FileHandler::getDocumentRoot(true));
		if (FileHandler::realpath($_SERVER['APPL_PHYSICAL_PATH']) === $document_root) {
			$script_path = str_replace($document_root, '', $path_name);
		} else {
			$script_path = $siteVirtualRootPath.str_replace($document_root.'/', '', $path_name);
		}

		$gFileHandlerSettings = array(0=>'127.0.0.1', 1=>$_SERVER['HTTP_HOST'], 2=>$siteVirtualRootPath);
		$http_contents = trim(@FileHandler::getHttpContents('http://'.$gFileHandlerSettings[0].':'.$_SERVER['SERVER_PORT'].$script_path, $gFileHandlerSettings[1]));

		if ('OK' !== $http_contents) {
			if (($gFileHandlerSettings[0] = @gethostbyname($_SERVER['HTTP_HOST'])) AND ('127.0.0.1' !== $gFileHandlerSettings[0])) {
				$gFileHandlerSettings[1] = $_SERVER['HTTP_HOST'];
			} else {
				$gFileHandlerSettings[0] = $_SERVER['HTTP_HOST'];
				$gFileHandlerSettings[1] = NULL;
			}
			$http_contents = trim(@FileHandler::getHttpContents('http://'.$gFileHandlerSettings[0].':'.$_SERVER['SERVER_PORT'].$script_path, $gFileHandlerSettings[1]));
		}
		
		if ('OK' !== $http_contents) {
			@unlink($path_name);
			return false;
		}

		//Start	将文件上传模块所需的配置信息写入临时文件存储
			if ($fp = @fopen(CACHE_PATH.'filehandler_settings.php', 'wb')) {
				$content = "<?php\r\n";
				$content .= "global \$gFileHandlerSettings;\r\n";
				$content .= '$gFileHandlerSettings = '.FileHandler::_var_export($gFileHandlerSettings, true).";";
				$content .= "\r\n?>";
				@flock($fp, 2);
				fwrite($fp, $content, strlen($content));
				fclose($fp);
			} else {
				@unlink($path_name);
				return false;
			}
		//End 将文件上传模块所需的配置信息写入临时文件存储
		
		@unlink($path_name);

		return true;
	}//end function buildConfigureFile

	function &getHttpContents($httpUrl, $httpHost = NULL)
	{
		$returnval = false;
		$httpUrl = trim($httpUrl);
		if ('' === $httpUrl) {
			return $returnval;
		}

		static $st_parsedurl = array();
		if (!isset($st_parsedurl[$httpUrl]) AND ($st_parsedurl[$httpUrl] = @parse_url($httpUrl))) {
			if (!isset($st_parsedurl[$httpUrl]['scheme']) OR 'http' !== $st_parsedurl[$httpUrl]['scheme']) {
				$st_parsedurl[$httpUrl] = array();
				return $returnval;
			}
			!isset($st_parsedurl[$httpUrl]['port']) ? ($st_parsedurl[$httpUrl]['port'] = 80) : ($st_parsedurl[$httpUrl]['port'] = intval($st_parsedurl[$httpUrl]['port']));
			if (!empty($st_parsedurl[$httpUrl]['query'])) {
				@parse_str($st_parsedurl[$httpUrl]['query'], $parsed_str);
				if (!empty($parsed_str) AND is_array($parsed_str)) {
					$sep = $st_parsedurl[$httpUrl]['query'] = '';
					foreach ($parsed_str AS $key => $val) {
						$st_parsedurl[$httpUrl]['query'] .= $sep.$key.'='.urlencode($val);
						$sep = '&';
					}//end foreach
				}
			}
		}
		$parsed_url =& $st_parsedurl[$httpUrl];
		if (empty($parsed_url)) {
			return $returnval;
		}

		$http_content = '';

		if (NULL === $httpHost) {
			static $is_allow_url_fopen;
			if (!isset($is_allow_url_fopen)) {
				$is_allow_url_fopen = (function_exists('ini_set') AND PHP_VERSION >= '4.0.4' AND PHP_VERSION <= '4.3.4') ? true : false;
			}
			if (true === $is_allow_url_fopen) {
				@ini_set('allow_url_fopen', 1);
				if ($fp = fopen($httpUrl, 'rb')) {
					while (!feof($fp)) $http_content .= fgets($fp, 1024);
					fclose($fp);
				}
			} elseif (empty($httpHost)) {
				static $st_http_host;
				global $_SERVER;
				!isset($st_http_host) AND ($st_http_host = !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']);
				$httpHost = $st_http_host ? $st_http_host : $parsed_url['host'];
			}
		}
		if (NULL !== $httpHost) {
			if ($fp = pfsockopen($parsed_url['host'], $parsed_url['port'], $errno, $errstr, 1)) {
				$http_protocal = "GET {$parsed_url['path']}?{$parsed_url['query']} HTTP/1.1\r\n";
				$http_protocal .= "Host: {$httpHost}\r\n";
				$http_protocal .= "Connection: Close\r\n\r\n";
				fwrite($fp, $http_protocal);

				$content_length = $transfer_encoeding = null;
				//Start Header 处理部分
					$http_header = '';
					$matchs = array();
					while (!feof($fp)) {
						$http_header = trim(fgets($fp));
						if ('' === $http_header) {
							break;
						}
						if (1 === preg_match('/^Content-Length:\s+(\d+)$/i', $http_header, $matchs) AND !empty($matchs)) {
							$content_length = $matchs[1];
						} elseif (1 == preg_match('/^Transfer-Encoding:\s+(chunked|.+)$/i', $http_header, $matchs) AND !empty($matchs)) {
							$transfer_encoeding = $matchs[1];
						}
					}
				//End Header 处理部分
				//Start Body 处理部分
					if (NULL !== $transfer_encoeding) {
						!feof($fp) AND ($content_length = @base_convert(trim(fgets($fp)), 16, 10));
						if ($content_length > 0) {
							while (!feof($fp)) {
								if (strlen($http_content) >= $content_length) {
									break;
								}
								$http_content .= fgets($fp);
							}//end while
						}
					}
					if ('' === $http_content) {
						while (!feof($fp)) $http_content .= fgets($fp);
					}
				//End Body 处理部分
				fclose($fp);
			}
		}
		
		('' !== $http_content) AND ($returnval =& $http_content);
		return $returnval;
	}//end function getHttpContents

	function getScriptName()
	{
		static $scriptname;
		if (!isset($scriptname)) {
			global $HTTP_SERVER_VARS, $_SERVER;
			!isset($_SERVER) AND ($_SERVER =& $HTTP_SERVER_VARS);
			if ($_SERVER['SCRIPT_NAME']) {
				$scriptname = $_SERVER['SCRIPT_NAME'];
			} elseif ($_SERVER['ORIG_SCRIPT_NAME']) {
				$scriptname = $_SERVER['ORIG_SCRIPT_NAME'];
			}  elseif ($_SERVER['PHP_SELF']) {
				$scriptname = $_SERVER['PHP_SELF'];
			} elseif ($_SERVER['PATH_INFO']) {
				$scriptname = $_SERVER['PATH_INFO'];
			} elseif ($_SERVER['ORIG_PATH_INFO']) {
				$scriptname = $_SERVER['ORIG_PATH_INFO'];
			} elseif ($_SERVER['REQUEST_URI']) {
				$scriptname = $_SERVER['REQUEST_URI'];
				if (false !== ($ipos = strpos($scriptname, '?'))) {
					$scriptname = substr($scriptname, 0, $ipos);
				}
			} elseif ($_SERVER['URL']) {
				$scriptname = $_SERVER['URL'];
				if (false !== ($ipos = strpos($scriptname, '?'))) {
					$scriptname = substr($scriptname, 0, $ipos);
				}
			}
		}
		return $scriptname;
	}//end function getScriptName
	function getDocumentRoot($reverseslash = true)
	{
		static $documentroot;
		if (!isset($documentroot)) {
			global $HTTP_SERVER_VARS, $_SERVER;
			!isset($_SERVER) AND ($_SERVER =& $HTTP_SERVER_VARS);
			if (!empty($_SERVER['APPL_PHYSICAL_PATH'])) {
				$documentroot = $_SERVER['APPL_PHYSICAL_PATH'];
				$lastindex = strlen($documentroot) - 1;
				('/' === $documentroot{$lastindex} OR '\\' === $documentroot{$lastindex}) AND ($documentroot = substr($documentroot, 0, -1));
			} elseif (getenv('DOCUMENT_ROOT')) {
				$documentroot = getenv('DOCUMENT_ROOT');
			} elseif ($_SERVER['DOCUMENT_ROOT']) {
				$documentroot = $_SERVER['DOCUMENT_ROOT'];
			} elseif ($_SERVER['PATH_TRANSLATED']) {	//	PHP4
				if (@is_dir($_SERVER['PATH_TRANSLATED'])) {
					$documentroot = $_SERVER['PATH_TRANSLATED'];
				} else {
					$pathtranslated = str_replace(array('\\', '//'), '/', $_SERVER['PATH_TRANSLATED']);
					$scripturi = FileHandler::getScriptName();
					$documentroot = str_replace($scripturi, '', $pathtranslated);
				}
			} elseif ($_SERVER['ORIG_PATH_TRANSLATED']) {	//	PHP5
				$pathtranslated = str_replace(array('\\', '//'), '/', $_SERVER['ORIG_PATH_TRANSLATED']);
				$scripturi = FileHandler::getScriptName();
				$documentroot = str_replace($scripturi, '', $pathtranslated);
			}
			(true === $reverseslash) AND $documentroot AND ($documentroot = str_replace(array('\\', '//'), '/', $documentroot));
		}
		return $documentroot;
	}//end function getDocumentRoot

	function _initialize()
	{
		unset($this->_errinfo);
		$this->_errinfo = array('errno'=>null, 'errstr'=>null, 'errfile'=>null, 'errline'=>null, 'is_safe_mode_restriction'=>false, 'invoke_method'=>null, 'myuid'=>null, 'dest_file'=>null, 'dest_file_owner'=>null);
	}//end function _initialize

	/**
	 * Description 检查在目标文件/目录，或者其父目录上(当第二个参数设为 TRUE 时)执行相关文件操作时是否会受到安全模式的限制。
	 * @author @dv
	 * @param string 要在其上执行操作的文件或目录
	 * @param boolean 如果设为true，则当检测出目标文件/目录受安全模式限制时，继续检测其父目是否受安全模式限制。
	 * @return boolean 如果目标文件/目录受安全模式限制，返回TRUE，否则返回 FALSE。如果有错误发生，则返回 -1 。
	 */
	function _is_safe_mode_restriction($destfile, $testparentdir = true)
	{
		if (1 == preg_match('/^http/i', $destfile)) {
			return false;
		}

		$realpath = realpath($destfile);
		if (false === $realpath AND (true !== $testparentdir)) {
			trigger_error("No such file or directory {$destfile}.", E_USER_WARNING);
			return -1;
		}

		if (function_exists('ini_get') AND !@ini_get('safe_mode')) {
			return false;
		}
		
		if (@is_file($destfile) AND @touch($destfile)) {
			return false;
		} elseif (true === $testparentdir AND ($parentdir = @dirname($destfile))) {
			static $st_test_file = '';
			empty($st_test_file) AND ($st_test_file = $parentdir.'/'.md5(uniqid(rand(), true)));
			if (@touch($st_test_file) AND @unlink($st_test_file)) {
				return false;
			}
		}

		$fileowner = @FileHandler::fileowner($realpath);
		$myuid = @FileHandler::getmyuid();
		if (is_numeric($myuid) AND ($fileowner == $myuid)) {
			return false;
		}
		if (true === $testparentdir) {
			$parentdir = dirname($destfile);
			if (false === ($realpath = realpath($parentdir))) {
				trigger_error("No such parent directory {$parentdir}.", E_USER_WARNING);
				return -1;
			}
			$fileowner = @FileHandler::fileowner($realpath);
			if (is_numeric($myuid) AND ($fileowner == $myuid)) {
				return false;
			} elseif (is_numeric($fileowner)) {
				return true;
			} else {
				return -1;
			}
		} elseif (is_numeric($fileowner)) {
			return true;
		} else {
			return -1;
		}
	}//end function _is_safe_mode_restriction

	/**
	 * Description 此函数用于解决 getmyuid() 被系统管理员禁用的问题。执行此函数要求系统已开启了安全模式。
	 * @author @dv
	 * @return int 返回当前正在运行的 PHP 脚本的 UID，失败则返回 FALSE 。
	 */
	function getmyuid()
	{
		static $cache_myuid;
		if (isset($cache_myuid)) {
			return $cache_myuid;
		}
		if (function_exists('getmyuid') AND ($myuid = @getmyuid())) {
			$cache_myuid = $myuid;
			return $myuid;
		}
		if (function_exists('ini_get') AND !@ini_get('safe_mode')) {
			return false;
		}
		$writabledir = FileHandler::find_writable_dir();
		if (false === $writabledir) {
			return false;
		}
		$destdir = $writabledir.'/'.md5(uniqid(rand(), true));
		if (!@mkdir($destdir) OR !@chmod($destdir, 0777)) {
			return false;
		}
		$myuid = false;
		$_THIS =& FileHandler::create_instance();
		$testdir = $destdir.'/__dv_test';
		set_error_handler(array(&$_THIS, '_error_handler'));
		$bln = mkdir($testdir);
		restore_error_handler();
		if (!$bln AND $_THIS->_errinfo['is_safe_mode_restriction'] AND is_numeric($_THIS->_errinfo['myuid'])) {
			$cache_myuid = $myuid = $_THIS->_errinfo['myuid'];
		}
		(false !== realpath($testdir)) AND @rmdir($testdir);
		@rmdir($destdir);
		$_THIS->_dispose();
		return $myuid;
	}//end function getmyuid

	/**
	 * Description 输出或返回一个变量的字符串表示(该字符串是合法的 PHP 代码)
	 * @author @dvbbs
	 * @param mixed 所有类型的变量
	 * @param boolean 其值为真时，返回关于传递给该函数的变量的结构信息，值为假时，直接输出字符串形式的变量的结构信息，并返回NULL
	 * @param boolean 其值为真时，将使用自定义算法代替系统函数var_export
	 * @return string 返回关于传递给该函数的变量的结构信息
	 */
	function &_var_export(&$mixedvar, $return = false, $usedvcode = false)
	{
		if (false !== $return) {
			$return = true;
		} else {
			$return = false;
		}
		if (false !== $usedvcode) {
			$usedvcode = true;
		} else {
			$usedvcode = false;
		}
		if ((false === $usedvcode) AND function_exists('var_export')) {
			return var_export($mixedvar, $return);
		} else {
			$returnval = '';
			$vartype = strtolower(gettype($mixedvar));
			switch ($vartype) {
				case 'boolean'://布尔类型
					if (true === $mixedvar) {
						$returnval = 'true';
					} else {
						$returnval = 'false';
					}
					break;
				case 'integer'://整数类型
				case 'float'://浮点类型
				case 'double'://浮点类型
					$returnval =& $mixedvar;
					break;
				case 'string'://字符串类型
					$returnval = "'".str_replace(array('\\', "'"), array('\\\\', "\\'"), $mixedvar)."'";
					break;
				case 'array'://数组类型
					if (empty($mixedvar)) {
						$returnval = 'array()';
					} else {
						$returnval = 'array(';
						foreach ($mixedvar AS $key => $val) {
							$returnval .= "'{$key}' => ".FileHandler::_var_export($val, true, $usedvcode).", ";
						}
						$returnval .= ')';
					}
					break;
				case 'NULL'://特殊类型NULL
					$returnval = 'NULL';
					break;
				case 'object'://对象类型
					$parentclass = get_parent_class($mixedvar).'';
					$returnval = "\r\nclass ".get_class($mixedvar).('' !== $parentclass ? " extends {$parentclass}" : '')." {\r\n";
					$vars =& get_object_vars($mixedvar);
					if (!empty($vars) AND is_array($vars)) {
						foreach ($vars AS $key => $val) {
							$returnval .= "var \${$key} = ".FileHandler::_var_export($val, true, $usedvcode).";\r\n";
						}
					}
					$returnval .= "\r\n}";
					break;
				case 'resource'://资源类型
					$returnval = 'NULL';
					break;
				case 'user function'://只用于 PHP 3，PHP4或更高版本已停用
				case 'unknown type'://未知的变量类型
				default:
					$returnval = 'NULL';
			}
			if (false === $returnval) {
				print $returnval;
				return NULL;
			} else {
				return $returnval;
			}
		}
	}

	/**
	 * Description 此函数用于解决 chmod() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 目标文件/目录
	 * @param string 要应用的模式
	 * @return boolean 将文件 pathname 的模式设置为 mode 。如果成功则返回 TRUE，失败则返回 FALSE 。
	 */
	function chmod($pathname, $mode)
	{
		$arrpathname = $arrmode = array();
		if (!is_array($pathname)) {
			$arrpathname[0] =& $pathname;
		} else {
			$arrpathname =& $pathname;
		}
		if (!is_array($mode)) {
			$arrmode[0] =& $mode;
		} else {
			$arrmode =& $mode;
		}
		$defaultmode = ($arrmode[0] > 0 ? $arrmode[0] : 0777);

		$returnval = false;
		$execcode = '';
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		foreach ($arrpathname AS $index => $currpath) {
			if (false === ($currpath = realpath($currpath))) {
				continue;
			}
			$currmode = (isset($arrmode[$index]) ? $arrmode[$index] : $defaultmode);
			if (chmod($currpath, $currmode)) {
				$returnval = true;
			} elseif ($_THIS->_errinfo['is_safe_mode_restriction']) {
				$currpath = str_replace(array('\\', '//'), '/', $currpath);
				$execcode .= "if (@chmod('$currpath', {$currmode})) {print 1;}\r\n";
			}
			$_THIS->_initialize();
		}//end foreach
		restore_error_handler();
		$_THIS->_dispose();
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function chmod

	/**
	 * Description 此函数用于解决 copy() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 原文件名
	 * @param string 新的文件名
	 * @return boolean 将文件从 source 拷贝到 dest。如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function copy($sourcefile, $destfile)
	{
		if (!is_array($sourcefile)) {
			$arrsource[0] = $sourcefile;
		} else {
			$arrsource =& $sourcefile;
		}
		if (!is_array($destfile)) {
			$arrdest[0] = $destfile;
		} else {
			$arrdest =& $destfile;
		}
		if (count($arrsource) > count($arrdest)) {
			trigger_error('Wrong parameter count for copy() ', E_USER_ERROR);
			return false;
		}
		
		$returnval = false;
		$execcode = '';
		foreach ($arrsource AS $index => $source) {
			if (false === ($source = realpath($source))) {
				continue;
			}
			if (FileHandler::is_dir($source)) {
				continue;
			}
			$dest = $arrdest[$index];
			if (realpath($dest) AND FileHandler::is_dir($dest)) {
				continue;
			}
			if (false === ($destparnetdir = realpath(dirname($dest)))) {
				continue;
			}
			$dest = $destparnetdir.'/'.basename($dest);
			$sourcetmp = FileHandler::_is_safe_mode_restriction($source);
			$desttmp = FileHandler::_is_safe_mode_restriction($dest);
			if ($sourcetmp === false AND $desttmp === false) {
				if (copy($source, $dest)) {
					$returnval = true;
				}
			} else {				
				$writabledir = FileHandler::find_writable_dir();
				if (empty($writabledir)) {
					continue;
				}
				if ($sourcetmp === false AND $desttmp === true) {
					$tmpfile = $writabledir.'/'.strtolower(substr(base64_encode(md5(uniqid(strtotime('now'),true))),20,8));
					if (copy($source, $tmpfile)) {
						$dest = str_replace(array('\\', '//'), '/', $dest);
						$tmpfile = str_replace(array('\\', '//'), '/', $tmpfile);
						$tmpfiles1[] = $tmpfile;
						$execcode .= "if(@copy('{$tmpfile}', '{$dest}')){print 1;}\r\n";
					}
				} elseif ($sourcetmp === true AND $desttmp === false) {
					$destbackup = $dest.'_backup_'.strtolower(substr(base64_encode(md5(uniqid(strtotime('now'),true))),20,8));
					if (!rename($dest, $destbackup)) {
						$tmpfiles2[] = $destbackup;
					}
					if (touch($dest)) {
						$dest = str_replace(array('\\', '//'), '/', $dest);
						$source = str_replace(array('\\', '//'), '/', $source);
						$execcode .= "if(@copy('{$source}', '{$dest}')){print 1;}\r\n";
					}
				} elseif ($sourcetmp === true AND $desttmp === true) {
					$dest = str_replace(array('\\', '//'), '/', $dest);
					$source = str_replace(array('\\', '//'), '/', $source);
					$execcode .= "if(@copy('{$source}', '{$dest}')){print 1;}\r\n";
				} else {
					//Nothing to do
				}
			}
		}//end foreach
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		if (!empty($tmpfiles1)) {
			$rmfiles = $rmdirs = array();
			foreach ($tmpfiles1 AS $tmpfile) {
				if (FileHandler::is_file($tmpfile)) {
					$rmfiles[] = $tmpfile;
				} elseif (FileHandler::is_dir($tmpfile)) {
					$rmdirs[] = $tmpfile;
				}
			}//end foreach
			if (!empty($rmfiles)) {
				FileHandler::unlink($rmfiles);
			}
			if (!empty($rmdirs)) {
				$rmdirs = arsort($rmdirs);
				FileHandler::rmdir($rmdirs);
			}
			unset($tmpfiles1);
		}
		if (!empty($tmpfiles2)) {
			$rmfiles = $rmdirs = array();
			foreach ($tmpfiles2 AS $tmpfile) {
				if (FileHandler::is_file($tmpfile)) {
					$rmfiles[] = $tmpfile;
				} elseif (FileHandler::is_dir($tmpfile)) {
					$rmdirs[] = $tmpfile;
				}
			}//end foreach
			if (!empty($rmfiles)) {
				FileHandler::unlink($rmfiles);
			}
			if (!empty($rmdirs)) {
				$rmdirs = arsort($rmdirs);
				FileHandler::rmdir($rmdirs);
			}
			unset($tmpfiles1);
		}
		return $returnval;
	}//end function copy

	/**
	 * Description 检测目录目录是否为空。
	 * @author xiaodu@dv
	 * @param string 目标目录
	 * @return 如果目标目录为空则返回 TRUE，否则返回 FALSE 。 失败时返回 -1 。
	 */
	function dir_is_empty($destdir)
	{
		if (false === ($realpath = realpath($destdir))) {
			trigger_error('No such directory '.$destdir, E_USER_ERROR);
			return -1;
		}
		$dirisempty = true;
		$issafemodrrestriction = FileHandler::_is_safe_mode_restriction($realpath);
		if (false === $issafemodrrestriction) { // 不受安全模式限制
			if ($handle = dir($realpath)) {
				while (false !== ($entry = $handle->read())) {
					if ($entry == '.' or $entry == '..') {
						continue;
					}
					$dirisempty = false;
					break;
				}//end while
				$handle->close();
			}
		} elseif (true === $issafemodrrestriction) { // 受安全模式限制
			$realpath = str_replace(array('\\', '//'), '/', $realpath);
			$execcode = <<<EOT
				\$dirisempty = 1;
				if (\$handle = dir('{$realpath}')) {
					while (false !== (\$entry = \$handle->read())) {
						if (\$entry == '.' OR \$entry == '..') {
							continue;
						}
						\$dirisempty = 0;
						break;
					}//end while
					\$handle->close();
				}
				print \$dirisempty;
EOT;
			$execresult = FileHandler::_exec($execcode);
			if ($execresult == 1) {
				$dirisempty = true;
			} elseif ($execresult == 0) {
				$dirisempty = false;
			} else {
				trigger_error($execresult, E_USER_ERROR);
			}
		} else { // 有错误发生
			trigger_error('No such directory '.$destdir, E_USER_ERROR);
			return -1;
		}
		return $dirisempty;
	}//end function dir_is_empty

	/**
	 * Description 此函数用于解决 file_exists() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 要检测的文件或目录
	 * @return boolean 如果要检测的文件或目录存在则返回 TRUE，否则返回 FALSE。
	 */
	function file_exists($filename)
	{
		if (realpath($filename)) {
			return true;
		} else {
			return false;
		}
	}//end function file_exists

	/**
	 * Description 获取目标文件的内容；此函数在系统函数 file_get_contents 存在时，将直接调用它并返回值
	 * @author xiaodu@dv
	 * @param string 目标文件名
	 * @return string 返回目标文件的内容，如果操作失败，返回FALSE
	 */
	function file_get_contents($file)
	{
		if (false !== ($realpath = realpath($file)) ) {
			$file = $realpath;
		}
		if (false === FileHandler::_is_safe_mode_restriction($file)) {
			if (function_exists('file_get_contents')) {
				return file_get_contents($file);
			} else {
				if ($fp = fopen($file, 'rb')) {
					$filecontents = '';
					$filesize = filesize($file);
					if ($filesize > 0) {
						$filecontents = @fread($fp, $filesize);
					} elseif (false !== $filesize) {
						while (!feof($fp)) {
							$filecontents .= fgets($fp);
						}
					}
					@fclose($fp);
					return $filecontents;
				}
			}
		} else {
			$file = str_replace(array('\\', '//'), '/', $file);
			$execcode = <<<EOT
				if (!function_exists('file_get_contents')) {
					print (file_get_contents('{$file}'));
					exit;
				} else {
					\$filecontents = '';
					if (\$fp = fopen('{$file}', 'rb')) {
						\$filecontents = '';
						//@flock(\$fp, 1);
						\$filesize = filesize('{$file}');
						if (\$filesize > 0) {
							\$filecontents = @fread(\$fp, \$filesize);
						} elseif (false !== \$filesize) {
							while (!feof(\$fp)) {
								\$filecontents .= fgets(\$fp);
							}
						}
						@fclose(\$fp);
						print (\$filecontents);
						exit;
					}
				}
EOT;
			$execresult = FileHandler::_exec($execcode);
			if (strlen($execresult) <= 0) {
				return '';
			} else {
				return ($execresult);
			}
		}
	}//end function file_get_contents

	/**
	 * Description 向目标文件写入数据内容；此函数在系统函数 file_put_contents 存在时，将直接调用它并写入值
	 * @author @dv
	 * @param string 目标文件名
	 * @param string 要写入的数据(使用引用传递的数据)
	 * @return int 返回写入文件的字节数。失败时返回FALSE
	 */
	function file_put_contents($destfile, &$contents)
	{
		if (false === realpath(dirname($destfile))) {
			return '';
		}
		$args = func_get_args();
		$numargs = func_num_args();
		$arg3 = '';
		if ($numargs >= 3) {
			$arg3 = func_get_arg(2);
		}
		switch ($arg3) {
			case 0: // FILE_USE_INCLUDE_PATH
				$openmode = 'wb';
				break;
			case 1: // FILE_APPEND
			default:
				$openmode = 'ab';
				break;
		}//end switch
		if (false === FileHandler::_is_safe_mode_restriction($destfile)) {
			if (function_exists('file_put_contents')) {
				return call_user_func_array('file_put_contents', $args);
			} else {
				if ($fp = fopen($destfile, $openmode)) {
					if (@flock($fp, 2|4)) {
						$writed = @fwrite($fp,$contents);
						@flock($fp, 3);
					} else {
						$writed = false;
					}
					@fclose($fp);
					return $writed;
				} else {
					return false;
				}
			}
		} else {
			$destfile = $args[0] = str_replace(array('\\', '//'), '/', realpath(dirname($args[0])).'/'.basename($args[0]));
			$tmpargs =& FileHandler::_var_export($args, true);
			$contents = str_replace(array('\\', "'"), array('\\\\', "\'"), $contents);
			$execcode = <<<EOT
			if (function_exists('file_put_contents')) {
				if (call_user_func_array('file_put_contents', {$tmpargs})) {
					print 1;
					exit;
				}
			} else {
				if (\$fp = fopen('{$destfile}', '{$openmode}')) {
					if (@flock(\$fp, 2|4)) {
						\$writed = @fwrite(\$fp,'{$contents}');
						@flock(\$fp, 3);
					} else {
						\$writed = false;
					}
					@fclose(\$fp);
					if (false !== \$writed) {
						print 1;
						exit;
					}
				}
			}
EOT;
			$execresult = FileHandler::_exec($execcode);
			if ($execresult == 1) {
				return true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
				return false;
			}
		}
	}//end function file_put_contents

	/**
	 * Description 此函数用于解决 fileowner() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 目标目录或文件
	 * @return boolean 如果成功则返回 目标目录或文件的UID，失败则返回 FALSE。
	 */
	function fileowner($filename)
	{
		$fileowner = false;
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		$fileowner = fileowner($filename);
		restore_error_handler();
		if (false === $fileowner AND $_THIS->_errinfo['is_safe_mode_restriction']) {
			$fileowner = $_THIS->_errinfo['dest_file_owner'];
		}
		$_THIS->_dispose();
		return $fileowner;
	}//end function fileowner

	/**
	 * Description 此函数用于解决 filesize() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 目标目录或文件
	 * @return boolean 如果成功则返回目标目录或文件的大小，出错则返回 FALSE。
	 */
	function filesize($filename)
	{
		$filename = realpath($filename);
		if (false === $filename) {
			return filesize($filename);
		}
		$filesize = false;
		if (false === FileHandler::_is_safe_mode_restriction($filename)) {
			return filesize($filename);
		} else {
			$filename = str_replace(array('\\', '//'), '/', $filename);
			$execcode = 'print filesize(\''.$filename.'\');';
			$execresult = FileHandler::_exec($execcode);
			if (is_numeric($execresult)) {
				return $execresult;
			} else {
				trigger_error($execresult, E_USER_WARNING);
				return false;
			}
		}
		return $filesize;
	}//end function filesize

	/**
	 * Description 从站点根目录开始，寻找所有可以写入的目录，并在找到第一个满足条件的目录时，将其返回。
	 * @author xiaodu@dv
	 * @param string 可写入的目录，如果没有指定或指定的值不存在，此函数将搜索整个站点。
	 * @return string 返回被找到的可写入的目录。找不到可写的目录或出错时返回 FALSE 。
	 */
	function find_writable_dir($writabledir = FH_DEFAULT_WRITABLE_DIR)
	{
		global $_SERVER;
		static $cachewritabledir;
		if ($writabledir = realpath($writabledir)) {
			if (@FileHandler::_dir_is_writable($writabledir)) {
				$cachewritabledir = FileHandler::realpath($writabledir);
			}
		}
		if (!isset($cachewritabledir)) {
			$documentroot = FileHandler::getDocumentRoot(true);
			$LIFO_queue = array();
			if ($tmpobj = @dir($documentroot)) {
				$LIFO_index = 0;
				$LIFO_queue[0] =& $tmpobj;
				$dir =& $tmpobj;
				while ($LIFO_index >= 0 AND !empty($dir)) {
					if (false === ($entry = $dir->read())) {
						$dir->close();
						unset($LIFO_queue[$LIFO_index]);
						$LIFO_index--;
						$dir =& $LIFO_queue[$LIFO_index];
						continue;
					}
					if ('..' == $entry) {
						continue;
					}
					$currfullentry = $dir->path.'/'.$entry;
					if (is_dir($currfullentry) AND FileHandler::_dir_is_writable($currfullentry)) {
						$cachewritabledir = $currfullentry;
						break;
					}
				}
				if (!empty($LIFO_queue) AND is_array($LIFO_queue)) {
					for ( ; $LIFO_index >= 0 ; $LIFO_index--) {
						$LIFO_queue[$LIFO_index]->close();
						unset($LIFO_queue[$LIFO_index]);
					}
				}
			}
			if (empty($cachewritabledir)) {
				$cachewritabledir = false;
			} else {
				$cachewritabledir = FileHandler::realpath($cachewritabledir);
			}
		}
		return $cachewritabledir;
	}//end function find_writable_dir

	/**
	 * Description 将文件或目录从 sourcefile 拷贝到 destfile ；支持深层目录拷贝，暂不支持符号连接。
	 * @author @dv
	 * @param string 原文件或目录名
	 * @param string 新的或目录文件名
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function icopy($sourcefile, $destfile)
	{
		if (false === ($sourcefile = realpath($sourcefile))) {
			trigger_error('No such file or directory.', E_USER_WARNING);
			return false;
		}
		if (FileHandler::is_file($sourcefile)) {
			return FileHandler::copy($sourcefile, $destfile);
		} elseif (FileHandler::is_file($destfile)) { // $sourcefile is a directory
			trigger_error("FileHandler::icopy({$destfile}): failed to open stream: Is a file.", E_USER_WARNING);
			return false;
		}
		$LIFO_queue = array(); // 轻便型后入先出队列
		if ($LIFO_queue[0] =& FileHandler::scandir($sourcefile)) {
			$LIFO_index = 0;
			$destdirs_make = $sourcefiles_copyto = $destfiles_copyto = array();
			$sourcedir = $sourcefile;
			$destdir = $destfile = realpath(dirname($destfile)).'/'.basename($destfile);
			if (!FileHandler::is_dir($destdir)) {
				$destdirs_make[] = $destdir;
			} else {				
				$destdir = $destdir.'/'.basename($sourcedir);
				if (!FileHandler::is_dir($destdir)) {
					$destdirs_make[] = $destdir;
				}
			}
			while ($LIFO_index >= 0) {
				if (isset($LIFO_queue[$LIFO_index]['files'])) {
					foreach ($LIFO_queue[$LIFO_index]['files'] AS $entry) {
						$sourcefiles_copyto[] = $sourcedir.'/'.$entry;
						$destfiles_copyto[] = $destdir.'/'.$entry;
					}
					unset($LIFO_queue[$LIFO_index]['files']);
				}
				$emptydirectories = true;
				if (isset($LIFO_queue[$LIFO_index]['directories'])) {
					foreach ($LIFO_queue[$LIFO_index]['directories'] AS $index => $entry) {
						unset($LIFO_queue[$LIFO_index]['directories'][$index]);
						if ($entry == '.' OR $entry == '..') {
							continue;
						}
						$srcfullentry = $sourcedir.'/'.$entry;
						$destfullentry = $destdir.'/'.$entry;
						if (!FileHandler::is_dir($destfullentry)) {
							$destdirs_make[] = $destfullentry;
						}
						if ($filelist =& FileHandler::scandir($srcfullentry)) {
							$sourcedir = $srcfullentry;
							$destdir = $destfullentry;
							$LIFO_index++;
							$LIFO_queue[$LIFO_index] =& $filelist;
							$emptydirectories = false;
							break;
						}
					}
				}
				if (true === $emptydirectories) {
					unset($LIFO_queue[$LIFO_index]['directories']);
					$LIFO_index--;
					$sourcedir = dirname($sourcedir);
					$destdir = dirname($destdir);
					if ($LIFO_index < 0) {
						unset($LIFO_queue);
						break;
					}
				}
			}
			$returnval = false;
			if (!empty($destdirs_make)) {
				$returnval = FileHandler::mkdir($destdirs_make);
			}
			if (!empty($sourcefiles_copyto)) {
				$returnval = FileHandler::copy($sourcefiles_copyto, $destfiles_copyto);
			}
			return $returnval;
		} else {
			trigger_error("FileHandler::icopy({$source}): No such file or directory", E_USER_WARNING);
			return false;
		}
	}//end function icopy

	/**
	 * Description 此函数用于解决 is_dir() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 要检测的目录
	 * @return boolean 如果目录存在且为正常的文件则返回 TRUE，否则返回 FALSE。
	 */
	function is_dir($filename)
	{
		if (@is_dir($filename)) {
			return true;
		}
		if (!FileHandler::file_exists($filename)) {
			return false;
		}
		$filename = realpath($filename);
		// 利用了另一个不受安全模式限制的函数 disk_free_space() 如果 $filename 是一个文件，disk_free_space($filename.'/') 将会返回 false
		if (false !== @disk_free_space($filename.'/')) {
			return true;
		}
		return false;
	}//end function is_dir

	/**
	 * Description 此函数用于解决 is_file() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author @dv
	 * @param string 要检测的目录
	 * @return boolean 如果目录存在且为正常的文件则返回 TRUE，否则返回 FALSE。
	 */
	function is_file($filename)
	{
		if (@is_file($filename)) {
			return true;
		}
		if (!FileHandler::file_exists($filename)) {
			return false;
		}
		$filename = realpath($filename);
		// 利用了另一个不受安全模式限制的函数 disk_free_space() 如果 $filename 是一个文件，disk_free_space($filename.'/') 将会返回 false
		if (false === @disk_free_space($filename.'/')) {
			return true;
		}
		return false;
	}//end function is_file

	/**
	 * Description 检测目标文件是否是通过 HTTP POST 提交过来的文件，此函数与安全模式是否受限制无关，仅提供版本兼容性
	 * @author @dv
	 * @param string 要检测的文件名
	 * @return boolean 如果成功返回TRUE，否则返回FALSE
	 */
	function is_uploaded_file($filename)
	{
		if( function_exists('is_uploaded_file') ){
			return is_uploaded_file($filename);
		} else{
			if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
				$tmp_file = dirname(tempnam('', ''));
			}
			$tmp_file .= '/' . basename($filename);
			/* User might have trailing slash in php.ini... */
			return (ereg_replace('/+', '/', $tmp_file) == $filename);
		}
	}//end function is_uploaded_file

	/**
	 * Description 检测目标文件或目录是否可以写入，此函数已将安全模式限制的因素考虑进去了，并且，支持对目录的检测。(直到 PHP5 或更高版本，系统函数 is_writable() 才支持对目录的检测)
	 * @author @dv
	 * @param string 要检测的文件或目录
	 * @return boolean 如果要检测的文件或目录可写则返回 TRUE ，否则返回 FALSE 。
	 */
	function is_writable($filename)
	{
		$filename = realpath($filename);
		if (false === $filename) { // $filename 不存在————既不是目录也不是文件
			return false;
		}
		$issmr = FileHandler::_is_safe_mode_restriction($filename, false);
		if (false === $issmr) {
			if (version_compare(PHP_VERSION, '4.4.2') >= 0 OR is_file($filename)) {
				return is_writable($filename);
			} else { // 这是一个目录
				$testfile = "{$filename}/".md5(uniqid(rand(), true));
				if (@touch($testfile)) {
					@unlink($testfile);
					return true;
				}
			}
			return false;
		} else {
			$filename = str_replace(array('\\', '//'), '/', $filename);
			$execcode = <<<EOT
				if (version_compare(PHP_VERSION, '4.4.2') >= 0 OR is_file('{$filename}')) {
					\$iswritable = is_writable('{$filename}');
				} else { // 这是一个目录
					\$testfile = "{$filename}/".md5(uniqid(rand(), true));
					if (@touch(\$testfile)) {
						@unlink(\$testfile);
						\$iswritable = true;
					}
				}
				if (true === \$iswritable) {
					print 1;
				} else {
					print 0;
				}
EOT;
			$execresult = @FileHandler::_exec($execcode);
			if (1 == $execresult) {
				return true;
			} else {
				return false;
			}
		}
	}//end function is_writable

	/**
	 * Description 此函数用于解决 mkdir() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 要创建的目录
	 * @param int 指定目录创建成功后，要改变的文件属性模式
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function mkdir($pathname, $mode = 0777)
	{
		$arrpathname = $arrmode = array();
		if (!is_array($pathname)) {
			$arrpathname[0] =& $pathname;
		} else {
			$arrpathname =& $pathname;
		}
		if (!is_array($mode)) {
			$arrmode[0] =& $mode;
		} else {
			$arrmode =& $mode;
		}
		$defaultmode = ($arrmode[0] > 0 ? $arrmode[0] : 0777);

		$returnval = false;
		$execcode = '';
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		foreach ($arrpathname AS $index => $currpath) {
			if ($parentdir = realpath(dirname($currpath))) {
				$currpath = $parentdir.'/'.basename($currpath);
			}
			$currmode = (isset($arrmode[$index]) ? $arrmode[$index] : $defaultmode);
			if (mkdir($currpath, $currmode)) {
				$returnval = true;
				@chmod($currpath, $currmode);
			} elseif ($_THIS->_errinfo['is_safe_mode_restriction']) {
				$currpath = str_replace(array('\\', '//'), '/', $currpath);
				$execcode .= "if(mkdir('{$currpath}', {$currmode})){@chmod('{$currpath}', {$currmode});print 1;}\r\n";
			}
			$_THIS->_initialize();
		}//end foreach
		restore_error_handler();
		$_THIS->_dispose();
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function mkdir


	/**
	 * Description 此函数用于解决 move_uploaded_file() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 上传文件的文件名
	 * @param string 目标文件
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */ 
	function move_uploaded_file($filename, $destination)
	{
		 $tmpfilesmove = $arrsrc = $arrdest = array();
		 if (!is_array($filename)) {
			 $arrsrc[0] =& $filename;
		 } else {
		 	$arrsrc =& $filename;
		 }
		 if (!is_array($destination)) {
			 $arrdest[0] =& $destination;
		 } else {
		 	$arrdest =& $destination;
		 }
		 if (count($arrsrc) != count($arrdest)) {
			 trigger_error('Wrong parameter count for move_uploaded_file()', E_USER_WARNING);
			 return false;
		 }
		 $returnval = '';
		 $writabledir = FileHandler::find_writable_dir();
		 foreach ($arrsrc AS $index => $currsrc) {
			 if (false === ($currsrc = realpath($currsrc))) {
				 continue;
			 }
			 if (FileHandler::is_uploaded_file($currsrc)) {
				 $currdest = $arrdest[$index];
				 $parentdir = realpath(dirname($currdest));
				 if (false === $parentdir) {
					 continue;
				 }
				 $basename = basename($currdest);
				 $currdest = $parentdir.'/'.$basename;
				 $issmr = FileHandler::_is_safe_mode_restriction($currdest);
				 if (false === $issmr) {
					 if (move_uploaded_file($currsrc, $currdest)) {
						 $returnval = true;
					 } else {
					 	trigger_error("Cannot move uploaded file {$currsrc} to {$currdest}", E_USER_WARNING);
					 }
				 } elseif (true === $issmr) {
					 if (empty($writabledir)) {
					 	trigger_error("Cannot find writable directory.", E_USER_WARNING);
						 continue;
					 }
					 $tmpfile = $writabledir.'/__dv_tmp_uploadedfile__'.$basename;
					 if (!move_uploaded_file($currsrc, $tmpfile)) {
						 trigger_error("Cannot move uploaded file {$currsrc} to temp {$tmpfile}", E_USER_WARNING);
						 continue;
					 }
					 $renamelist_src[] = $tmpfile;
					 $renamelist_dest[] = $currdest;
				 } else {
					trigger_error("Cannot move uploaded file {$currsrc} to {$currdest} cause unknown", E_USER_WARNING);
				 	continue;
				 }
			 }
		 }//end foreach
		 if (!empty($renamelist_src) AND !empty($renamelist_dest)) {
			 if (FileHandler::rename($renamelist_src, $renamelist_dest)) {
				 $returnval = true;
			 }
		 }
		 return $returnval;
	}//end function move_uploaded_file

	function pathinfo($path)
	{
		if (function_exists('pathinfo')) {
			return pathinfo($path);
		} else {
			$returnval = array('dirname'=>dirname($path), 'basename'=>basename($path));
			$extension = str_replace('.', '', strrchr($returnval['basename'], '.'));
			if ($extension) {
				$returnval['extension'] = $extension;
			}
			return $returnval;
		}
	}//end function pathinfo

	function realpath($path)
	{
		settype($path, 'string');
		if ('' === $path) {
			return false;
		}
		static $st_cache = array();
		if (!isset($st_cache[$path])) {
			$st_cache[$path] = realpath($path);
			!empty($st_cache[$path]) AND ($st_cache[$path] = str_replace(array('\\', '//'), '/', $st_cache[$path]));
		}
		return $st_cache[$path];
	}//end function realpath

	/**
	 * Description 递归删除目录，并根据选项$opts进行有选择地删除————使用循环代替传统的递归算法，速度更快更高效。(暂时不完全支持安全模式下删除)
	 * @author xiaodu@dv
	 * @param string 目标目录
	 * @param int 删除选项，允许的值为0,1,2,3
	 * @return array 如果目标目录不存在，或不可写，则返回FALSE，否则，返回一个有四个元素的键值数组；分别表示：subdircount 键表示子文件夹的总数、subdirremovednum 键表示已成功删除的子文件夹的总数、subfilecount 键表示子文件的总数、subfileremovednum 键表示已成功删除的子文件的总数
	 */
	function recursion_removedir($destdir, $rmopts = 0)
	{
		if ($rmopts < 0 OR $rmopts > 3) {
			$rmopts = 0;
		}
		if ($rmopts == 0) { // 全部删除
			$rmself = true;
			$rmsubfile = true;
			$rmsubdir = true;
		} elseif ($rmopts == 1) { // 只删除所有子文件
			$rmself = false;
			$rmsubfile = true;
			$rmsubdir = false;
		} elseif ($rmopts == 2) { // 只删除所有子文件夹
			$rmself = false;
			$rmsubfile = false;
			$rmsubdir = true;
		} elseif ($rmopts == 3) { // 只删除所有子文件和文件夹
			$rmself = false;
			$rmsubfile = true;
			$rmsubdir = true;
		}
		if (false === $rmself AND false === $rmsubfile AND false === $rmsubdir) {
			return false;
		}

		$olddestdir = $destdir = realpath($destdir);
		if ((false === $destdir)) {
			trigger_error("FileHandler::recursion_removedir(): No such directory ", E_USER_WARNING);
			return false;
		}

		$subdircount = 0;
		$subdirremovednum = 0;
		$subfilecount = 0;
		$subfileremovednum = 0;
		$LIFO_queue = array();
		if ($filelist =& FileHandler::scandir($destdir)) {
			$LIFO_index = 0;
			$LIFO_queue[0] =& $filelist;
			$file_removelist = $dir_removelist = array();
			while ($LIFO_index >= 0) {
				if (isset($LIFO_queue[$LIFO_index]['files'])) {
					$subfilecount += count($LIFO_queue[$LIFO_index]['files']);
					if (true === $rmsubfile) {
						foreach ($LIFO_queue[$LIFO_index]['files'] AS $entry) {
							$file_removelist[] = $destdir.'/'.$entry;
						}
					}
					unset($LIFO_queue[$LIFO_index]['files']);
				}
				$emptydirectories = true;
				if (isset($LIFO_queue[$LIFO_index]['directories'])) {
					if ($count = count($LIFO_queue[$LIFO_index]['directories'])) {
						$subdircount += $count - 2;
					}
					foreach ($LIFO_queue[$LIFO_index]['directories'] AS $index => $entry) {
						unset($LIFO_queue[$LIFO_index]['directories'][$index]);
						if ($entry == '.' OR $entry == '..') {
							continue;
						}
						$currdirrealpath = $destdir.'/'.$entry;
						if (true === $rmsubdir) {
							$dir_removelist[] = $currdirrealpath;
						}
						if ($filelist =& FileHandler::scandir($currdirrealpath)) {
							$destdir = $currdirrealpath;
							$LIFO_index++;
							$LIFO_queue[$LIFO_index] =& $filelist;
							$emptydirectories = false;
							break;
						}
					}
				}
				if (true === $emptydirectories) {
					unset($LIFO_queue[$LIFO_index]['directories']);
					$LIFO_index--;
					$destdir = dirname($destdir);
					if ($LIFO_index < 0) {
						unset($LIFO_queue);
						break;
					}
				}
			}
			$total = 0;
			if (!empty($file_removelist) AND is_array($file_removelist)) {
				@FileHandler::unlink($file_removelist, $total, $subfileremovednum);
			}
			if (!empty($dir_removelist) AND is_array($dir_removelist)) {
				if (true === $rmself) {
					$dir_removelist[] = $olddestdir;
				}
				@FileHandler::rmdir($dir_removelist, $total, $subdirremovednum);
			}
		}
		return array('subdircount' => $subdircount, 'subdirremovednum' => $subdirremovednum, 'subfilecount' => $subfilecount, 'subfileremovednum' => $subfileremovednum);
	}//end function recursion_rmdir

	/**
	 * Description 此函数用于解决 rename() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author xiaodu@dv
	 * @param string 原文件名
	 * @param string 新的文件名
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function rename($oldname, $newname)
	{
		$cleanuponerror = $cleanuponsuc = $arroldname = $arrnewname = array();
		if (!is_array($oldname)) {
			$arroldname[0] =& $oldname;
		} else {
			$arroldname =& $oldname;
		}
		if (!is_array($newname)) {
			$arrnewname[0] =& $newname;
		}else {
			$arrnewname =& $newname;
		}
		if (count($arroldname) != count($arrnewname)) {
			trigger_error('Wrong parameter count for rename() ', E_USER_ERROR);
			return false;
		}


		static $writabledir;
		static $myuid;
		if (!isset($writabledir)) {
			$writabledir = FileHandler::find_writable_dir();
			$myuid = @FileHandler::getmyuid();
		}

		$returnval = true;
		$execcode = $execcodeonsuc = $execcodeonerror = '';
		function_exists('ini_set') AND @ini_set('track_errors', 1);
		global $php_errormsg;
		foreach ($arroldname AS $index => $curr_oldname) {
			if (false === ($curr_oldname = realpath($curr_oldname))) {
				trigger_error("No such file or directory {$arroldname[$index]}.", E_USER_WARNING);
				continue;
			}
			$curr_newname = $arrnewname[$index];
			$new_parentdir = dirname($curr_newname);
			$new_basename = basename($curr_newname);
			if (false === ($new_parentdir = realpath($new_parentdir))) {
				trigger_error("No such parent directory {$new_parentdir}.", E_USER_WARNING);
				continue;
			}
			$curr_newname = $new_parentdir.'/'.$new_basename;

			$old_isdir = FileHandler::is_dir($curr_oldname);
			if ($old_isdir) {
				trigger_error("FileHandler::rename(): Directory is not supported at version 1.0 beta.",E_USER_WARNING);
				continue;
			}
			$new_isfile = FileHandler::is_file($curr_newname);
			if ($old_isdir AND $new_isfile) { // 只允许在文件与文件之间，目录与目录之间进行操作
				trigger_error("{$curr_newname} is not a directory.",E_USER_WARNING);
				continue;
			}
			$old_isfile = !$old_isdir;
			$new_isdir = (realpath($curr_newname) ? !$new_isfile : FileHandler::is_dir($curr_newname));
			if ($old_isfile AND $new_isdir) { // 只允许在文件与文件之间，目录与目录之间进行操作
				trigger_error("{$curr_newname} is not file.",E_USER_WARNING);
				continue;
			}

			$old_issmr = FileHandler::_is_safe_mode_restriction($curr_oldname);
			$new_issmr = FileHandler::_is_safe_mode_restriction($curr_newname);
			if (!is_bool($old_issmr) AND !is_bool($new_issmr)) {
				continue;
			} elseif (false === $old_issmr AND false === $new_issmr) {
				if (!rename($curr_oldname, $curr_newname)) {
					trigger_error($php_errormsg, E_USER_WARNING);
					$returnval = false;
				}
			} elseif (true === $old_issmr AND true === $new_issmr) {
				$curr_oldname = str_replace(array('\\', '//'), '/', $curr_oldname);
				$curr_newname = str_replace(array('\\', '//'), '/', $curr_newname);
				$execcode .= "if(rename('{$curr_oldname}', '$curr_newname')){print 1;}";
			} else {
				if (empty($writabledir)) {
					trigger_error('Cannot find writable directory for owner '.$myuid.'.', E_USER_WARNING);
					continue;
				}
				if ($old_isfile) {
					if (true === $old_issmr AND false === $new_issmr) { // $curr_oldname 被安全模式限制 $curr_newname 不受安全模式限制
						$tmpfile = realpath(tempnam($writabledir, '__dv_tmpfile__'));
						if (false === $tmpfile) {
							continue;
						}
						if (file_exists($curr_newname) AND !copy($curr_newname, $tmpfile)) {
							unlink($tmpfile);
							continue;
						}
						chmod($tmpfile, 0755);
						$curr_oldname = str_replace(array('\\', '//'), '/', $curr_oldname);
						$tmpfile = str_replace(array('\\', '//'), '/', $tmpfile);
						$execcode .= "if(rename('{$curr_oldname}', '{$tmpfile}')){print 1;}";
						$cleanuponsuc[] = array('rename', array($tmpfile, $curr_newname));
						$execcodeonerror .= "rename('{$tmpfile}', '{$curr_oldname}')";
						$cleanuponerror[] = array('unlink', array($tmpfile));
					} elseif (false === $old_issmr AND true === $new_issmr) { // $curr_newname 被安全模式限制 $curr_oldname 不受安全模式限制
						$tmpfile = realpath(tempnam($writabledir, '__dv_tmpfile_'.rand(1, strtotime('now')).'__'));
						if (false === $tmpfile) {
							continue;
						}
						if (false === copy($curr_oldname, $tmpfile)) {
							unlink($tmpfile);
							continue;
						}
						$curr_newname = str_replace(array('\\', '//'), '/', $curr_newname);
						$tmpfile = str_replace(array('\\', '//'), '/', $tmpfile);
						$execcode .= "if(rename('{$tmpfile}', '{$curr_newname}')){print 1;}";
						$cleanuponsuc[] = array('unlink', array($curr_oldname));
						$cleanuponerror[] = array('unlink', array($tmpfile));
					} else {
						continue;
					}
				} elseif ($old_isdir) { // 暂不提供对文件夹的 rename 支持
					//Not supported
				} else {
					//Nothing to do
				}
			}
		}//end foreach

		if (!empty($execcode)) {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
				if (!empty($cleanuponsuc)) {
					foreach ($cleanuponsuc AS $val) {
						@call_user_func_array($val[0], $val[1]);
					}//end foreach
				}
			} else {
				$returnval = false;
				if (!empty($execcodeonerror)) {
					@FileHandler::_exec($execcodeonerror);
				}
				if (!empty($cleanuponerror)) {
					foreach ($cleanuponerror AS $val) {
						@call_user_func_array($val[0], $val[1]);
					}//end foreach
				}
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function rename

	/**
	 * Description 删除文件或目录；支持删除子目录和子文件
	 * @author @dv
	 * @param string 要在其上执行操作的文件或目录
	 * @param array 删除选项
	 * @return boolean 如果允许文件操作，返回TRUE，否则返回 FALSE。
	 */
	function remove($destpath, $opts = array())
	{
		//Start 选项设置初始化
			//Start 递归删除目录选项
				if (!isset($opts['recursion'])) {
					$opts['recursion'] = true;
				} else {
					$opts['recursion'] = false;
				}
			//End 递归删除目录选项
		//End 选项设置初始化
		$file_removelist = $dir_removelist = $arrdestpath = array();
		if (!is_array($destpath)) {
			$arrdestpath[0] =& $destpath;
		} else {
			$arrdestpath =& $destpath;
		}
		$returnval = false;
		foreach ($arrdestpath AS $currdestpath) {
			if (false === ($currdestpath = realpath($currdestpath))) {
				continue;
			} elseif (FileHandler::is_dir($currdestpath)) {
				if (false === $opts['recursion']) {
					$dir_removelist[] = $currdestpath;
				} else {
					if (FileHandler::recursion_removedir($currdestpath)) {
						$returnval = true;
					}
				}
			} else {
				$file_removelist[] = $currdestpath;
			}
		}//end foreach
		if (!empty($file_removelist)) {
			if (FileHandler::unlink($file_removelist)) {
				$returnval = true;
			}
		}
		if (!empty($dir_removelist)) {
			if (FileHandler::rmdir($dir_removelist)) {
				$returnval = true;
			}
		}
		return $returnval;
	}//end function remove

	/**
	 * Description 此函数用于解决 rmdir() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author @dv
	 * @param string 原文件名
	 * @param string 新的文件名
	 * @param string 具有0777属性的目录，该目录必须和当前脚本具有相同UID的，并且可以通过http访问该目录
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function rmdir($destdir)
	{
		if (!is_array($destdir)) {
			$arrdest[0] = $destdir;
		} else {
			$arrdest =& $destdir;
			arsort($arrdest);
		}
		$returnval = false;
		$execcode = '';
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		foreach ($arrdest AS $rmdestdir) {
			if ( false === ($rmdestdir = realpath($rmdestdir))) {
				continue;
			}
			if (rmdir($rmdestdir)) {
				$returnval = true;
			} elseif ($_THIS->_errinfo['is_safe_mode_restriction']) {
				$rmdestdir = str_replace(array('\\', '//'), '/', $rmdestdir);
				$execcode .= "if (@rmdir('{$rmdestdir}')) {print 1;}\r\n";
			}
		}//end foreach
		restore_error_handler();
		$_THIS->_dispose();
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function rmdir

	/**
	 * Description 列出指定路径中的文件和目录。
	 * @author @dv
	 * @param string 目标目录
	 * @return array 返回一个 array，包含有 directory 中的文件和目录。如果 directory 不是一个目录，则返回布尔值 FALSE，并产生一条 E_WARNING 级别的错误
	 */
	function &scandir($directory)
	{
		$returnval = false;
		if (false === ($directory = realpath($directory))) {
			return $returnval;
		}
		if (!FileHandler::is_dir($directory)) {
			trigger_error("FileHandler::scandir({$directory}): No suche directory.", E_WARNING);
			return $returnval;
		}
		if (false === FileHandler::_is_safe_mode_restriction($directory)) {
			if ($res_dir = dir($directory)) {
				$returnval = array();
				while (false !== ($entry = $res_dir->read())) {
					$fullentry = $res_dir->path.'/'.$entry;
					if (is_file($fullentry)) {
						$returnval['files'][] = $entry;
					} elseif (is_dir($fullentry)) {
						$returnval['directories'][] = $entry;
					}
				}
				$res_dir->close();
			}
		} else {
			$writabledir = FileHandler::find_writable_dir();
			if (empty($writabledir)) {
				return $returnval;
			}
			$directory = str_replace(array('\\', '//'), '/', $directory);
			$execcode = <<<EOT
				if (\$res_dir = @dir('{$directory}')) {
					\$returnval = array();
					while (false !== (\$entry = \$res_dir->read())) {
						\$fullentry = \$res_dir->path.'/'.\$entry;
						if (is_file(\$fullentry)) {
							\$returnval['files'][] = \$entry;
						} elseif (is_dir(\$fullentry)) {
							\$returnval['directories'][] = \$entry;
						}
					}
					\$res_dir->close();
					print serialize(\$returnval);
				}
EOT;
			if ($execresult = FileHandler::_exec($execcode)) {
				$returnval = @unserialize(stripslashes($execresult));
			}
			if (!$returnval) {
				trigger_error("FileHandler::scandir({$directory}): {$execresult}", E_USER_WARNING);
			}
		}
		return $returnval;
	}

	/**
	 * Description 此函数用于解决 touch() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author @dv
	 * @param string 原文件名
	 * @param string 新的文件名
	 * @return boolean 将文件从 source 拷贝到 dest。如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function touch($filename)
	{
		$numargs = func_num_args();
		if ($numargs > 3) {
			trigger_error('Wrong parameter count for touch() ', E_USER_ERROR);
			return false;
		}
		$args1 = $args2 = $args3 = array();
		if (!is_array($filename)) {
			$args1[0] =& $filename;
		} else {
			$args1 =& $filename;
		}
		if ($numargs >= 2) {
			$arg2 = func_get_arg(1);
			if (!is_array($arg2)) {
				$args2[0] = $arg2;
			} else {
				$args2 =& $arg2;
			}
		}
		if (3 === $numargs) {
			$arg3 = func_get_arg(2);
			if (!is_array($arg3)) {
				$args3[0] = $arg3;
			} else {
				$args3 =& $arg3;
			}
		}

		$returnval = false;
		$execcode = '';
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		foreach ($args1 AS $index => $arg1) {
			if (false === ($parentdir = realpath(dirname($arg1)))) {
				continue;
			}
			$arg1 = $parentdir.'/'.basename($arg1);
			$currargs = array(0=>&$arg1);
			if ($numargs >= 2 AND isset($args2[$index])) {
				$currargs[1] =& $args2[$index];
			}
			if (3 === $numargs AND isset($args3[$index])) {
				$currargs[2] =& $args3[$index];
			}
			if (call_user_func_array('touch', $currargs)) {
				$returnval = true;
			} elseif ($_THIS->_errinfo['is_safe_mode_restriction']) {
				$execcode .= "if(@call_user_func_array('touch',".FileHandler::_var_export($currargs, true).")){print 1;}\r\n";
			}
			$_THIS->_initialize();
		}//end foreach
		restore_error_handler();
		$_THIS->_dispose();
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function touch

	/**
	 * Description 此函数用于解决 unlink() 在安全模式下受限制的问题。只要被操作的文件或目录，其UID与脚本UID或者运行时UID相同，就可以在安全模式下不受限制的运行。
	 * @author @dv
	 * @param string 目标文件名
	 * @return boolean 如果成功则返回 TRUE，失败则返回 FALSE。
	 */
	function unlink($destfile)
	{
		$arrdestfile = array();
		if (!is_array($destfile)) {
			$arrdestfile[0] =& $destfile;
		} else {
			$arrdestfile =& $destfile;
			arsort($arrdestfile);
		}

		$returnval = false;
		$execcode = '';
		$_THIS =& FileHandler::create_instance();
		set_error_handler(array(&$_THIS, '_error_handler'));
		foreach ($arrdestfile AS $index => $currfile) {
			if (false === ($currfile = realpath($currfile))) {
				continue;
			}
			if (unlink($currfile)) {
				$returnval = true;
			} elseif ($_THIS->_errinfo['is_safe_mode_restriction']) {
				$currfile = str_replace(array('\\', '//'), '/', $currfile);
				$execcode .= "if (@unlink('$currfile')) {print 1;}\r\n";
			}
			$_THIS->_initialize();
		}//end foreach
		restore_error_handler();
		$_THIS->_dispose();
		if ($execcode !== '') {
			$execresult = FileHandler::_exec($execcode);
			$tmplower = strtolower($execresult);
			if (false === strpos($tmplower, 'warning:') OR false === strpos($tmplower, 'on line')) {
				$returnval = true;
			} else {
				trigger_error($execresult, E_USER_WARNING);
			}
		}
		return $returnval;
	}//end function unlink
}// end class FileHandler
?>