/**
 * Loads sub-templates contained in an external file
 * <pre>
 *  * file : the resource name of the file to load
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    2.0
 * @date       2013-09-06
 * @package    Dwoo
 */
function functionLoadTemplatesCompile(Compiler $compiler, $file)
{
    $file = substr($file, 1, -1);
    if ($file === '') {
        return null;
    }
    if (preg_match('#^([a-z]{2,}):(.*)$#i', $file, $m)) {
        // resource:identifier given, extract them
        $resource = $m[1];
        $identifier = $m[2];
    } else {
        // get the current template's resource
        $resource = $compiler->getDwoo()->getTemplate()->getResourceName();
        $identifier = $file;
    }
    $tpl = $compiler->getDwoo()->templateFactory($resource, $identifier);
    if ($tpl === null) {
        throw new CompilationException($compiler, 'Load Templates : Resource "' . $resource . ':' . $identifier . '" not found.');
    } else {
        if ($tpl === false) {
            throw new CompilationException($compiler, 'Load Templates : Resource "' . $resource . '" does not support includes.');
        }
    }
    $cmp = clone $compiler;
    $cmp->compile($compiler->getDwoo(), $tpl);
    foreach ($cmp->getTemplatePlugins() as $template => $args) {
        $compiler->addTemplatePlugin($template, $args['params'], $args['uuid'], $args['body']);
    }
    foreach ($cmp->getUsedPlugins() as $plugin => $type) {
        $compiler->addUsedPlugin($plugin, $type);
    }
    $out = '\'\';// checking for modification in ' . $resource . ':' . $identifier . "\r\n";
    $modCheck = $tpl->getIsModifiedCode();
    if ($modCheck) {
        $out .= 'if (!(' . $modCheck . ')) { ob_end_clean(); return false; }';
    } else {
        $out .= 'try {
	$tpl = $this->templateFactory("' . $resource . '", "' . $identifier . '");
} catch (\\Dwoo\\Exception $e) {
	$this->triggerError(\'Load Templates : Resource <em>' . $resource . '</em> was not added to Dwoo, can not extend <em>' . $identifier . '</em>\', E_USER_WARNING);
}
if ($tpl === null)
	$this->triggerError(\'Load Templates : Resource "' . $resource . ':' . $identifier . '" was not found.\', E_USER_WARNING);
elseif ($tpl === false)
	$this->triggerError(\'Load Templates : Resource "' . $resource . '" does not support extends.\', E_USER_WARNING);
if ($tpl->getUid() != "' . $tpl->getUid() . '") { ob_end_clean(); return false; }';
    }
    return $out;
}
/**
 * Checks whether an extended file has been modified, and if so recompiles the current template. This is for internal use only, do not use.
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    2.0
 * @date       2013-09-01
 * @package    Dwoo
 */
function functionExtendsCheckCompile(Compiler $compiler, $file)
{
    preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m);
    $resource = $m[1];
    $identifier = $m[2];
    $tpl = $compiler->getDwoo()->templateFactory($resource, $identifier);
    if ($tpl === null) {
        throw new CompilationException($compiler, 'Load Templates : Resource "' . $resource . ':' . $identifier . '" not found.');
    } elseif ($tpl === false) {
        throw new CompilationException($compiler, 'Load Templates : Resource "' . $resource . '" does not support includes.');
    }
    $out = '\'\';// checking for modification in ' . $resource . ':' . $identifier . "\r\n";
    $modCheck = $tpl->getIsModifiedCode();
    if ($modCheck) {
        $out .= 'if (!(' . $modCheck . ')) { ob_end_clean(); return false; }';
    } else {
        $out .= 'try {
	$tpl = $this->templateFactory("' . $resource . '", "' . $identifier . '");
} catch (\\Dwoo\\Exception $e) {
	$this->triggerError(\'Load Templates : Resource <em>' . $resource . '</em> was not added to Dwoo, can not extend <em>' . $identifier . '</em>\', E_USER_WARNING);
}
if ($tpl === null)
	$this->triggerError(\'Load Templates : Resource "' . $resource . ':' . $identifier . '" was not found.\', E_USER_WARNING);
elseif ($tpl === false)
	$this->triggerError(\'Load Templates : Resource "' . $resource . '" does not support extends.\', E_USER_WARNING);
if ($tpl->getUid() != "' . $tpl->getUid() . '") { ob_end_clean(); return false; }';
    }
    return $out;
}
 public static function preProcessing(Compiler $compiler, array $params, $prepend, $append, $type)
 {
     $params = $compiler->getCompiledParams($params);
     $func = $params['__funcname'];
     $pluginType = $params['__functype'];
     $params = $params['*'];
     if ($pluginType & Core::CUSTOM_PLUGIN) {
         $customPlugins = $compiler->getDwoo()->getCustomPlugins();
         $callback = $customPlugins[$func]['callback'];
         if (is_array($callback)) {
             if (is_object($callback[0])) {
                 $callback = '$this->customPlugins[\'' . $func . '\'][0]->' . $callback[1] . '(';
             } else {
                 $callback = '' . $callback[0] . '::' . $callback[1] . '(';
             }
         } else {
             $callback = $callback . '(';
         }
     } else {
         $callback = 'smarty_block_' . $func . '(';
     }
     $paramsOut = '';
     foreach ($params as $i => $p) {
         $paramsOut .= var_export($i, true) . ' => ' . $p . ',';
     }
     $curBlock =& $compiler->getCurrentBlock();
     $curBlock['params']['postOut'] = Compiler::PHP_OPEN . ' $_block_content = ob_get_clean(); $_block_repeat=false; echo ' . $callback . '$_tag_stack[count($_tag_stack)-1], $_block_content, $this, $_block_repeat); } array_pop($_tag_stack);' . Compiler::PHP_CLOSE;
     return Compiler::PHP_OPEN . $prepend . ' if (!isset($_tag_stack)){ $_tag_stack = array(); } $_tag_stack[] = array(' . $paramsOut . '); $_block_repeat=true; ' . $callback . '$_tag_stack[count($_tag_stack)-1], null, $this, $_block_repeat); while ($_block_repeat) { ob_start();' . Compiler::PHP_CLOSE;
 }
Example #4
0
/**
 * Ternary if operation
 *
 * It evaluates the first argument and returns the second if it's true, or the third if it's false
 * <pre>
 *  * rest : you can not use named parameters to call this, use it either with three arguments in the correct order (expression, true result, false result) or write it as in php (expression ? true result : false result)
 * </pre>
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from the use of this software.
 *
 * @author     Jordi Boggiano <*****@*****.**>
 * @copyright  Copyright (c) 2008, Jordi Boggiano
 * @license    http://dwoo.org/LICENSE   Modified BSD License
 * @link       http://dwoo.org/
 * @version    2.0
 * @date       2013-09-06
 * @package    Dwoo
 */
function functionTifCompile(Compiler $compiler, array $rest, array $tokens)
{
    // load if plugin
    if (!class_exists('\\Dwoo\\Plugins\\Blocks\\BlockIf')) {
        try {
            $compiler->getDwoo()->getLoader()->loadPlugin('if');
        } catch (\Exception $e) {
            throw new CompilationException($compiler, 'Tif: the if plugin is required to use Tif');
        }
    }
    if (count($rest) == 1) {
        return $rest[0];
    }
    // fetch false result and remove the ":" if it was present
    $falseResult = array_pop($rest);
    if (trim(end($rest), '"\'') === ':') {
        // remove the ':' if present
        array_pop($rest);
    } elseif (trim(end($rest), '"\'') === '?' || count($rest) === 1) {
        if ($falseResult === '?' || $falseResult === ':') {
            throw new CompilationException($compiler, 'Tif: incomplete tif statement, value missing after ' . $falseResult);
        }
        // there was in fact no false result provided, so we move it to be the true result instead
        $trueResult = $falseResult;
        $falseResult = "''";
    }
    // fetch true result if needed
    if (!isset($trueResult)) {
        $trueResult = array_pop($rest);
        // no true result provided so we use the expression arg
        if ($trueResult === '?') {
            $trueResult = true;
        }
    }
    // remove the '?' if present
    if (trim(end($rest), '"\'') === '?') {
        array_pop($rest);
    }
    // check params were correctly provided
    if (empty($rest) || $trueResult === null || $falseResult === null) {
        throw new CompilationException($compiler, 'Tif: you must provide three parameters serving as <expression> ? <true value> : <false value>');
    }
    // parse condition
    $condition = BlockIf::replaceKeywords($rest, $tokens, $compiler);
    return '((' . implode(' ', $condition) . ') ? ' . ($trueResult === true ? implode(' ', $condition) : $trueResult) . ' : ' . $falseResult . ')';
}
    public static function compile(Compiler $compiler, $file)
    {
        list($l, $r) = $compiler->getDelimiters();
        self::$l = preg_quote($l, '/');
        self::$r = preg_quote($r, '/');
        self::$regex = '/
			' . self::$l . 'block\\s(["\']?)(.+?)\\1' . self::$r . '(?:\\r?\\n?)
			((?:
				(?R)
				|
				[^' . self::$l . ']*
				(?:
					(?! ' . self::$l . '\\/?block\\b )
					' . self::$l . '
					[^' . self::$l . ']*+
				)*
			)*)
			' . self::$l . '\\/block' . self::$r . '
			/six';
        if ($compiler->getLooseOpeningHandling()) {
            self::$l .= '\\s*';
            self::$r = '\\s*' . self::$r;
        }
        $inheritanceTree = array(array('source' => $compiler->getTemplateSource()));
        //$curPath         = dirname($compiler->getDwoo()->getTemplate()->getResourceIdentifier()) . DIRECTORY_SEPARATOR;
        $curTpl = $compiler->getDwoo()->getTemplate();
        while (!empty($file)) {
            if ($file === '""' || $file === "''" || substr($file, 0, 1) !== '"' && substr($file, 0, 1) !== '\'') {
                throw new CompilationException($compiler, 'Extends : The file name must be a non-empty string');
                return;
            }
            if (preg_match('#^["\']([a-z]{2,}):(.*?)["\']$#i', $file, $m)) {
                // resource:identifier given, extract them
                $resource = $m[1];
                $identifier = $m[2];
            } else {
                // get the current template's resource
                $resource = $curTpl->getResourceName();
                $identifier = substr($file, 1, -1);
            }
            try {
                $parent = $compiler->getDwoo()->templateFactory($resource, $identifier, null, null, null, $curTpl);
            } catch (\Dwoo\Exception\SecurityException $e) {
                throw new CompilationException($compiler, 'Extends : Security restriction : ' . $e->getMessage());
            } catch (\Dwoo\Exception $e) {
                throw new Exception($compiler, 'Extends : ' . $e->getMessage());
            }
            if ($parent === null) {
                throw new CompilationException($compiler, 'Extends : Resource "' . $resource . ':' . $identifier . '" not found.');
            } elseif ($parent === false) {
                throw new CompilationException($compiler, 'Extends : Resource "' . $resource . '" does not support extends.');
            }
            $curTpl = $parent;
            $newParent = array('source' => $parent->getSource(), 'resource' => $resource, 'identifier' => $parent->getResourceIdentifier(), 'uid' => $parent->getUid());
            if (array_search($newParent, $inheritanceTree, true) !== false) {
                throw new CompilationException($compiler, 'Extends : Recursive template inheritance detected');
            }
            $inheritanceTree[] = $newParent;
            if (preg_match('/^' . self::$l . 'extends(?:\\(?\\s*|\\s+)(?:file=)?\\s*((["\']).+?\\2|\\S+?)\\s*\\)?\\s*?' . self::$r . '/i', $parent->getSource(), $match)) {
                $curPath = dirname($identifier) . DIRECTORY_SEPARATOR;
                if (isset($match[2]) && $match[2] == '"') {
                    $file = '"' . str_replace('"', '\\"', substr($match[1], 1, -1)) . '"';
                } elseif (isset($match[2]) && $match[2] == "'") {
                    $file = '"' . substr($match[1], 1, -1) . '"';
                } else {
                    $file = '"' . $match[1] . '"';
                }
            } else {
                $file = false;
            }
        }
        while (true) {
            $parent = array_pop($inheritanceTree);
            $child = end($inheritanceTree);
            self::$childSource = $child['source'];
            self::$lastReplacement = count($inheritanceTree) === 1;
            if (!isset($newSource)) {
                $newSource = $parent['source'];
            }
            $newSource = preg_replace_callback(self::$regex, array(__CLASS__, 'replaceBlock'), $newSource);
            $newSource = $l . 'do extendsCheck(' . var_export($parent['resource'] . ':' . $parent['identifier'], true) . ')' . $r . $newSource;
            if (self::$lastReplacement) {
                break;
            }
        }
        $compiler->setTemplateSource($newSource);
        $compiler->recompile();
    }
 /**
  * @param Compiler $compiler
  * @param int      $message
  */
 public function __construct(Compiler $compiler, $message)
 {
     $this->compiler = $compiler;
     $this->template = $compiler->getDwoo()->getTemplate();
     parent::__construct('Compilation error at line ' . $compiler->getLine() . ' in "' . $this->template->getResourceName() . ':' . $this->template->getResourceIdentifier() . '" : ' . $message);
 }