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;
150 * Protected constructor
152 * @param $className Name of the class
155 protected function __construct ($className) {
156 // Call parent constructor
157 parent::__construct($className);
161 * Search for a variable in the stack
163 * @param $var The variable we are looking for
164 * @param $stack Optional variable stack to look in
165 * @return $idx FALSE means not found, >=0 means found on a specific index
167 private function isVariableAlreadySet ($var, $stack = null) {
168 // First everything is not found
171 // If the stack is null, use the current group
172 if (is_null($stack)) $stack = $this->currGroup;
174 // Is the group there?
175 if ($this->isVarStackSet($stack)) {
177 foreach ($this->getVarStack($stack) as $idx => $currEntry) {
178 //* DEBUG: */ echo __METHOD__.":currGroup={$stack},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
179 // Is the entry found?
180 if ($currEntry['name'] == $var) {
182 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
189 // Return the current position
194 * Checks wether the given variable stack is set
196 * @param $stack Variable stack to check
197 * @return $isSet Wether the given variable stack is set
199 protected final function isVarStackSet ($stack) {
201 $isSet = isset($this->varStack[$stack]);
208 * Getter for given variable stack
210 * @param $stack Variable stack to check
211 * @return $varStack Found variable stack
213 public final function getVarStack ($stack) {
214 return $this->varStack[$stack];
218 * Return a content of a variable or null if not found
220 * @param $var The variable we are looking for
221 * @param $stack Optional variable stack to look in
222 * @return $content Content of the variable or null if not found
224 protected function readVariable ($var, $stack = null) {
225 // First everything is not found
228 // If the stack is null, use the current group
229 if (is_null($stack)) $stack = $this->currGroup;
231 // Get variable index
232 $found = $this->isVariableAlreadySet($var, $stack);
234 // Is the variable found?
235 if ($found !== false) {
237 $content = $this->getVariableValue($stack, $found);
240 // Return the current position
241 //* DEBUG: */ echo __METHOD__.": group=".$stack.",var=".$var.", content[".gettype($content)."]=".$content."<br />\n";
246 * Add a variable to the stack
248 * @param $var The variable we are looking for
249 * @param $value The value we want to store in the variable
252 private function addVariable ($var, $value) {
253 // Set general variable group
254 $this->setVariableGroup('general');
256 // Add it to the stack
257 $this->addGroupVariable($var, $value);
261 * Returns all variables of current group or empty array
263 * @return $result Wether array of found variables or empty array
265 private function readCurrentGroup () {
266 // Default is not found
269 // Is the group there?
270 if ($this->isVarStackSet($this->currGroup)) {
272 $result = $this->getVarStack($this->currGroup);
280 * Settter for variable group
282 * @param $groupName Name of variable group
283 * @param $add Wether add this group
286 public function setVariableGroup ($groupName, $add = true) {
288 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
289 $this->currGroup = $groupName;
291 // Skip group 'general'
292 if (($groupName != 'general') && ($add === true)) {
293 $this->varGroups[$groupName] = 'OK';
299 * Adds a variable to current group
301 * @param $var Variable to set
302 * @param $value Value to store in variable
305 public function addGroupVariable ($var, $value) {
306 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
308 // Get current variables in group
309 $currVars = $this->readCurrentGroup();
311 // Append our variable
317 // Add it to the stack
318 $this->setVarStack($this->currGroup, $currVars);
322 * Modify an entry on the stack
324 * @param $var The variable we are looking for
325 * @param $value The value we want to store in the variable
328 private function modifyVariable ($var, $value) {
329 // Get index for variable
330 $idx = $this->isVariableAlreadySet($var);
332 // Is the variable set?
333 if ($idx !== false) {
335 $this->setVariableValue($this->currGroup, $idx, $value);
340 * Setter for template type. Only 'html', 'emails' and 'compiled' should
343 * @param $templateType The current template's type
346 protected final function setTemplateType ($templateType) {
347 $this->templateType = (string) $templateType;
351 * Setter for the last loaded template's FQFN
353 * @param $template The last loaded template
356 private final function setLastTemplate ($template) {
357 $this->lastTemplate = (string) $template;
361 * Getter for the last loaded template's FQFN
363 * @return $template The last loaded template
365 private final function getLastTemplate () {
366 return $this->lastTemplate;
370 * Setter for base path
372 * @param $templateBasePath The relative base path for all templates
375 public final function setTemplateBasePath ($templateBasePath) {
377 $this->templateBasePath = (string) $templateBasePath;
381 * Getter for base path
383 * @return $templateBasePath The relative base path for all templates
385 public final function getTemplateBasePath () {
387 return $this->templateBasePath;
391 * Getter for generic base path
393 * @return $templateBasePath The relative base path for all templates
395 public final function getGenericBasePath () {
397 return $this->genericBasePath;
401 * Setter for template extension
403 * @param $templateExtension The file extension for all uncompiled
407 public final function setRawTemplateExtension ($templateExtension) {
409 $this->templateExtension = (string) $templateExtension;
413 * Setter for code template extension
415 * @param $codeExtension The file extension for all uncompiled
419 public final function setCodeTemplateExtension ($codeExtension) {
421 $this->codeExtension = (string) $codeExtension;
425 * Getter for template extension
427 * @return $templateExtension The file extension for all uncompiled
430 public final function getRawTemplateExtension () {
432 return $this->templateExtension;
436 * Getter for code-template extension
438 * @return $codeExtension The file extension for all code-
441 public final function getCodeTemplateExtension () {
443 return $this->codeExtension;
447 * Setter for path of compiled templates
449 * @param $compileOutputPath The local base path for all compiled
453 public final function setCompileOutputPath ($compileOutputPath) {
455 $this->compileOutputPath = (string) $compileOutputPath;
459 * Getter for template type
461 * @return $templateType The current template's type
463 public final function getTemplateType () {
464 return $this->templateType;
468 * Assign (add) a given variable with a value
470 * @param $var The variable we are looking for
471 * @param $value The value we want to store in the variable
473 * @throws EmptyVariableException If the variable name is left empty
475 public final function assignVariable ($var, $value) {
476 // Trim spaces of variable name
479 // Empty variable found?
481 // Throw an exception
482 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
485 // First search for the variable if it was already added
486 $idx = $this->isVariableAlreadySet($var);
489 if ($idx === false) {
490 // Add it to the stack
491 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
492 $this->addVariable($var, $value);
493 } elseif (!empty($value)) {
494 // Modify the stack entry
495 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
496 $this->modifyVariable($var, $value);
501 * Removes a given variable
503 * @param $var The variable we are looking for
506 public final function removeVariable ($var) {
507 // First search for the variable if it was already added
508 $idx = $this->isVariableAlreadySet($var);
511 if ($idx !== false) {
512 // Remove this variable
513 $this->varStack->offsetUnset($idx);
518 * Private setter for raw template data
520 * @param $rawTemplateData The raw data from the template
523 protected final function setRawTemplateData ($rawTemplateData) {
524 // And store it in this class
525 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
526 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->getVarStack($this->currGroup)).', groups='.count($this->varStack).'<br />\n';
527 $this->rawTemplateData = (string) $rawTemplateData;
531 * Getter for raw template data
533 * @return $rawTemplateData The raw data from the template
535 public final function getRawTemplateData () {
536 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
537 return $this->rawTemplateData;
541 * Private setter for compiled templates
545 private final function setCompiledData ($compiledData) {
546 // And store it in this class
547 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
548 $this->compiledData = (string) $compiledData;
552 * Getter for compiled templates
554 * @return $compiledData Compiled template data
556 public final function getCompiledData () {
557 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
558 return $this->compiledData;
562 * Private loader for all template types
564 * @param $template The template we shall load
565 * @param $extOther An other extension to use
567 * @throws FileIoException If the template was not found
569 protected function loadTemplate ($template, $extOther = '') {
570 // Get extension for the template if empty
571 if (empty($extOther)) {
572 // None provided, so get the raw one
573 $ext = $this->getRawTemplateExtension();
576 $ext = (string) $extOther;
579 // Is language support enabled?
580 if ($this->isLanguageSupportEnabled()) {
581 // Construct the FQFN for the template by honoring the current language
582 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
583 $this->getConfigInstance()->getConfigEntry('base_path'),
584 $this->getTemplateBasePath(),
585 $this->getGenericBasePath(),
586 $this->getLanguageInstance()->getLanguageCode(),
587 $this->getTemplateType(),
592 // Construct the FQFN for the template without language
593 $fqfn = sprintf("%s%s%s%s/%s%s",
594 $this->getConfigInstance()->getConfigEntry('base_path'),
595 $this->getTemplateBasePath(),
596 $this->getGenericBasePath(),
597 $this->getTemplateType(),
605 // Load the raw template data
606 $this->loadRawTemplateData($fqfn);
607 } catch (FileIoException $e) {
608 // If we shall load a code-template we need to switch the file extension
609 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
610 // Switch over to the code-template extension and try it again
611 $ext = $this->getCodeTemplateExtension();
614 $this->loadTemplate($template, $ext);
617 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
624 * A private loader for raw template names
626 * @param $fqfn The full-qualified file name for a template
629 private function loadRawTemplateData ($fqfn) {
630 // Get a input/output instance from the middleware
631 $ioInstance = $this->getFileIoInstance();
633 // Some debug code to look on the file which is being loaded
634 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
636 // Load the raw template
637 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
639 // Store the template's contents into this class
640 $this->setRawTemplateData($rawTemplateData);
642 // Remember the template's FQFN
643 $this->setLastTemplate($fqfn);
647 * Try to assign an extracted template variable as a "content" or 'config'
650 * @param $varName The variable's name (shall be content orconfig) by
652 * @param $var The variable we want to assign
654 private function assignTemplateVariable ($varName, $var) {
655 // Is it not a config variable?
656 if ($varName != 'config') {
657 // Regular template variables
658 $this->assignVariable($var, '');
660 // Configuration variables
661 $this->assignConfigVariable($var);
666 * Extract variables from a given raw data stream
668 * @param $rawData The raw template data we shall analyze
671 private function extractVariablesFromRawData ($rawData) {
673 $rawData = (string) $rawData;
675 // Search for variables
676 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
678 // Did we find some variables?
679 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
680 // Initialize all missing variables
681 foreach ($variableMatches[3] as $key => $var) {
683 $varName = $variableMatches[1][$key];
685 // Workarround: Do not assign empty variables
687 // Try to assign it, empty strings are being ignored
688 $this->assignTemplateVariable($varName, $var);
695 * Main analysis of the loaded template
697 * @param $templateMatches Found template place-holders, see below
700 *---------------------------------
701 * Structure of $templateMatches:
702 *---------------------------------
703 * [0] => Array - An array with all full matches
704 * [1] => Array - An array with left part (before the ':') of a match
705 * [2] => Array - An array with right part of a match including ':'
706 * [3] => Array - An array with right part of a match excluding ':'
708 private function analyzeTemplate (array $templateMatches) {
709 // Backup raw template data
710 $backup = $this->getRawTemplateData();
712 // Initialize some arrays
713 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
715 // Load all requested templates
716 foreach ($templateMatches[1] as $template) {
718 // Load and compile only templates which we have not yet loaded
719 // RECURSIVE PROTECTION! BE CAREFUL HERE!
720 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
722 // Template not found, but maybe variable assigned?
723 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
724 if ($this->isVariableAlreadySet($template) !== false) {
725 // Use that content here
726 $this->loadedRawData[$template] = $this->readVariable($template);
728 // Recursive protection:
729 $this->loadedTemplates[] = $template;
730 } elseif ($this->isVariableAlreadySet($template, 'config')) {
731 // Use that content here
732 $this->loadedRawData[$template] = $this->readVariable($template, 'config');
734 // Recursive protection:
735 $this->loadedTemplates[] = $template;
737 // Then try to search for code-templates
739 // Load the code template and remember it's contents
740 $this->loadCodeTemplate($template);
741 $this->loadedRawData[$template] = $this->getRawTemplateData();
743 // Remember this template for recursion detection
744 // RECURSIVE PROTECTION!
745 $this->loadedTemplates[] = $template;
746 } catch (FileIoException $e) {
747 // Even this is not done... :/
748 $this->rawTemplates[] = $template;
754 // Restore the raw template data
755 $this->setRawTemplateData($backup);
759 * Compile a given raw template code and remember it for later usage
761 * @param $code The raw template code
762 * @param $template The template's name
765 private function compileCode ($code, $template) {
766 // Is this template already compiled?
767 if (in_array($template, $this->compiledTemplates)) {
772 // Remember this template being compiled
773 $this->compiledTemplates[] = $template;
775 // Compile the loaded code in five steps:
777 // 1. Backup current template data
778 $backup = $this->getRawTemplateData();
780 // 2. Set the current template's raw data as the new content
781 $this->setRawTemplateData($code);
783 // 3. Compile the template data
784 $this->compileTemplate();
786 // 4. Remember it's contents
787 $this->loadedRawData[$template] = $this->getRawTemplateData();
789 // 5. Restore the previous raw content from backup variable
790 $this->setRawTemplateData($backup);
794 * Insert all given and loaded templates by running through all loaded
795 * codes and searching for their place-holder in the main template
797 * @param $templateMatches See method analyzeTemplate()
800 private function insertAllTemplates (array $templateMatches) {
801 // Run through all loaded codes
802 foreach ($this->loadedRawData as $template => $code) {
804 // Search for the template
805 $foundIndex = array_search($template, $templateMatches[1]);
807 // Lookup the matching template replacement
808 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
810 // Get the current raw template
811 $rawData = $this->getRawTemplateData();
813 // Replace the space holder with the template code
814 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
816 // Set the new raw data
817 $this->setRawTemplateData($rawData);
823 * Load all extra raw templates
827 private function loadExtraRawTemplates () {
828 // Are there some raw templates we need to load?
829 if (count($this->rawTemplates) > 0) {
830 // Try to load all raw templates
831 foreach ($this->rawTemplates as $key => $template) {
834 $this->loadWebTemplate($template);
836 // Remember it's contents
837 $this->rawTemplates[$template] = $this->getRawTemplateData();
839 // Remove it from the loader list
840 unset($this->rawTemplates[$key]);
842 // Remember this template for recursion detection
843 // RECURSIVE PROTECTION!
844 $this->loadedTemplates[] = $template;
845 } catch (FileIoException $e) {
846 // This template was never found. We silently ignore it
847 unset($this->rawTemplates[$key]);
854 * Assign all found template variables
856 * @param $varMatches An array full of variable/value pairs.
858 * @todo Unfinished work or don't die here.
860 private function assignAllVariables (array $varMatches) {
861 // Search for all variables
862 foreach ($varMatches[1] as $key => $var) {
864 // Detect leading equals
865 if (substr($varMatches[2][$key], 0, 1) == '=') {
866 // Remove and cast it
867 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
870 // Do we have some quotes left and right side? Then it is free text
871 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
872 // Free string detected! Which we can assign directly
873 $this->assignVariable($var, $varMatches[3][$key]);
874 } elseif (!empty($varMatches[2][$key])) {
875 // @TODO Non-string found so we need some deeper analysis...
876 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
879 } // for ($varMatches ...
882 * Compiles all loaded raw templates
884 * @param $templateMatches See method analyzeTemplate() for details
887 private function compileRawTemplateData (array $templateMatches) {
888 // Are some code-templates found which we need to compile?
889 if (count($this->loadedRawData) > 0) {
892 foreach ($this->loadedRawData as $template => $code) {
894 // Is this template already compiled?
895 if (in_array($template, $this->compiledTemplates)) {
900 // Search for the template
901 $foundIndex = array_search($template, $templateMatches[1]);
903 // Lookup the matching variable data
904 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
906 // Split it up with another reg. exp. into variable=value pairs
907 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
909 // Assign all variables
910 $this->assignAllVariables($varMatches);
912 } // END - if (isset($templateMatches ...
914 // Compile the loaded template
915 $this->compileCode($code, $template);
917 } // END - foreach ($this->loadedRawData ...
919 // Insert all templates
920 $this->insertAllTemplates($templateMatches);
922 } // END - if (count($this->loadedRawData) ...
926 * Inserts all raw templates into their respective variables
930 private function insertRawTemplates () {
931 // Load all templates
932 foreach ($this->rawTemplates as $template => $content) {
933 // Set the template as a variable with the content
934 $this->assignVariable($template, $content);
939 * Finalizes the compilation of all template variables
943 private function finalizeVariableCompilation () {
945 $content = $this->getRawTemplateData();
946 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
948 // Do we have the stack?
949 if (!$this->isVarStackSet('general')) {
950 // Abort here silently
951 // @TODO This silent abort should be logged, maybe.
955 // Walk through all variables
956 foreach ($this->getVarStack('general') as $currEntry) {
957 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
958 // Replace all [$var] or {?$var?} with the content
959 // @TODO Old behaviour, will become obsolete!
960 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
962 // @TODO Yet another old way
963 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
966 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
969 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
971 // Set the content back
972 $this->setRawTemplateData($content);
976 * Load a specified web template into the engine
978 * @param $template The web template we shall load which is located in
982 public function loadWebTemplate ($template) {
984 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
986 // Load the special template
987 $this->loadTemplate($template);
991 * Assign a given congfiguration variable with a value
993 * @param $var The configuration variable we want to assign
996 public function assignConfigVariable ($var) {
997 // Sweet and simple...
998 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
999 $this->setVariable('config', $var, $this->getConfigInstance()->getConfigEntry($var));
1003 * Load a specified code template into the engine
1005 * @param $template The code template we shall load which is
1006 * located in 'code' by default
1009 public function loadCodeTemplate ($template) {
1010 // Set template type
1011 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1013 // Load the special template
1014 $this->loadTemplate($template);
1018 * Compiles configuration place-holders in all variables. This 'walks'
1019 * through the variable stack 'general'. It interprets all values from that
1020 * variables as configuration entries after compiling them.
1024 public final function compileConfigInVariables () {
1025 // Do we have the stack?
1026 if (!$this->isVarStackSet('general')) {
1027 // Abort here silently
1028 // @TODO This silent abort should be logged, maybe.
1032 // Iterate through all general variables
1033 foreach ($this->getVarStack('general') as $idx=>$currVariable) {
1034 // Compile the value
1035 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1037 // Remove it from stack
1038 $this->removeVariable($idx, 'general');
1040 // Re-assign the variable
1041 $this->assignConfigVariable($value);
1046 * Compile all variables by inserting their respective values
1049 * @todo Make this code some nicer...
1051 public final function compileVariables () {
1052 // Initialize the $content array
1053 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1056 // Iterate through all general variables
1057 foreach ($this->getVarStack('general') as $currVariable) {
1058 // Transfer it's name/value combination to the $content array
1059 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
1060 $dummy[$currVariable['name']] = $currVariable['value'];
1063 // Set the new variable (don't remove the second dollar!)
1064 $$validVar = $dummy;
1066 // Prepare all configuration variables
1068 if ($this->isVarStackSet('config')) {
1069 $config = $this->getVarStack('config');
1072 // Remove some variables
1074 unset($currVariable);
1076 // Run the compilation three times to get content from helper classes in
1079 // Finalize the compilation of template variables
1080 $this->finalizeVariableCompilation();
1082 // Prepare the eval() command for comiling the template
1083 $eval = sprintf("\$result = \"%s\";",
1084 addslashes($this->getRawTemplateData())
1087 // This loop does remove the backslashes (\) in PHP parameters
1088 while (strpos($eval, $this->codeBegin) !== false) {
1089 // Get left part before "<?"
1090 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1092 // Get all from right of "<?"
1093 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1095 // Cut middle part out and remove escapes
1096 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1097 $evalMiddle = stripslashes($evalMiddle);
1099 // Remove the middle part from right one
1100 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1102 // And put all together
1103 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1106 // Prepare PHP code for eval() command
1107 $eval = str_replace(
1116 // Run the constructed command. This will "compile" all variables in
1119 // Goes something wrong?
1120 if ((!isset($result)) || (empty($result))) {
1121 // Output eval command
1122 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1124 // Output backtrace here
1125 $this->debugBackTrace();
1128 // Set raw template data
1129 $this->setRawTemplateData($result);
1133 // Final variable assignment
1134 $this->finalizeVariableCompilation();
1136 // Set the new content
1137 $this->setCompiledData($this->getRawTemplateData());
1141 * Compile all required templates into the current loaded one
1144 * @throws UnexpectedTemplateTypeException If the template type is
1146 * @throws InvalidArrayCountException If an unexpected array
1147 * count has been found
1149 public function compileTemplate () {
1150 // We will only work with template type "code" from configuration
1151 if ($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('code_template_type')) {
1153 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1156 // Get the raw data.
1157 $rawData = $this->getRawTemplateData();
1159 // Remove double spaces and trim leading/trailing spaces
1160 $rawData = trim(str_replace(' ', ' ', $rawData));
1162 // Search for raw variables
1163 $this->extractVariablesFromRawData($rawData);
1165 // Search for code-tags which are {? ?}
1166 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1168 // Analyze the matches array
1169 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1170 // Entries are found:
1172 // The main analysis
1173 $this->analyzeTemplate($templateMatches);
1175 // Compile raw template data
1176 $this->compileRawTemplateData($templateMatches);
1178 // Are there some raw templates left for loading?
1179 $this->loadExtraRawTemplates();
1181 // Are some raw templates found and loaded?
1182 if (count($this->rawTemplates) > 0) {
1184 // Insert all raw templates
1185 $this->insertRawTemplates();
1187 // Remove the raw template content as well
1188 $this->setRawTemplateData('');
1192 } // END - if($templateMatches ...
1196 * Loads a given view helper (by name)
1198 * @param $helperName The helper's name
1201 protected function loadViewHelper ($helperName) {
1202 // Make first character upper case, rest low
1203 $helperName = $this->convertToClassName($helperName);
1205 // Is this view helper loaded?
1206 if (!isset($this->helpers[$helperName])) {
1207 // Create a class name
1208 $className = "{$helperName}ViewHelper";
1210 // Generate new instance
1211 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1214 // Return the requested instance
1215 return $this->helpers[$helperName];
1219 * Assigns the last loaded raw template content with a given variable
1221 * @param $templateName Name of the template we want to assign
1222 * @param $variableName Name of the variable we want to assign
1225 public function assignTemplateWithVariable ($templateName, $variableName) {
1226 // Get the content from last loaded raw template
1227 $content = $this->getRawTemplateData();
1229 // Assign the variable
1230 $this->assignVariable($variableName, $content);
1232 // Purge raw content
1233 $this->setRawTemplateData('');
1237 * Transfers the content of this template engine to a given response instance
1239 * @param $responseInstance An instance of a response class
1242 public function transferToResponse (Responseable $responseInstance) {
1243 // Get the content and set it in response class
1244 $responseInstance->writeToBody($this->getCompiledData());
1248 * Assigns all the application data with template variables
1250 * @param $appInstance A manageable application instance
1253 public function assignApplicationData (ManageableApplication $appInstance) {
1254 // Get long name and assign it
1255 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1257 // Get short name and assign it
1258 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1260 // Get version number and assign it
1261 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1263 // Assign extra application-depending data
1264 $appInstance->assignExtraTemplateData($this);
1268 * "Compiles" a variable by replacing {?var?} with it's content
1270 * @param $rawCode Raw code to compile
1271 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1272 * @return $rawCode Compile code with inserted variable value
1274 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1275 // Find the variables
1276 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1277 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1279 // Compile all variables
1280 //* DEBUG: */ echo __METHOD__.":<pre>".print_r($varMatches, true)."</pre>\n";
1281 foreach ($varMatches[0] as $match) {
1282 // Add variable tags around it
1283 $varCode = '{?' . $match . '?}';
1285 // Is the variable found in code? (safes some calls)
1286 if (strpos($rawCode, $varCode) !== false) {
1287 // Replace the variable with it's value, if found
1288 $value = $this->readVariable($match);
1289 //* DEBUG: */ echo __METHOD__.": match=".$match.",value[".gettype($value)."]=".$value."<br />\n";
1290 if (($setMatchAsCode === true) && (is_null($value))) {
1292 $rawCode = str_replace($varCode, $match, $rawCode);
1295 $rawCode = str_replace($varCode, $value, $rawCode);
1300 // Return the compiled data
1301 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1306 * Getter for variable group array
1308 * @return $vargroups All variable groups
1310 public final function getVariableGroups () {
1311 return $this->varGroups;
1315 * Renames a variable in code and in stack
1317 * @param $oldName Old name of variable
1318 * @param $newName New name of variable
1321 public function renameVariable ($oldName, $newName) {
1322 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1323 // Get raw template code
1324 $rawData = $this->getRawTemplateData();
1327 $rawData = str_replace($oldName, $newName, $rawData);
1329 // Set the code back
1330 $this->setRawTemplateData($rawData);
1334 * Renders the given XML content
1336 * @param $content Valid XML content or if not set the current loaded raw content
1338 * @throws XmlParserException If an XML error was found
1340 public function renderXmlContent ($content = null) {
1341 // Is the content set?
1342 if (is_null($content)) {
1343 // Get current content
1344 $content = $this->getRawTemplateData();
1347 // Get a XmlParser instance
1348 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1350 // Check if we have XML compacting enabled
1351 if ($this->isXmlCompactingEnabled()) {
1352 // Yes, so get a decorator class for transparent compacting
1353 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1356 // Parse the XML document
1357 $parserInstance->parseXmlContent($content);
1361 * Enables or disables language support
1363 * @param $languageSupport New language support setting
1366 public final function enableLanguageSupport ($languageSupport = true) {
1367 $this->languageSupport = (bool) $languageSupport;
1371 * Checks wether language support is enabled
1373 * @return $languageSupport Wether language support is enabled or disabled
1375 public final function isLanguageSupportEnabled () {
1376 return $this->languageSupport;
1380 * Enables or disables XML compacting
1382 * @param $xmlCompacting New XML compacting setting
1385 public final function enableXmlCompacting ($xmlCompacting = true) {
1386 $this->xmlCompacting = (bool) $xmlCompacting;
1390 * Checks wether XML compacting is enabled
1392 * @return $xmlCompacting Wether XML compacting is enabled or disabled
1394 public final function isXmlCompactingEnabled () {
1395 return $this->xmlCompacting;