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 = '?>';
135 * Language support is enabled by default
137 private $languageSupport = true;
139 // Exception codes for the template engine
140 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
141 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
142 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
145 * Protected constructor
147 * @param $className Name of the class
150 protected function __construct ($className) {
151 // Call parent constructor
152 parent::__construct($className);
156 * Search for a variable in the stack
158 * @param $var The variable we are looking for
159 * @return $idx FALSE means not found, >=0 means found on a specific index
161 private function isVariableAlreadySet ($var) {
162 // First everything is not found
165 // Is the group there?
166 if (isset($this->varStack[$this->currGroup])) {
168 foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
169 //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
170 // Is the entry found?
171 if ($currEntry['name'] == $var) {
173 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
180 // Return the current position
185 * Return a content of a variable or null if not found
187 * @param $var The variable we are looking for
188 * @return $content Content of the variable or null if not found
190 protected function readVariable ($var) {
191 // First everything is not found
194 // Get variable index
195 $found = $this->isVariableAlreadySet($var);
197 // Is the variable found?
198 if ($found !== false) {
200 $found = $this->varStack[$this->currGroup][$found]['value'];
203 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
205 // Return the current position
210 * Add a variable to the stack
212 * @param $var The variable we are looking for
213 * @param $value The value we want to store in the variable
216 private function addVariable ($var, $value) {
217 // Set general variable group
218 $this->setVariableGroup('general');
220 // Add it to the stack
221 $this->addGroupVariable($var, $value);
225 * Returns all variables of current group or empty array
227 * @return $result Wether array of found variables or empty array
229 private function readCurrentGroup () {
230 // Default is not found
233 // Is the group there?
234 if (isset($this->varStack[$this->currGroup])) {
236 $result = $this->varStack[$this->currGroup];
244 * Settter for variable group
246 * @param $groupName Name of variable group
247 * @param $add Wether add this group
250 public function setVariableGroup ($groupName, $add = true) {
252 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
253 $this->currGroup = $groupName;
255 // Skip group 'general'
256 if (($groupName != 'general') && ($add === true)) {
257 $this->varGroups[$groupName] = 'OK';
263 * Adds a variable to current group
265 * @param $var Variable to set
266 * @param $value Value to store in variable
269 public function addGroupVariable ($var, $value) {
270 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
272 // Get current variables in group
273 $currVars = $this->readCurrentGroup();
275 // Append our variable
281 // Add it to the stack
282 $this->varStack[$this->currGroup] = $currVars;
286 * Modify an entry on the stack
288 * @param $var The variable we are looking for
289 * @param $value The value we want to store in the variable
292 private function modifyVariable ($var, $value) {
293 // Get index for variable
294 $idx = $this->isVariableAlreadySet($var);
296 // Is the variable set?
297 if ($idx !== false) {
299 $this->varStack[$this->currGroup][$idx]['value'] = $value;
304 * Setter for template type. Only 'html', 'emails' and 'compiled' should
307 * @param $templateType The current template's type
310 protected final function setTemplateType ($templateType) {
311 $this->templateType = (string) $templateType;
315 * Setter for the last loaded template's FQFN
317 * @param $template The last loaded template
320 private final function setLastTemplate ($template) {
321 $this->lastTemplate = (string) $template;
325 * Getter for the last loaded template's FQFN
327 * @return $template The last loaded template
329 private final function getLastTemplate () {
330 return $this->lastTemplate;
334 * Setter for base path
336 * @param $templateBasePath The relative base path for all templates
339 public final function setTemplateBasePath ($templateBasePath) {
341 $this->templateBasePath = (string) $templateBasePath;
345 * Getter for base path
347 * @return $templateBasePath The relative base path for all templates
349 public final function getTemplateBasePath () {
351 return $this->templateBasePath;
355 * Getter for generic base path
357 * @return $templateBasePath The relative base path for all templates
359 public final function getGenericBasePath () {
361 return $this->genericBasePath;
365 * Setter for template extension
367 * @param $templateExtension The file extension for all uncompiled
371 public final function setRawTemplateExtension ($templateExtension) {
373 $this->templateExtension = (string) $templateExtension;
377 * Setter for code template extension
379 * @param $codeExtension The file extension for all uncompiled
383 public final function setCodeTemplateExtension ($codeExtension) {
385 $this->codeExtension = (string) $codeExtension;
389 * Getter for template extension
391 * @return $templateExtension The file extension for all uncompiled
394 public final function getRawTemplateExtension () {
396 return $this->templateExtension;
400 * Getter for code-template extension
402 * @return $codeExtension The file extension for all code-
405 public final function getCodeTemplateExtension () {
407 return $this->codeExtension;
411 * Setter for path of compiled templates
413 * @param $compileOutputPath The local base path for all compiled
417 public final function setCompileOutputPath ($compileOutputPath) {
419 $this->compileOutputPath = (string) $compileOutputPath;
423 * Getter for template type
425 * @return $templateType The current template's type
427 public final function getTemplateType () {
428 return $this->templateType;
432 * Assign (add) a given variable with a value
434 * @param $var The variable we are looking for
435 * @param $value The value we want to store in the variable
437 * @throws EmptyVariableException If the variable name is left empty
439 public final function assignVariable ($var, $value) {
440 // Trim spaces of variable name
443 // Empty variable found?
445 // Throw an exception
446 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
449 // First search for the variable if it was already added
450 $idx = $this->isVariableAlreadySet($var);
453 if ($idx === false) {
454 // Add it to the stack
455 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
456 $this->addVariable($var, $value);
457 } elseif (!empty($value)) {
458 // Modify the stack entry
459 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
460 $this->modifyVariable($var, $value);
465 * Removes a given variable
467 * @param $var The variable we are looking for
470 public final function removeVariable ($var) {
471 // First search for the variable if it was already added
472 $idx = $this->isVariableAlreadySet($var);
475 if ($idx !== false) {
476 // Remove this variable
477 $this->varStack->offsetUnset($idx);
482 * Private setter for raw template data
484 * @param $rawTemplateData The raw data from the template
487 protected final function setRawTemplateData ($rawTemplateData) {
488 // And store it in this class
489 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
490 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->varStack[$this->currGroup]).', groups='.count($this->varStack).'<br />\n';
491 $this->rawTemplateData = (string) $rawTemplateData;
495 * Getter for raw template data
497 * @return $rawTemplateData The raw data from the template
499 public final function getRawTemplateData () {
500 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
501 return $this->rawTemplateData;
505 * Private setter for compiled templates
509 private final function setCompiledData ($compiledData) {
510 // And store it in this class
511 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
512 $this->compiledData = (string) $compiledData;
516 * Getter for compiled templates
518 * @return $compiledData Compiled template data
520 public final function getCompiledData () {
521 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
522 return $this->compiledData;
526 * Private loader for all template types
528 * @param $template The template we shall load
529 * @param $extOther An other extension to use
531 * @throws FileIoException If the template was not found
533 protected function loadTemplate ($template, $extOther = '') {
534 // Get extension for the template if empty
535 if (empty($extOther)) {
536 // None provided, so get the raw one
537 $ext = $this->getRawTemplateExtension();
540 $ext = (string) $extOther;
543 // Is language support enabled?
544 if ($this->isLanguageSupportEnabled()) {
545 // Construct the FQFN for the template by honoring the current language
546 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
547 $this->getConfigInstance()->getConfigEntry('base_path'),
548 $this->getTemplateBasePath(),
549 $this->getGenericBasePath(),
550 $this->getLanguageInstance()->getLanguageCode(),
551 $this->getTemplateType(),
556 // Construct the FQFN for the template without language
557 $fqfn = sprintf("%s%s%s%s/%s%s",
558 $this->getConfigInstance()->getConfigEntry('base_path'),
559 $this->getTemplateBasePath(),
560 $this->getGenericBasePath(),
561 $this->getTemplateType(),
569 // Load the raw template data
570 $this->loadRawTemplateData($fqfn);
571 } catch (FileIoException $e) {
572 // If we shall load a code-template we need to switch the file extension
573 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
574 // Switch over to the code-template extension and try it again
575 $ext = $this->getCodeTemplateExtension();
578 $this->loadTemplate($template, $ext);
581 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
588 * A private loader for raw template names
590 * @param $fqfn The full-qualified file name for a template
593 private function loadRawTemplateData ($fqfn) {
594 // Get a input/output instance from the middleware
595 $ioInstance = $this->getFileIoInstance();
597 // Some debug code to look on the file which is being loaded
598 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
600 // Load the raw template
601 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
603 // Store the template's contents into this class
604 $this->setRawTemplateData($rawTemplateData);
606 // Remember the template's FQFN
607 $this->setLastTemplate($fqfn);
611 * Try to assign an extracted template variable as a "content" or 'config'
614 * @param $varName The variable's name (shall be content orconfig) by
616 * @param $var The variable we want to assign
618 private function assignTemplateVariable ($varName, $var) {
619 // Is it not a config variable?
620 if ($varName != 'config') {
621 // Regular template variables
622 $this->assignVariable($var, '');
624 // Configuration variables
625 $this->assignConfigVariable($var);
630 * Extract variables from a given raw data stream
632 * @param $rawData The raw template data we shall analyze
635 private function extractVariablesFromRawData ($rawData) {
637 $rawData = (string) $rawData;
639 // Search for variables
640 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
642 // Did we find some variables?
643 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
644 // Initialize all missing variables
645 foreach ($variableMatches[3] as $key => $var) {
647 $varName = $variableMatches[1][$key];
649 // Workarround: Do not assign empty variables
651 // Try to assign it, empty strings are being ignored
652 $this->assignTemplateVariable($varName, $var);
659 * Main analysis of the loaded template
661 * @param $templateMatches Found template place-holders, see below
664 *---------------------------------
665 * Structure of $templateMatches:
666 *---------------------------------
667 * [0] => Array - An array with all full matches
668 * [1] => Array - An array with left part (before the ':') of a match
669 * [2] => Array - An array with right part of a match including ':'
670 * [3] => Array - An array with right part of a match excluding ':'
672 private function analyzeTemplate (array $templateMatches) {
673 // Backup raw template data
674 $backup = $this->getRawTemplateData();
676 // Initialize some arrays
677 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
679 // Load all requested templates
680 foreach ($templateMatches[1] as $template) {
682 // Load and compile only templates which we have not yet loaded
683 // RECURSIVE PROTECTION! BE CAREFUL HERE!
684 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
686 // Template not found, but maybe variable assigned?
687 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
688 if ($this->isVariableAlreadySet($template) !== false) {
689 // Use that content here
690 $this->loadedRawData[$template] = $this->readVariable($template);
692 // Recursive protection:
693 $this->loadedTemplates[] = $template;
694 } elseif (isset($this->varStack['config'][$template])) {
695 // Use that content here
696 $this->loadedRawData[$template] = $this->varStack['config'][$template];
698 // Recursive protection:
699 $this->loadedTemplates[] = $template;
701 // Then try to search for code-templates
703 // Load the code template and remember it's contents
704 $this->loadCodeTemplate($template);
705 $this->loadedRawData[$template] = $this->getRawTemplateData();
707 // Remember this template for recursion detection
708 // RECURSIVE PROTECTION!
709 $this->loadedTemplates[] = $template;
710 } catch (FileIoException $e) {
711 // Even this is not done... :/
712 $this->rawTemplates[] = $template;
718 // Restore the raw template data
719 $this->setRawTemplateData($backup);
723 * Compile a given raw template code and remember it for later usage
725 * @param $code The raw template code
726 * @param $template The template's name
729 private function compileCode ($code, $template) {
730 // Is this template already compiled?
731 if (in_array($template, $this->compiledTemplates)) {
736 // Remember this template being compiled
737 $this->compiledTemplates[] = $template;
739 // Compile the loaded code in five steps:
741 // 1. Backup current template data
742 $backup = $this->getRawTemplateData();
744 // 2. Set the current template's raw data as the new content
745 $this->setRawTemplateData($code);
747 // 3. Compile the template data
748 $this->compileTemplate();
750 // 4. Remember it's contents
751 $this->loadedRawData[$template] = $this->getRawTemplateData();
753 // 5. Restore the previous raw content from backup variable
754 $this->setRawTemplateData($backup);
758 * Insert all given and loaded templates by running through all loaded
759 * codes and searching for their place-holder in the main template
761 * @param $templateMatches See method analyzeTemplate()
764 private function insertAllTemplates (array $templateMatches) {
765 // Run through all loaded codes
766 foreach ($this->loadedRawData as $template => $code) {
768 // Search for the template
769 $foundIndex = array_search($template, $templateMatches[1]);
771 // Lookup the matching template replacement
772 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
774 // Get the current raw template
775 $rawData = $this->getRawTemplateData();
777 // Replace the space holder with the template code
778 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
780 // Set the new raw data
781 $this->setRawTemplateData($rawData);
787 * Load all extra raw templates
791 private function loadExtraRawTemplates () {
792 // Are there some raw templates we need to load?
793 if (count($this->rawTemplates) > 0) {
794 // Try to load all raw templates
795 foreach ($this->rawTemplates as $key => $template) {
798 $this->loadWebTemplate($template);
800 // Remember it's contents
801 $this->rawTemplates[$template] = $this->getRawTemplateData();
803 // Remove it from the loader list
804 unset($this->rawTemplates[$key]);
806 // Remember this template for recursion detection
807 // RECURSIVE PROTECTION!
808 $this->loadedTemplates[] = $template;
809 } catch (FileIoException $e) {
810 // This template was never found. We silently ignore it
811 unset($this->rawTemplates[$key]);
818 * Assign all found template variables
820 * @param $varMatches An array full of variable/value pairs.
822 * @todo Unfinished work or don't die here.
824 private function assignAllVariables (array $varMatches) {
825 // Search for all variables
826 foreach ($varMatches[1] as $key => $var) {
828 // Detect leading equals
829 if (substr($varMatches[2][$key], 0, 1) == '=') {
830 // Remove and cast it
831 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
834 // Do we have some quotes left and right side? Then it is free text
835 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
836 // Free string detected! Which we can assign directly
837 $this->assignVariable($var, $varMatches[3][$key]);
838 } elseif (!empty($varMatches[2][$key])) {
839 // @TODO Non-string found so we need some deeper analysis...
840 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
843 } // for ($varMatches ...
846 * Compiles all loaded raw templates
848 * @param $templateMatches See method analyzeTemplate() for details
851 private function compileRawTemplateData (array $templateMatches) {
852 // Are some code-templates found which we need to compile?
853 if (count($this->loadedRawData) > 0) {
856 foreach ($this->loadedRawData as $template => $code) {
858 // Is this template already compiled?
859 if (in_array($template, $this->compiledTemplates)) {
864 // Search for the template
865 $foundIndex = array_search($template, $templateMatches[1]);
867 // Lookup the matching variable data
868 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
870 // Split it up with another reg. exp. into variable=value pairs
871 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
873 // Assign all variables
874 $this->assignAllVariables($varMatches);
876 } // END - if (isset($templateMatches ...
878 // Compile the loaded template
879 $this->compileCode($code, $template);
881 } // END - foreach ($this->loadedRawData ...
883 // Insert all templates
884 $this->insertAllTemplates($templateMatches);
886 } // END - if (count($this->loadedRawData) ...
890 * Inserts all raw templates into their respective variables
894 private function insertRawTemplates () {
895 // Load all templates
896 foreach ($this->rawTemplates as $template => $content) {
897 // Set the template as a variable with the content
898 $this->assignVariable($template, $content);
903 * Finalizes the compilation of all template variables
907 private function finalizeVariableCompilation () {
909 $content = $this->getRawTemplateData();
910 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
912 // Walk through all variables
913 foreach ($this->varStack['general'] as $currEntry) {
914 //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
915 // Replace all [$var] or {?$var?} with the content
916 // @TODO Old behaviour, will become obsolete!
917 $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
919 // @TODO Yet another old way
920 $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
923 $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
926 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
928 // Set the content back
929 $this->setRawTemplateData($content);
933 * Load a specified web template into the engine
935 * @param $template The web template we shall load which is located in
939 public function loadWebTemplate ($template) {
941 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
943 // Load the special template
944 $this->loadTemplate($template);
948 * Assign a given congfiguration variable with a value
950 * @param $var The configuration variable we want to assign
953 public function assignConfigVariable ($var) {
954 // Sweet and simple...
955 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
956 $this->varStack['config'][$var] = $this->getConfigInstance()->getConfigEntry($var);
960 * Load a specified email template into the engine
962 * @param $template The email template we shall load which is located in
963 * 'emails' by default
966 * @see See loadCodeTemplate()
968 public function loadEmailTemplate ($template) {
970 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
972 // Load the special template
973 $this->loadTemplate($template);
977 * Load a specified code template into the engine
979 * @param $template The code template we shall load which is
980 * located in 'code' by default
983 public function loadCodeTemplate ($template) {
985 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
987 // Load the special template
988 $this->loadTemplate($template);
992 * Compile all variables by inserting their respective values
995 * @todo Make this code some nicer...
997 public final function compileVariables () {
998 // Initialize the $content array
999 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1002 // Iterate through all general variables
1003 foreach ($this->varStack['general'] as $currVariable) {
1004 // Transfer it's name/value combination to the $content array
1005 //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
1006 $dummy[$currVariable['name']] = $currVariable['value'];
1009 // Set the new variable (don't remove the second dollar!)
1010 $$validVar = $dummy;
1012 // Prepare all configuration variables
1014 if (isset($this->varStack['config'])) {
1015 $config = $this->varStack['config'];
1018 // Remove some variables
1020 unset($currVariable);
1022 // Run the compilation three times to get content from helper classes in
1025 // Finalize the compilation of template variables
1026 $this->finalizeVariableCompilation();
1028 // Prepare the eval() command for comiling the template
1029 $eval = sprintf("\$result = \"%s\";",
1030 addslashes($this->getRawTemplateData())
1033 // This loop does remove the backslashes (\) in PHP parameters
1034 while (strpos($eval, $this->codeBegin) !== false) {
1035 // Get left part before "<?"
1036 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1038 // Get all from right of "<?"
1039 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1041 // Cut middle part out and remove escapes
1042 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1043 $evalMiddle = stripslashes($evalMiddle);
1045 // Remove the middle part from right one
1046 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1048 // And put all together
1049 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1052 // Prepare PHP code for eval() command
1053 $eval = str_replace(
1062 // Run the constructed command. This will "compile" all variables in
1065 // Goes something wrong?
1066 if ((!isset($result)) || (empty($result))) {
1067 // Output eval command
1068 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1070 // Output backtrace here
1071 $this->debugBackTrace();
1074 // Set raw template data
1075 $this->setRawTemplateData($result);
1079 // Final variable assignment
1080 $this->finalizeVariableCompilation();
1082 // Set the new content
1083 $this->setCompiledData($this->getRawTemplateData());
1087 * Compile all required templates into the current loaded one
1090 * @throws UnexpectedTemplateTypeException If the template type is
1092 * @throws InvalidArrayCountException If an unexpected array
1093 * count has been found
1095 public function compileTemplate () {
1096 // We will only work with template type "code" from configuration
1097 if ($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('code_template_type')) {
1099 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1102 // Get the raw data.
1103 $rawData = $this->getRawTemplateData();
1105 // Remove double spaces and trim leading/trailing spaces
1106 $rawData = trim(str_replace(' ', ' ', $rawData));
1108 // Search for raw variables
1109 $this->extractVariablesFromRawData($rawData);
1111 // Search for code-tags which are {? ?}
1112 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1114 // Analyze the matches array
1115 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1116 // Entries are found:
1118 // The main analysis
1119 $this->analyzeTemplate($templateMatches);
1121 // Compile raw template data
1122 $this->compileRawTemplateData($templateMatches);
1124 // Are there some raw templates left for loading?
1125 $this->loadExtraRawTemplates();
1127 // Are some raw templates found and loaded?
1128 if (count($this->rawTemplates) > 0) {
1130 // Insert all raw templates
1131 $this->insertRawTemplates();
1133 // Remove the raw template content as well
1134 $this->setRawTemplateData('');
1138 } // END - if($templateMatches ...
1142 * A old deprecated method
1146 * @see BaseTemplateEngine::transferToResponse
1148 public function output () {
1149 // Check which type of template we have
1150 switch ($this->getTemplateType()) {
1151 case 'html': // Raw HTML templates can be send to the output buffer
1153 $this->getWebOutputInstance()->output($this->getCompiledData());
1156 default: // Unknown type found
1157 // Construct message
1158 $msg = sprintf("[%s->%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1159 $this->__toString(),
1161 $this->getTemplateType()
1164 // Write the problem to the world...
1165 $this->debugOutput($msg);
1171 * Loads a given view helper (by name)
1173 * @param $helperName The helper's name
1176 protected function loadViewHelper ($helperName) {
1177 // Make first character upper case, rest low
1178 $helperName = $this->convertToClassName($helperName);
1180 // Is this view helper loaded?
1181 if (!isset($this->helpers[$helperName])) {
1182 // Create a class name
1183 $className = "{$helperName}ViewHelper";
1185 // Generate new instance
1186 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1189 // Return the requested instance
1190 return $this->helpers[$helperName];
1194 * Assigns the last loaded raw template content with a given variable
1196 * @param $templateName Name of the template we want to assign
1197 * @param $variableName Name of the variable we want to assign
1200 public function assignTemplateWithVariable ($templateName, $variableName) {
1201 // Get the content from last loaded raw template
1202 $content = $this->getRawTemplateData();
1204 // Assign the variable
1205 $this->assignVariable($variableName, $content);
1207 // Purge raw content
1208 $this->setRawTemplateData('');
1212 * Transfers the content of this template engine to a given response instance
1214 * @param $responseInstance An instance of a response class
1217 public function transferToResponse (Responseable $responseInstance) {
1218 // Get the content and set it in response class
1219 $responseInstance->writeToBody($this->getCompiledData());
1223 * Assigns all the application data with template variables
1225 * @param $appInstance A manageable application instance
1228 public function assignApplicationData (ManageableApplication $appInstance) {
1229 // Get long name and assign it
1230 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1232 // Get short name and assign it
1233 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1235 // Get version number and assign it
1236 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1238 // Assign extra application-depending data
1239 $appInstance->assignExtraTemplateData($this);
1243 * "Compiles" a variable by replacing {?var?} with it's content
1245 * @param $rawCode Raw code to compile
1246 * @return $rawCode Compile code with inserted variable value
1248 public function compileRawCode ($rawCode) {
1249 // Find the variables
1250 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1251 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1253 // Compile all variables
1254 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1255 foreach ($varMatches[0] as $match) {
1256 // Add variable tags around it
1257 $varCode = '{?' . $match . '?}';
1259 // Is the variable found in code? (safes some calls)
1260 if (strpos($rawCode, $varCode) !== false) {
1261 // Replace the variable with it's value, if found
1262 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1263 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1267 // Return the compiled data
1272 * Getter for variable group array
1274 * @return $vargroups All variable groups
1276 public final function getVariableGroups () {
1277 return $this->varGroups;
1281 * Renames a variable in code and in stack
1283 * @param $oldName Old name of variable
1284 * @param $newName New name of variable
1287 public function renameVariable ($oldName, $newName) {
1288 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1289 // Get raw template code
1290 $rawData = $this->getRawTemplateData();
1293 $rawData = str_replace($oldName, $newName, $rawData);
1295 // Set the code back
1296 $this->setRawTemplateData($rawData);
1300 * Renders the given XML content
1302 * @param $content Valid XML content or if not set the current loaded raw content
1304 * @throws XmlParserException If an XML error was found
1306 public function renderXmlContent ($content = null) {
1307 // Is the content set?
1308 if (is_null($content)) {
1309 // Get current content
1310 $content = $this->getRawTemplateData();
1313 // Get a XmlParser instance
1314 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1316 // Parse the XML document
1317 $parserInstance->parseXmlContent($content);
1321 * Enables or disables language support
1323 * @param $languageSupport New language support setting
1326 public final function enableLanguageSupport ($languageSupport = true) {
1327 $this->languageSupport = (bool) $languageSupport;
1331 * Checks wether language support is enabled
1333 * @return $languageSupport Wether language support is enabled or disabled
1335 public final function isLanguageSupportEnabled () {
1336 return $this->languageSupport;