3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 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 = '?>';
134 // Exception codes for the template engine
135 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
136 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
137 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
140 * Protected constructor
142 * @param $className Name of the class
145 protected function __construct ($className) {
146 // Call parent constructor
147 parent::__construct($className);
151 * Search for a variable in the stack
153 * @param $var The variable we are looking for
154 * @return $idx FALSE means not found, >=0 means found on a specific index
156 private function isVariableAlreadySet ($var) {
157 // First everything is not found
160 // Is the group there?
161 if (isset($this->varStack[$this->currGroup])) {
163 foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
164 //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
165 // Is the entry found?
166 if ($currEntry['name'] == $var) {
168 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
175 // Return the current position
180 * Return a content of a variable or null if not found
182 * @param $var The variable we are looking for
183 * @return $content Content of the variable or null if not found
185 protected function readVariable ($var) {
186 // First everything is not found
189 // Get variable index
190 $found = $this->isVariableAlreadySet($var);
192 // Is the variable found?
193 if ($found !== false) {
195 $found = $this->varStack[$this->currGroup][$found]['value'];
198 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
200 // Return the current position
205 * Add a variable to the stack
207 * @param $var The variable we are looking for
208 * @param $value The value we want to store in the variable
211 private function addVariable ($var, $value) {
212 // Set general variable group
213 $this->setVariableGroup('general');
215 // Add it to the stack
216 $this->addGroupVariable($var, $value);
220 * Returns all variables of current group or empty array
222 * @return $result Wether array of found variables or empty array
224 private function readCurrentGroup () {
225 // Default is not found
228 // Is the group there?
229 if (isset($this->varStack[$this->currGroup])) {
231 $result = $this->varStack[$this->currGroup];
239 * Settter for variable group
241 * @param $groupName Name of variable group
242 * @param $add Wether add this group
245 public function setVariableGroup ($groupName, $add = true) {
247 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
248 $this->currGroup = $groupName;
250 // Skip group 'general'
251 if (($groupName != 'general') && ($add === true)) {
252 $this->varGroups[$groupName] = 'OK';
258 * Adds a variable to current group
260 * @param $var Variable to set
261 * @param $value Value to store in variable
264 public function addGroupVariable ($var, $value) {
265 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
267 // Get current variables in group
268 $currVars = $this->readCurrentGroup();
270 // Append our variable
276 // Add it to the stack
277 $this->varStack[$this->currGroup] = $currVars;
281 * Modify an entry on the stack
283 * @param $var The variable we are looking for
284 * @param $value The value we want to store in the variable
287 private function modifyVariable ($var, $value) {
288 // Get index for variable
289 $idx = $this->isVariableAlreadySet($var);
291 // Is the variable set?
292 if ($idx !== false) {
294 $this->varStack[$this->currGroup][$idx]['value'] = $value;
299 * Setter for template type. Only 'html', 'emails' and 'compiled' should
302 * @param $templateType The current template's type
305 protected final function setTemplateType ($templateType) {
306 $this->templateType = (string) $templateType;
310 * Setter for the last loaded template's FQFN
312 * @param $template The last loaded template
315 private final function setLastTemplate ($template) {
316 $this->lastTemplate = (string) $template;
320 * Getter for the last loaded template's FQFN
322 * @return $template The last loaded template
324 private final function getLastTemplate () {
325 return $this->lastTemplate;
329 * Setter for base path
331 * @param $templateBasePath The relative base path for all templates
334 public final function setTemplateBasePath ($templateBasePath) {
336 $this->templateBasePath = (string) $templateBasePath;
340 * Getter for base path
342 * @return $templateBasePath The relative base path for all templates
344 public final function getTemplateBasePath () {
346 return $this->templateBasePath;
350 * Getter for generic base path
352 * @return $templateBasePath The relative base path for all templates
354 public final function getGenericBasePath () {
356 return $this->genericBasePath;
360 * Setter for template extension
362 * @param $templateExtension The file extension for all uncompiled
366 public final function setRawTemplateExtension ($templateExtension) {
368 $this->templateExtension = (string) $templateExtension;
372 * Setter for code template extension
374 * @param $codeExtension The file extension for all uncompiled
378 public final function setCodeTemplateExtension ($codeExtension) {
380 $this->codeExtension = (string) $codeExtension;
384 * Getter for template extension
386 * @return $templateExtension The file extension for all uncompiled
389 public final function getRawTemplateExtension () {
391 return $this->templateExtension;
395 * Getter for code-template extension
397 * @return $codeExtension The file extension for all code-
400 public final function getCodeTemplateExtension () {
402 return $this->codeExtension;
406 * Setter for path of compiled templates
408 * @param $compileOutputPath The local base path for all compiled
412 public final function setCompileOutputPath ($compileOutputPath) {
414 $this->compileOutputPath = (string) $compileOutputPath;
418 * Getter for template type
420 * @return $templateType The current template's type
422 public final function getTemplateType () {
423 return $this->templateType;
427 * Assign (add) a given variable with a value
429 * @param $var The variable we are looking for
430 * @param $value The value we want to store in the variable
432 * @throws EmptyVariableException If the variable name is left empty
434 public final function assignVariable ($var, $value) {
435 // Trim spaces of variable name
438 // Empty variable found?
440 // Throw an exception
441 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
444 // First search for the variable if it was already added
445 $idx = $this->isVariableAlreadySet($var);
448 if ($idx === false) {
449 // Add it to the stack
450 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
451 $this->addVariable($var, $value);
452 } elseif (!empty($value)) {
453 // Modify the stack entry
454 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
455 $this->modifyVariable($var, $value);
460 * Removes a given variable
462 * @param $var The variable we are looking for
465 public final function removeVariable ($var) {
466 // First search for the variable if it was already added
467 $idx = $this->isVariableAlreadySet($var);
470 if ($idx !== false) {
471 // Remove this variable
472 $this->varStack->offsetUnset($idx);
477 * Private setter for raw template data
479 * @param $rawTemplateData The raw data from the template
482 protected final function setRawTemplateData ($rawTemplateData) {
483 // And store it in this class
484 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
485 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->varStack[$this->currGroup]).', groups='.count($this->varStack).'<br />\n';
486 $this->rawTemplateData = (string) $rawTemplateData;
490 * Getter for raw template data
492 * @return $rawTemplateData The raw data from the template
494 public final function getRawTemplateData () {
495 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
496 return $this->rawTemplateData;
500 * Private setter for compiled templates
504 private final function setCompiledData ($compiledData) {
505 // And store it in this class
506 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
507 $this->compiledData = (string) $compiledData;
511 * Getter for compiled templates
513 * @return $compiledData Compiled template data
515 public final function getCompiledData () {
516 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
517 return $this->compiledData;
521 * Private loader for all template types
523 * @param $template The template we shall load
524 * @param $extOther An other extension to use
526 * @throws FileNotFoundException If the template was not found
528 protected function loadTemplate ($template, $extOther = '') {
529 // Get extension for the template if empty
530 if (empty($extOther)) {
531 // None provided, so get the raw one
532 $ext = $this->getRawTemplateExtension();
535 $ext = (string) $extOther;
538 // Construct the FQFN for the template by honoring the current language
539 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
540 $this->getConfigInstance()->getConfigEntry('base_path'),
541 $this->getTemplateBasePath(),
542 $this->getGenericBasePath(),
543 $this->getLanguageInstance()->getLanguageCode(),
544 $this->getTemplateType(),
551 // Load the raw template data
552 $this->loadRawTemplateData($fqfn);
553 } catch (FileNotFoundException $e) {
554 // If we shall load a code-template we need to switch the file extension
555 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
556 // Switch over to the code-template extension and try it again
557 $ext = $this->getCodeTemplateExtension();
560 $this->loadTemplate($template, $ext);
563 throw new FileNotFoundException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
570 * A private loader for raw template names
572 * @param $fqfn The full-qualified file name for a template
575 private function loadRawTemplateData ($fqfn) {
576 // Get a input/output instance from the middleware
577 $ioInstance = $this->getFileIoInstance();
579 // Some debug code to look on the file which is being loaded
580 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
582 // Load the raw template
583 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
585 // Store the template's contents into this class
586 $this->setRawTemplateData($rawTemplateData);
588 // Remember the template's FQFN
589 $this->setLastTemplate($fqfn);
593 * Try to assign an extracted template variable as a "content" or 'config'
596 * @param $varName The variable's name (shall be content orconfig) by
598 * @param $var The variable we want to assign
600 private function assignTemplateVariable ($varName, $var) {
601 // Is it not a config variable?
602 if ($varName != 'config') {
603 // Regular template variables
604 $this->assignVariable($var, '');
606 // Configuration variables
607 $this->assignConfigVariable($var);
612 * Extract variables from a given raw data stream
614 * @param $rawData The raw template data we shall analyze
617 private function extractVariablesFromRawData ($rawData) {
619 $rawData = (string) $rawData;
621 // Search for variables
622 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
624 // Did we find some variables?
625 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
626 // Initialize all missing variables
627 foreach ($variableMatches[3] as $key => $var) {
629 $varName = $variableMatches[1][$key];
631 // Workarround: Do not assign empty variables
633 // Try to assign it, empty strings are being ignored
634 $this->assignTemplateVariable($varName, $var);
641 * Main analysis of the loaded template
643 * @param $templateMatches Found template place-holders, see below
646 *---------------------------------
647 * Structure of $templateMatches:
648 *---------------------------------
649 * [0] => Array - An array with all full matches
650 * [1] => Array - An array with left part (before the ':') of a match
651 * [2] => Array - An array with right part of a match including ':'
652 * [3] => Array - An array with right part of a match excluding ':'
654 private function analyzeTemplate (array $templateMatches) {
655 // Backup raw template data
656 $backup = $this->getRawTemplateData();
658 // Initialize some arrays
659 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
661 // Load all requested templates
662 foreach ($templateMatches[1] as $template) {
664 // Load and compile only templates which we have not yet loaded
665 // RECURSIVE PROTECTION! BE CAREFUL HERE!
666 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
668 // Template not found, but maybe variable assigned?
669 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
670 if ($this->isVariableAlreadySet($template) !== false) {
671 // Use that content here
672 $this->loadedRawData[$template] = $this->readVariable($template);
674 // Recursive protection:
675 $this->loadedTemplates[] = $template;
676 } elseif (isset($this->varStack['config'][$template])) {
677 // Use that content here
678 $this->loadedRawData[$template] = $this->varStack['config'][$template];
680 // Recursive protection:
681 $this->loadedTemplates[] = $template;
683 // Then try to search for code-templates
685 // Load the code template and remember it's contents
686 $this->loadCodeTemplate($template);
687 $this->loadedRawData[$template] = $this->getRawTemplateData();
689 // Remember this template for recursion detection
690 // RECURSIVE PROTECTION!
691 $this->loadedTemplates[] = $template;
692 } catch (FileNotFoundException $e) {
693 // Even this is not done... :/
694 $this->rawTemplates[] = $template;
695 } catch (FilePointerNotOpenedException $e) {
696 // Even this is not done... :/
697 $this->rawTemplates[] = $template;
703 // Restore the raw template data
704 $this->setRawTemplateData($backup);
708 * Compile a given raw template code and remember it for later usage
710 * @param $code The raw template code
711 * @param $template The template's name
714 private function compileCode ($code, $template) {
715 // Is this template already compiled?
716 if (in_array($template, $this->compiledTemplates)) {
721 // Remember this template being compiled
722 $this->compiledTemplates[] = $template;
724 // Compile the loaded code in five steps:
726 // 1. Backup current template data
727 $backup = $this->getRawTemplateData();
729 // 2. Set the current template's raw data as the new content
730 $this->setRawTemplateData($code);
732 // 3. Compile the template data
733 $this->compileTemplate();
735 // 4. Remember it's contents
736 $this->loadedRawData[$template] = $this->getRawTemplateData();
738 // 5. Restore the previous raw content from backup variable
739 $this->setRawTemplateData($backup);
743 * Insert all given and loaded templates by running through all loaded
744 * codes and searching for their place-holder in the main template
746 * @param $templateMatches See method analyzeTemplate()
749 private function insertAllTemplates (array $templateMatches) {
750 // Run through all loaded codes
751 foreach ($this->loadedRawData as $template => $code) {
753 // Search for the template
754 $foundIndex = array_search($template, $templateMatches[1]);
756 // Lookup the matching template replacement
757 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
759 // Get the current raw template
760 $rawData = $this->getRawTemplateData();
762 // Replace the space holder with the template code
763 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
765 // Set the new raw data
766 $this->setRawTemplateData($rawData);
772 * Load all extra raw templates
776 private function loadExtraRawTemplates () {
777 // Are there some raw templates we need to load?
778 if (count($this->rawTemplates) > 0) {
779 // Try to load all raw templates
780 foreach ($this->rawTemplates as $key => $template) {
783 $this->loadWebTemplate($template);
785 // Remember it's contents
786 $this->rawTemplates[$template] = $this->getRawTemplateData();
788 // Remove it from the loader list
789 unset($this->rawTemplates[$key]);
791 // Remember this template for recursion detection
792 // RECURSIVE PROTECTION!
793 $this->loadedTemplates[] = $template;
794 } catch (FileNotFoundException $e) {
795 // This template was never found. We silently ignore it
796 unset($this->rawTemplates[$key]);
797 } catch (FilePointerNotOpenedException $e) {
798 // This template was never found. We silently ignore it
799 unset($this->rawTemplates[$key]);
806 * Assign all found template variables
808 * @param $varMatches An array full of variable/value pairs.
810 * @todo Unfinished work or don't die here.
812 private function assignAllVariables (array $varMatches) {
813 // Search for all variables
814 foreach ($varMatches[1] as $key => $var) {
816 // Detect leading equals
817 if (substr($varMatches[2][$key], 0, 1) == '=') {
818 // Remove and cast it
819 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
822 // Do we have some quotes left and right side? Then it is free text
823 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
824 // Free string detected! Which we can assign directly
825 $this->assignVariable($var, $varMatches[3][$key]);
826 } elseif (!empty($varMatches[2][$key])) {
827 // @TODO Non-string found so we need some deeper analysis...
828 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
831 } // for ($varMatches ...
834 * Compiles all loaded raw templates
836 * @param $templateMatches See method analyzeTemplate() for details
839 private function compileRawTemplateData (array $templateMatches) {
840 // Are some code-templates found which we need to compile?
841 if (count($this->loadedRawData) > 0) {
844 foreach ($this->loadedRawData as $template => $code) {
846 // Is this template already compiled?
847 if (in_array($template, $this->compiledTemplates)) {
852 // Search for the template
853 $foundIndex = array_search($template, $templateMatches[1]);
855 // Lookup the matching variable data
856 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
858 // Split it up with another reg. exp. into variable=value pairs
859 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
861 // Assign all variables
862 $this->assignAllVariables($varMatches);
864 } // END - if (isset($templateMatches ...
866 // Compile the loaded template
867 $this->compileCode($code, $template);
869 } // END - foreach ($this->loadedRawData ...
871 // Insert all templates
872 $this->insertAllTemplates($templateMatches);
874 } // END - if (count($this->loadedRawData) ...
878 * Inserts all raw templates into their respective variables
882 private function insertRawTemplates () {
883 // Load all templates
884 foreach ($this->rawTemplates as $template => $content) {
885 // Set the template as a variable with the content
886 $this->assignVariable($template, $content);
891 * Finalizes the compilation of all template variables
895 private function finalizeVariableCompilation () {
897 $content = $this->getRawTemplateData();
898 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
900 // Walk through all variables
901 foreach ($this->varStack['general'] as $currEntry) {
902 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
903 // Replace all [$var] or {?$var?} with the content
904 // @TODO Old behaviour, will become obsolete!
905 $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
907 // @TODO Yet another old way
908 $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
911 $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
914 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
916 // Set the content back
917 $this->setRawTemplateData($content);
921 * Load a specified web template into the engine
923 * @param $template The web template we shall load which is located in
927 public function loadWebTemplate ($template) {
929 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
931 // Load the special template
932 $this->loadTemplate($template);
936 * Assign a given congfiguration variable with a value
938 * @param $var The configuration variable we want to assign
941 public function assignConfigVariable ($var) {
942 // Sweet and simple...
943 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
944 $this->varStack['config'][$var] = $this->getConfigInstance()->getConfigEntry($var);
948 * Load a specified email template into the engine
950 * @param $template The email template we shall load which is located in
951 * 'emails' by default
954 public function loadEmailTemplate ($template) {
956 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
958 // Load the special template
959 $this->loadTemplate($template);
963 * Load a specified code template into the engine
965 * @param $template The code template we shall load which is
966 * located in 'code' by default
969 public function loadCodeTemplate ($template) {
971 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
973 // Load the special template
974 $this->loadTemplate($template);
978 * Compile all variables by inserting their respective values
981 * @todo Make this code some nicer...
983 public final function compileVariables () {
984 // Initialize the $content array
985 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
988 // Iterate through all general variables
989 foreach ($this->varStack['general'] as $currVariable) {
990 // Transfer it's name/value combination to the $content array
991 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
992 $dummy[$currVariable['name']] = $currVariable['value'];
995 // Set the new variable (don't remove the second dollar!)
998 // Prepare all configuration variables
1000 if (isset($this->varStack['config'])) {
1001 $config = $this->varStack['config'];
1004 // Remove some variables
1006 unset($currVariable);
1008 // Run the compilation three times to get content from helper classes in
1011 // Finalize the compilation of template variables
1012 $this->finalizeVariableCompilation();
1014 // Prepare the eval() command for comiling the template
1015 $eval = sprintf("\$result = \"%s\";",
1016 addslashes($this->getRawTemplateData())
1019 // This loop does remove the backslashes (\) in PHP parameters
1020 while (strpos($eval, $this->codeBegin) !== false) {
1021 // Get left part before "<?"
1022 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1024 // Get all from right of "<?"
1025 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1027 // Cut middle part out and remove escapes
1028 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1029 $evalMiddle = stripslashes($evalMiddle);
1031 // Remove the middle part from right one
1032 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1034 // And put all together
1035 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1038 // Prepare PHP code for eval() command
1039 $eval = str_replace(
1048 // Run the constructed command. This will "compile" all variables in
1051 // Goes something wrong?
1052 if ((!isset($result)) || (empty($result))) {
1053 // Output eval command
1054 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1056 // Output backtrace here
1057 $this->debugBackTrace();
1060 // Set raw template data
1061 $this->setRawTemplateData($result);
1065 // Final variable assignment
1066 $this->finalizeVariableCompilation();
1068 // Set the new content
1069 $this->setCompiledData($this->getRawTemplateData());
1073 * Compile all required templates into the current loaded one
1076 * @throws UnexpectedTemplateTypeException If the template type is
1078 * @throws InvalidArrayCountException If an unexpected array
1079 * count has been found
1081 public function compileTemplate () {
1082 // We will only work with template type "code" from configuration
1083 if ($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('code_template_type')) {
1085 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1088 // Get the raw data.
1089 $rawData = $this->getRawTemplateData();
1091 // Remove double spaces and trim leading/trailing spaces
1092 $rawData = trim(str_replace(' ', ' ', $rawData));
1094 // Search for raw variables
1095 $this->extractVariablesFromRawData($rawData);
1097 // Search for code-tags which are {? ?}
1098 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1100 // Analyze the matches array
1101 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1102 // Entries are found:
1104 // The main analysis
1105 $this->analyzeTemplate($templateMatches);
1107 // Compile raw template data
1108 $this->compileRawTemplateData($templateMatches);
1110 // Are there some raw templates left for loading?
1111 $this->loadExtraRawTemplates();
1113 // Are some raw templates found and loaded?
1114 if (count($this->rawTemplates) > 0) {
1116 // Insert all raw templates
1117 $this->insertRawTemplates();
1119 // Remove the raw template content as well
1120 $this->setRawTemplateData('');
1124 } // END - if($templateMatches ...
1128 * A old deprecated method
1132 * @see BaseTemplateEngine::transferToResponse
1134 public function output () {
1135 // Check which type of template we have
1136 switch ($this->getTemplateType()) {
1137 case 'html': // Raw HTML templates can be send to the output buffer
1139 $this->getWebOutputInstance()->output($this->getCompiledData());
1142 default: // Unknown type found
1143 // Construct message
1144 $msg = sprintf("[%s->%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1145 $this->__toString(),
1147 $this->getTemplateType()
1150 // Write the problem to the world...
1151 $this->debugOutput($msg);
1157 * Loads a given view helper (by name)
1159 * @param $helperName The helper's name
1162 protected function loadViewHelper ($helperName) {
1163 // Make first character upper case, rest low
1164 $helperName = $this->convertToClassName($helperName);
1166 // Is this view helper loaded?
1167 if (!isset($this->helpers[$helperName])) {
1168 // Create a class name
1169 $className = "{$helperName}ViewHelper";
1171 // Generate new instance
1172 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1175 // Return the requested instance
1176 return $this->helpers[$helperName];
1180 * Assigns the last loaded raw template content with a given variable
1182 * @param $templateName Name of the template we want to assign
1183 * @param $variableName Name of the variable we want to assign
1186 public function assignTemplateWithVariable ($templateName, $variableName) {
1187 // Get the content from last loaded raw template
1188 $content = $this->getRawTemplateData();
1190 // Assign the variable
1191 $this->assignVariable($variableName, $content);
1193 // Purge raw content
1194 $this->setRawTemplateData('');
1198 * Transfers the content of this template engine to a given response instance
1200 * @param $responseInstance An instance of a response class
1203 public function transferToResponse (Responseable $responseInstance) {
1204 // Get the content and set it in response class
1205 $responseInstance->writeToBody($this->getCompiledData());
1209 * Assigns all the application data with template variables
1211 * @param $appInstance A manageable application instance
1214 public function assignApplicationData (ManageableApplication $appInstance) {
1215 // Get long name and assign it
1216 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1218 // Get short name and assign it
1219 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1221 // Get version number and assign it
1222 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1224 // Assign extra application-depending data
1225 $appInstance->assignExtraTemplateData($this);
1229 * "Compiles" a variable by replacing {?var?} with it's content
1231 * @param $rawCode Raw code to compile
1232 * @return $rawCode Compile code with inserted variable value
1234 public function compileRawCode ($rawCode) {
1235 // Find the variables
1236 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1237 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1239 // Compile all variables
1240 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1241 foreach ($varMatches[0] as $match) {
1242 // Add variable tags around it
1243 $varCode = '{?' . $match . '?}';
1245 // Is the variable found in code? (safes some calls)
1246 if (strpos($rawCode, $varCode) !== false) {
1247 // Replace the variable with it's value, if found
1248 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1249 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1253 // Return the compiled data
1258 * Getter for variable group array
1260 * @return $vargroups All variable groups
1262 public final function getVariableGroups () {
1263 return $this->varGroups;
1267 * Renames a variable in code and in stack
1269 * @param $oldName Old name of variable
1270 * @param $newName New name of variable
1273 public function renameVariable ($oldName, $newName) {
1274 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1275 // Get raw template code
1276 $rawData = $this->getRawTemplateData();
1279 $rawData = str_replace($oldName, $newName, $rawData);
1281 // Set the code back
1282 $this->setRawTemplateData($rawData);
1286 * Renders the given XML content
1288 * @param $content Valid XML content or if not set the current loaded raw content
1290 * @throws XmlParserException If an XML error was found
1292 public final function renderXmlContent ($content = null) {
1293 // Is the content set?
1294 if (is_null($content)) {
1295 // Get current content
1296 $content = $this->getRawTemplateData();
1299 // Convert all to UTF8
1300 if (function_exists('recode')) {
1301 $content = recode("html..utf8", $content);
1303 // @TODO We need to find a fallback solution here
1306 // Get an XML parser
1307 $xmlParser = xml_parser_create();
1309 // Force case-folding to on
1310 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
1313 xml_set_object($xmlParser, $this);
1315 // Set handler call-backs
1316 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
1317 xml_set_character_data_handler($xmlParser, 'characterHandler');
1319 // Now parse the XML tree
1320 if (!xml_parse($xmlParser, $content)) {
1321 // Error found in XML!
1322 //die('<pre>'.htmlentities($content).'</pre>');
1323 throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
1327 xml_parser_free($xmlParser);