<?

/*
  模板函数集合 by zain
  文件名：func_template.php
  创建日期：2011.3.7
  更改日期：2011.3.7
 */

//引入模板页
function Template($tplname) {
    global $conf_tplpath;
    $tplname = WEB_TEMPLATE . $conf_tplpath . '/' . $tplname;

    if (strpos($tplname, '.') === false)
        $tplname .= ".html";
    $tplname = Pcv($tplname);
    return getTplName($tplname);
}

/**
 * @param string $tplname
 * @return string
 */
function getTplName($tplname) {
    $cache_name = str_replace(array('template/', '/'), array('', '_'), $tplname);
    $cache_name = Pcv($cache_name);

    $cache_name = WEB_SHTML . "/tpl_cache/" . $cache_name;
    if (!file_exists($cache_name) || filemtime($tplname) > filemtime($cache_name)) {

        $file_str = readover($tplname);

        $s = array(
            "{@", "@}",
            "<!--#", "#-->",
        );
        $e = array(
            "\nEOT;\necho ", ";print <<<EOT\n",
            "\nEOT;\n", "print <<<EOT\n",
        );
        if (function_exists('str_ireplace'))
            $file_str = str_ireplace($s, $e, $file_str);
        else
            $file_str = str_replace($s, $e, $file_str);

        $file = "<?php\n";
        $file .= "print <<<EOT\n$file_str\nEOT;\n?>";
        $file = preg_replace("/print \<\<\<EOT[\n\r]*EOT;/s", "", $file);

        writeover($cache_name, $file);
    }

    return $cache_name;
}

/**
 * @copyright PHPWind
 * @param string $filename
 * @param string $method
 * @return string
 */
function readover($filename, $method = "rb") {
    strpos($filename, '..') !== false && exit('Forbidden');
    if ($handle = @fopen($filename, $method)) {
        flock($handle, LOCK_SH);
        $filedata = fread($handle, filesize($filename));
        fclose($handle);
    }
    return $filedata;
}

/**
 * @copyright PHPWind
 * @param string $filename ?
 * @param string $data ?д
 * @param string $method 
 * @param boolean $iflock ?
 */
function writeover($filename, $data, $method = "rb+", $iflock = 1, $check = 1, $chmod = 1) {
    $check && strpos($filename, '..') !== false && exit('Forbidden');
    touch($filename);
    $handle = fopen($filename, $method);
    $iflock && flock($handle, LOCK_EX);
    if (@fwrite($handle, $data) === FALSE) {
        fclose($handle);
        return false;
    }
    if ($method == "rb+")
        ftruncate($handle, strlen($data));
    fclose($handle);
    $chmod && @chmod($filename, 0777);
    return true;
}

/**
 * @param string $filename
 * @param var $ifcheck
 * @return unknown
 */
function Pcv($filename, $ifcheck = 1) {
    strpos($filename, 'http://') !== false && exit('Forbidden');
    $ifcheck && strpos($filename, '..') !== false && exit('Forbidden');
    return $filename;
}

?>