Просмотр файла contrib/template_file_cache.php

Размер файла: 11.14Kb
<?php
/***************************************************************************
 *                              template.php
 *                            -------------------
 *      Разработка: phpBB Group.
 *      Оптимизация под WAP: Гутник Игорь ( чел ).
 *          2007 год
 ***************************************************************************/

class Template {
	var $classname = 'Template';

	// variable that holds all the data we'll be substituting into
	// the compiled templates.
	var $_tpldata = array();

	// Hash of filenames for each template handle.
	var $files = array();

	// Root template directories
	var $cache_root = 'cache/';
	var $root = '';

	// this will hash handle names to the compiled code for that handle.
	var $compiled_code = array();

	// This will hold the uncompiled code for that handle.
	var $uncompiled_code = array();

	/**
	 * Constructor. Simply sets the root dir.
	 *
	 */
	function Template($root = '.')
	{
		global $board_config, $db;

		$this->set_rootdir($root);
		$this->db = $db;
	}

	function destroy()
	{
		$this->_tpldata = array();
	}

	function set_rootdir($dir)
	{
		global $phpbb_root_path;

		if (is_file($dir) || is_link($dir))
		{
			return false;
		}

		$this->root = phpbb_realpath($dir);
		$this->cachedir = phpbb_realpath($phpbb_root_path . $this->cache_root) . substr($dir, strrpos($dir, '/')) . '/';

		if (!file_exists($this->cachedir . 'admin/'))
		{
			@umask(0);
			if (!file_exists($this->cachedir))
			{
				mkdir($this->cachedir, 0777);
			}
			mkdir($this->cachedir . 'admin/', 0777);
		}

		return true;
	}

	function set_filenames($filename_array)
	{
		if (!is_array($filename_array))
		{
			return false;
		}

		$template_names = '';
		@reset($filename_array);
		while (list($handle, $filename) = @each($filename_array))
		{
			$this->filename[$handle] = $filename;
			$this->files[$handle] = $this->make_filename($filename);
		}

		return true;
	}

	function pparse($handle)
	{
		global $phpEx;

		$cache_file = $this->cachedir . $this->filename[$handle] . '.' . $phpEx;

		if(@filemtime($cache_file) == @filemtime($this->files[$handle]))
		{
			$_str = '';
			include($cache_file);

			if ($_str != '')
			{
				echo $_str;
			}
		}
		else 
		{
			if (!$this->loadfile($handle))
			{
				die("Template->pparse(): Couldn't load template file for handle $handle");
			}

			// Actually compile the code now.
			$this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);

			$fp = fopen($cache_file, 'w+');
			fwrite ($fp, '<?php' . "\n" . $this->compiled_code[$handle] . "\n?" . '>');
			fclose($fp);

			touch($cache_file, filemtime($this->files[$handle]));
			@chmod($cache_file, 0777);

			eval($this->compiled_code[$handle]);
		}
	
		return true;
	}

	function assign_var_from_handle($varname, $handle)
	{
		global $phpEx;

		$cache_file = $this->cachedir . $this->filename[$handle] . '.' . $phpEx;

		if(@filemtime($cache_file) == @filemtime($this->files[$handle]))
		{
			$_str = '';
			include($cache_file);
		}
		else 
		{
			if (!$this->loadfile($handle))
			{
				die("Template->pparse(): Couldn't load template file for handle $handle");
			}

			$code = $this->compile($this->uncompiled_code[$handle], true, '_str');

			$fp = fopen($cache_file, 'w+');
			fwrite ($fp, '<?php' . "\n" . $code . "\n?" . '>');
			fclose($fp);

			touch($cache_file, filemtime($this->files[$handle]));
			@chmod($cache_file, 0777);

			// Compile It, With The "no Echo Statements" Option On.
			$_str = '';
			// evaluate the variable assignment.
			eval($code);
		
		}

		// assign the value of the generated variable to the given varname.
		$this->assign_var($varname, $_str);

		return true;
	}

	function assign_block_vars($blockname, $vararray)
	{
		if (strstr($blockname, '.'))
		{
			// Nested block.
			$blocks = explode('.', $blockname);
			$blockcount = sizeof($blocks) - 1;

			$str = &$this->_tpldata; 
			for ($i = 0; $i < $blockcount; $i++) 
			{
				$str = &$str[$blocks[$i]]; 
				$str = &$str[sizeof($str) - 1]; 
			} 

			$str[$blocks[$blockcount]][] = $vararray;
		}
		else
		{

			$this->_tpldata[$blockname][] = $vararray;
		}

		return true;
	}

	function assign_vars($vararray)
	{
		reset ($vararray);
		while (list($key, $val) = each($vararray))
		{
			$this->_tpldata['.'][0][$key] = $val;
		}

		return true;
	}

	function assign_var($varname, $varval)
	{
		$this->_tpldata['.'][0][$varname] = $varval;

		return true;
	}

	function make_filename($filename)
	{
		// Check if it's an absolute or relative path.
		if (substr($filename, 0, 1) != '/')
		{
			$filename = phpbb_realpath($this->root . '/' . $filename);
		}

		if (!file_exists($filename))
		{
			die("Template->make_filename(): Error - file $filename does not exist");
		}

		return $filename;
	}

	function loadfile($handle)
	{
		// If the file for this handle is already loaded and compiled, do nothing.
		if (!empty($this->uncompiled_code[$handle]))
		{
			return true;
		}

		// If we don't have a file assigned to this handle, die.
		if (!isset($this->files[$handle]))
		{
			die("Template->loadfile(): No file specified for handle $handle");
		}

		$filename = $this->files[$handle];

		$str = implode('', @file($filename));
		if (empty($str))
		{
			die("Template->loadfile(): File $filename for handle $handle is empty");
		}

		$this->uncompiled_code[$handle] = $str;

		return true;
	}

	function compile($code, $do_not_echo = false, $retvar = '')
	{
		$concat = (!$do_not_echo) ? ',' : '.';

		// replace \ with \\ and then ' with \'.
		$code = str_replace('\\', '\\\\', $code);
		$code = str_replace('\'', '\\\'', $code);

		// change template varrefs into PHP varrefs

		// This one will handle varrefs WITH namespaces
		$varrefs = array();
		preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
		$varcount = sizeof($varrefs[1]);
		for ($i = 0; $i < $varcount; $i++)
		{
			$namespace = $varrefs[1][$i];
			$varname = $varrefs[3][$i];
			$new = $this->generate_block_varref($namespace, $varname, $concat);

			$code = str_replace($varrefs[0][$i], $new, $code);
		}

		// This will handle the remaining root-level varrefs
		$code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' $concat ((isset(\$this->_tpldata['.'][0]['\\1'])) ? \$this->_tpldata['.'][0]['\\1'] : '') $concat '", $code);

		// Break it up into lines.
		$code_lines = explode("\n", $code);

		$block_nesting_level = 0;
		$block_names = array();
		$block_names[0] = '.';

		// Second: prepend echo ', append ' . "\n"; to each line.
		$line_count = sizeof($code_lines);
		for ($i = 0; $i < $line_count; $i++)
		{
			$code_lines[$i] = chop($code_lines[$i]);
			if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
			{
				$n[0] = $m[0];
				$n[1] = $m[1];

				// Added: dougk_ff7-Keeps templates from bombing if begin is on the same line as end.. I think. :)
				if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n))
				{
					$block_nesting_level++;
					$block_names[$block_nesting_level] = $m[1];
					if ($block_nesting_level < 2)
					{
						// Block is not nested.
						$code_lines[$i] = '$_' . $a[1] . '_count = (isset($this->_tpldata[\'' . $n[1] . '\'])) ?  sizeof($this->_tpldata[\'' . $n[1] . '\']) : 0;';
						$code_lines[$i] .= 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
						$code_lines[$i] .= '{';
					}
					else
					{
						// This block is nested.

						// Generate a namespace string for this block.
						$namespace = substr(implode('.', $block_names), 0, -1);
						// strip leading period from root level..
						$namespace = substr($namespace, 2);
						// Get a reference to the data array for this block that depends on the
						// current indices of all parent blocks.
						$varref = $this->generate_block_data_ref($namespace, false);
						// Create the for loop code to iterate over this block.
						$code_lines[$i] = '$_' . $a[1] . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
						$code_lines[$i] .= 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
						$code_lines[$i] .= '{';
					}

					// We have the end of a block.
					unset($block_names[$block_nesting_level]);
					$block_nesting_level--;
					$code_lines[$i] .= '} // END ' . $n[1];
					$m[0] = $n[0];
					$m[1] = $n[1];
				}
				else
				{
					// We have the start of a block.
					$block_nesting_level++;
					$block_names[$block_nesting_level] = $m[1];
					if ($block_nesting_level < 2)
					{
						// Block is not nested.
						$code_lines[$i] = '$_' . $m[1] . '_count = (isset($this->_tpldata[\'' . $m[1] . '\'])) ? sizeof($this->_tpldata[\'' . $m[1] . '\']) : 0;';
						$code_lines[$i] .= 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
						$code_lines[$i] .= '{';
					}
					else
					{
						// This block is nested.

						// Generate a namespace string for this block.
						$namespace = implode('.', $block_names);
						// strip leading period from root level..
						$namespace = substr($namespace, 2);
						// Get a reference to the data array for this block that depends on the
						// current indices of all parent blocks.
						$varref = $this->generate_block_data_ref($namespace, false);
						// Create the for loop code to iterate over this block.
						$code_lines[$i] = '$_' . $m[1] . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
						$code_lines[$i] .= 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
						$code_lines[$i] .= '{';
					}
				}
			}
			else if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
			{
				// We have the end of a block.
				unset($block_names[$block_nesting_level]);
				$block_nesting_level--;
				$code_lines[$i] = '} // END ' . $m[1];
			}
			else
			{
				// We have an ordinary line of code.
				if (!$do_not_echo)
				{
					$code_lines[$i] = "echo '" . $code_lines[$i] . "\n';\n";
				}
				else
				{
					$code_lines[$i] = '$' . $retvar . ".= '" . $code_lines[$i] . "\n';\n"; 
				}
			}
		}

		// Bring it back into a single string of lines of code.
		$code = implode("\n", $code_lines);
		return $code;
	}

	function generate_block_varref($namespace, $varname, $concat)
	{
		// Strip the trailing period.
		$namespace = substr($namespace, 0, strlen($namespace) - 1);

		// Get a reference to the data block for this namespace.
		$varref = $this->generate_block_data_ref($namespace, true);
		// Prepend the necessary code to stick this in an echo line.

		// Append the variable reference.
		$varref .= "['$varname']";

		$varref = "' $concat ((isset($varref)) ? $varref : '') $concat '";

		return $varref;

	}

	function generate_block_data_ref($blockname, $include_last_iterator)
	{
		// Get an array of the blocks involved.
		$blocks = explode('.', $blockname);
		$blockcount = sizeof($blocks) - 1;
		$varref = '$this->_tpldata';
		// Build up the string with everything but the last child.
		for ($i = 0; $i < $blockcount; $i++)
		{
			$varref .= "['" . $blocks[$i] . "'][\$_" . $blocks[$i] . '_i]';
		}
		// Add the block reference for the last child.
		$varref .= "['" . $blocks[$blockcount] . "']";
		// Add the iterator for the last child if requried.
		if ($include_last_iterator)
		{
			$varref .= '[$_' . $blocks[$blockcount] . '_i]';
		}

		return $varref;
	}

}

?>