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/%s%s",
527 $this->getConfigInstance()->readConfig('application_path'),
528 Registry::getRegistry()->getInstance('application')->getAppShortName(),
529 $this->getBasePath(),
530 $this->getLanguageInstance()->getLanguageCode(),
531 $this->getTemplateType(),
536 // Load the raw template data
537 $this->loadRawTemplateData($fqfn);
541 * A private loader for raw template names
543 * @param $fqfn The full-qualified file name for a template
546 private function loadRawTemplateData ($fqfn) {
547 // Get a input/output instance from the middleware
548 $ioInstance = $this->getFileIoInstance();
550 // Some debug code to look on the file which is being loaded
551 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
553 // Load the raw template
554 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
556 // Store the template's contents into this class
557 $this->setRawTemplateData($rawTemplateData);
559 // Remember the template's FQFN
560 $this->setLastTemplate($fqfn);
564 * Try to assign an extracted template variable as a "content" or 'config'
567 * @param $varName The variable's name (shall be content orconfig) by
569 * @param $var The variable we want to assign
571 private function assignTemplateVariable ($varName, $var) {
572 // Is it not a config variable?
573 if ($varName != 'config') {
574 // Regular template variables
575 $this->assignVariable($var, '');
577 // Configuration variables
578 $this->assignConfigVariable($var);
583 * Extract variables from a given raw data stream
585 * @param $rawData The raw template data we shall analyze
588 private function extractVariablesFromRawData ($rawData) {
590 $rawData = (string) $rawData;
592 // Search for variables
593 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
595 // Did we find some variables?
596 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
597 // Initialize all missing variables
598 foreach ($variableMatches[3] as $key => $var) {
600 $varName = $variableMatches[1][$key];
602 // Workarround: Do not assign empty variables
604 // Try to assign it, empty strings are being ignored
605 $this->assignTemplateVariable($varName, $var);
612 * Main analysis of the loaded template
614 * @param $templateMatches Found template place-holders, see below
617 *---------------------------------
618 * Structure of $templateMatches:
619 *---------------------------------
620 * [0] => Array - An array with all full matches
621 * [1] => Array - An array with left part (before the ':') of a match
622 * [2] => Array - An array with right part of a match including ':'
623 * [3] => Array - An array with right part of a match excluding ':'
625 private function analyzeTemplate (array $templateMatches) {
626 // Backup raw template data
627 $backup = $this->getRawTemplateData();
629 // Initialize some arrays
630 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
632 // Load all requested templates
633 foreach ($templateMatches[1] as $template) {
635 // Load and compile only templates which we have not yet loaded
636 // RECURSIVE PROTECTION! BE CAREFUL HERE!
637 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
639 // Template not found, but maybe variable assigned?
640 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
641 if ($this->isVariableAlreadySet($template) !== false) {
642 // Use that content here
643 $this->loadedRawData[$template] = $this->readVariable($template);
645 // Recursive protection:
646 $this->loadedTemplates[] = $template;
647 } elseif (isset($this->varStack['config'][$template])) {
648 // Use that content here
649 $this->loadedRawData[$template] = $this->varStack['config'][$template];
651 // Recursive protection:
652 $this->loadedTemplates[] = $template;
654 // Then try to search for code-templates
656 // Load the code template and remember it's contents
657 $this->loadCodeTemplate($template);
658 $this->loadedRawData[$template] = $this->getRawTemplateData();
660 // Remember this template for recursion detection
661 // RECURSIVE PROTECTION!
662 $this->loadedTemplates[] = $template;
663 } catch (FileNotFoundException $e) {
664 // Even this is not done... :/
665 $this->rawTemplates[] = $template;
666 } catch (FilePointerNotOpenedException $e) {
667 // Even this is not done... :/
668 $this->rawTemplates[] = $template;
674 // Restore the raw template data
675 $this->setRawTemplateData($backup);
679 * Compile a given raw template code and remember it for later usage
681 * @param $code The raw template code
682 * @param $template The template's name
685 private function compileCode ($code, $template) {
686 // Is this template already compiled?
687 if (in_array($template, $this->compiledTemplates)) {
692 // Remember this template being compiled
693 $this->compiledTemplates[] = $template;
695 // Compile the loaded code in five steps:
697 // 1. Backup current template data
698 $backup = $this->getRawTemplateData();
700 // 2. Set the current template's raw data as the new content
701 $this->setRawTemplateData($code);
703 // 3. Compile the template data
704 $this->compileTemplate();
706 // 4. Remember it's contents
707 $this->loadedRawData[$template] = $this->getRawTemplateData();
709 // 5. Restore the previous raw content from backup variable
710 $this->setRawTemplateData($backup);
714 * Insert all given and loaded templates by running through all loaded
715 * codes and searching for their place-holder in the main template
717 * @param $templateMatches See method analyzeTemplate()
720 private function insertAllTemplates (array $templateMatches) {
721 // Run through all loaded codes
722 foreach ($this->loadedRawData as $template => $code) {
724 // Search for the template
725 $foundIndex = array_search($template, $templateMatches[1]);
727 // Lookup the matching template replacement
728 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
730 // Get the current raw template
731 $rawData = $this->getRawTemplateData();
733 // Replace the space holder with the template code
734 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
736 // Set the new raw data
737 $this->setRawTemplateData($rawData);
743 * Load all extra raw templates
747 private function loadExtraRawTemplates () {
748 // Are there some raw templates we need to load?
749 if (count($this->rawTemplates) > 0) {
750 // Try to load all raw templates
751 foreach ($this->rawTemplates as $key => $template) {
754 $this->loadWebTemplate($template);
756 // Remember it's contents
757 $this->rawTemplates[$template] = $this->getRawTemplateData();
759 // Remove it from the loader list
760 unset($this->rawTemplates[$key]);
762 // Remember this template for recursion detection
763 // RECURSIVE PROTECTION!
764 $this->loadedTemplates[] = $template;
765 } catch (FileNotFoundException $e) {
766 // This template was never found. We silently ignore it
767 unset($this->rawTemplates[$key]);
768 } catch (FilePointerNotOpenedException $e) {
769 // This template was never found. We silently ignore it
770 unset($this->rawTemplates[$key]);
777 * Assign all found template variables
779 * @param $varMatches An array full of variable/value pairs.
781 * @todo Unfinished work or don't die here.
783 private function assignAllVariables (array $varMatches) {
784 // Search for all variables
785 foreach ($varMatches[1] as $key => $var) {
787 // Detect leading equals
788 if (substr($varMatches[2][$key], 0, 1) == '=') {
789 // Remove and cast it
790 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
793 // Do we have some quotes left and right side? Then it is free text
794 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
795 // Free string detected! Which we can assign directly
796 $this->assignVariable($var, $varMatches[3][$key]);
797 } elseif (!empty($varMatches[2][$key])) {
798 // @TODO Non-string found so we need some deeper analysis...
799 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
802 } // for ($varMatches ...
805 * Compiles all loaded raw templates
807 * @param $templateMatches See method analyzeTemplate() for details
810 private function compileRawTemplateData (array $templateMatches) {
811 // Are some code-templates found which we need to compile?
812 if (count($this->loadedRawData) > 0) {
815 foreach ($this->loadedRawData as $template => $code) {
817 // Is this template already compiled?
818 if (in_array($template, $this->compiledTemplates)) {
823 // Search for the template
824 $foundIndex = array_search($template, $templateMatches[1]);
826 // Lookup the matching variable data
827 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
829 // Split it up with another reg. exp. into variable=value pairs
830 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
832 // Assign all variables
833 $this->assignAllVariables($varMatches);
835 } // END - if (isset($templateMatches ...
837 // Compile the loaded template
838 $this->compileCode($code, $template);
840 } // END - foreach ($this->loadedRawData ...
842 // Insert all templates
843 $this->insertAllTemplates($templateMatches);
845 } // END - if (count($this->loadedRawData) ...
849 * Inserts all raw templates into their respective variables
853 private function insertRawTemplates () {
854 // Load all templates
855 foreach ($this->rawTemplates as $template => $content) {
856 // Set the template as a variable with the content
857 $this->assignVariable($template, $content);
862 * Finalizes the compilation of all template variables
866 private function finalizeVariableCompilation () {
868 $content = $this->getRawTemplateData();
869 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
871 // Walk through all variables
872 foreach ($this->varStack['general'] as $currEntry) {
873 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
874 // Replace all [$var] or {?$var?} with the content
875 // @TODO Old behaviour, will become obsolete!
876 $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
878 // @TODO Yet another old way
879 $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
882 $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
885 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
887 // Set the content back
888 $this->setRawTemplateData($content);
892 * Load a specified web template into the engine
894 * @param $template The web template we shall load which is located in
898 public function loadWebTemplate ($template) {
900 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
902 // Load the special template
903 $this->loadTemplate($template);
907 * Assign a given congfiguration variable with a value
909 * @param $var The configuration variable we want to assign
912 public function assignConfigVariable ($var) {
913 // Sweet and simple...
914 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
915 $this->varStack['config'][$var] = $this->getConfigInstance()->readConfig($var);
919 * Load a specified email template into the engine
921 * @param $template The email template we shall load which is located in
922 * 'emails' by default
925 public function loadEmailTemplate ($template) {
927 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
929 // Load the special template
930 $this->loadTemplate($template);
934 * Load a specified code template into the engine
936 * @param $template The code template we shall load which is
937 * located in 'code' by default
940 public function loadCodeTemplate ($template) {
942 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
944 // Load the special template
945 $this->loadTemplate($template);
949 * Compile all variables by inserting their respective values
952 * @todo Make this code some nicer...
954 public final function compileVariables () {
955 // Initialize the $content array
956 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
959 // Iterate through all general variables
960 foreach ($this->varStack['general'] as $currVariable) {
961 // Transfer it's name/value combination to the $content array
962 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
963 $dummy[$currVariable['name']] = $currVariable['value'];
966 // Set the new variable (don't remove the second dollar!)
969 // Prepare all configuration variables
971 if (isset($this->varStack['config'])) {
972 $config = $this->varStack['config'];
975 // Remove some variables
977 unset($currVariable);
979 // Run the compilation three times to get content from helper classes in
982 // Finalize the compilation of template variables
983 $this->finalizeVariableCompilation();
985 // Prepare the eval() command for comiling the template
986 $eval = sprintf("\$result = \"%s\";",
987 addslashes($this->getRawTemplateData())
990 // This loop does remove the backslashes (\) in PHP parameters
991 while (strpos($eval, $this->codeBegin) !== false) {
992 // Get left part before "<?"
993 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
995 // Get all from right of "<?"
996 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
998 // Cut middle part out and remove escapes
999 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1000 $evalMiddle = stripslashes($evalMiddle);
1002 // Remove the middle part from right one
1003 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1005 // And put all together
1006 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1009 // Prepare PHP code for eval() command
1010 $eval = str_replace(
1019 // Run the constructed command. This will "compile" all variables in
1022 // Goes something wrong?
1023 if ((!isset($result)) || (empty($result))) {
1024 // Output eval command
1025 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1027 // Output backtrace here
1028 $this->debugBackTrace();
1031 // Set raw template data
1032 $this->setRawTemplateData($result);
1036 // Final variable assignment
1037 $this->finalizeVariableCompilation();
1039 // Set the new content
1040 $this->setCompiledData($this->getRawTemplateData());
1044 * Compile all required templates into the current loaded one
1047 * @throws UnexpectedTemplateTypeException If the template type is
1049 * @throws InvalidArrayCountException If an unexpected array
1050 * count has been found
1052 public function compileTemplate () {
1053 // We will only work with template type "code" from configuration
1054 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1056 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1059 // Get the raw data.
1060 $rawData = $this->getRawTemplateData();
1062 // Remove double spaces and trim leading/trailing spaces
1063 $rawData = trim(str_replace(' ', ' ', $rawData));
1065 // Search for raw variables
1066 $this->extractVariablesFromRawData($rawData);
1068 // Search for code-tags which are {? ?}
1069 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1071 // Analyze the matches array
1072 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1073 // Entries are found:
1075 // The main analysis
1076 $this->analyzeTemplate($templateMatches);
1078 // Compile raw template data
1079 $this->compileRawTemplateData($templateMatches);
1081 // Are there some raw templates left for loading?
1082 $this->loadExtraRawTemplates();
1084 // Are some raw templates found and loaded?
1085 if (count($this->rawTemplates) > 0) {
1087 // Insert all raw templates
1088 $this->insertRawTemplates();
1090 // Remove the raw template content as well
1091 $this->setRawTemplateData('');
1095 } // END - if($templateMatches ...
1099 * A old deprecated method
1103 * @see BaseTemplateEngine::transferToResponse
1105 public function output () {
1106 // Check which type of template we have
1107 switch ($this->getTemplateType()) {
1108 case 'html': // Raw HTML templates can be send to the output buffer
1110 $this->getWebOutputInstance()->output($this->getCompiledData());
1113 default: // Unknown type found
1114 // Construct message
1115 $msg = sprintf("[%s->%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1116 $this->__toString(),
1118 $this->getTemplateType()
1121 // Write the problem to the world...
1122 $this->debugOutput($msg);
1128 * Loads a given view helper (by name)
1130 * @param $helperName The helper's name
1133 protected function loadViewHelper ($helperName) {
1134 // Make first character upper case, rest low
1135 $helperName = $this->convertToClassName($helperName);
1137 // Is this view helper loaded?
1138 if (!isset($this->helpers[$helperName])) {
1139 // Create a class name
1140 $className = "{$helperName}ViewHelper";
1142 // Generate new instance
1143 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1146 // Return the requested instance
1147 return $this->helpers[$helperName];
1151 * Assigns the last loaded raw template content with a given variable
1153 * @param $templateName Name of the template we want to assign
1154 * @param $variableName Name of the variable we want to assign
1157 public function assignTemplateWithVariable ($templateName, $variableName) {
1158 // Get the content from last loaded raw template
1159 $content = $this->getRawTemplateData();
1161 // Assign the variable
1162 $this->assignVariable($variableName, $content);
1164 // Purge raw content
1165 $this->setRawTemplateData('');
1169 * Transfers the content of this template engine to a given response instance
1171 * @param $responseInstance An instance of a response class
1174 public function transferToResponse (Responseable $responseInstance) {
1175 // Get the content and set it in response class
1176 $responseInstance->writeToBody($this->getCompiledData());
1180 * Assigns all the application data with template variables
1182 * @param $appInstance A manageable application instance
1185 public function assignApplicationData (ManageableApplication $appInstance) {
1186 // Get long name and assign it
1187 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1189 // Get short name and assign it
1190 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1192 // Get version number and assign it
1193 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1195 // Assign extra application-depending data
1196 $appInstance->assignExtraTemplateData($this);
1200 * "Compiles" a variable by replacing {?var?} with it's content
1202 * @param $rawCode Raw code to compile
1203 * @return $rawCode Compile code with inserted variable value
1205 public function compileRawCode ($rawCode) {
1206 // Find the variables
1207 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1208 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1210 // Compile all variables
1211 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1212 foreach ($varMatches[0] as $match) {
1213 // Add variable tags around it
1214 $varCode = '{?' . $match . '?}';
1216 // Is the variable found in code? (safes some calls)
1217 if (strpos($rawCode, $varCode) !== false) {
1218 // Replace the variable with it's value, if found
1219 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1220 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1224 // Return the compiled data
1229 * Getter for variable group array
1231 * @return $vargroups All variable groups
1233 public final function getVariableGroups () {
1234 return $this->varGroups;
1238 * Renames a variable in code and in stack
1240 * @param $oldName Old name of variable
1241 * @param $newName New name of variable
1244 public function renameVariable ($oldName, $newName) {
1245 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1246 // Get raw template code
1247 $rawData = $this->getRawTemplateData();
1250 $rawData = str_replace($oldName, $newName, $rawData);
1252 // Set the code back
1253 $this->setRawTemplateData($rawData);
1257 * Renders the given XML content
1259 * @param $content Valid XML content or if not set the current loaded raw content
1261 * @throws XmlParserException If an XML error was found
1263 public final function renderXmlContent ($content = null) {
1264 // Is the content set?
1265 if (is_null($content)) {
1266 // Get current content
1267 $content = $this->getRawTemplateData();
1270 // Convert all to UTF8
1271 if (function_exists('recode')) {
1272 $content = recode("html..utf8", $content);
1274 // @TODO We need to find a fallback solution here
1277 // Get an XML parser
1278 $xmlParser = xml_parser_create();
1280 // Force case-folding to on
1281 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
1284 xml_set_object($xmlParser, $this);
1286 // Set handler call-backs
1287 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
1288 xml_set_character_data_handler($xmlParser, 'characterHandler');
1290 // Now parse the XML tree
1291 if (!xml_parse($xmlParser, $content)) {
1292 // Error found in XML!
1293 //die('<pre>'.htmlentities($content).'</pre>');
1294 throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
1298 xml_parser_free($xmlParser);