3 namespace CoreFramework\TemplateEngine;
5 // Import framework stuff
6 use CoreFramework\Object\BaseFrameworkSystem;
9 * A generic template engine
11 * @author Roland Haeder <webmaster@shipsimu.org>
13 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14 * @license GNU GPL 3.0 or any newer version
15 * @link http://www.shipsimu.org
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 class BaseTemplateEngine extends BaseFrameworkSystem {
32 * The local path name where all templates and sub folders for special
33 * templates are stored. We will internally determine the language plus
34 * "html" for web templates or "emails" for email templates
36 private $templateBasePath = '';
41 private $templateType = 'html';
44 * The extension for web and email templates (not compiled templates)
46 private $templateExtension = '.tpl';
49 * The extension for code templates (not compiled templates)
51 private $codeExtension = '.ctp';
54 * Path relative to $templateBasePath and language code for compiled code-templates
56 private $compileOutputPath = 'templates/_compiled/';
59 * The path name for all templates
61 private $genericBasePath = 'templates/';
64 * The raw (maybe uncompiled) template
66 private $rawTemplateData = '';
69 * Template data with compiled-in variables
71 private $compiledData = '';
74 * The last loaded template's FQFN for debugging the engine
76 private $lastTemplate = '';
79 * The variable stack for the templates
81 private $varStack = array();
84 * Loaded templates for recursive protection and detection
86 private $loadedTemplates = array();
89 * Compiled templates for recursive protection and detection
91 private $compiledTemplates = array();
94 * Loaded raw template data
96 private $loadedRawData = NULL;
99 * Raw templates which are linked in code templates
101 private $rawTemplates = NULL;
104 * A regular expression for variable=value pairs
106 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
109 * A regular expression for filtering out code tags
111 * E.g.: {?template:variable=value;var2=value2;[...]?}
113 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
116 * A regular expression to find template comments like <!-- Comment here //-->
118 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
123 private $helpers = array();
126 * Current variable group
128 private $currGroup = 'general';
131 * All template groups except "general"
133 private $variableGroups = array();
138 private $codeBegin = '<?php';
143 private $codeEnd = '?>';
146 * Language support is enabled by default
148 private $languageSupport = TRUE;
151 * XML compacting is disabled by default
153 private $xmlCompacting = FALSE;
155 // Exception codes for the template engine
156 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
157 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
158 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
159 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
162 * Protected constructor
164 * @param $className Name of the class
167 protected function __construct ($className) {
168 // Call parent constructor
169 parent::__construct($className);
171 // Init file I/O instance
172 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
175 $this->setFileIoInstance($ioInstance);
179 * Search for a variable in the stack
181 * @param $variableName The variable we are looking for
182 * @param $variableGroup Optional variable group to look in
183 * @return $index FALSE means not found, >=0 means found on a specific index
185 private function getVariableIndex ($variableName, $variableGroup = NULL) {
186 // Replace all dashes to underscores to match variables with configuration entries
187 $variableName = trim(self::convertDashesToUnderscores($variableName));
189 // First everything is not found
192 // If the stack is NULL, use the current group
193 if (is_null($variableGroup)) {
195 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
196 $variableGroup = $this->currGroup;
199 // Is the group there?
200 if ($this->isVarStackSet($variableGroup)) {
202 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
203 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
204 // Is the entry found?
205 if ($currEntry['name'] == $variableName) {
207 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':FOUND!');
214 // Return the current position
219 * Checks whether the given variable group is set
221 * @param $variableGroup Variable group to check
222 * @return $isSet Whether the given variable group is set
224 protected final function isVarStackSet ($variableGroup) {
226 $isSet = isset($this->varStack[$variableGroup]);
233 * Getter for given variable group
235 * @param $variableGroup Variable group to check
236 * @return $varStack Found variable group
238 public final function getVarStack ($variableGroup) {
239 return $this->varStack[$variableGroup];
243 * Setter for given variable group
245 * @param $variableGroup Variable group to check
246 * @param $varStack Variable stack to check
249 protected final function setVarStack ($variableGroup, array $varStack) {
250 $this->varStack[$variableGroup] = $varStack;
254 * Return a content of a variable or null if not found
256 * @param $variableName The variable we are looking for
257 * @param $variableGroup Optional variable group to look in
258 * @return $content Content of the variable or null if not found
260 protected function readVariable ($variableName, $variableGroup = NULL) {
261 // Replace all dashes to underscores to match variables with configuration entries
262 $variableName = trim(self::convertDashesToUnderscores($variableName));
264 // First everything is not found
267 // If the stack is NULL, use the current group
268 if (is_null($variableGroup)) {
270 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
271 $variableGroup = $this->currGroup;
274 // Get variable index
275 $found = $this->getVariableIndex($variableName, $variableGroup);
277 // Is the variable found?
278 if ($found !== FALSE) {
280 $content = $this->getVariableValue($variableGroup, $found);
283 // Return the current position
284 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
289 * Add a variable to the stack
291 * @param $variableName Name of variable to add
292 * @param $value Value we want to store in the variable
295 private function addVariable ($variableName, $value) {
296 // Set general variable group
297 $this->setVariableGroup('general');
299 // Add it to the stack
300 $this->addGroupVariable($variableName, $value);
304 * Returns all variables of current group or empty array
306 * @return $result Whether array of found variables or empty array
308 private function readCurrentGroup () {
309 // Default is not found
312 // Is the group there?
313 if ($this->isVarStackSet($this->currGroup)) {
315 $result = $this->getVarStack($this->currGroup);
323 * Settter for variable group
325 * @param $groupName Name of variable group
326 * @param $add Whether add this group
329 public function setVariableGroup ($groupName, $add = TRUE) {
331 //* DEBIG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
332 $this->currGroup = $groupName;
334 // Skip group 'general'
335 if (($groupName != 'general') && ($add === TRUE)) {
336 $this->variableGroups[$groupName] = 'OK';
342 * Adds a variable to current group
344 * @param $variableName Variable to set
345 * @param $value Value to store in variable
348 public function addGroupVariable ($variableName, $value) {
349 // Replace all dashes to underscores to match variables with configuration entries
350 $variableName = trim(self::convertDashesToUnderscores($variableName));
353 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
355 // Get current variables in group
356 $currVars = $this->readCurrentGroup();
358 // Append our variable
359 array_push($currVars, $this->generateVariableArray($variableName, $value));
361 // Add it to the stack
362 $this->setVarStack($this->currGroup, $currVars);
366 * Getter for variable value, throws a NoVariableException if the variable is not found
368 * @param $variableGroup Variable group to use
369 * @param $index Index in variable array
370 * @return $value Value to set
372 private function getVariableValue ($variableGroup, $index) {
374 return $this->varStack[$variableGroup][$index]['value'];
378 * Modify an entry on the stack
380 * @param $variableName The variable we are looking for
381 * @param $value The value we want to store in the variable
383 * @throws NoVariableException If the given variable is not found
385 private function modifyVariable ($variableName, $value) {
386 // Replace all dashes to underscores to match variables with configuration entries
387 $variableName = trim(self::convertDashesToUnderscores($variableName));
389 // Get index for variable
390 $index = $this->getVariableIndex($variableName);
392 // Is the variable set?
393 if ($index === FALSE) {
394 // Unset variables cannot be modified
395 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
399 $this->setVariableValue($this->currGroup, $index, $value);
403 * Sets a variable value for given variable group and index
405 * @param $variableGroup Variable group to use
406 * @param $index Index in variable array
407 * @param $value Value to set
410 private function setVariableValue ($variableGroup, $index, $value) {
411 $this->varStack[$variableGroup][$index]['value'] = $value;
415 * Sets a variable within given group. This method does detect if the
416 * variable is already set. If so, the variable got modified, otherwise
419 * @param $variableGroup Variable group to use
420 * @param $variableName Variable to set
421 * @param $value Value to set
424 protected function setVariable ($variableGroup, $variableName, $value) {
425 // Replace all dashes to underscores to match variables with configuration entries
426 $variableName = trim(self::convertDashesToUnderscores($variableName));
428 // Get index for variable
429 $index = $this->getVariableIndex($variableName);
431 // Is the variable set?
432 if ($index === FALSE) {
433 // Is the stack there?
434 if (!isset($this->varStack[$variableGroup])) {
435 // Then initialize it here
436 $this->varStack[$variableGroup] = array();
440 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
443 $this->setVariableValue($this->currGroup, $index, $value);
448 * "Generates" (better returns) an array for all variables for given
449 * variable/value pay.
451 * @param $variableName Variable to set
452 * @param $value Value to set
453 * @return $varData Variable data array
455 private function generateVariableArray ($variableName, $value) {
456 // Replace all dashes to underscores to match variables with configuration entries
457 $variableName = trim(self::convertDashesToUnderscores($variableName));
459 // Generate the temporary array
461 'name' => $variableName,
470 * Setter for template type. Only 'html', 'emails' and 'compiled' should
473 * @param $templateType The current template's type
476 protected final function setTemplateType ($templateType) {
477 $this->templateType = (string) $templateType;
481 * Getter for template type
483 * @return $templateType The current template's type
485 public final function getTemplateType () {
486 return $this->templateType;
490 * Setter for the last loaded template's FQFN
492 * @param $template The last loaded template
495 private final function setLastTemplate ($template) {
496 $this->lastTemplate = (string) $template;
500 * Getter for the last loaded template's FQFN
502 * @return $template The last loaded template
504 private final function getLastTemplate () {
505 return $this->lastTemplate;
509 * Setter for base path
511 * @param $templateBasePath The relative base path for all templates
514 protected final function setTemplateBasePath ($templateBasePath) {
516 $this->templateBasePath = (string) $templateBasePath;
520 * Getter for base path
522 * @return $templateBasePath The relative base path for all templates
524 public final function getTemplateBasePath () {
526 return $this->templateBasePath;
530 * Getter for generic base path
532 * @return $templateBasePath The relative base path for all templates
534 public final function getGenericBasePath () {
536 return $this->genericBasePath;
540 * Setter for template extension
542 * @param $templateExtension The file extension for all uncompiled
546 protected final function setRawTemplateExtension ($templateExtension) {
548 $this->templateExtension = (string) $templateExtension;
552 * Setter for code template extension
554 * @param $codeExtension The file extension for all uncompiled
558 protected final function setCodeTemplateExtension ($codeExtension) {
560 $this->codeExtension = (string) $codeExtension;
564 * Getter for template extension
566 * @return $templateExtension The file extension for all uncompiled
569 public final function getRawTemplateExtension () {
571 return $this->templateExtension;
575 * Getter for code-template extension
577 * @return $codeExtension The file extension for all code-
580 public final function getCodeTemplateExtension () {
582 return $this->codeExtension;
586 * Setter for path of compiled templates
588 * @param $compileOutputPath The local base path for all compiled
592 protected final function setCompileOutputPath ($compileOutputPath) {
594 $this->compileOutputPath = (string) $compileOutputPath;
598 * Unsets the given offset in the variable group
600 * @param $index Index to unset
601 * @param $variableGroup Variable group (default: currGroup)
604 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
605 // Is the variable group not set?
606 if (is_null($variableGroup)) {
607 // Then set it to current
608 $variableGroup = $this->currGroup;
611 // Is the entry there?
612 if (!isset($this->varStack[$variableGroup][$index])) {
613 // Abort here, we need fixing!
614 $this->debugInstance();
618 unset($this->varStack[$variableGroup][$index]);
622 * Private setter for raw template data
624 * @param $rawTemplateData The raw data from the template
627 protected final function setRawTemplateData ($rawTemplateData) {
628 // And store it in this class
629 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
630 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
631 $this->rawTemplateData = (string) $rawTemplateData;
635 * Getter for raw template data
637 * @return $rawTemplateData The raw data from the template
639 public final function getRawTemplateData () {
640 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
641 return $this->rawTemplateData;
645 * Private setter for compiled templates
649 private final function setCompiledData ($compiledData) {
650 // And store it in this class
651 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
652 $this->compiledData = (string) $compiledData;
656 * Getter for compiled templates, must be public for e.g. Mailer classes.
658 * @return $compiledData Compiled template data
660 public final function getCompiledData () {
661 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
662 return $this->compiledData;
666 * Private loader for all template types
668 * @param $template The template we shall load
669 * @param $extOther An other extension to use
671 * @throws FileNotFoundException If the template was not found
673 protected function loadTemplate ($template, $extOther = '') {
674 // Get extension for the template if empty
675 if (empty($extOther)) {
676 // None provided, so get the raw one
677 $ext = $this->getRawTemplateExtension();
680 $ext = (string) $extOther;
684 * Construct the FQFN for the template without language as language is
685 * now entirely done by php_intl. These old thing with language-based
686 * template paths comes from an older time.
688 $fqfn = sprintf('%s%s%s%s/%s%s',
689 $this->getConfigInstance()->getConfigEntry('base_path'),
690 $this->getTemplateBasePath(),
691 $this->getGenericBasePath(),
692 $this->getTemplateType(),
699 // Load the raw template data
700 $this->loadRawTemplateData($fqfn);
701 } catch (FileNotFoundException $e) {
702 // If we shall load a code-template we need to switch the file extension
703 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
704 // Switch over to the code-template extension and try it again
705 $ext = $this->getCodeTemplateExtension();
708 $this->loadTemplate($template, $ext);
711 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
718 * A private loader for raw template names
720 * @param $fqfn The full-qualified file name for a template
723 private function loadRawTemplateData ($fqfn) {
724 // Some debug code to look on the file which is being loaded
725 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
727 // Load the raw template
728 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
730 // Store the template's contents into this class
731 $this->setRawTemplateData($rawTemplateData);
733 // Remember the template's FQFN
734 $this->setLastTemplate($fqfn);
738 * Try to assign an extracted template variable as a "content" or 'config'
741 * @param $variableName The variable's name (shall be content or config)
743 * @param $variableName The variable we want to assign
746 private function assignTemplateVariable ($variableName, $var) {
747 // Replace all dashes to underscores to match variables with configuration entries
748 $variableName = trim(self::convertDashesToUnderscores($variableName));
751 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
753 // Is it not a config variable?
754 if ($variableName != 'config') {
755 // Regular template variables
756 $this->assignVariable($variableName, '');
758 // Configuration variables
759 $this->assignConfigVariable($var);
764 * Extract variables from a given raw data stream
766 * @param $rawData The raw template data we shall analyze
769 private function extractVariablesFromRawData ($rawData) {
771 $rawData = (string) $rawData;
773 // Search for variables
774 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
777 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
779 // Did we find some variables?
780 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
781 // Initialize all missing variables
782 foreach ($variableMatches[3] as $key => $var) {
784 $variableName = $variableMatches[1][$key];
786 // Workarround: Do not assign empty variables
788 // Try to assign it, empty strings are being ignored
789 $this->assignTemplateVariable($variableName, $var);
796 * Main analysis of the loaded template
798 * @param $templateMatches Found template place-holders, see below
801 *---------------------------------
802 * Structure of $templateMatches:
803 *---------------------------------
804 * [0] => Array - An array with all full matches
805 * [1] => Array - An array with left part (before the ':') of a match
806 * [2] => Array - An array with right part of a match including ':'
807 * [3] => Array - An array with right part of a match excluding ':'
809 private function analyzeTemplate (array $templateMatches) {
810 // Backup raw template data
811 $backup = $this->getRawTemplateData();
813 // Initialize some arrays
814 if (is_null($this->loadedRawData)) {
816 $this->loadedRawData = array();
817 $this->rawTemplates = array();
820 // Load all requested templates
821 foreach ($templateMatches[1] as $template) {
822 // Load and compile only templates which we have not yet loaded
823 // RECURSIVE PROTECTION! BE CAREFUL HERE!
824 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
826 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
828 // Template not found, but maybe variable assigned?
829 if ($this->getVariableIndex($template) !== FALSE) {
830 // Use that content here
831 $this->loadedRawData[$template] = $this->readVariable($template);
833 // Recursive protection:
834 array_push($this->loadedTemplates, $template);
836 // Then try to search for code-templates
838 // Load the code template and remember it's contents
839 $this->loadCodeTemplate($template);
840 $this->loadedRawData[$template] = $this->getRawTemplateData();
842 // Remember this template for recursion detection
843 // RECURSIVE PROTECTION!
844 array_push($this->loadedTemplates, $template);
845 } catch (FileNotFoundException $e) {
846 // Even this is not done... :/
847 array_push($this->rawTemplates, $template);
853 // Restore the raw template data
854 $this->setRawTemplateData($backup);
858 * Compile a given raw template code and remember it for later usage
860 * @param $code The raw template code
861 * @param $template The template's name
864 private function compileCode ($code, $template) {
865 // Is this template already compiled?
866 if (in_array($template, $this->compiledTemplates)) {
871 // Remember this template being compiled
872 array_push($this->compiledTemplates, $template);
874 // Compile the loaded code in five steps:
876 // 1. Backup current template data
877 $backup = $this->getRawTemplateData();
879 // 2. Set the current template's raw data as the new content
880 $this->setRawTemplateData($code);
882 // 3. Compile the template data
883 $this->compileTemplate();
885 // 4. Remember it's contents
886 $this->loadedRawData[$template] = $this->getRawTemplateData();
888 // 5. Restore the previous raw content from backup variable
889 $this->setRawTemplateData($backup);
893 * Insert all given and loaded templates by running through all loaded
894 * codes and searching for their place-holder in the main template
896 * @param $templateMatches See method analyzeTemplate()
899 private function insertAllTemplates (array $templateMatches) {
900 // Run through all loaded codes
901 foreach ($this->loadedRawData as $template => $code) {
903 // Search for the template
904 $foundIndex = array_search($template, $templateMatches[1]);
906 // Lookup the matching template replacement
907 if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
909 // Get the current raw template
910 $rawData = $this->getRawTemplateData();
912 // Replace the space holder with the template code
913 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
915 // Set the new raw data
916 $this->setRawTemplateData($rawData);
922 * Load all extra raw templates
926 private function loadExtraRawTemplates () {
927 // Are there some raw templates we need to load?
928 if (count($this->rawTemplates) > 0) {
929 // Try to load all raw templates
930 foreach ($this->rawTemplates as $key => $template) {
933 $this->loadHtmlTemplate($template);
935 // Remember it's contents
936 $this->rawTemplates[$template] = $this->getRawTemplateData();
938 // Remove it from the loader list
939 unset($this->rawTemplates[$key]);
941 // Remember this template for recursion detection
942 // RECURSIVE PROTECTION!
943 array_push($this->loadedTemplates, $template);
944 } catch (FileNotFoundException $e) {
945 // This template was never found. We silently ignore it
946 unset($this->rawTemplates[$key]);
953 * Assign all found template variables
955 * @param $varMatches An array full of variable/value pairs.
957 * @todo Unfinished work or don't die here.
959 private function assignAllVariables (array $varMatches) {
961 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
963 // Search for all variables
964 foreach ($varMatches[1] as $key => $var) {
965 // Replace all dashes to underscores to match variables with configuration entries
966 $var = trim(self::convertDashesToUnderscores($var));
969 self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
971 // Detect leading equals
972 if (substr($varMatches[2][$key], 0, 1) == '=') {
973 // Remove and cast it
974 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
977 // Do we have some quotes left and right side? Then it is free text
978 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
979 // Free string detected! Which we can assign directly
980 $this->assignVariable($var, $varMatches[3][$key]);
981 } elseif (!empty($varMatches[2][$key])) {
982 // @TODO Non-string found so we need some deeper analysis...
983 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
989 * Compiles all loaded raw templates
991 * @param $templateMatches See method analyzeTemplate() for details
994 private function compileRawTemplateData (array $templateMatches) {
996 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
998 // Are some code-templates found which we need to compile?
999 if (count($this->loadedRawData) > 0) {
1000 // Then compile all!
1001 foreach ($this->loadedRawData as $template => $code) {
1003 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1005 // Is this template already compiled?
1006 if (in_array($template, $this->compiledTemplates)) {
1008 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1012 // Search for the template
1013 $foundIndex = array_search($template, $templateMatches[1]);
1015 // Lookup the matching variable data
1016 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1017 // Split it up with another reg. exp. into variable=value pairs
1018 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1019 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1021 // Assign all variables
1022 $this->assignAllVariables($varMatches);
1023 } // END - if (isset($templateMatches ...
1025 // Compile the loaded template
1026 $this->compileCode($code, $template);
1027 } // END - foreach ($this->loadedRawData ...
1029 // Insert all templates
1030 $this->insertAllTemplates($templateMatches);
1031 } // END - if (count($this->loadedRawData) ...
1035 * Inserts all raw templates into their respective variables
1039 private function insertRawTemplates () {
1040 // Load all templates
1041 foreach ($this->rawTemplates as $template => $content) {
1042 // Set the template as a variable with the content
1043 $this->assignVariable($template, $content);
1048 * Finalizes the compilation of all template variables
1052 private function finalizeVariableCompilation () {
1054 $content = $this->getRawTemplateData();
1055 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1057 // Do we have the stack?
1058 if (!$this->isVarStackSet('general')) {
1059 // Abort here silently
1060 // @TODO This silent abort should be logged, maybe.
1064 // Walk through all variables
1065 foreach ($this->getVarStack('general') as $currEntry) {
1066 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1067 // Replace all [$var] or {?$var?} with the content
1068 // @TODO Old behaviour, will become obsolete!
1069 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1071 // @TODO Yet another old way
1072 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1074 // The new behaviour
1075 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1078 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1080 // Set the content back
1081 $this->setRawTemplateData($content);
1085 * Load a specified HTML template into the engine
1087 * @param $template The web template we shall load which is located in
1091 public function loadHtmlTemplate ($template) {
1092 // Set template type
1093 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1095 // Load the special template
1096 $this->loadTemplate($template);
1100 * Assign (add) a given variable with a value
1102 * @param $variableName The variable we are looking for
1103 * @param $value The value we want to store in the variable
1105 * @throws EmptyVariableException If the variable name is left empty
1107 public final function assignVariable ($variableName, $value) {
1108 // Replace all dashes to underscores to match variables with configuration entries
1109 $variableName = trim(self::convertDashesToUnderscores($variableName));
1111 // Empty variable found?
1112 if (empty($variableName)) {
1113 // Throw an exception
1114 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1117 // First search for the variable if it was already added
1118 $index = $this->getVariableIndex($variableName);
1121 if ($index === FALSE) {
1122 // Add it to the stack
1123 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1124 $this->addVariable($variableName, $value);
1125 } elseif (!empty($value)) {
1126 // Modify the stack entry
1127 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1128 $this->modifyVariable($variableName, $value);
1133 * Removes a given variable
1135 * @param $variableName The variable we are looking for
1136 * @param $variableGroup Name of variable group (default: 'general')
1139 public final function removeVariable ($variableName, $variableGroup = 'general') {
1140 // First search for the variable if it was already added
1141 $index = $this->getVariableIndex($variableName, $variableGroup);
1144 if ($index !== FALSE) {
1145 // Remove this variable
1146 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1147 $this->unsetVariableStackOffset($index, $variableGroup);
1152 * Assigns the last loaded raw template content with a given variable
1154 * @param $templateName Name of the template we want to assign
1155 * @param $variableName Name of the variable we want to assign
1158 public function assignTemplateWithVariable ($templateName, $variableName) {
1159 // Get the content from last loaded raw template
1160 $content = $this->getRawTemplateData();
1162 // Assign the variable
1163 $this->assignVariable($variableName, $content);
1165 // Purge raw content
1166 $this->setRawTemplateData('');
1170 * Assign a given congfiguration variable with a value
1172 * @param $variableName The configuration variable we want to assign
1175 public function assignConfigVariable ($variableName) {
1176 // Replace all dashes to underscores to match variables with configuration entries
1177 $variableName = trim(self::convertDashesToUnderscores($variableName));
1179 // Sweet and simple...
1180 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1181 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1185 * Assigns a lot variables into the stack of currently loaded template.
1186 * This method should only be used in very rare circumstances, e.g. when
1187 * you have to copy a whole set of variables into the template engine.
1188 * Before you use this method, please make sure you have considered all
1189 * other possiblities.
1191 * @param $variables An array with variables to be assigned
1194 public function assignMultipleVariables (array $variables) {
1196 foreach ($variables as $name => $value) {
1197 // Set variable with name for 'config' group
1198 $this->assignVariable($name, $value);
1203 * Assigns all the application data with template variables
1205 * @param $applicationInstance A manageable application instance
1208 public function assignApplicationData (ManageableApplication $applicationInstance) {
1209 // Get long name and assign it
1210 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1212 // Get short name and assign it
1213 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1215 // Get version number and assign it
1216 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1218 // Assign extra application-depending data
1219 $applicationInstance->assignExtraTemplateData($this);
1223 * Load a specified code template into the engine
1225 * @param $template The code template we shall load which is
1226 * located in 'code' by default
1229 public function loadCodeTemplate ($template) {
1230 // Set template type
1231 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type'));
1233 // Load the special template
1234 $this->loadTemplate($template);
1238 * Load a specified email template into the engine
1240 * @param $template The email template we shall load which is
1241 * located in 'emails' by default
1244 public function loadEmailTemplate ($template) {
1245 // Set template type
1246 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1248 // Load the special template
1249 $this->loadTemplate($template);
1253 * Compiles configuration place-holders in all variables. This 'walks'
1254 * through the variable group 'general'. It interprets all values from that
1255 * variables as configuration entries after compiling them.
1259 public final function compileConfigInVariables () {
1260 // Do we have the stack?
1261 if (!$this->isVarStackSet('general')) {
1262 // Abort here silently
1263 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1267 // Iterate through all general variables
1268 foreach ($this->getVarStack('general') as $index => $currVariable) {
1269 // Compile the value
1270 $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1273 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1275 // Remove it from stack
1276 $this->removeVariable($currVariable['name'], 'general');
1277 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1279 // Is it a configuration key?
1280 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1281 // The value itself is a configuration entry
1282 $this->assignConfigVariable($value);
1284 // Re-assign the value directly
1285 $this->assignVariable($currVariable['name'], $value);
1291 * Compile all variables by inserting their respective values
1294 * @todo Make this code some nicer...
1296 public final function compileVariables () {
1297 // Initialize the $content array
1298 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1301 // Iterate through all general variables
1302 foreach ($this->getVarStack('general') as $currVariable) {
1303 // Transfer it's name/value combination to the $content array
1304 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1305 $dummy[$currVariable['name']] = $currVariable['value'];
1308 // Set the new variable (don't remove the second dollar!)
1309 $$validVar = $dummy;
1311 // Remove some variables
1313 unset($currVariable);
1315 // Run the compilation three times to get content from helper classes in
1318 // Finalize the compilation of template variables
1319 $this->finalizeVariableCompilation();
1321 // Prepare the eval() command for comiling the template
1322 $eval = sprintf('$result = "%s";',
1323 addslashes($this->getRawTemplateData())
1326 // This loop does remove the backslashes (\) in PHP parameters
1327 while (strpos($eval, $this->codeBegin) !== FALSE) {
1328 // Get left part before "<?"
1329 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1331 // Get all from right of "<?"
1332 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1334 // Cut middle part out and remove escapes
1335 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1336 $evalMiddle = stripslashes($evalMiddle);
1338 // Remove the middle part from right one
1339 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1341 // And put all together
1342 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1345 // Prepare PHP code for eval() command
1346 $eval = str_replace(
1355 // Run the constructed command. This will "compile" all variables in
1358 // Goes something wrong?
1359 if ((!isset($result)) || (empty($result))) {
1360 // Output eval command
1361 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1363 // Output backtrace here
1364 $this->debugBackTrace();
1367 // Set raw template data
1368 $this->setRawTemplateData($result);
1372 // Final variable assignment
1373 $this->finalizeVariableCompilation();
1375 // Set the new content
1376 $this->setCompiledData($this->getRawTemplateData());
1380 * Compile all required templates into the current loaded one
1383 * @throws UnexpectedTemplateTypeException If the template type is
1385 * @throws InvalidArrayCountException If an unexpected array
1386 * count has been found
1388 public function compileTemplate () {
1389 // Get code type to make things shorter
1390 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type');
1392 // We will only work with template type "code" from configuration
1393 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1395 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1398 // Get the raw data.
1399 $rawData = $this->getRawTemplateData();
1401 // Remove double spaces and trim leading/trailing spaces
1402 $rawData = trim(str_replace(' ', ' ', $rawData));
1404 // Search for raw variables
1405 $this->extractVariablesFromRawData($rawData);
1407 // Search for code-tags which are {? ?}
1408 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1411 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1413 // Analyze the matches array
1414 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1415 // Entries are found:
1417 // The main analysis
1418 $this->analyzeTemplate($templateMatches);
1420 // Compile raw template data
1421 $this->compileRawTemplateData($templateMatches);
1423 // Are there some raw templates left for loading?
1424 $this->loadExtraRawTemplates();
1426 // Are some raw templates found and loaded?
1427 if (count($this->rawTemplates) > 0) {
1428 // Insert all raw templates
1429 $this->insertRawTemplates();
1431 // Remove the raw template content as well
1432 $this->setRawTemplateData('');
1434 } // END - if($templateMatches ...
1438 * Loads a given view helper (by name)
1440 * @param $helperName The helper's name
1443 protected function loadViewHelper ($helperName) {
1444 // Is this view helper loaded?
1445 if (!isset($this->helpers[$helperName])) {
1446 // Create a class name
1447 $className = self::convertToClassName($helperName) . 'ViewHelper';
1449 // Generate new instance
1450 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1453 // Return the requested instance
1454 return $this->helpers[$helperName];
1458 * Transfers the content of this template engine to a given response instance
1460 * @param $responseInstance An instance of a response class
1463 public function transferToResponse (Responseable $responseInstance) {
1464 // Get the content and set it in response class
1465 $responseInstance->writeToBody($this->getCompiledData());
1469 * "Compiles" a variable by replacing {?var?} with it's content
1471 * @param $rawCode Raw code to compile
1472 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1473 * @return $rawCode Compile code with inserted variable value
1475 public function compileRawCode ($rawCode, $setMatchAsCode=FALSE) {
1476 // Find the variables
1477 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1478 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1480 // Compile all variables
1481 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, TRUE) . '</pre>');
1482 foreach ($varMatches[0] as $match) {
1483 // Add variable tags around it
1484 $varCode = '{?' . $match . '?}';
1487 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1489 // Is the variable found in code? (safes some calls)
1490 if (strpos($rawCode, $varCode) !== FALSE) {
1492 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1494 // Use $match as new value or $value from read variable?
1495 if ($setMatchAsCode === TRUE) {
1497 $rawCode = str_replace($varCode, $match, $rawCode);
1499 // Read the variable
1500 $value = $this->readVariable($match);
1503 $rawCode = str_replace($varCode, $value, $rawCode);
1508 // Return the compiled data
1509 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1514 * Getter for variable group array
1516 * @return $variableGroups All variable groups
1518 public final function getVariableGroups () {
1519 return $this->variableGroups;
1523 * Renames a variable in code and in stack
1525 * @param $oldName Old name of variable
1526 * @param $newName New name of variable
1529 public function renameVariable ($oldName, $newName) {
1530 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1531 // Get raw template code
1532 $rawData = $this->getRawTemplateData();
1535 $rawData = str_replace($oldName, $newName, $rawData);
1537 // Set the code back
1538 $this->setRawTemplateData($rawData);
1542 * Renders the given XML content
1544 * @param $content Valid XML content or if not set the current loaded raw content
1546 * @throws XmlParserException If an XML error was found
1548 public function renderXmlContent ($content = NULL) {
1549 // Is the content set?
1550 if (is_null($content)) {
1551 // Get current content
1552 $content = $this->getRawTemplateData();
1555 // Get a XmlParser instance
1556 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1558 // Check if XML compacting is enabled
1559 if ($this->isXmlCompactingEnabled()) {
1560 // Yes, so get a decorator class for transparent compacting
1561 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1564 // Parse the XML document
1565 $parserInstance->parseXmlContent($content);
1569 * Enables or disables language support
1571 * @param $languageSupport New language support setting
1574 public final function enableLanguageSupport ($languageSupport = TRUE) {
1575 $this->languageSupport = (bool) $languageSupport;
1579 * Checks whether language support is enabled
1581 * @return $languageSupport Whether language support is enabled or disabled
1583 public final function isLanguageSupportEnabled () {
1584 return $this->languageSupport;
1588 * Enables or disables XML compacting
1590 * @param $xmlCompacting New XML compacting setting
1593 public final function enableXmlCompacting ($xmlCompacting = TRUE) {
1594 $this->xmlCompacting = (bool) $xmlCompacting;
1598 * Checks whether XML compacting is enabled
1600 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1602 public final function isXmlCompactingEnabled () {
1603 return $this->xmlCompacting;
1607 * Removes all commentd, tabs and new-line characters to compact the content
1609 * @param $uncompactedContent The uncompacted content
1610 * @return $compactedContent The compacted content
1612 public function compactContent ($uncompactedContent) {
1613 // First, remove all tab/new-line/revert characters
1614 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1616 // Then regex all comments like <!-- //--> away
1617 preg_match_all($this->regExpComments, $compactedContent, $matches);
1619 // Do we have entries?
1620 if (isset($matches[0][0])) {
1622 foreach ($matches[0] as $match) {
1624 $compactedContent = str_replace($match, '', $compactedContent);
1628 // Set the content again
1629 $this->setRawTemplateData($compactedContent);
1631 // Return compacted content
1632 return $compactedContent;