Get called subtemplates from compiled template and save call count

@param \Smarty_Internal_Template $tpl
16984
public function registerSubTemplates(Smarty_Internal_Template $tpl)
    {
        foreach ($tpl->compiled->includes as $name => $count) {
            if (isset($this->subTplInfo[$name])) {
                $this->subTplInfo[$name] += $count;
            } else {
                $this->subTplInfo[$name] = $count;
            }
        }
    }
4035
public function show($tpl = "")
    {
        if (!empty($tpl)) {
            $this->display($tpl);
        } else {
            $this->display(strtolower($this->apiClassName) .'/'.strtolower($this->action) . '.tpl');
        }
        exit();
    }
561561
public static function getQueryTemplateArray($tpl, array $arguments)
    {
        $argNum = count($arguments);
        for ($i = $argNum; $i > 0; $i--) {
            $tpl = str_replace('%' . $i, $arguments[$i - 1], $tpl);
        }

        return $tpl;
    }
159879
public static function count_templates_parameters() {
        $includes = new external_value(
            PARAM_ALPHA,
            'What other contextes to fetch the frameworks from. (children, parents, self)',
            VALUE_DEFAULT,
            'children'
        );

        $params = array(
            'context' => self::get_context_parameters(),
            'includes' => $includes
        );
        return new external_function_parameters($params);
    }
418672
protected function renderTpl($tpl, $data = array())
    {
        if (!empty($tpl)) {
            extract($data);
            ob_start();
            eval('?>'.$tpl.'<?php ');
            $tpl = ob_get_clean();
        }

        return $tpl;
    }
883592
public function extend($tpl, array $data = [])
    {
        echo $this->render($tpl, array_merge($this->data, $data));
    }
1354054
public function end_compile(Smarty_Internal_Template $template)
    {
        if (!empty($template->compiler->trace_uid)) {
            $key = $template->compiler->trace_uid;
        } else {
            if (isset($this->ignore_uid[$template->source->uid])) {
                return;
            }

            $key = $this->get_key($template);
        }
        $this->template_data[$this->index][$key]['compile_time'] +=
            microtime(true) - $this->template_data[$this->index][$key]['start_time'];
    }
999921
protected function processObjectTemplate(PersistentObject $tpl, SelectStatement $selectStmt) {
    // avoid infinite recursion
    $oidStr = $tpl->getOID()->__toString();
    if (isset($this->processedNodes[$oidStr])) {
      return;
    }

    $mapper = self::getMapper($tpl->getType());
    $tableName = self::processTableName($tpl);
    $this->involvedTypes[$tpl->getType()] = true;

    // add condition
    $condition = '';
    $iter = new NodeValueIterator($tpl, false);
    foreach($iter as $valueName => $value) {
      // check if the value was set when building the query
      if (isset($this->conditions[$oidStr][$valueName])) {
        $criterion = $this->conditions[$oidStr][$valueName];
        if ($criterion instanceof Criteria) {
          $attributeDesc = $mapper->getAttribute($valueName);
          if ($attributeDesc) {
            // add the combine operator, if there are already other conditions
            if (strlen($condition) > 0) {
              $condition .= ' '.$criterion->getCombineOperator().' ';
            }
            // because the attributes are not selected with alias, the column name has to be used
            $index = sizeof(array_keys($this->parameterCriteriaMap));
            $placeholder = ':'.$tableName['alias'].'_'.$attributeDesc->getColumn().$index;
            list($criteriaCondition, $criteriaPlaceholder) = $mapper->renderCriteria($criterion,
                    $placeholder, $tableName['alias'], $attributeDesc->getColumn());
            $condition .= $criteriaCondition;
            if ($criteriaPlaceholder) {
              $value = $this->getParameterPosition($criterion, $this->conditions);
              if (is_array($criteriaPlaceholder)) {
                $value = array_fill(0, sizeof($criteriaPlaceholder), $value);
                $this->parameterCriteriaMap = array_merge($this->parameterCriteriaMap,
                        array_combine($criteriaPlaceholder, $value));
              }
              else {
                $this->parameterCriteriaMap[$criteriaPlaceholder] = $value;
              }
            }
          }
        }
      }
    }
    if (strlen($condition) > 0) {
      $combineOperator = $tpl->getProperty(self::PROPERTY_COMBINE_OPERATOR);
      $selectStmt->where('('.$condition.')', $combineOperator);
    }

    // register the node as processed
    $this->processedNodes[$oidStr] = $tpl;

    // add relations to children (this includes also many to many relations)
    // and process children
    foreach ($mapper->getRelations() as $relationDescription) {
      $children = $tpl->getValue($relationDescription->getOtherRole());
      if ($children) {
        $children = !is_array($children) ? [$children] : $children;
        for ($i=0, $count=sizeof($children); $i<$count; $i++) {
          $curChild = $children[$i];
          if ($curChild instanceof Node) {
            // process relations

            // don't process the relation twice (e.g. in a many to many relation, both
            // ends are child ends)
            if (!isset($this->processedNodes[$curChild->getOID()->__toString()])) {
              // don't join the tables twice
              $childTableName = self::processTableName($curChild);
              $fromPart = $selectStmt->getRawState(SelectStatement::TABLE);
              if (!isset($fromPart[$childTableName['alias']])) {
                $childMapper = self::getMapper($curChild->getType());
                if ($relationDescription instanceof RDBManyToOneRelationDescription) {
                  $idAttr = $childMapper->getAttribute($relationDescription->getIdName());
                  $fkAttr = $mapper->getAttribute($relationDescription->getFkName());
                  $joinCondition = $tpl->getProperty(self::PROPERTY_TABLE_NAME).'.'.$fkAttr->getColumn().' = '.
                      $curChild->getProperty(self::PROPERTY_TABLE_NAME).'.'.$idAttr->getColumn();
                  $selectStmt->join([$childTableName['alias'] => $childTableName['name']], $joinCondition, []);
                }
                elseif ($relationDescription instanceof RDBOneToManyRelationDescription) {
                  $idAttr = $mapper->getAttribute($relationDescription->getIdName());
                  $fkAttr = $childMapper->getAttribute($relationDescription->getFkName());
                  $joinCondition = $curChild->getProperty(self::PROPERTY_TABLE_NAME).'.'.$fkAttr->getColumn().' = '.
                      $tpl->getProperty(self::PROPERTY_TABLE_NAME).'.'.$idAttr->getColumn();
                  $selectStmt->join([$childTableName['alias'] => $childTableName['name']], $joinCondition, []);
                }
                elseif ($relationDescription instanceof RDBManyToManyRelationDescription) {
                  $thisRelationDescription = $relationDescription->getThisEndRelation();
                  $otherRelationDescription = $relationDescription->getOtherEndRelation();

                  $nmMapper = self::getMapper($thisRelationDescription->getOtherType());
                  $otherFkAttr = $nmMapper->getAttribute($otherRelationDescription->getFkName());
                  $otherIdAttr = $childMapper->getAttribute($otherRelationDescription->getIdName());
                  $thisFkAttr = $nmMapper->getAttribute($thisRelationDescription->getFkName());
                  $thisIdAttr = $mapper->getAttribute($thisRelationDescription->getIdName());

                  $nmAlias = $nmMapper->getRealTableName().ucfirst($childTableName['alias']);

                  $joinCondition1 = $nmAlias.'.'.$thisFkAttr->getColumn().' = '.
                      $tpl->getProperty(self::PROPERTY_TABLE_NAME).'.'.
                      $thisIdAttr->getColumn();
                  $joinCondition2 = $curChild->getProperty(self::PROPERTY_TABLE_NAME).'.'.$otherIdAttr->getColumn().' = '.
                      $nmAlias.'.'.$otherFkAttr->getColumn();

                  $selectStmt->join([$nmAlias => $nmMapper->getRealTableName()], $joinCondition1, []);
                  $selectStmt->join([$childTableName['alias'] => $childTableName['name']], $joinCondition2, []);

                  // register the nm type
                  $this->involvedTypes[$nmMapper->getType()] = true;
                }
              }
            }

            // process child
            if (!in_array($curChild->getOID(), $this->groupedOIDs)) {
              $this->processObjectTemplate($curChild, $selectStmt);
            }
          }
        }
      }
    }
  }
1078980
public function start_render(Smarty_Internal_Template $template)
    {
        $key = $this->get_key($template);
        $this->template_data[$this->index][$key]['start_time'] = microtime(true);
    }
555959
public function render(Smarty_Internal_Template $_template)
    {
        if ($_template->source->handler->uncompiled) {
            if ($_template->smarty->debugging) {
                $_template->smarty->_debug->start_render($_template);
            }
            $this->handler->renderUncompiled($_template->source, $_template);
            if (isset($_template->parent) && $_template->parent->_objType == 2 && !empty($_template->tpl_function)) {
                $_template->parent->tpl_function =
                    array_merge($_template->parent->tpl_function, $_template->tpl_function);
            }
            if ($_template->smarty->debugging) {
                $_template->smarty->_debug->end_render($_template);
            }
        }
    }
625503
public function getRenderedTemplateCode(Smarty_Internal_Template $_template, $unifunc = null)
    {
        $unifunc = isset($unifunc) ? $unifunc : $this->unifunc;
        $level = ob_get_level();
        try {
            if (empty($unifunc) || !is_callable($unifunc)) {
                throw new SmartyException("Invalid compiled template for '{$_template->template_resource}'");
            }
            if (isset($_template->smarty->security_policy)) {
                $_template->smarty->security_policy->startTemplate($_template);
            }
            //
            // render compiled or saved template code
            //
            if (!isset($_template->_cache['capture_stack'])) {
                $_template->_cache['capture_stack'] = array();
            }
            $_saved_capture_level = count($_template->_cache['capture_stack']);
            $unifunc($_template);
            // any unclosed {capture} tags ?
            if ($_saved_capture_level != count($_template->_cache['capture_stack'])) {
                $_template->capture_error();
            }
            if (isset($_template->smarty->security_policy)) {
                $_template->smarty->security_policy->exitTemplate();
            }
            return null;
        }
        catch (Exception $e) {
            while (ob_get_level() > $level) {
                ob_end_clean();
            }
             if (isset($_template->smarty->security_policy)) {
                $_template->smarty->security_policy->exitTemplate();
            }
            throw $e;
        }
    }
84277
public function renderTemplate($tpl, array $render) {
    $registry = new \Drutiny\Registry();
    $loader = new \Twig_Loader_Filesystem($registry->templateDirs());
    $twig = new \Twig_Environment($loader, array(
      'cache' => sys_get_temp_dir() . '/drutiny/cache',
      'auto_reload' => TRUE,
      // 'debug' => true,
    ));
    // $twig->addExtension(new \Twig_Extension_Debug());

    // Filter to sort arrays by a property.
    $twig->addFilter(new \Twig_SimpleFilter('psort', function (array $array, array $args = []) {
        $property = reset($args);

        usort($array, function ($a, $b) use ($property) {
          if ($a[$property] == $b[$property]) {
            return 0;
          }
          $index = [$a[$property], $b[$property]];
          sort($index);
          return $index[0] == $a[$property] ? 1 : -1;
        });

        return $array;
    },
    ['is_variadic' => true]));

    $template = $twig->load($tpl . '.' . $this->getFormat() . '.twig');
    $contents = $template->render($render);
    return $contents;
  }
597652
public function fetch($tpl_name, &$tpl_source, &$mtime)
	{
		if(file_exists($tpl_name))
		{
			$tpl_source	= ec(file_get_contents($tpl_name));
			$mtime = filemtime($tpl_name);
			return;
		}

		if(($dirs = $this->smarty->getTemplateVars('template_dirnames')))
		{
			foreach($dirs as $dir)
			{
				if(file_exists($fn = str_replace('xfile:', '', $dir)."/".$tpl_name))
				{
					$tpl_source = ec(file_get_contents($fn));
					$mtime = filemtime($fn);
					return;
				}
			}
		}

		foreach($this->smarty->getTemplateDir() as $d)
		{
			if(file_exists($fn = "$d/$tpl_name"))
			{
				$tpl_source = ec(file_get_contents($fn));
				$mtime = filemtime($fn);
				return;
			}
		}

		foreach(bors_dirs(true) as $dir)
		{
			if(file_exists($fn = $dir.'/templates/'.$tpl_name))
			{
				$tpl_source = ec(file_get_contents($fn));
				$mtime = filemtime($fn);
				return;
			}

			if(file_exists($fn = $dir.'/'.$tpl_name))
			{
				$tpl_source = ec(file_get_contents($fn));
				$mtime = filemtime($fn);
				return;
			}
		}

		$tpl_source = NULL;
		$mtime = NULL;
		return;
	}
337900
function compile( $compiled_template_filename = '' )
		{
			if (empty($this->template))
			{
				return;
			}
			/* Quick hack to allow subtemplates */
			if(eregi("<!-- INCLUDE", $this->template))
			{
				while ($this->count_subtemplates() > 0)
				{
					preg_match_all('/<!-- INCLUDE ([a-zA-Z0-9_.]+) -->/', $this->template, $tvar);
					foreach($tvar[1] as $subfile)
					{
						if(file_exists($this->template_dir . "/$subfile"))
						{
							$subst = implode('',file($this->template_dir . "/$subfile"));
						}
						else
						{
							$subst = 'SmartTemplate Parser Error: Subtemplate not found: \''.$subfile.'\'';
						}
						$this->template = str_replace("<!-- INCLUDE $subfile -->", $subst, $this->template);
					}
				}
			}
			//	END, ELSE Blocks
			$page  =  preg_replace("/<!-- ENDIF.+?-->/",  "<?php\n}\n?>",  $this->template);
			$page  =  preg_replace("/<!-- END[ a-zA-Z0-9_.]* -->/",  "<?php\n}\n\$_obj=\$_stack[--\$_stack_cnt];}\n?>",  $page);
			$page  =  str_replace("<!-- ELSE -->",  "<?php\n} else {\n?>",  $page);

			//	'BEGIN - END' Blocks
			if (preg_match_all('/<!-- BEGIN ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n"
							. "if (!empty(\$$parent"."['$block'])){\n"
							. "if (!is_array(\$$parent"."['$block']))\n"
							. "\$$parent"."['$block']=array(array('$block'=>\$$parent"."['$block']));\n"
							. "\$_tmp_arr_keys=array_keys(\$$parent"."['$block']);\n"
							. "if (\$_tmp_arr_keys[0]!='0')\n"
							. "\$$parent"."['$block']=array(0=>\$$parent"."['$block']);\n"
							. "\$_stack[\$_stack_cnt++]=\$_obj;\n"
							. "foreach (\$$parent"."['$block'] as \$rowcnt=>\$$block) {\n"
							. "\$$block"."['ROWCNT']=\$rowcnt;\n"
							. "\$$block"."['ALTROW']=\$rowcnt%2;\n"
							. "\$$block"."['ROWBIT']=\$rowcnt%2;\n"
							. "\$_obj=&\$$block;\n?>";
					$page  =  str_replace("<!-- BEGIN $tag -->",  $code,  $page);
				}
			}

			//	'IF nnn=mmm' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+)[ ]*([!=<>]+)[ ]*(["]?[^"]*["]?) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					list($parent, $block)  =  $this->var_name($tag);
					$cmp   =  $var[3][$cnt];
					$val   =  $var[4][$cnt];
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					if ($cmp == '=')
					{
						$cmp  =  '==';
					}
					
					if (preg_match('/"([^"]*)"/',$val,$matches))
					{
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \"".$matches[1]."\"){\n?>";
					}
					elseif (preg_match('/([^"]*)/',$val,$matches))
					{
						list($parent_right, $block_right)  =  $this->var_name($matches[1]);
						$code  =  "<?php\n$else"."if (\$$parent"."['$block'] $cmp \$$parent_right"."['$block_right']){\n?>";
					}
					
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	'IF nnn' Blocks
			if (preg_match_all('/<!-- (ELSE)?IF ([a-zA-Z0-9_.]+) -->/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					$else  =  ($var[1][$cnt] == 'ELSE') ? '} else' : '';
					list($parent, $block)  =  $this->var_name($tag);
					$code  =  "<?php\n$else"."if (!empty(\$$parent"."['$block'])){\n?>";
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Replace Scalars
			if (preg_match_all('/{([a-zA-Z0-9_. >]+)}/', $page, $var))
			{
				foreach ($var[1] as $fulltag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($fulltag);

					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\n$cmd \$$block"."['$skalar'];\n?>\n";
					$page  =  str_replace('{'.$fulltag.'}',  $code,  $page);
				}
			}


			//	ROSI Special: Replace Translations
			if (preg_match_all('/<"([a-zA-Z0-9_.]+)">/', $page, $var))
			{
				foreach ($var[1] as $tag)
				{
					list($block, $skalar)  =  $this->var_name($tag);
					$code  =  "<?php\necho gettext('$skalar');\n?>\n";
					$page  =  str_replace('<"'.$tag.'">',  $code,  $page);
				}
			}


			//	Include Extensions
			$header = '';
			if (preg_match_all('/{([a-zA-Z0-9_]+):([^}]*)}/', $page, $var))
			{
				foreach ($var[2] as $cnt => $tag)
				{
					//	Determin Command (echo / $obj[n]=)
					list($cmd, $tag)  =  $this->cmd_name($tag);

					$extension  =  $var[1][$cnt];
					if (!isset($this->extension_tagged[$extension]))
					{
						$header  .=  "include_once \"smarttemplate_extensions/smarttemplate_extension_$extension.php\";\n";
						$this->extension_tagged[$extension]  =  true;
					}
					if (!strlen($tag))
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension();\n?>\n";
					}
					elseif (substr($tag, 0, 1) == '"')
					{
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension($tag);\n?>\n";
					}
					elseif (strpos($tag, ','))
					{
						list($tag, $addparam)  =  explode(',', $tag, 2);
						list($block, $skalar)  =  $this->var_name($tag);
						if (preg_match('/^([a-zA-Z_]+)/', $addparam, $match))
						{
							$nexttag   =  $match[1];
							list($nextblock, $nextskalar)  =  $this->var_name($nexttag);
							$addparam  =  substr($addparam, strlen($nexttag));
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],\$$nextblock"."['$nextskalar']"."$addparam);\n?>\n";
						}
						else
						{
							$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar'],$addparam);\n?>\n";
						}
					}
					else
					{
						list($block, $skalar)  =  $this->var_name($tag);
						$code  =  "<?php\n$cmd smarttemplate_extension_$extension(\$$block"."['$skalar']);\n?>\n";
					}
					$page  =  str_replace($var[0][$cnt],  $code,  $page);
				}
			}

			//	Add Include Header
			if (isset($header) && !empty($header))
			{
				$page  =  "<?php\n$header\n?>$page";
			}

			//	Store Code to Temp Dir
			if (strlen($compiled_template_filename))
			{
		        if ($hd  =  fopen($compiled_template_filename,  "w"))
		        {
			        fwrite($hd,  $page);
			        fclose($hd);
			        return true;
			    }
			    else
			    {
			    	$this->error  =  "Could not write compiled file.";
			        return false;
			    }
			}
			else
			{
				return $page;
			}
		}
1183979
private function doIfElseEndif($tpl) {

		$stack = [];
		$nesting = 0;

		while(true) {
			preg_match('~(.*?)\{(if\s*\((.+?)\)\s*|else|end_if)\}(.*)~si', $tpl, $matches);

			if(count($matches) < 5) {
				break;
			}

			$right = $matches[4];
			$left = $matches[1];

			switch($matches[2]) {
				case 'else':
					$last = &$stack[$nesting-1];

					$last['else'] = true;

					if($last['condition'] && (!isset($last['parentCond']) || $last['parentCond'])) {
						$last['left'] .= $left;
					}
					break;

				case 'end_if':
					$last = &$stack[$nesting-1];

					if(((!$last['condition'] && $last['else']) || ($last['condition'] && !$last['else'])) && (!isset($last['parentCond']) || $last['parentCond'])) {
						$last['left'] .= $left;
					}

					--$nesting;

					if($nesting > 0) {
						$stack[$nesting-1]['left'] .= $stack[$nesting]['left'];
						$stack[$nesting]['left'] = '';
					}
					break;

				default:
					if($nesting > 0) {
						if(
							($stack[$nesting - 1]['condition'] && $stack[$nesting - 1]['else']) ||
							(!$stack[$nesting - 1]['condition'] && !$stack[$nesting - 1]['else']) ||
							($stack[$nesting - 1]['parentCond'] === false)
						) {
							$left = '';
							$parentCond = false;
							$cond = null;
						}
						else {
							$parentCond = true;
							$cond = $this->evalCondition($matches[3]);
						}
					}
					else {
						$cond = $this->evalCondition($matches[3]);
					}

					if(!empty($stack[$nesting]['left'])) {
						$left = $stack[$nesting]['left'].$left;
					}

					$stack[$nesting] = [
						'left' => $left,
						'condition' => $cond,
						'parentCond' => isset($parentCond) ? $parentCond : null,
						'else' => false
					];
					++$nesting;
					break;
			}
			$tpl = $right;
		}

		// append last right

		return empty($stack[0]['left']) ? $tpl : $stack[0]['left'] . $right;
	}
976764
public function meta($tpl, $outputtype = '', $trusted = true)
    {
        if (in_array($tpl, $this->processedMeta)) {
            // we want to process meta only one time, when a template is included
            // several time in an other template, or, more important, when a template
            // is included in a recursive manner (in this case, it did cause infinite loop, see #1396).
            return $this->_meta;
        }
        $this->processedMeta[] = $tpl;
        $md = $this->getTemplate($tpl, $outputtype, $trusted);

        $fct = 'template_meta_'.$md;
        $fct($this);

        return $this->_meta;
    }
145539
public function display($tpl = null)
	{
		$result = $this->loadTemplate($tpl);

		if ($result instanceof Exception)
		{
			return $result;
		}

		echo $result;
	}