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->varStack->offsetUnset($index);
598 * Private setter for raw template data
600 * @param $rawTemplateData The raw data from the template
603 protected final function setRawTemplateData ($rawTemplateData) {
604 // And store it in this class
605 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
606 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->getVarStack($this->currGroup)).', groups='.count($this->varStack).'<br />\n';
607 $this->rawTemplateData = (string) $rawTemplateData;
611 * Getter for raw template data
613 * @return $rawTemplateData The raw data from the template
615 public final function getRawTemplateData () {
616 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
617 return $this->rawTemplateData;
621 * Private setter for compiled templates
625 private final function setCompiledData ($compiledData) {
626 // And store it in this class
627 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
628 $this->compiledData = (string) $compiledData;
632 * Getter for compiled templates
634 * @return $compiledData Compiled template data
636 public final function getCompiledData () {
637 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
638 return $this->compiledData;
642 * Private loader for all template types
644 * @param $template The template we shall load
645 * @param $extOther An other extension to use
647 * @throws FileIoException If the template was not found
649 protected function loadTemplate ($template, $extOther = '') {
650 // Get extension for the template if empty
651 if (empty($extOther)) {
652 // None provided, so get the raw one
653 $ext = $this->getRawTemplateExtension();
656 $ext = (string) $extOther;
659 // Is language support enabled?
660 if ($this->isLanguageSupportEnabled()) {
661 // Construct the FQFN for the template by honoring the current language
662 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
663 $this->getConfigInstance()->getConfigEntry('base_path'),
664 $this->getTemplateBasePath(),
665 $this->getGenericBasePath(),
666 $this->getLanguageInstance()->getLanguageCode(),
667 $this->getTemplateType(),
672 // Construct the FQFN for the template without language
673 $fqfn = sprintf("%s%s%s%s/%s%s",
674 $this->getConfigInstance()->getConfigEntry('base_path'),
675 $this->getTemplateBasePath(),
676 $this->getGenericBasePath(),
677 $this->getTemplateType(),
685 // Load the raw template data
686 $this->loadRawTemplateData($fqfn);
687 } catch (FileIoException $e) {
688 // If we shall load a code-template we need to switch the file extension
689 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
690 // Switch over to the code-template extension and try it again
691 $ext = $this->getCodeTemplateExtension();
694 $this->loadTemplate($template, $ext);
697 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
704 * A private loader for raw template names
706 * @param $fqfn The full-qualified file name for a template
709 private function loadRawTemplateData ($fqfn) {
710 // Get a input/output instance from the middleware
711 $ioInstance = $this->getFileIoInstance();
713 // Some debug code to look on the file which is being loaded
714 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
716 // Load the raw template
717 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
719 // Store the template's contents into this class
720 $this->setRawTemplateData($rawTemplateData);
722 // Remember the template's FQFN
723 $this->setLastTemplate($fqfn);
727 * Try to assign an extracted template variable as a "content" or 'config'
730 * @param $varName The variable's name (shall be content orconfig) by
732 * @param $var The variable we want to assign
734 private function assignTemplateVariable ($varName, $var) {
735 // Is it not a config variable?
736 if ($varName != 'config') {
737 // Regular template variables
738 $this->assignVariable($var, '');
740 // Configuration variables
741 $this->assignConfigVariable($var);
746 * Extract variables from a given raw data stream
748 * @param $rawData The raw template data we shall analyze
751 private function extractVariablesFromRawData ($rawData) {
753 $rawData = (string) $rawData;
755 // Search for variables
756 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
758 // Did we find some variables?
759 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
760 // Initialize all missing variables
761 foreach ($variableMatches[3] as $key => $var) {
763 $varName = $variableMatches[1][$key];
765 // Workarround: Do not assign empty variables
767 // Try to assign it, empty strings are being ignored
768 $this->assignTemplateVariable($varName, $var);
775 * Main analysis of the loaded template
777 * @param $templateMatches Found template place-holders, see below
780 *---------------------------------
781 * Structure of $templateMatches:
782 *---------------------------------
783 * [0] => Array - An array with all full matches
784 * [1] => Array - An array with left part (before the ':') of a match
785 * [2] => Array - An array with right part of a match including ':'
786 * [3] => Array - An array with right part of a match excluding ':'
788 private function analyzeTemplate (array $templateMatches) {
789 // Backup raw template data
790 $backup = $this->getRawTemplateData();
792 // Initialize some arrays
793 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
795 // Load all requested templates
796 foreach ($templateMatches[1] as $template) {
798 // Load and compile only templates which we have not yet loaded
799 // RECURSIVE PROTECTION! BE CAREFUL HERE!
800 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
802 // Template not found, but maybe variable assigned?
803 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
804 if ($this->getVariableIndex($template) !== false) {
805 // Use that content here
806 $this->loadedRawData[$template] = $this->readVariable($template);
808 // Recursive protection:
809 $this->loadedTemplates[] = $template;
810 } elseif ($this->getVariableIndex($template, 'config')) {
811 // Use that content here
812 $this->loadedRawData[$template] = $this->readVariable($template, 'config');
814 // Recursive protection:
815 $this->loadedTemplates[] = $template;
817 // Then try to search for code-templates
819 // Load the code template and remember it's contents
820 $this->loadCodeTemplate($template);
821 $this->loadedRawData[$template] = $this->getRawTemplateData();
823 // Remember this template for recursion detection
824 // RECURSIVE PROTECTION!
825 $this->loadedTemplates[] = $template;
826 } catch (FileIoException $e) {
827 // Even this is not done... :/
828 $this->rawTemplates[] = $template;
834 // Restore the raw template data
835 $this->setRawTemplateData($backup);
839 * Compile a given raw template code and remember it for later usage
841 * @param $code The raw template code
842 * @param $template The template's name
845 private function compileCode ($code, $template) {
846 // Is this template already compiled?
847 if (in_array($template, $this->compiledTemplates)) {
852 // Remember this template being compiled
853 $this->compiledTemplates[] = $template;
855 // Compile the loaded code in five steps:
857 // 1. Backup current template data
858 $backup = $this->getRawTemplateData();
860 // 2. Set the current template's raw data as the new content
861 $this->setRawTemplateData($code);
863 // 3. Compile the template data
864 $this->compileTemplate();
866 // 4. Remember it's contents
867 $this->loadedRawData[$template] = $this->getRawTemplateData();
869 // 5. Restore the previous raw content from backup variable
870 $this->setRawTemplateData($backup);
874 * Insert all given and loaded templates by running through all loaded
875 * codes and searching for their place-holder in the main template
877 * @param $templateMatches See method analyzeTemplate()
880 private function insertAllTemplates (array $templateMatches) {
881 // Run through all loaded codes
882 foreach ($this->loadedRawData as $template => $code) {
884 // Search for the template
885 $foundIndex = array_search($template, $templateMatches[1]);
887 // Lookup the matching template replacement
888 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
890 // Get the current raw template
891 $rawData = $this->getRawTemplateData();
893 // Replace the space holder with the template code
894 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
896 // Set the new raw data
897 $this->setRawTemplateData($rawData);
903 * Load all extra raw templates
907 private function loadExtraRawTemplates () {
908 // Are there some raw templates we need to load?
909 if (count($this->rawTemplates) > 0) {
910 // Try to load all raw templates
911 foreach ($this->rawTemplates as $key => $template) {
914 $this->loadWebTemplate($template);
916 // Remember it's contents
917 $this->rawTemplates[$template] = $this->getRawTemplateData();
919 // Remove it from the loader list
920 unset($this->rawTemplates[$key]);
922 // Remember this template for recursion detection
923 // RECURSIVE PROTECTION!
924 $this->loadedTemplates[] = $template;
925 } catch (FileIoException $e) {
926 // This template was never found. We silently ignore it
927 unset($this->rawTemplates[$key]);
934 * Assign all found template variables
936 * @param $varMatches An array full of variable/value pairs.
938 * @todo Unfinished work or don't die here.
940 private function assignAllVariables (array $varMatches) {
941 // Search for all variables
942 foreach ($varMatches[1] as $key => $var) {
944 // Detect leading equals
945 if (substr($varMatches[2][$key], 0, 1) == '=') {
946 // Remove and cast it
947 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
950 // Do we have some quotes left and right side? Then it is free text
951 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
952 // Free string detected! Which we can assign directly
953 $this->assignVariable($var, $varMatches[3][$key]);
954 } elseif (!empty($varMatches[2][$key])) {
955 // @TODO Non-string found so we need some deeper analysis...
956 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
959 } // for ($varMatches ...
962 * Compiles all loaded raw templates
964 * @param $templateMatches See method analyzeTemplate() for details
967 private function compileRawTemplateData (array $templateMatches) {
968 // Are some code-templates found which we need to compile?
969 if (count($this->loadedRawData) > 0) {
972 foreach ($this->loadedRawData as $template => $code) {
974 // Is this template already compiled?
975 if (in_array($template, $this->compiledTemplates)) {
980 // Search for the template
981 $foundIndex = array_search($template, $templateMatches[1]);
983 // Lookup the matching variable data
984 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
986 // Split it up with another reg. exp. into variable=value pairs
987 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
989 // Assign all variables
990 $this->assignAllVariables($varMatches);
992 } // END - if (isset($templateMatches ...
994 // Compile the loaded template
995 $this->compileCode($code, $template);
997 } // END - foreach ($this->loadedRawData ...
999 // Insert all templates
1000 $this->insertAllTemplates($templateMatches);
1002 } // END - if (count($this->loadedRawData) ...
1006 * Inserts all raw templates into their respective variables
1010 private function insertRawTemplates () {
1011 // Load all templates
1012 foreach ($this->rawTemplates as $template => $content) {
1013 // Set the template as a variable with the content
1014 $this->assignVariable($template, $content);
1019 * Finalizes the compilation of all template variables
1023 private function finalizeVariableCompilation () {
1025 $content = $this->getRawTemplateData();
1026 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
1028 // Do we have the stack?
1029 if (!$this->isVarStackSet('general')) {
1030 // Abort here silently
1031 // @TODO This silent abort should be logged, maybe.
1035 // Walk through all variables
1036 foreach ($this->getVarStack('general') as $currEntry) {
1037 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
1038 // Replace all [$var] or {?$var?} with the content
1039 // @TODO Old behaviour, will become obsolete!
1040 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1042 // @TODO Yet another old way
1043 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1045 // The new behaviour
1046 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1049 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
1051 // Set the content back
1052 $this->setRawTemplateData($content);
1056 * Load a specified web template into the engine
1058 * @param $template The web template we shall load which is located in
1062 public function loadWebTemplate ($template) {
1063 // Set template type
1064 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
1066 // Load the special template
1067 $this->loadTemplate($template);
1071 * Assign a given congfiguration variable with a value
1073 * @param $var The configuration variable we want to assign
1076 public function assignConfigVariable ($var) {
1077 // Sweet and simple...
1078 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
1079 $this->setVariable('config', $var, $this->getConfigInstance()->getConfigEntry($var));
1083 * Load a specified code template into the engine
1085 * @param $template The code template we shall load which is
1086 * located in 'code' by default
1089 public function loadCodeTemplate ($template) {
1090 // Set template type
1091 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1093 // Load the special template
1094 $this->loadTemplate($template);
1098 * Compiles configuration place-holders in all variables. This 'walks'
1099 * through the variable stack 'general'. It interprets all values from that
1100 * variables as configuration entries after compiling them.
1104 public final function compileConfigInVariables () {
1105 // Do we have the stack?
1106 if (!$this->isVarStackSet('general')) {
1107 // Abort here silently
1108 // @TODO This silent abort should be logged, maybe.
1112 // Iterate through all general variables
1113 foreach ($this->getVarStack('general') as $index=>$currVariable) {
1114 // Compile the value
1115 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1117 // Remove it from stack
1118 $this->removeVariable($index, 'general');
1120 // Re-assign the variable
1121 $this->assignConfigVariable($value);
1126 * Compile all variables by inserting their respective values
1129 * @todo Make this code some nicer...
1131 public final function compileVariables () {
1132 // Initialize the $content array
1133 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1136 // Iterate through all general variables
1137 foreach ($this->getVarStack('general') as $currVariable) {
1138 // Transfer it's name/value combination to the $content array
1139 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
1140 $dummy[$currVariable['name']] = $currVariable['value'];
1143 // Set the new variable (don't remove the second dollar!)
1144 $$validVar = $dummy;
1146 // Prepare all configuration variables
1148 if ($this->isVarStackSet('config')) {
1149 $config = $this->getVarStack('config');
1152 // Remove some variables
1154 unset($currVariable);
1156 // Run the compilation three times to get content from helper classes in
1159 // Finalize the compilation of template variables
1160 $this->finalizeVariableCompilation();
1162 // Prepare the eval() command for comiling the template
1163 $eval = sprintf("\$result = \"%s\";",
1164 addslashes($this->getRawTemplateData())
1167 // This loop does remove the backslashes (\) in PHP parameters
1168 while (strpos($eval, $this->codeBegin) !== false) {
1169 // Get left part before "<?"
1170 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1172 // Get all from right of "<?"
1173 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1175 // Cut middle part out and remove escapes
1176 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1177 $evalMiddle = stripslashes($evalMiddle);
1179 // Remove the middle part from right one
1180 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1182 // And put all together
1183 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1186 // Prepare PHP code for eval() command
1187 $eval = str_replace(
1196 // Run the constructed command. This will "compile" all variables in
1199 // Goes something wrong?
1200 if ((!isset($result)) || (empty($result))) {
1201 // Output eval command
1202 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1204 // Output backtrace here
1205 $this->debugBackTrace();
1208 // Set raw template data
1209 $this->setRawTemplateData($result);
1213 // Final variable assignment
1214 $this->finalizeVariableCompilation();
1216 // Set the new content
1217 $this->setCompiledData($this->getRawTemplateData());
1221 * Compile all required templates into the current loaded one
1224 * @throws UnexpectedTemplateTypeException If the template type is
1226 * @throws InvalidArrayCountException If an unexpected array
1227 * count has been found
1229 public function compileTemplate () {
1230 // We will only work with template type "code" from configuration
1231 if ($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('code_template_type')) {
1233 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1236 // Get the raw data.
1237 $rawData = $this->getRawTemplateData();
1239 // Remove double spaces and trim leading/trailing spaces
1240 $rawData = trim(str_replace(' ', ' ', $rawData));
1242 // Search for raw variables
1243 $this->extractVariablesFromRawData($rawData);
1245 // Search for code-tags which are {? ?}
1246 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1248 // Analyze the matches array
1249 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1250 // Entries are found:
1252 // The main analysis
1253 $this->analyzeTemplate($templateMatches);
1255 // Compile raw template data
1256 $this->compileRawTemplateData($templateMatches);
1258 // Are there some raw templates left for loading?
1259 $this->loadExtraRawTemplates();
1261 // Are some raw templates found and loaded?
1262 if (count($this->rawTemplates) > 0) {
1264 // Insert all raw templates
1265 $this->insertRawTemplates();
1267 // Remove the raw template content as well
1268 $this->setRawTemplateData('');
1272 } // END - if($templateMatches ...
1276 * Loads a given view helper (by name)
1278 * @param $helperName The helper's name
1281 protected function loadViewHelper ($helperName) {
1282 // Make first character upper case, rest low
1283 $helperName = $this->convertToClassName($helperName);
1285 // Is this view helper loaded?
1286 if (!isset($this->helpers[$helperName])) {
1287 // Create a class name
1288 $className = "{$helperName}ViewHelper";
1290 // Generate new instance
1291 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1294 // Return the requested instance
1295 return $this->helpers[$helperName];
1299 * Assigns the last loaded raw template content with a given variable
1301 * @param $templateName Name of the template we want to assign
1302 * @param $variableName Name of the variable we want to assign
1305 public function assignTemplateWithVariable ($templateName, $variableName) {
1306 // Get the content from last loaded raw template
1307 $content = $this->getRawTemplateData();
1309 // Assign the variable
1310 $this->assignVariable($variableName, $content);
1312 // Purge raw content
1313 $this->setRawTemplateData('');
1317 * Transfers the content of this template engine to a given response instance
1319 * @param $responseInstance An instance of a response class
1322 public function transferToResponse (Responseable $responseInstance) {
1323 // Get the content and set it in response class
1324 $responseInstance->writeToBody($this->getCompiledData());
1328 * Assigns all the application data with template variables
1330 * @param $appInstance A manageable application instance
1333 public function assignApplicationData (ManageableApplication $appInstance) {
1334 // Get long name and assign it
1335 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1337 // Get short name and assign it
1338 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1340 // Get version number and assign it
1341 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1343 // Assign extra application-depending data
1344 $appInstance->assignExtraTemplateData($this);
1348 * "Compiles" a variable by replacing {?var?} with it's content
1350 * @param $rawCode Raw code to compile
1351 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1352 * @return $rawCode Compile code with inserted variable value
1354 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1355 // Find the variables
1356 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1357 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1359 // Compile all variables
1360 //* DEBUG: */ echo __METHOD__.":<pre>".print_r($varMatches, true)."</pre>\n";
1361 foreach ($varMatches[0] as $match) {
1362 // Add variable tags around it
1363 $varCode = '{?' . $match . '?}';
1365 // Is the variable found in code? (safes some calls)
1366 if (strpos($rawCode, $varCode) !== false) {
1367 // Replace the variable with it's value, if found
1368 $value = $this->readVariable($match);
1369 //* DEBUG: */ echo __METHOD__.": match=".$match.",value[".gettype($value)."]=".$value."<br />\n";
1370 if (($setMatchAsCode === true) && (is_null($value))) {
1372 $rawCode = str_replace($varCode, $match, $rawCode);
1375 $rawCode = str_replace($varCode, $value, $rawCode);
1380 // Return the compiled data
1381 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1386 * Getter for variable group array
1388 * @return $vargroups All variable groups
1390 public final function getVariableGroups () {
1391 return $this->varGroups;
1395 * Renames a variable in code and in stack
1397 * @param $oldName Old name of variable
1398 * @param $newName New name of variable
1401 public function renameVariable ($oldName, $newName) {
1402 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1403 // Get raw template code
1404 $rawData = $this->getRawTemplateData();
1407 $rawData = str_replace($oldName, $newName, $rawData);
1409 // Set the code back
1410 $this->setRawTemplateData($rawData);
1414 * Renders the given XML content
1416 * @param $content Valid XML content or if not set the current loaded raw content
1418 * @throws XmlParserException If an XML error was found
1420 public function renderXmlContent ($content = null) {
1421 // Is the content set?
1422 if (is_null($content)) {
1423 // Get current content
1424 $content = $this->getRawTemplateData();
1427 // Get a XmlParser instance
1428 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1430 // Check if we have XML compacting enabled
1431 if ($this->isXmlCompactingEnabled()) {
1432 // Yes, so get a decorator class for transparent compacting
1433 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1436 // Parse the XML document
1437 $parserInstance->parseXmlContent($content);
1441 * Enables or disables language support
1443 * @param $languageSupport New language support setting
1446 public final function enableLanguageSupport ($languageSupport = true) {
1447 $this->languageSupport = (bool) $languageSupport;
1451 * Checks wether language support is enabled
1453 * @return $languageSupport Wether language support is enabled or disabled
1455 public final function isLanguageSupportEnabled () {
1456 return $this->languageSupport;
1460 * Enables or disables XML compacting
1462 * @param $xmlCompacting New XML compacting setting
1465 public final function enableXmlCompacting ($xmlCompacting = true) {
1466 $this->xmlCompacting = (bool) $xmlCompacting;
1470 * Checks wether XML compacting is enabled
1472 * @return $xmlCompacting Wether XML compacting is enabled or disabled
1474 public final function isXmlCompactingEnabled () {
1475 return $this->xmlCompacting;