3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007 - 2009 Roland Haeder, this is free software
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 $basePath = '';
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 $basePath and language code for compiled code-templates
50 private $compileOutputPath = 'templates/_compiled';
53 * The raw (maybe uncompiled) template
55 private $rawTemplateData = '';
58 * Template data with compiled-in variables
60 private $compiledData = '';
63 * The last loaded template's FQFN for debugging the engine
65 private $lastTemplate = '';
68 * The variable stack for the templates
70 private $varStack = array();
73 * Loaded templates for recursive protection and detection
75 private $loadedTemplates = array();
78 * Compiled templates for recursive protection and detection
80 private $compiledTemplates = array();
83 * Loaded raw template data
85 private $loadedRawData = null;
88 * Raw templates which are linked in code templates
90 private $rawTemplates = null;
93 * A regular expression for variable=value pairs
95 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
98 * A regular expression for filtering out code tags
100 * E.g.: {?template:variable=value;var2=value2;[...]?}
102 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
107 private $helpers = array();
110 * Current variable group
112 private $currGroup = 'general';
115 * All template groups except "general"
117 private $varGroups = array();
122 private $codeBegin = '<?php';
127 private $codeEnd = '?>';
129 // Exception codes for the template engine
130 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
131 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
132 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
135 * Protected constructor
137 * @param $className Name of the class
140 protected function __construct ($className) {
141 // Call parent constructor
142 parent::__construct($className);
145 $this->removeNumberFormaters();
146 $this->removeSystemArray();
150 * Search for a variable in the stack
152 * @param $var The variable we are looking for
153 * @return $idx FALSE means not found, >=0 means found on a specific index
155 private function isVariableAlreadySet ($var) {
156 // First everything is not found
159 // Is the group there?
160 if (isset($this->varStack[$this->currGroup])) {
162 foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
163 //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
164 // Is the entry found?
165 if ($currEntry['name'] == $var) {
167 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
174 // Return the current position
179 * Return a content of a variable or null if not found
181 * @param $var The variable we are looking for
182 * @return $content Content of the variable or null if not found
184 protected function readVariable ($var) {
185 // First everything is not found
188 // Get variable index
189 $found = $this->isVariableAlreadySet($var);
191 // Is the variable found?
192 if ($found !== false) {
194 $found = $this->varStack[$this->currGroup][$found]['value'];
197 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
199 // Return the current position
204 * Add a variable to the stack
206 * @param $var The variable we are looking for
207 * @param $value The value we want to store in the variable
210 private function addVariable ($var, $value) {
211 // Set general variable group
212 $this->setVariableGroup('general');
214 // Add it to the stack
215 $this->addGroupVariable($var, $value);
219 * Returns all variables of current group or empty array
221 * @return $result Wether array of found variables or empty array
223 private function readCurrentGroup () {
224 // Default is not found
227 // Is the group there?
228 if (isset($this->varStack[$this->currGroup])) {
230 $result = $this->varStack[$this->currGroup];
238 * Settter for variable group
240 * @param $groupName Name of variable group
241 * @param $add Wether add this group
244 public function setVariableGroup ($groupName, $add = true) {
246 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
247 $this->currGroup = $groupName;
249 // Skip group 'general'
250 if (($groupName != 'general') && ($add === true)) {
251 $this->varGroups[$groupName] = 'OK';
257 * Adds a variable to current group
259 * @param $var Variable to set
260 * @param $value Value to store in variable
263 public function addGroupVariable ($var, $value) {
264 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
266 // Get current variables in group
267 $currVars = $this->readCurrentGroup();
269 // Append our variable
275 // Add it to the stack
276 $this->varStack[$this->currGroup] = $currVars;
280 * Modify an entry on the stack
282 * @param $var The variable we are looking for
283 * @param $value The value we want to store in the variable
286 private function modifyVariable ($var, $value) {
287 // Get index for variable
288 $idx = $this->isVariableAlreadySet($var);
290 // Is the variable set?
291 if ($idx !== false) {
293 $this->varStack[$this->currGroup][$idx]['value'] = $value;
298 * Setter for template type. Only 'html', 'emails' and 'compiled' should
301 * @param $templateType The current template's type
304 private final function setTemplateType ($templateType) {
305 $this->templateType = (string) $templateType;
309 * Setter for the last loaded template's FQFN
311 * @param $template The last loaded template
314 private final function setLastTemplate ($template) {
315 $this->lastTemplate = (string) $template;
319 * Getter for the last loaded template's FQFN
321 * @return $template The last loaded template
323 private final function getLastTemplate () {
324 return $this->lastTemplate;
328 * Setter for base path
330 * @param $basePath The local base path for all templates
333 public final function setBasePath ($basePath) {
335 $this->basePath = (string) $basePath;
339 * Getter for base path
341 * @return $basePath The local base path for all templates
343 public final function getBasePath () {
345 return $this->basePath;
349 * Setter for template extension
351 * @param $templateExtension The file extension for all uncompiled
355 public final function setRawTemplateExtension ($templateExtension) {
357 $this->templateExtension = (string) $templateExtension;
361 * Setter for code template extension
363 * @param $codeExtension The file extension for all uncompiled
367 public final function setCodeTemplateExtension ($codeExtension) {
369 $this->codeExtension = (string) $codeExtension;
373 * Getter for template extension
375 * @return $templateExtension The file extension for all uncompiled
378 public final function getRawTemplateExtension () {
380 return $this->templateExtension;
384 * Getter for code-template extension
386 * @return $codeExtension The file extension for all code-
389 public final function getCodeTemplateExtension () {
391 return $this->codeExtension;
395 * Setter for path of compiled templates
397 * @param $compileOutputPath The local base path for all compiled
401 public final function setCompileOutputPath ($compileOutputPath) {
403 $this->compileOutputPath = (string) $compileOutputPath;
407 * Getter for template type
409 * @return $templateType The current template's type
411 public final function getTemplateType () {
412 return $this->templateType;
416 * Assign (add) a given variable with a value
418 * @param $var The variable we are looking for
419 * @param $value The value we want to store in the variable
421 * @throws EmptyVariableException If the variable name is left empty
423 public final function assignVariable ($var, $value) {
424 // Trim spaces of variable name
427 // Empty variable found?
429 // Throw an exception
430 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
433 // First search for the variable if it was already added
434 $idx = $this->isVariableAlreadySet($var);
437 if ($idx === false) {
438 // Add it to the stack
439 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
440 $this->addVariable($var, $value);
441 } elseif (!empty($value)) {
442 // Modify the stack entry
443 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
444 $this->modifyVariable($var, $value);
449 * Removes a given variable
451 * @param $var The variable we are looking for
454 public final function removeVariable ($var) {
455 // First search for the variable if it was already added
456 $idx = $this->isVariableAlreadySet($var);
459 if ($idx !== false) {
460 // Remove this variable
461 $this->varStack->offsetUnset($idx);
466 * Private setter for raw template data
468 * @param $rawTemplateData The raw data from the template
471 protected final function setRawTemplateData ($rawTemplateData) {
472 // And store it in this class
473 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
474 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->varStack[$this->currGroup]).', groups='.count($this->varStack).'<br />\n';
475 $this->rawTemplateData = (string) $rawTemplateData;
479 * Getter for raw template data
481 * @return $rawTemplateData The raw data from the template
483 public final function getRawTemplateData () {
484 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
485 return $this->rawTemplateData;
489 * Private setter for compiled templates
493 private final function setCompiledData ($compiledData) {
494 // And store it in this class
495 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
496 $this->compiledData = (string) $compiledData;
500 * Getter for compiled templates
502 * @return $compiledData Compiled template data
504 public final function getCompiledData () {
505 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
506 return $this->compiledData;
510 * Private loader for all template types
512 * @param $template The template we shall load
515 private function loadTemplate ($template) {
516 // Get extension for the template
517 $ext = $this->getRawTemplateExtension();
519 // If we shall load a code-template we need to switch the file extension
520 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
521 // Switch over to the code-template extension
522 $ext = $this->getCodeTemplateExtension();
525 // Construct the FQFN for the template by honoring the current language
526 $fqfn = sprintf("%s%s/%s/%s%s",
527 $this->getBasePath(),
528 $this->getLanguageInstance()->getLanguageCode(),
529 $this->getTemplateType(),
534 // Load the raw template data
535 $this->loadRawTemplateData($fqfn);
539 * A private loader for raw template names
541 * @param $fqfn The full-qualified file name for a template
544 private function loadRawTemplateData ($fqfn) {
545 // Get a input/output instance from the middleware
546 $ioInstance = $this->getFileIoInstance();
548 // Some debug code to look on the file which is being loaded
549 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
551 // Load the raw template
552 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
554 // Store the template's contents into this class
555 $this->setRawTemplateData($rawTemplateData);
557 // Remember the template's FQFN
558 $this->setLastTemplate($fqfn);
562 * Try to assign an extracted template variable as a "content" or 'config'
565 * @param $varName The variable's name (shall be content orconfig) by
567 * @param $var The variable we want to assign
569 private function assignTemplateVariable ($varName, $var) {
570 // Is it not a config variable?
571 if ($varName != 'config') {
572 // Regular template variables
573 $this->assignVariable($var, '');
575 // Configuration variables
576 $this->assignConfigVariable($var);
581 * Extract variables from a given raw data stream
583 * @param $rawData The raw template data we shall analyze
586 private function extractVariablesFromRawData ($rawData) {
588 $rawData = (string) $rawData;
590 // Search for variables
591 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
593 // Did we find some variables?
594 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
595 // Initialize all missing variables
596 foreach ($variableMatches[3] as $key => $var) {
598 $varName = $variableMatches[1][$key];
600 // Workarround: Do not assign empty variables
602 // Try to assign it, empty strings are being ignored
603 $this->assignTemplateVariable($varName, $var);
610 * Main analysis of the loaded template
612 * @param $templateMatches Found template place-holders, see below
615 *---------------------------------
616 * Structure of $templateMatches:
617 *---------------------------------
618 * [0] => Array - An array with all full matches
619 * [1] => Array - An array with left part (before the ':') of a match
620 * [2] => Array - An array with right part of a match including ':'
621 * [3] => Array - An array with right part of a match excluding ':'
623 private function analyzeTemplate (array $templateMatches) {
624 // Backup raw template data
625 $backup = $this->getRawTemplateData();
627 // Initialize some arrays
628 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
630 // Load all requested templates
631 foreach ($templateMatches[1] as $template) {
633 // Load and compile only templates which we have not yet loaded
634 // RECURSIVE PROTECTION! BE CAREFUL HERE!
635 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
637 // Template not found, but maybe variable assigned?
638 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
639 if ($this->isVariableAlreadySet($template) !== false) {
640 // Use that content here
641 $this->loadedRawData[$template] = $this->readVariable($template);
643 // Recursive protection:
644 $this->loadedTemplates[] = $template;
645 } elseif (isset($this->varStack['config'][$template])) {
646 // Use that content here
647 $this->loadedRawData[$template] = $this->varStack['config'][$template];
649 // Recursive protection:
650 $this->loadedTemplates[] = $template;
652 // Then try to search for code-templates
654 // Load the code template and remember it's contents
655 $this->loadCodeTemplate($template);
656 $this->loadedRawData[$template] = $this->getRawTemplateData();
658 // Remember this template for recursion detection
659 // RECURSIVE PROTECTION!
660 $this->loadedTemplates[] = $template;
661 } catch (FileNotFoundException $e) {
662 // Even this is not done... :/
663 $this->rawTemplates[] = $template;
664 } catch (FilePointerNotOpenedException $e) {
665 // Even this is not done... :/
666 $this->rawTemplates[] = $template;
672 // Restore the raw template data
673 $this->setRawTemplateData($backup);
677 * Compile a given raw template code and remember it for later usage
679 * @param $code The raw template code
680 * @param $template The template's name
683 private function compileCode ($code, $template) {
684 // Is this template already compiled?
685 if (in_array($template, $this->compiledTemplates)) {
690 // Remember this template being compiled
691 $this->compiledTemplates[] = $template;
693 // Compile the loaded code in five steps:
695 // 1. Backup current template data
696 $backup = $this->getRawTemplateData();
698 // 2. Set the current template's raw data as the new content
699 $this->setRawTemplateData($code);
701 // 3. Compile the template data
702 $this->compileTemplate();
704 // 4. Remember it's contents
705 $this->loadedRawData[$template] = $this->getRawTemplateData();
707 // 5. Restore the previous raw content from backup variable
708 $this->setRawTemplateData($backup);
712 * Insert all given and loaded templates by running through all loaded
713 * codes and searching for their place-holder in the main template
715 * @param $templateMatches See method analyzeTemplate()
718 private function insertAllTemplates (array $templateMatches) {
719 // Run through all loaded codes
720 foreach ($this->loadedRawData as $template => $code) {
722 // Search for the template
723 $foundIndex = array_search($template, $templateMatches[1]);
725 // Lookup the matching template replacement
726 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
728 // Get the current raw template
729 $rawData = $this->getRawTemplateData();
731 // Replace the space holder with the template code
732 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
734 // Set the new raw data
735 $this->setRawTemplateData($rawData);
741 * Load all extra raw templates
745 private function loadExtraRawTemplates () {
746 // Are there some raw templates we need to load?
747 if (count($this->rawTemplates) > 0) {
748 // Try to load all raw templates
749 foreach ($this->rawTemplates as $key => $template) {
752 $this->loadWebTemplate($template);
754 // Remember it's contents
755 $this->rawTemplates[$template] = $this->getRawTemplateData();
757 // Remove it from the loader list
758 unset($this->rawTemplates[$key]);
760 // Remember this template for recursion detection
761 // RECURSIVE PROTECTION!
762 $this->loadedTemplates[] = $template;
763 } catch (FileNotFoundException $e) {
764 // This template was never found. We silently ignore it
765 unset($this->rawTemplates[$key]);
766 } catch (FilePointerNotOpenedException $e) {
767 // This template was never found. We silently ignore it
768 unset($this->rawTemplates[$key]);
775 * Assign all found template variables
777 * @param $varMatches An array full of variable/value pairs.
779 * @todo Unfinished work or don't die here.
781 private function assignAllVariables (array $varMatches) {
782 // Search for all variables
783 foreach ($varMatches[1] as $key => $var) {
785 // Detect leading equals
786 if (substr($varMatches[2][$key], 0, 1) == '=') {
787 // Remove and cast it
788 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
791 // Do we have some quotes left and right side? Then it is free text
792 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
793 // Free string detected! Which we can assign directly
794 $this->assignVariable($var, $varMatches[3][$key]);
795 } elseif (!empty($varMatches[2][$key])) {
796 // @TODO Non-string found so we need some deeper analysis...
797 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
800 } // for ($varMatches ...
803 * Compiles all loaded raw templates
805 * @param $templateMatches See method analyzeTemplate() for details
808 private function compileRawTemplateData (array $templateMatches) {
809 // Are some code-templates found which we need to compile?
810 if (count($this->loadedRawData) > 0) {
813 foreach ($this->loadedRawData as $template => $code) {
815 // Is this template already compiled?
816 if (in_array($template, $this->compiledTemplates)) {
821 // Search for the template
822 $foundIndex = array_search($template, $templateMatches[1]);
824 // Lookup the matching variable data
825 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
827 // Split it up with another reg. exp. into variable=value pairs
828 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
830 // Assign all variables
831 $this->assignAllVariables($varMatches);
833 } // END - if (isset($templateMatches ...
835 // Compile the loaded template
836 $this->compileCode($code, $template);
838 } // END - foreach ($this->loadedRawData ...
840 // Insert all templates
841 $this->insertAllTemplates($templateMatches);
843 } // END - if (count($this->loadedRawData) ...
847 * Inserts all raw templates into their respective variables
851 private function insertRawTemplates () {
852 // Load all templates
853 foreach ($this->rawTemplates as $template => $content) {
854 // Set the template as a variable with the content
855 $this->assignVariable($template, $content);
860 * Finalizes the compilation of all template variables
864 private function finalizeVariableCompilation () {
866 $content = $this->getRawTemplateData();
867 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
869 // Walk through all variables
870 foreach ($this->varStack['general'] as $currEntry) {
871 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
872 // Replace all [$var] or {?$var?} with the content
873 // @TODO Old behaviour, will become obsolete!
874 $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
876 // @TODO Yet another old way
877 $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
880 $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
883 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
885 // Set the content back
886 $this->setRawTemplateData($content);
890 * Load a specified web template into the engine
892 * @param $template The web template we shall load which is located in
896 public function loadWebTemplate ($template) {
898 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
900 // Load the special template
901 $this->loadTemplate($template);
905 * Assign a given congfiguration variable with a value
907 * @param $var The configuration variable we want to assign
910 public function assignConfigVariable ($var) {
911 // Sweet and simple...
912 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
913 $this->varStack['config'][$var] = $this->getConfigInstance()->readConfig($var);
917 * Load a specified email template into the engine
919 * @param $template The email template we shall load which is located in
920 * 'emails' by default
923 public function loadEmailTemplate ($template) {
925 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
927 // Load the special template
928 $this->loadTemplate($template);
932 * Load a specified code template into the engine
934 * @param $template The code template we shall load which is
935 * located in 'code' by default
938 public function loadCodeTemplate ($template) {
940 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
942 // Load the special template
943 $this->loadTemplate($template);
947 * Compile all variables by inserting their respective values
950 * @todo Make this code some nicer...
952 public final function compileVariables () {
953 // Initialize the $content array
954 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
957 // Iterate through all general variables
958 foreach ($this->varStack['general'] as $currVariable) {
959 // Transfer it's name/value combination to the $content array
960 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
961 $dummy[$currVariable['name']] = $currVariable['value'];
964 // Set the new variable (don't remove the second dollar!)
967 // Prepare all configuration variables
969 if (isset($this->varStack['config'])) {
970 $config = $this->varStack['config'];
973 // Remove some variables
975 unset($currVariable);
977 // Run the compilation three times to get content from helper classes in
980 // Finalize the compilation of template variables
981 $this->finalizeVariableCompilation();
983 // Prepare the eval() command for comiling the template
984 $eval = sprintf("\$result = \"%s\";",
985 addslashes($this->getRawTemplateData())
988 // This loop does remove the backslashes (\) in PHP parameters
989 while (strpos($eval, $this->codeBegin) !== false) {
990 // Get left part before "<?"
991 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
993 // Get all from right of "<?"
994 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
996 // Cut middle part out and remove escapes
997 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
998 $evalMiddle = stripslashes($evalMiddle);
1000 // Remove the middle part from right one
1001 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1003 // And put all together
1004 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1007 // Prepare PHP code for eval() command
1008 $eval = str_replace(
1017 // Run the constructed command. This will "compile" all variables in
1020 // Goes something wrong?
1021 if (!isset($result)) {
1022 // Output eval command
1023 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1025 // Output backtrace here
1026 $this->debugBackTrace();
1029 // Set raw template data
1030 $this->setRawTemplateData($result);
1034 // Final variable assignment
1035 $this->finalizeVariableCompilation();
1037 // Set the new content
1038 $this->setCompiledData($this->getRawTemplateData());
1042 * Compile all required templates into the current loaded one
1045 * @throws UnexpectedTemplateTypeException If the template type is
1047 * @throws InvalidArrayCountException If an unexpected array
1048 * count has been found
1050 public function compileTemplate () {
1051 // We will only work with template type "code" from configuration
1052 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1054 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1057 // Get the raw data.
1058 $rawData = $this->getRawTemplateData();
1060 // Remove double spaces and trim leading/trailing spaces
1061 $rawData = trim(str_replace(' ', ' ', $rawData));
1063 // Search for raw variables
1064 $this->extractVariablesFromRawData($rawData);
1066 // Search for code-tags which are {? ?}
1067 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1069 // Analyze the matches array
1070 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1071 // Entries are found:
1073 // The main analysis
1074 $this->analyzeTemplate($templateMatches);
1076 // Compile raw template data
1077 $this->compileRawTemplateData($templateMatches);
1079 // Are there some raw templates left for loading?
1080 $this->loadExtraRawTemplates();
1082 // Are some raw templates found and loaded?
1083 if (count($this->rawTemplates) > 0) {
1085 // Insert all raw templates
1086 $this->insertRawTemplates();
1088 // Remove the raw template content as well
1089 $this->setRawTemplateData('');
1093 } // END - if($templateMatches ...
1097 * A old deprecated method
1101 * @see BaseTemplateEngine::transferToResponse
1103 public function output () {
1104 // Check which type of template we have
1105 switch ($this->getTemplateType()) {
1106 case 'html': // Raw HTML templates can be send to the output buffer
1108 $this->getWebOutputInstance()->output($this->getCompiledData());
1111 default: // Unknown type found
1112 // Construct message
1113 $msg = sprintf("[%s->%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1114 $this->__toString(),
1116 $this->getTemplateType()
1119 // Write the problem to the world...
1120 $this->debugOutput($msg);
1126 * Loads a given view helper (by name)
1128 * @param $helperName The helper's name
1131 protected function loadViewHelper ($helperName) {
1132 // Make first character upper case, rest low
1133 $helperName = $this->convertToClassName($helperName);
1135 // Is this view helper loaded?
1136 if (!isset($this->helpers[$helperName])) {
1137 // Create a class name
1138 $className = "{$helperName}ViewHelper";
1140 // Generate new instance
1141 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1144 // Return the requested instance
1145 return $this->helpers[$helperName];
1149 * Assigns the last loaded raw template content with a given variable
1151 * @param $templateName Name of the template we want to assign
1152 * @param $variableName Name of the variable we want to assign
1155 public function assignTemplateWithVariable ($templateName, $variableName) {
1156 // Get the content from last loaded raw template
1157 $content = $this->getRawTemplateData();
1159 // Assign the variable
1160 $this->assignVariable($variableName, $content);
1162 // Purge raw content
1163 $this->setRawTemplateData('');
1167 * Transfers the content of this template engine to a given response instance
1169 * @param $responseInstance An instance of a response class
1172 public function transferToResponse (Responseable $responseInstance) {
1173 // Get the content and set it in response class
1174 $responseInstance->writeToBody($this->getCompiledData());
1178 * Assigns all the application data with template variables
1180 * @param $appInstance A manageable application instance
1183 public function assignApplicationData (ManageableApplication $appInstance) {
1184 // Get long name and assign it
1185 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1187 // Get short name and assign it
1188 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1190 // Get version number and assign it
1191 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1193 // Assign extra application-depending data
1194 $appInstance->assignExtraTemplateData($this);
1198 * "Compiles" a variable by replacing {?var?} with it's content
1200 * @param $rawCode Raw code to compile
1201 * @return $rawCode Compile code with inserted variable value
1203 public function compileRawCode ($rawCode) {
1204 // Find the variables
1205 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1206 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1208 // Compile all variables
1209 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1210 foreach ($varMatches[0] as $match) {
1211 // Add variable tags around it
1212 $varCode = '{?' . $match . '?}';
1214 // Is the variable found in code? (safes some calls)
1215 if (strpos($rawCode, $varCode) !== false) {
1216 // Replace the variable with it's value, if found
1217 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1218 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1222 // Return the compiled data
1227 * Getter for variable group array
1229 * @return $vargroups All variable groups
1231 public final function getVariableGroups () {
1232 return $this->varGroups;
1236 * Renames a variable in code and in stack
1238 * @param $oldName Old name of variable
1239 * @param $newName New name of variable
1242 public function renameVariable ($oldName, $newName) {
1243 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1244 // Get raw template code
1245 $rawData = $this->getRawTemplateData();
1248 $rawData = str_replace($oldName, $newName, $rawData);
1250 // Set the code back
1251 $this->setRawTemplateData($rawData);
1255 * Renders the given XML content
1257 * @param $content Valid XML content or if not set the current loaded raw content
1259 * @throws XmlParserException If an XML error was found
1261 public final function renderXmlContent ($content = null) {
1262 // Is the content set?
1263 if (is_null($content)) {
1264 // Get current content
1265 $content = $this->getRawTemplateData();
1268 // Convert all to UTF8
1269 if (function_exists('recode')) {
1270 $content = recode("html..utf8", $content);
1272 // @TODO We need to find a fallback solution here
1275 // Get an XML parser
1276 $xmlParser = xml_parser_create();
1278 // Force case-folding to on
1279 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
1282 xml_set_object($xmlParser, $this);
1284 // Set handler call-backs
1285 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
1286 xml_set_character_data_handler($xmlParser, 'characterHandler');
1288 // Now parse the XML tree
1289 if (!xml_parse($xmlParser, $content)) {
1290 // Error found in XML!
1291 //die('<pre>'.htmlentities($content).'</pre>');
1292 throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
1296 xml_parser_free($xmlParser);