3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseTemplateEngine extends BaseFrameworkSystem {
26 * The local path name where all templates and sub folders for special
27 * templates are stored. We will internally determine the language plus
28 * "html" for web templates or "emails" for email templates
30 private $templateBasePath = '';
35 private $templateType = 'html';
38 * The extension for web and email templates (not compiled templates)
40 private $templateExtension = '.tpl';
43 * The extension for code templates (not compiled templates)
45 private $codeExtension = '.ctp';
48 * Path relative to $templateBasePath and language code for compiled code-templates
50 private $compileOutputPath = 'templates/_compiled/';
53 * The path name for all templates
55 private $genericBasePath = 'templates/';
58 * The raw (maybe uncompiled) template
60 private $rawTemplateData = '';
63 * Template data with compiled-in variables
65 private $compiledData = '';
68 * The last loaded template's FQFN for debugging the engine
70 private $lastTemplate = '';
73 * The variable stack for the templates
75 private $varStack = array();
78 * Loaded templates for recursive protection and detection
80 private $loadedTemplates = array();
83 * Compiled templates for recursive protection and detection
85 private $compiledTemplates = array();
88 * Loaded raw template data
90 private $loadedRawData = null;
93 * Raw templates which are linked in code templates
95 private $rawTemplates = null;
98 * A regular expression for variable=value pairs
100 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
103 * A regular expression for filtering out code tags
105 * E.g.: {?template:variable=value;var2=value2;[...]?}
107 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
112 private $helpers = array();
115 * Current variable group
117 private $currGroup = 'general';
120 * All template groups except "general"
122 private $varGroups = array();
127 private $codeBegin = '<?php';
132 private $codeEnd = '?>';
135 * Language support is enabled by default
137 private $languageSupport = true;
140 * XML compacting is disabled by default
142 private $xmlCompacting = false;
144 // Exception codes for the template engine
145 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
146 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
147 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
148 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
151 * Protected constructor
153 * @param $className Name of the class
156 protected function __construct ($className) {
157 // Call parent constructor
158 parent::__construct($className);
162 * Search for a variable in the stack
164 * @param $var The variable we are looking for
165 * @param $stack Optional variable stack to look in
166 * @return $index FALSE means not found, >=0 means found on a specific index
168 private function getVariableIndex ($var, $stack = null) {
169 // First everything is not found
172 // If the stack is null, use the current group
173 if (is_null($stack)) $stack = $this->currGroup;
175 // Is the group there?
176 if ($this->isVarStackSet($stack)) {
178 foreach ($this->getVarStack($stack) as $index => $currEntry) {
179 //* DEBUG: */ echo __METHOD__.":currGroup={$stack},idx={$index},currEntry={$currEntry['name']},var={$var}<br />\n";
180 // Is the entry found?
181 if ($currEntry['name'] == $var) {
183 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
190 // Return the current position
195 * Checks wether the given variable stack is set
197 * @param $stack Variable stack to check
198 * @return $isSet Wether the given variable stack is set
200 protected final function isVarStackSet ($stack) {
202 $isSet = isset($this->varStack[$stack]);
209 * Getter for given variable stack
211 * @param $stack Variable stack to check
212 * @return $varStack Found variable stack
214 public final function getVarStack ($stack) {
215 return $this->varStack[$stack];
219 * Setter for given variable stack
221 * @param $stack Variable stack to check
222 * @param $varStack Variable stack to check
225 protected final function setVarStack ($stack, array $varStack) {
226 $this->varStack[$stack] = $varStack;
230 * Return a content of a variable or null if not found
232 * @param $var The variable we are looking for
233 * @param $stack Optional variable stack to look in
234 * @return $content Content of the variable or null if not found
236 protected function readVariable ($var, $stack = null) {
237 // First everything is not found
240 // If the stack is null, use the current group
241 if (is_null($stack)) $stack = $this->currGroup;
243 // Get variable index
244 $found = $this->getVariableIndex($var, $stack);
246 // Is the variable found?
247 if ($found !== false) {
249 $content = $this->getVariableValue($stack, $found);
252 // Return the current position
253 //* DEBUG: */ echo __METHOD__.": group=".$stack.",var=".$var.", content[".gettype($content)."]=".$content."<br />\n";
258 * Add a variable to the stack
260 * @param $var The variable we are looking for
261 * @param $value The value we want to store in the variable
264 private function addVariable ($var, $value) {
265 // Set general variable group
266 $this->setVariableGroup('general');
268 // Add it to the stack
269 $this->addGroupVariable($var, $value);
273 * Returns all variables of current group or empty array
275 * @return $result Wether array of found variables or empty array
277 private function readCurrentGroup () {
278 // Default is not found
281 // Is the group there?
282 if ($this->isVarStackSet($this->currGroup)) {
284 $result = $this->getVarStack($this->currGroup);
292 * Settter for variable group
294 * @param $groupName Name of variable group
295 * @param $add Wether add this group
298 public function setVariableGroup ($groupName, $add = true) {
300 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
301 $this->currGroup = $groupName;
303 // Skip group 'general'
304 if (($groupName != 'general') && ($add === true)) {
305 $this->varGroups[$groupName] = 'OK';
311 * Adds a variable to current group
313 * @param $var Variable to set
314 * @param $value Value to store in variable
317 public function addGroupVariable ($var, $value) {
318 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
320 // Get current variables in group
321 $currVars = $this->readCurrentGroup();
323 // Append our variable
324 $currVars[] = $this->generateVariableArray($var, $value);
326 // Add it to the stack
327 $this->setVarStack($this->currGroup, $currVars);
331 * Getter for variable value, throws a NoVariableException if the variable is not found
333 * @param $varGroup Variable group to use
334 * @param $index Index in variable array
335 * @return $value Value to set
337 private function getVariableValue ($varGroup, $index) {
339 return $this->varStack[$varGroup][$index]['value'];
343 * Modify an entry on the stack
345 * @param $var The variable we are looking for
346 * @param $value The value we want to store in the variable
348 * @throws NoVariableException If the given variable is not found
350 private function modifyVariable ($var, $value) {
351 // Get index for variable
352 $index = $this->getVariableIndex($var);
354 // Is the variable set?
355 if ($index === false) {
356 // Unset variables cannot be modified
357 throw new NoVariableException(array($this, $var, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
361 $this->setVariableValue($this->currGroup, $index, $value);
365 * Sets a variable value for given variable group and index
367 * @param $varGroup Variable group to use
368 * @param $index Index in variable array
369 * @param $value Value to set
372 private function setVariableValue ($varGroup, $index, $value) {
373 $this->varStack[$varGroup][$index]['value'] = $value;
377 * Sets a variable within given group. This method does detect if the
378 * variable is already set. If so, the variable got modified, otherwise
381 * @param $varGroup Variable group to use
382 * @param $var Variable to set
383 * @param $value Value to set
386 protected function setVariable ($varGroup, $var, $value) {
387 // Get index for variable
388 $index = $this->getVariableIndex($var);
390 // Is the variable set?
391 if ($index === false) {
393 $this->varStack[$varGroup][] = $this->generateVariableArray($var, $value);
396 $this->setVariableValue($this->currGroup, $index, $value);
401 * "Generates" (better returns) an array for all variables for given
402 * variable/value pay.
404 * @param $var Variable to set
405 * @param $value Value to set
406 * @return $varData Variable data array
408 private function generateVariableArray ($var, $value) {
409 // Generate the temporary array
420 * Setter for template type. Only 'html', 'emails' and 'compiled' should
423 * @param $templateType The current template's type
426 protected final function setTemplateType ($templateType) {
427 $this->templateType = (string) $templateType;
431 * Setter for the last loaded template's FQFN
433 * @param $template The last loaded template
436 private final function setLastTemplate ($template) {
437 $this->lastTemplate = (string) $template;
441 * Getter for the last loaded template's FQFN
443 * @return $template The last loaded template
445 private final function getLastTemplate () {
446 return $this->lastTemplate;
450 * Setter for base path
452 * @param $templateBasePath The relative base path for all templates
455 public final function setTemplateBasePath ($templateBasePath) {
457 $this->templateBasePath = (string) $templateBasePath;
461 * Getter for base path
463 * @return $templateBasePath The relative base path for all templates
465 public final function getTemplateBasePath () {
467 return $this->templateBasePath;
471 * Getter for generic base path
473 * @return $templateBasePath The relative base path for all templates
475 public final function getGenericBasePath () {
477 return $this->genericBasePath;
481 * Setter for template extension
483 * @param $templateExtension The file extension for all uncompiled
487 public final function setRawTemplateExtension ($templateExtension) {
489 $this->templateExtension = (string) $templateExtension;
493 * Setter for code template extension
495 * @param $codeExtension The file extension for all uncompiled
499 public final function setCodeTemplateExtension ($codeExtension) {
501 $this->codeExtension = (string) $codeExtension;
505 * Getter for template extension
507 * @return $templateExtension The file extension for all uncompiled
510 public final function getRawTemplateExtension () {
512 return $this->templateExtension;
516 * Getter for code-template extension
518 * @return $codeExtension The file extension for all code-
521 public final function getCodeTemplateExtension () {
523 return $this->codeExtension;
527 * Setter for path of compiled templates
529 * @param $compileOutputPath The local base path for all compiled
533 public final function setCompileOutputPath ($compileOutputPath) {
535 $this->compileOutputPath = (string) $compileOutputPath;
539 * Getter for template type
541 * @return $templateType The current template's type
543 public final function getTemplateType () {
544 return $this->templateType;
548 * Assign (add) a given variable with a value
550 * @param $var The variable we are looking for
551 * @param $value The value we want to store in the variable
553 * @throws EmptyVariableException If the variable name is left empty
555 public final function assignVariable ($var, $value) {
556 // Trim spaces of variable name
559 // Empty variable found?
561 // Throw an exception
562 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
565 // First search for the variable if it was already added
566 $index = $this->getVariableIndex($var);
569 if ($index === false) {
570 // Add it to the stack
571 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
572 $this->addVariable($var, $value);
573 } elseif (!empty($value)) {
574 // Modify the stack entry
575 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
576 $this->modifyVariable($var, $value);
581 * Removes a given variable
583 * @param $var The variable we are looking for
586 public final function removeVariable ($var) {
587 // First search for the variable if it was already added
588 $index = $this->getVariableIndex($var);
591 if ($index !== false) {
592 // Remove this variable
593 $this->unsetVariableStackOffset($index);
598 * Unsets the given offset in the variable stack
600 * @param $index Index to unset
603 protected final function unsetVariableStackOffset ($index) {
604 // Is the entry there?
605 if (!isset($this->varStack[$this->currGroup][$index])) {
606 // Abort here, we need fixing!
607 $this->debugInstance();
611 unset($this->varStack[$this->currGroup][$index]);
615 * Private setter for raw template data
617 * @param $rawTemplateData The raw data from the template
620 protected final function setRawTemplateData ($rawTemplateData) {
621 // And store it in this class
622 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
623 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->getVarStack($this->currGroup)).', groups='.count($this->varStack).'<br />\n';
624 $this->rawTemplateData = (string) $rawTemplateData;
628 * Getter for raw template data
630 * @return $rawTemplateData The raw data from the template
632 public final function getRawTemplateData () {
633 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
634 return $this->rawTemplateData;
638 * Private setter for compiled templates
642 private final function setCompiledData ($compiledData) {
643 // And store it in this class
644 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
645 $this->compiledData = (string) $compiledData;
649 * Getter for compiled templates
651 * @return $compiledData Compiled template data
653 public final function getCompiledData () {
654 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
655 return $this->compiledData;
659 * Private loader for all template types
661 * @param $template The template we shall load
662 * @param $extOther An other extension to use
664 * @throws FileIoException If the template was not found
666 protected function loadTemplate ($template, $extOther = '') {
667 // Get extension for the template if empty
668 if (empty($extOther)) {
669 // None provided, so get the raw one
670 $ext = $this->getRawTemplateExtension();
673 $ext = (string) $extOther;
676 // Is language support enabled?
677 if ($this->isLanguageSupportEnabled()) {
678 // Construct the FQFN for the template by honoring the current language
679 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
680 $this->getConfigInstance()->getConfigEntry('base_path'),
681 $this->getTemplateBasePath(),
682 $this->getGenericBasePath(),
683 $this->getLanguageInstance()->getLanguageCode(),
684 $this->getTemplateType(),
689 // Construct the FQFN for the template without language
690 $fqfn = sprintf("%s%s%s%s/%s%s",
691 $this->getConfigInstance()->getConfigEntry('base_path'),
692 $this->getTemplateBasePath(),
693 $this->getGenericBasePath(),
694 $this->getTemplateType(),
702 // Load the raw template data
703 $this->loadRawTemplateData($fqfn);
704 } catch (FileIoException $e) {
705 // If we shall load a code-template we need to switch the file extension
706 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
707 // Switch over to the code-template extension and try it again
708 $ext = $this->getCodeTemplateExtension();
711 $this->loadTemplate($template, $ext);
714 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
721 * A private loader for raw template names
723 * @param $fqfn The full-qualified file name for a template
726 private function loadRawTemplateData ($fqfn) {
727 // Get a input/output instance from the middleware
728 $ioInstance = $this->getFileIoInstance();
730 // Some debug code to look on the file which is being loaded
731 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
733 // Load the raw template
734 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
736 // Store the template's contents into this class
737 $this->setRawTemplateData($rawTemplateData);
739 // Remember the template's FQFN
740 $this->setLastTemplate($fqfn);
744 * Try to assign an extracted template variable as a "content" or 'config'
747 * @param $varName The variable's name (shall be content orconfig) by
749 * @param $var The variable we want to assign
751 private function assignTemplateVariable ($varName, $var) {
752 // Is it not a config variable?
753 if ($varName != 'config') {
754 // Regular template variables
755 $this->assignVariable($var, '');
757 // Configuration variables
758 $this->assignConfigVariable($var);
763 * Extract variables from a given raw data stream
765 * @param $rawData The raw template data we shall analyze
768 private function extractVariablesFromRawData ($rawData) {
770 $rawData = (string) $rawData;
772 // Search for variables
773 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
775 // Did we find some variables?
776 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
777 // Initialize all missing variables
778 foreach ($variableMatches[3] as $key => $var) {
780 $varName = $variableMatches[1][$key];
782 // Workarround: Do not assign empty variables
784 // Try to assign it, empty strings are being ignored
785 $this->assignTemplateVariable($varName, $var);
792 * Main analysis of the loaded template
794 * @param $templateMatches Found template place-holders, see below
797 *---------------------------------
798 * Structure of $templateMatches:
799 *---------------------------------
800 * [0] => Array - An array with all full matches
801 * [1] => Array - An array with left part (before the ':') of a match
802 * [2] => Array - An array with right part of a match including ':'
803 * [3] => Array - An array with right part of a match excluding ':'
805 private function analyzeTemplate (array $templateMatches) {
806 // Backup raw template data
807 $backup = $this->getRawTemplateData();
809 // Initialize some arrays
810 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
812 // Load all requested templates
813 foreach ($templateMatches[1] as $template) {
815 // Load and compile only templates which we have not yet loaded
816 // RECURSIVE PROTECTION! BE CAREFUL HERE!
817 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
819 // Template not found, but maybe variable assigned?
820 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
821 if ($this->getVariableIndex($template) !== false) {
822 // Use that content here
823 $this->loadedRawData[$template] = $this->readVariable($template);
825 // Recursive protection:
826 $this->loadedTemplates[] = $template;
827 } elseif ($this->getVariableIndex($template, 'config')) {
828 // Use that content here
829 $this->loadedRawData[$template] = $this->readVariable($template, 'config');
831 // Recursive protection:
832 $this->loadedTemplates[] = $template;
834 // Then try to search for code-templates
836 // Load the code template and remember it's contents
837 $this->loadCodeTemplate($template);
838 $this->loadedRawData[$template] = $this->getRawTemplateData();
840 // Remember this template for recursion detection
841 // RECURSIVE PROTECTION!
842 $this->loadedTemplates[] = $template;
843 } catch (FileIoException $e) {
844 // Even this is not done... :/
845 $this->rawTemplates[] = $template;
851 // Restore the raw template data
852 $this->setRawTemplateData($backup);
856 * Compile a given raw template code and remember it for later usage
858 * @param $code The raw template code
859 * @param $template The template's name
862 private function compileCode ($code, $template) {
863 // Is this template already compiled?
864 if (in_array($template, $this->compiledTemplates)) {
869 // Remember this template being compiled
870 $this->compiledTemplates[] = $template;
872 // Compile the loaded code in five steps:
874 // 1. Backup current template data
875 $backup = $this->getRawTemplateData();
877 // 2. Set the current template's raw data as the new content
878 $this->setRawTemplateData($code);
880 // 3. Compile the template data
881 $this->compileTemplate();
883 // 4. Remember it's contents
884 $this->loadedRawData[$template] = $this->getRawTemplateData();
886 // 5. Restore the previous raw content from backup variable
887 $this->setRawTemplateData($backup);
891 * Insert all given and loaded templates by running through all loaded
892 * codes and searching for their place-holder in the main template
894 * @param $templateMatches See method analyzeTemplate()
897 private function insertAllTemplates (array $templateMatches) {
898 // Run through all loaded codes
899 foreach ($this->loadedRawData as $template => $code) {
901 // Search for the template
902 $foundIndex = array_search($template, $templateMatches[1]);
904 // Lookup the matching template replacement
905 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
907 // Get the current raw template
908 $rawData = $this->getRawTemplateData();
910 // Replace the space holder with the template code
911 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
913 // Set the new raw data
914 $this->setRawTemplateData($rawData);
920 * Load all extra raw templates
924 private function loadExtraRawTemplates () {
925 // Are there some raw templates we need to load?
926 if (count($this->rawTemplates) > 0) {
927 // Try to load all raw templates
928 foreach ($this->rawTemplates as $key => $template) {
931 $this->loadWebTemplate($template);
933 // Remember it's contents
934 $this->rawTemplates[$template] = $this->getRawTemplateData();
936 // Remove it from the loader list
937 unset($this->rawTemplates[$key]);
939 // Remember this template for recursion detection
940 // RECURSIVE PROTECTION!
941 $this->loadedTemplates[] = $template;
942 } catch (FileIoException $e) {
943 // This template was never found. We silently ignore it
944 unset($this->rawTemplates[$key]);
951 * Assign all found template variables
953 * @param $varMatches An array full of variable/value pairs.
955 * @todo Unfinished work or don't die here.
957 private function assignAllVariables (array $varMatches) {
958 // Search for all variables
959 foreach ($varMatches[1] as $key => $var) {
961 // Detect leading equals
962 if (substr($varMatches[2][$key], 0, 1) == '=') {
963 // Remove and cast it
964 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
967 // Do we have some quotes left and right side? Then it is free text
968 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
969 // Free string detected! Which we can assign directly
970 $this->assignVariable($var, $varMatches[3][$key]);
971 } elseif (!empty($varMatches[2][$key])) {
972 // @TODO Non-string found so we need some deeper analysis...
973 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
976 } // for ($varMatches ...
980 * Compiles all loaded raw templates
982 * @param $templateMatches See method analyzeTemplate() for details
985 private function compileRawTemplateData (array $templateMatches) {
986 // Are some code-templates found which we need to compile?
987 if (count($this->loadedRawData) > 0) {
990 foreach ($this->loadedRawData as $template => $code) {
992 // Is this template already compiled?
993 if (in_array($template, $this->compiledTemplates)) {
998 // Search for the template
999 $foundIndex = array_search($template, $templateMatches[1]);
1001 // Lookup the matching variable data
1002 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1004 // Split it up with another reg. exp. into variable=value pairs
1005 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1007 // Assign all variables
1008 $this->assignAllVariables($varMatches);
1010 } // END - if (isset($templateMatches ...
1012 // Compile the loaded template
1013 $this->compileCode($code, $template);
1015 } // END - foreach ($this->loadedRawData ...
1017 // Insert all templates
1018 $this->insertAllTemplates($templateMatches);
1020 } // END - if (count($this->loadedRawData) ...
1024 * Inserts all raw templates into their respective variables
1028 private function insertRawTemplates () {
1029 // Load all templates
1030 foreach ($this->rawTemplates as $template => $content) {
1031 // Set the template as a variable with the content
1032 $this->assignVariable($template, $content);
1037 * Finalizes the compilation of all template variables
1041 private function finalizeVariableCompilation () {
1043 $content = $this->getRawTemplateData();
1044 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
1046 // Do we have the stack?
1047 if (!$this->isVarStackSet('general')) {
1048 // Abort here silently
1049 // @TODO This silent abort should be logged, maybe.
1053 // Walk through all variables
1054 foreach ($this->getVarStack('general') as $currEntry) {
1055 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
1056 // Replace all [$var] or {?$var?} with the content
1057 // @TODO Old behaviour, will become obsolete!
1058 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1060 // @TODO Yet another old way
1061 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1063 // The new behaviour
1064 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1067 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
1069 // Set the content back
1070 $this->setRawTemplateData($content);
1074 * Load a specified web template into the engine
1076 * @param $template The web template we shall load which is located in
1080 public function loadWebTemplate ($template) {
1081 // Set template type
1082 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
1084 // Load the special template
1085 $this->loadTemplate($template);
1089 * Assign a given congfiguration variable with a value
1091 * @param $var The configuration variable we want to assign
1094 public function assignConfigVariable ($var) {
1095 // Sweet and simple...
1096 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
1097 $this->setVariable('config', $var, $this->getConfigInstance()->getConfigEntry($var));
1101 * Load a specified code template into the engine
1103 * @param $template The code template we shall load which is
1104 * located in 'code' by default
1107 public function loadCodeTemplate ($template) {
1108 // Set template type
1109 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1111 // Load the special template
1112 $this->loadTemplate($template);
1116 * Compiles configuration place-holders in all variables. This 'walks'
1117 * through the variable stack 'general'. It interprets all values from that
1118 * variables as configuration entries after compiling them.
1122 public final function compileConfigInVariables () {
1123 // Do we have the stack?
1124 if (!$this->isVarStackSet('general')) {
1125 // Abort here silently
1126 // @TODO This silent abort should be logged, maybe.
1130 // Iterate through all general variables
1131 foreach ($this->getVarStack('general') as $index=>$currVariable) {
1132 // Compile the value
1133 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1135 // Remove it from stack
1136 $this->removeVariable($index, 'general');
1138 // Re-assign the variable
1139 $this->assignConfigVariable($value);
1144 * Compile all variables by inserting their respective values
1147 * @todo Make this code some nicer...
1149 public final function compileVariables () {
1150 // Initialize the $content array
1151 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1154 // Iterate through all general variables
1155 foreach ($this->getVarStack('general') as $currVariable) {
1156 // Transfer it's name/value combination to the $content array
1157 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
1158 $dummy[$currVariable['name']] = $currVariable['value'];
1161 // Set the new variable (don't remove the second dollar!)
1162 $$validVar = $dummy;
1164 // Prepare all configuration variables
1166 if ($this->isVarStackSet('config')) {
1167 $config = $this->getVarStack('config');
1170 // Remove some variables
1172 unset($currVariable);
1174 // Run the compilation three times to get content from helper classes in
1177 // Finalize the compilation of template variables
1178 $this->finalizeVariableCompilation();
1180 // Prepare the eval() command for comiling the template
1181 $eval = sprintf("\$result = \"%s\";",
1182 addslashes($this->getRawTemplateData())
1185 // This loop does remove the backslashes (\) in PHP parameters
1186 while (strpos($eval, $this->codeBegin) !== false) {
1187 // Get left part before "<?"
1188 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1190 // Get all from right of "<?"
1191 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1193 // Cut middle part out and remove escapes
1194 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1195 $evalMiddle = stripslashes($evalMiddle);
1197 // Remove the middle part from right one
1198 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1200 // And put all together
1201 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1204 // Prepare PHP code for eval() command
1205 $eval = str_replace(
1214 // Run the constructed command. This will "compile" all variables in
1217 // Goes something wrong?
1218 if ((!isset($result)) || (empty($result))) {
1219 // Output eval command
1220 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1222 // Output backtrace here
1223 $this->debugBackTrace();
1226 // Set raw template data
1227 $this->setRawTemplateData($result);
1231 // Final variable assignment
1232 $this->finalizeVariableCompilation();
1234 // Set the new content
1235 $this->setCompiledData($this->getRawTemplateData());
1239 * Compile all required templates into the current loaded one
1242 * @throws UnexpectedTemplateTypeException If the template type is
1244 * @throws InvalidArrayCountException If an unexpected array
1245 * count has been found
1247 public function compileTemplate () {
1248 // Get code type to make things shorter
1249 $codeType = $this->getConfigInstance()->getConfigEntry('code_template_type');
1251 // We will only work with template type "code" from configuration
1252 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1254 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1257 // Get the raw data.
1258 $rawData = $this->getRawTemplateData();
1260 // Remove double spaces and trim leading/trailing spaces
1261 $rawData = trim(str_replace(' ', ' ', $rawData));
1263 // Search for raw variables
1264 $this->extractVariablesFromRawData($rawData);
1266 // Search for code-tags which are {? ?}
1267 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1269 // Analyze the matches array
1270 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1271 // Entries are found:
1273 // The main analysis
1274 $this->analyzeTemplate($templateMatches);
1276 // Compile raw template data
1277 $this->compileRawTemplateData($templateMatches);
1279 // Are there some raw templates left for loading?
1280 $this->loadExtraRawTemplates();
1282 // Are some raw templates found and loaded?
1283 if (count($this->rawTemplates) > 0) {
1285 // Insert all raw templates
1286 $this->insertRawTemplates();
1288 // Remove the raw template content as well
1289 $this->setRawTemplateData('');
1293 } // END - if($templateMatches ...
1297 * Loads a given view helper (by name)
1299 * @param $helperName The helper's name
1302 protected function loadViewHelper ($helperName) {
1303 // Make first character upper case, rest low
1304 $helperName = $this->convertToClassName($helperName);
1306 // Is this view helper loaded?
1307 if (!isset($this->helpers[$helperName])) {
1308 // Create a class name
1309 $className = "{$helperName}ViewHelper";
1311 // Generate new instance
1312 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1315 // Return the requested instance
1316 return $this->helpers[$helperName];
1320 * Assigns the last loaded raw template content with a given variable
1322 * @param $templateName Name of the template we want to assign
1323 * @param $variableName Name of the variable we want to assign
1326 public function assignTemplateWithVariable ($templateName, $variableName) {
1327 // Get the content from last loaded raw template
1328 $content = $this->getRawTemplateData();
1330 // Assign the variable
1331 $this->assignVariable($variableName, $content);
1333 // Purge raw content
1334 $this->setRawTemplateData('');
1338 * Transfers the content of this template engine to a given response instance
1340 * @param $responseInstance An instance of a response class
1343 public function transferToResponse (Responseable $responseInstance) {
1344 // Get the content and set it in response class
1345 $responseInstance->writeToBody($this->getCompiledData());
1349 * Assigns all the application data with template variables
1351 * @param $appInstance A manageable application instance
1354 public function assignApplicationData (ManageableApplication $appInstance) {
1355 // Get long name and assign it
1356 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1358 // Get short name and assign it
1359 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1361 // Get version number and assign it
1362 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1364 // Assign extra application-depending data
1365 $appInstance->assignExtraTemplateData($this);
1369 * "Compiles" a variable by replacing {?var?} with it's content
1371 * @param $rawCode Raw code to compile
1372 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1373 * @return $rawCode Compile code with inserted variable value
1375 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1376 // Find the variables
1377 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1378 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1380 // Compile all variables
1381 //* DEBUG: */ echo __METHOD__.":<pre>".print_r($varMatches, true)."</pre>\n";
1382 foreach ($varMatches[0] as $match) {
1383 // Add variable tags around it
1384 $varCode = '{?' . $match . '?}';
1386 // Is the variable found in code? (safes some calls)
1387 if (strpos($rawCode, $varCode) !== false) {
1388 // Replace the variable with it's value, if found
1389 $value = $this->readVariable($match);
1390 //* DEBUG: */ echo __METHOD__.": match=".$match.",value[".gettype($value)."]=".$value."<br />\n";
1391 if (($setMatchAsCode === true) && (is_null($value))) {
1393 $rawCode = str_replace($varCode, $match, $rawCode);
1396 $rawCode = str_replace($varCode, $value, $rawCode);
1401 // Return the compiled data
1402 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1407 * Getter for variable group array
1409 * @return $vargroups All variable groups
1411 public final function getVariableGroups () {
1412 return $this->varGroups;
1416 * Renames a variable in code and in stack
1418 * @param $oldName Old name of variable
1419 * @param $newName New name of variable
1422 public function renameVariable ($oldName, $newName) {
1423 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1424 // Get raw template code
1425 $rawData = $this->getRawTemplateData();
1428 $rawData = str_replace($oldName, $newName, $rawData);
1430 // Set the code back
1431 $this->setRawTemplateData($rawData);
1435 * Renders the given XML content
1437 * @param $content Valid XML content or if not set the current loaded raw content
1439 * @throws XmlParserException If an XML error was found
1441 public function renderXmlContent ($content = null) {
1442 // Is the content set?
1443 if (is_null($content)) {
1444 // Get current content
1445 $content = $this->getRawTemplateData();
1448 // Get a XmlParser instance
1449 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1451 // Check if we have XML compacting enabled
1452 if ($this->isXmlCompactingEnabled()) {
1453 // Yes, so get a decorator class for transparent compacting
1454 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1457 // Parse the XML document
1458 $parserInstance->parseXmlContent($content);
1462 * Enables or disables language support
1464 * @param $languageSupport New language support setting
1467 public final function enableLanguageSupport ($languageSupport = true) {
1468 $this->languageSupport = (bool) $languageSupport;
1472 * Checks wether language support is enabled
1474 * @return $languageSupport Wether language support is enabled or disabled
1476 public final function isLanguageSupportEnabled () {
1477 return $this->languageSupport;
1481 * Enables or disables XML compacting
1483 * @param $xmlCompacting New XML compacting setting
1486 public final function enableXmlCompacting ($xmlCompacting = true) {
1487 $this->xmlCompacting = (bool) $xmlCompacting;
1491 * Checks wether XML compacting is enabled
1493 * @return $xmlCompacting Wether XML compacting is enabled or disabled
1495 public final function isXmlCompactingEnabled () {
1496 return $this->xmlCompacting;
1500 * Removes all commentd, tabs and new-line characters to compact the content
1502 * @param $uncompactedContent The uncompacted content
1503 * @return $compactedContent The compacted content
1505 public function compactContent ($uncompactedContent) {
1506 // First, remove all tab/new-line/revert characters
1507 $compactedContent = str_replace("\t", '', str_replace("\n", '', str_replace("\r", '', $uncompactedContent)));
1509 // Then regex all comments like <!-- //--> away
1510 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
1512 // Do we have entries?
1513 if (isset($matches[0][0])) {
1515 foreach ($matches[0] as $match) {
1517 $compactedContent = str_replace($match, '', $compactedContent);
1521 // Return compacted content
1522 return $compactedContent;