3 namespace CoreFramework\Template\Engine;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Filesystem\FileNotFoundException;
9 use CoreFramework\Generic\EmptyVariableException;
10 use CoreFramework\Manager\ManageableApplication;
11 use CoreFramework\Object\BaseFrameworkSystem;
12 use CoreFramework\Response\Responseable;
15 * A generic template engine
17 * @author Roland Haeder <webmaster@shipsimu.org>
19 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
20 * @license GNU GPL 3.0 or any newer version
21 * @link http://www.shipsimu.org
23 * This program is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 class BaseTemplateEngine extends BaseFrameworkSystem {
38 * The local path name where all templates and sub folders for special
39 * templates are stored. We will internally determine the language plus
40 * "html" for web templates or "emails" for email templates
42 private $templateBasePath = '';
47 private $templateType = 'html';
50 * The extension for web and email templates (not compiled templates)
52 private $templateExtension = '.tpl';
55 * The extension for code templates (not compiled templates)
57 private $codeExtension = '.ctp';
60 * Path relative to $templateBasePath and language code for compiled code-templates
62 private $compileOutputPath = 'templates/_compiled/';
65 * The path name for all templates
67 private $genericBasePath = 'templates/';
70 * The raw (maybe uncompiled) template
72 private $rawTemplateData = '';
75 * Template data with compiled-in variables
77 private $compiledData = '';
80 * The last loaded template's FQFN for debugging the engine
82 private $lastTemplate = '';
85 * The variable stack for the templates
87 private $varStack = array();
90 * Loaded templates for recursive protection and detection
92 private $loadedTemplates = array();
95 * Compiled templates for recursive protection and detection
97 private $compiledTemplates = array();
100 * Loaded raw template data
102 private $loadedRawData = NULL;
105 * Raw templates which are linked in code templates
107 private $rawTemplates = NULL;
110 * A regular expression for variable=value pairs
112 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
115 * A regular expression for filtering out code tags
117 * E.g.: {?template:variable=value;var2=value2;[...]?}
119 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
122 * A regular expression to find template comments like <!-- Comment here //-->
124 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
129 private $helpers = array();
132 * Current variable group
134 private $currGroup = 'general';
137 * All template groups except "general"
139 private $variableGroups = array();
144 private $codeBegin = '<?php';
149 private $codeEnd = '?>';
152 * Language support is enabled by default
154 private $languageSupport = true;
157 * XML compacting is disabled by default
159 private $xmlCompacting = false;
161 // Exception codes for the template engine
162 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
163 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
164 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
165 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
168 * Protected constructor
170 * @param $className Name of the class
173 protected function __construct ($className) {
174 // Call parent constructor
175 parent::__construct($className);
177 // Init file I/O instance
178 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
181 $this->setFileIoInstance($ioInstance);
185 * Search for a variable in the stack
187 * @param $variableName The variable we are looking for
188 * @param $variableGroup Optional variable group to look in
189 * @return $index false means not found, >=0 means found on a specific index
191 private function getVariableIndex ($variableName, $variableGroup = NULL) {
192 // Replace all dashes to underscores to match variables with configuration entries
193 $variableName = trim(self::convertDashesToUnderscores($variableName));
195 // First everything is not found
198 // If the stack is NULL, use the current group
199 if (is_null($variableGroup)) {
201 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
202 $variableGroup = $this->currGroup;
205 // Is the group there?
206 if ($this->isVarStackSet($variableGroup)) {
208 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
209 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
210 // Is the entry found?
211 if ($currEntry['name'] == $variableName) {
213 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
220 // Return the current position
225 * Checks whether the given variable group is set
227 * @param $variableGroup Variable group to check
228 * @return $isSet Whether the given variable group is set
230 protected final function isVarStackSet ($variableGroup) {
232 $isSet = isset($this->varStack[$variableGroup]);
239 * Getter for given variable group
241 * @param $variableGroup Variable group to check
242 * @return $varStack Found variable group
244 public final function getVarStack ($variableGroup) {
245 return $this->varStack[$variableGroup];
249 * Setter for given variable group
251 * @param $variableGroup Variable group to check
252 * @param $varStack Variable stack to check
255 protected final function setVarStack ($variableGroup, array $varStack) {
256 $this->varStack[$variableGroup] = $varStack;
260 * Return a content of a variable or null if not found
262 * @param $variableName The variable we are looking for
263 * @param $variableGroup Optional variable group to look in
264 * @return $content Content of the variable or null if not found
266 protected function readVariable ($variableName, $variableGroup = NULL) {
267 // Replace all dashes to underscores to match variables with configuration entries
268 $variableName = trim(self::convertDashesToUnderscores($variableName));
270 // First everything is not found
273 // If the stack is NULL, use the current group
274 if (is_null($variableGroup)) {
276 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
277 $variableGroup = $this->currGroup;
280 // Get variable index
281 $found = $this->getVariableIndex($variableName, $variableGroup);
283 // Is the variable found?
284 if ($found !== false) {
286 $content = $this->getVariableValue($variableGroup, $found);
289 // Return the current position
290 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
295 * Add a variable to the stack
297 * @param $variableName Name of variable to add
298 * @param $value Value we want to store in the variable
301 private function addVariable ($variableName, $value) {
302 // Set general variable group
303 $this->setVariableGroup('general');
305 // Add it to the stack
306 $this->addGroupVariable($variableName, $value);
310 * Returns all variables of current group or empty array
312 * @return $result Whether array of found variables or empty array
314 private function readCurrentGroup () {
315 // Default is not found
318 // Is the group there?
319 if ($this->isVarStackSet($this->currGroup)) {
321 $result = $this->getVarStack($this->currGroup);
329 * Settter for variable group
331 * @param $groupName Name of variable group
332 * @param $add Whether add this group
335 public function setVariableGroup ($groupName, $add = true) {
337 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
338 $this->currGroup = $groupName;
340 // Skip group 'general'
341 if (($groupName != 'general') && ($add === true)) {
342 $this->variableGroups[$groupName] = 'OK';
348 * Adds a variable to current group
350 * @param $variableName Variable to set
351 * @param $value Value to store in variable
354 public function addGroupVariable ($variableName, $value) {
355 // Replace all dashes to underscores to match variables with configuration entries
356 $variableName = trim(self::convertDashesToUnderscores($variableName));
359 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
361 // Get current variables in group
362 $currVars = $this->readCurrentGroup();
364 // Append our variable
365 array_push($currVars, $this->generateVariableArray($variableName, $value));
367 // Add it to the stack
368 $this->setVarStack($this->currGroup, $currVars);
372 * Getter for variable value, throws a NoVariableException if the variable is not found
374 * @param $variableGroup Variable group to use
375 * @param $index Index in variable array
376 * @return $value Value to set
378 private function getVariableValue ($variableGroup, $index) {
380 return $this->varStack[$variableGroup][$index]['value'];
384 * Modify an entry on the stack
386 * @param $variableName The variable we are looking for
387 * @param $value The value we want to store in the variable
389 * @throws NoVariableException If the given variable is not found
391 private function modifyVariable ($variableName, $value) {
392 // Replace all dashes to underscores to match variables with configuration entries
393 $variableName = trim(self::convertDashesToUnderscores($variableName));
395 // Get index for variable
396 $index = $this->getVariableIndex($variableName);
398 // Is the variable set?
399 if ($index === false) {
400 // Unset variables cannot be modified
401 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
405 $this->setVariableValue($this->currGroup, $index, $value);
409 * Sets a variable value for given variable group and index
411 * @param $variableGroup Variable group to use
412 * @param $index Index in variable array
413 * @param $value Value to set
416 private function setVariableValue ($variableGroup, $index, $value) {
417 $this->varStack[$variableGroup][$index]['value'] = $value;
421 * Sets a variable within given group. This method does detect if the
422 * variable is already set. If so, the variable got modified, otherwise
425 * @param $variableGroup Variable group to use
426 * @param $variableName Variable to set
427 * @param $value Value to set
430 protected function setVariable ($variableGroup, $variableName, $value) {
431 // Replace all dashes to underscores to match variables with configuration entries
432 $variableName = trim(self::convertDashesToUnderscores($variableName));
434 // Get index for variable
435 $index = $this->getVariableIndex($variableName);
437 // Is the variable set?
438 if ($index === false) {
439 // Is the stack there?
440 if (!isset($this->varStack[$variableGroup])) {
441 // Then initialize it here
442 $this->varStack[$variableGroup] = array();
446 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
449 $this->setVariableValue($this->currGroup, $index, $value);
454 * "Generates" (better returns) an array for all variables for given
455 * variable/value pay.
457 * @param $variableName Variable to set
458 * @param $value Value to set
459 * @return $varData Variable data array
461 private function generateVariableArray ($variableName, $value) {
462 // Replace all dashes to underscores to match variables with configuration entries
463 $variableName = trim(self::convertDashesToUnderscores($variableName));
465 // Generate the temporary array
467 'name' => $variableName,
476 * Setter for template type. Only 'html', 'emails' and 'compiled' should
479 * @param $templateType The current template's type
482 protected final function setTemplateType ($templateType) {
483 $this->templateType = (string) $templateType;
487 * Getter for template type
489 * @return $templateType The current template's type
491 public final function getTemplateType () {
492 return $this->templateType;
496 * Setter for the last loaded template's FQFN
498 * @param $template The last loaded template
501 private final function setLastTemplate ($template) {
502 $this->lastTemplate = (string) $template;
506 * Getter for the last loaded template's FQFN
508 * @return $template The last loaded template
510 private final function getLastTemplate () {
511 return $this->lastTemplate;
515 * Setter for base path
517 * @param $templateBasePath The relative base path for all templates
520 protected final function setTemplateBasePath ($templateBasePath) {
522 $this->templateBasePath = (string) $templateBasePath;
526 * Getter for base path
528 * @return $templateBasePath The relative base path for all templates
530 public final function getTemplateBasePath () {
532 return $this->templateBasePath;
536 * Getter for generic base path
538 * @return $templateBasePath The relative base path for all templates
540 public final function getGenericBasePath () {
542 return $this->genericBasePath;
546 * Setter for template extension
548 * @param $templateExtension The file extension for all uncompiled
552 protected final function setRawTemplateExtension ($templateExtension) {
554 $this->templateExtension = (string) $templateExtension;
558 * Setter for code template extension
560 * @param $codeExtension The file extension for all uncompiled
564 protected final function setCodeTemplateExtension ($codeExtension) {
566 $this->codeExtension = (string) $codeExtension;
570 * Getter for template extension
572 * @return $templateExtension The file extension for all uncompiled
575 public final function getRawTemplateExtension () {
577 return $this->templateExtension;
581 * Getter for code-template extension
583 * @return $codeExtension The file extension for all code-
586 public final function getCodeTemplateExtension () {
588 return $this->codeExtension;
592 * Setter for path of compiled templates
594 * @param $compileOutputPath The local base path for all compiled
598 protected final function setCompileOutputPath ($compileOutputPath) {
600 $this->compileOutputPath = (string) $compileOutputPath;
604 * Unsets the given offset in the variable group
606 * @param $index Index to unset
607 * @param $variableGroup Variable group (default: currGroup)
610 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
611 // Is the variable group not set?
612 if (is_null($variableGroup)) {
613 // Then set it to current
614 $variableGroup = $this->currGroup;
617 // Is the entry there?
618 if (!isset($this->varStack[$variableGroup][$index])) {
619 // Abort here, we need fixing!
620 $this->debugInstance();
624 unset($this->varStack[$variableGroup][$index]);
628 * Private setter for raw template data
630 * @param $rawTemplateData The raw data from the template
633 protected final function setRawTemplateData ($rawTemplateData) {
634 // And store it in this class
635 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
636 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
637 $this->rawTemplateData = (string) $rawTemplateData;
641 * Getter for raw template data
643 * @return $rawTemplateData The raw data from the template
645 public final function getRawTemplateData () {
646 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
647 return $this->rawTemplateData;
651 * Private setter for compiled templates
655 private final function setCompiledData ($compiledData) {
656 // And store it in this class
657 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
658 $this->compiledData = (string) $compiledData;
662 * Getter for compiled templates, must be public for e.g. Mailer classes.
664 * @return $compiledData Compiled template data
666 public final function getCompiledData () {
667 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
668 return $this->compiledData;
672 * Private loader for all template types
674 * @param $template The template we shall load
675 * @param $extOther An other extension to use
677 * @throws FileNotFoundException If the template was not found
679 protected function loadTemplate ($template, $extOther = '') {
680 // Get extension for the template if empty
681 if (empty($extOther)) {
682 // None provided, so get the raw one
683 $ext = $this->getRawTemplateExtension();
686 $ext = (string) $extOther;
690 * Construct the FQFN for the template without language as language is
691 * now entirely done by php_intl. These old thing with language-based
692 * template paths comes from an older time.
694 $fqfn = sprintf('%s%s%s%s/%s%s',
695 $this->getConfigInstance()->getConfigEntry('application_base_path'),
696 $this->getTemplateBasePath(),
697 $this->getGenericBasePath(),
698 $this->getTemplateType(),
705 // Load the raw template data
706 $this->loadRawTemplateData($fqfn);
707 } catch (FileNotFoundException $e) {
708 // If we shall load a code-template we need to switch the file extension
709 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
710 // Switch over to the code-template extension and try it again
711 $ext = $this->getCodeTemplateExtension();
714 $this->loadTemplate($template, $ext);
717 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
724 * A private loader for raw template names
726 * @param $fqfn The full-qualified file name for a template
729 private function loadRawTemplateData ($fqfn) {
730 // Some debug code to look on the file which is being loaded
731 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
733 // Load the raw template
734 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
736 // Store the template's contents into this class
737 $this->setRawTemplateData($rawTemplateData);
739 // Remember the template's FQFN
740 $this->setLastTemplate($fqfn);
744 * Try to assign an extracted template variable as a "content" or 'config'
747 * @param $variableName The variable's name (shall be content or config)
749 * @param $variableName The variable we want to assign
752 private function assignTemplateVariable ($variableName, $var) {
753 // Replace all dashes to underscores to match variables with configuration entries
754 $variableName = trim(self::convertDashesToUnderscores($variableName));
757 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
759 // Is it not a config variable?
760 if ($variableName != 'config') {
761 // Regular template variables
762 $this->assignVariable($variableName, '');
764 // Configuration variables
765 $this->assignConfigVariable($var);
770 * Extract variables from a given raw data stream
772 * @param $rawData The raw template data we shall analyze
775 private function extractVariablesFromRawData ($rawData) {
777 $rawData = (string) $rawData;
779 // Search for variables
780 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
783 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
785 // Did we find some variables?
786 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
787 // Initialize all missing variables
788 foreach ($variableMatches[3] as $key => $var) {
790 $variableName = $variableMatches[1][$key];
792 // Workarround: Do not assign empty variables
794 // Try to assign it, empty strings are being ignored
795 $this->assignTemplateVariable($variableName, $var);
802 * Main analysis of the loaded template
804 * @param $templateMatches Found template place-holders, see below
807 *---------------------------------
808 * Structure of $templateMatches:
809 *---------------------------------
810 * [0] => Array - An array with all full matches
811 * [1] => Array - An array with left part (before the ':') of a match
812 * [2] => Array - An array with right part of a match including ':'
813 * [3] => Array - An array with right part of a match excluding ':'
815 private function analyzeTemplate (array $templateMatches) {
816 // Backup raw template data
817 $backup = $this->getRawTemplateData();
819 // Initialize some arrays
820 if (is_null($this->loadedRawData)) {
822 $this->loadedRawData = array();
823 $this->rawTemplates = array();
826 // Load all requested templates
827 foreach ($templateMatches[1] as $template) {
828 // Load and compile only templates which we have not yet loaded
829 // RECURSIVE PROTECTION! BE CAREFUL HERE!
830 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
832 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
834 // Template not found, but maybe variable assigned?
835 if ($this->getVariableIndex($template) !== false) {
836 // Use that content here
837 $this->loadedRawData[$template] = $this->readVariable($template);
839 // Recursive protection:
840 array_push($this->loadedTemplates, $template);
842 // Then try to search for code-templates
844 // Load the code template and remember it's contents
845 $this->loadCodeTemplate($template);
846 $this->loadedRawData[$template] = $this->getRawTemplateData();
848 // Remember this template for recursion detection
849 // RECURSIVE PROTECTION!
850 array_push($this->loadedTemplates, $template);
851 } catch (FileNotFoundException $e) {
852 // Even this is not done... :/
853 array_push($this->rawTemplates, $template);
859 // Restore the raw template data
860 $this->setRawTemplateData($backup);
864 * Compile a given raw template code and remember it for later usage
866 * @param $code The raw template code
867 * @param $template The template's name
870 private function compileCode ($code, $template) {
871 // Is this template already compiled?
872 if (in_array($template, $this->compiledTemplates)) {
877 // Remember this template being compiled
878 array_push($this->compiledTemplates, $template);
880 // Compile the loaded code in five steps:
882 // 1. Backup current template data
883 $backup = $this->getRawTemplateData();
885 // 2. Set the current template's raw data as the new content
886 $this->setRawTemplateData($code);
888 // 3. Compile the template data
889 $this->compileTemplate();
891 // 4. Remember it's contents
892 $this->loadedRawData[$template] = $this->getRawTemplateData();
894 // 5. Restore the previous raw content from backup variable
895 $this->setRawTemplateData($backup);
899 * Insert all given and loaded templates by running through all loaded
900 * codes and searching for their place-holder in the main template
902 * @param $templateMatches See method analyzeTemplate()
905 private function insertAllTemplates (array $templateMatches) {
906 // Run through all loaded codes
907 foreach ($this->loadedRawData as $template => $code) {
909 // Search for the template
910 $foundIndex = array_search($template, $templateMatches[1]);
912 // Lookup the matching template replacement
913 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
915 // Get the current raw template
916 $rawData = $this->getRawTemplateData();
918 // Replace the space holder with the template code
919 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
921 // Set the new raw data
922 $this->setRawTemplateData($rawData);
928 * Load all extra raw templates
932 private function loadExtraRawTemplates () {
933 // Are there some raw templates we need to load?
934 if (count($this->rawTemplates) > 0) {
935 // Try to load all raw templates
936 foreach ($this->rawTemplates as $key => $template) {
939 $this->loadHtmlTemplate($template);
941 // Remember it's contents
942 $this->rawTemplates[$template] = $this->getRawTemplateData();
944 // Remove it from the loader list
945 unset($this->rawTemplates[$key]);
947 // Remember this template for recursion detection
948 // RECURSIVE PROTECTION!
949 array_push($this->loadedTemplates, $template);
950 } catch (FileNotFoundException $e) {
951 // This template was never found. We silently ignore it
952 unset($this->rawTemplates[$key]);
959 * Assign all found template variables
961 * @param $varMatches An array full of variable/value pairs.
963 * @todo Unfinished work or don't die here.
965 private function assignAllVariables (array $varMatches) {
967 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
969 // Search for all variables
970 foreach ($varMatches[1] as $key => $var) {
971 // Replace all dashes to underscores to match variables with configuration entries
972 $var = trim(self::convertDashesToUnderscores($var));
975 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
977 // Detect leading equals
978 if (substr($varMatches[2][$key], 0, 1) == '=') {
979 // Remove and cast it
980 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
983 // Do we have some quotes left and right side? Then it is free text
984 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
985 // Free string detected! Which we can assign directly
986 $this->assignVariable($var, $varMatches[3][$key]);
987 } elseif (!empty($varMatches[2][$key])) {
988 // @TODO Non-string found so we need some deeper analysis...
989 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
995 * Compiles all loaded raw templates
997 * @param $templateMatches See method analyzeTemplate() for details
1000 private function compileRawTemplateData (array $templateMatches) {
1002 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1004 // Are some code-templates found which we need to compile?
1005 if (count($this->loadedRawData) > 0) {
1006 // Then compile all!
1007 foreach ($this->loadedRawData as $template => $code) {
1009 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1011 // Is this template already compiled?
1012 if (in_array($template, $this->compiledTemplates)) {
1014 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1018 // Search for the template
1019 $foundIndex = array_search($template, $templateMatches[1]);
1021 // Lookup the matching variable data
1022 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1023 // Split it up with another reg. exp. into variable=value pairs
1024 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1025 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1027 // Assign all variables
1028 $this->assignAllVariables($varMatches);
1029 } // END - if (isset($templateMatches ...
1031 // Compile the loaded template
1032 $this->compileCode($code, $template);
1033 } // END - foreach ($this->loadedRawData ...
1035 // Insert all templates
1036 $this->insertAllTemplates($templateMatches);
1037 } // END - if (count($this->loadedRawData) ...
1041 * Inserts all raw templates into their respective variables
1045 private function insertRawTemplates () {
1046 // Load all templates
1047 foreach ($this->rawTemplates as $template => $content) {
1048 // Set the template as a variable with the content
1049 $this->assignVariable($template, $content);
1054 * Finalizes the compilation of all template variables
1058 private function finalizeVariableCompilation () {
1060 $content = $this->getRawTemplateData();
1061 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1063 // Do we have the stack?
1064 if (!$this->isVarStackSet('general')) {
1065 // Abort here silently
1066 // @TODO This silent abort should be logged, maybe.
1070 // Walk through all variables
1071 foreach ($this->getVarStack('general') as $currEntry) {
1072 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1073 // Replace all [$var] or {?$var?} with the content
1074 // @TODO Old behaviour, will become obsolete!
1075 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1077 // @TODO Yet another old way
1078 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1080 // The new behaviour
1081 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1084 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1086 // Set the content back
1087 $this->setRawTemplateData($content);
1091 * Load a specified HTML template into the engine
1093 * @param $template The web template we shall load which is located in
1097 public function loadHtmlTemplate ($template) {
1098 // Set template type
1099 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1101 // Load the special template
1102 $this->loadTemplate($template);
1106 * Assign (add) a given variable with a value
1108 * @param $variableName The variable we are looking for
1109 * @param $value The value we want to store in the variable
1111 * @throws EmptyVariableException If the variable name is left empty
1113 public final function assignVariable ($variableName, $value) {
1114 // Replace all dashes to underscores to match variables with configuration entries
1115 $variableName = trim(self::convertDashesToUnderscores($variableName));
1117 // Empty variable found?
1118 if (empty($variableName)) {
1119 // Throw an exception
1120 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1123 // First search for the variable if it was already added
1124 $index = $this->getVariableIndex($variableName);
1127 if ($index === false) {
1128 // Add it to the stack
1129 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1130 $this->addVariable($variableName, $value);
1131 } elseif (!empty($value)) {
1132 // Modify the stack entry
1133 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1134 $this->modifyVariable($variableName, $value);
1139 * Removes a given variable
1141 * @param $variableName The variable we are looking for
1142 * @param $variableGroup Name of variable group (default: 'general')
1145 public final function removeVariable ($variableName, $variableGroup = 'general') {
1146 // First search for the variable if it was already added
1147 $index = $this->getVariableIndex($variableName, $variableGroup);
1150 if ($index !== false) {
1151 // Remove this variable
1152 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1153 $this->unsetVariableStackOffset($index, $variableGroup);
1158 * Assigns the last loaded raw template content with a given variable
1160 * @param $templateName Name of the template we want to assign
1161 * @param $variableName Name of the variable we want to assign
1164 public function assignTemplateWithVariable ($templateName, $variableName) {
1165 // Get the content from last loaded raw template
1166 $content = $this->getRawTemplateData();
1168 // Assign the variable
1169 $this->assignVariable($variableName, $content);
1171 // Purge raw content
1172 $this->setRawTemplateData('');
1176 * Assign a given congfiguration variable with a value
1178 * @param $variableName The configuration variable we want to assign
1181 public function assignConfigVariable ($variableName) {
1182 // Replace all dashes to underscores to match variables with configuration entries
1183 $variableName = trim(self::convertDashesToUnderscores($variableName));
1185 // Sweet and simple...
1186 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1187 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1191 * Assigns a lot variables into the stack of currently loaded template.
1192 * This method should only be used in very rare circumstances, e.g. when
1193 * you have to copy a whole set of variables into the template engine.
1194 * Before you use this method, please make sure you have considered all
1195 * other possiblities.
1197 * @param $variables An array with variables to be assigned
1200 public function assignMultipleVariables (array $variables) {
1202 foreach ($variables as $name => $value) {
1203 // Set variable with name for 'config' group
1204 $this->assignVariable($name, $value);
1209 * Assigns all the application data with template variables
1211 * @param $applicationInstance A manageable application instance
1214 public function assignApplicationData (ManageableApplication $applicationInstance) {
1215 // Get long name and assign it
1216 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1218 // Get short name and assign it
1219 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1221 // Get version number and assign it
1222 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1224 // Assign extra application-depending data
1225 $applicationInstance->assignExtraTemplateData($this);
1229 * Load a specified code template into the engine
1231 * @param $template The code template we shall load which is
1232 * located in 'code' by default
1235 public function loadCodeTemplate ($template) {
1236 // Set template type
1237 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1239 // Load the special template
1240 $this->loadTemplate($template);
1244 * Load a specified email template into the engine
1246 * @param $template The email template we shall load which is
1247 * located in 'emails' by default
1250 public function loadEmailTemplate ($template) {
1251 // Set template type
1252 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1254 // Load the special template
1255 $this->loadTemplate($template);
1259 * Compiles configuration place-holders in all variables. This 'walks'
1260 * through the variable group 'general'. It interprets all values from that
1261 * variables as configuration entries after compiling them.
1265 public final function compileConfigInVariables () {
1266 // Do we have the stack?
1267 if (!$this->isVarStackSet('general')) {
1268 // Abort here silently
1269 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1273 // Iterate through all general variables
1274 foreach ($this->getVarStack('general') as $index => $currVariable) {
1275 // Compile the value
1276 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1279 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1281 // Remove it from stack
1282 $this->removeVariable($currVariable['name'], 'general');
1283 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1285 // Is it a configuration key?
1286 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1287 // The value itself is a configuration entry
1288 $this->assignConfigVariable($value);
1290 // Re-assign the value directly
1291 $this->assignVariable($currVariable['name'], $value);
1297 * Compile all variables by inserting their respective values
1300 * @todo Make this code some nicer...
1302 public final function compileVariables () {
1303 // Initialize the $content array
1304 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1307 // Iterate through all general variables
1308 foreach ($this->getVarStack('general') as $currVariable) {
1309 // Transfer it's name/value combination to the $content array
1310 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1311 $dummy[$currVariable['name']] = $currVariable['value'];
1314 // Set the new variable (don't remove the second dollar!)
1315 $$validVar = $dummy;
1317 // Remove some variables
1319 unset($currVariable);
1321 // Run the compilation three times to get content from helper classes in
1324 // Finalize the compilation of template variables
1325 $this->finalizeVariableCompilation();
1327 // Prepare the eval() command for comiling the template
1328 $eval = sprintf('$result = "%s";',
1329 addslashes($this->getRawTemplateData())
1332 // This loop does remove the backslashes (\) in PHP parameters
1333 while (strpos($eval, $this->codeBegin) !== false) {
1334 // Get left part before "<?"
1335 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1337 // Get all from right of "<?"
1338 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1340 // Cut middle part out and remove escapes
1341 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1342 $evalMiddle = stripslashes($evalMiddle);
1344 // Remove the middle part from right one
1345 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1347 // And put all together
1348 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1351 // Prepare PHP code for eval() command
1352 $eval = str_replace(
1361 // Run the constructed command. This will "compile" all variables in
1364 // Goes something wrong?
1365 if ((!isset($result)) || (empty($result))) {
1366 // Output eval command
1367 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1369 // Output backtrace here
1370 $this->debugBackTrace();
1373 // Set raw template data
1374 $this->setRawTemplateData($result);
1378 // Final variable assignment
1379 $this->finalizeVariableCompilation();
1381 // Set the new content
1382 $this->setCompiledData($this->getRawTemplateData());
1386 * Compile all required templates into the current loaded one
1389 * @throws UnexpectedTemplateTypeException If the template type is
1391 * @throws InvalidArrayCountException If an unexpected array
1392 * count has been found
1394 public function compileTemplate () {
1395 // Get code type to make things shorter
1396 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1398 // We will only work with template type "code" from configuration
1399 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1401 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1404 // Get the raw data.
1405 $rawData = $this->getRawTemplateData();
1407 // Remove double spaces and trim leading/trailing spaces
1408 $rawData = trim(str_replace(' ', ' ', $rawData));
1410 // Search for raw variables
1411 $this->extractVariablesFromRawData($rawData);
1413 // Search for code-tags which are {? ?}
1414 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1417 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1419 // Analyze the matches array
1420 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1421 // Entries are found:
1423 // The main analysis
1424 $this->analyzeTemplate($templateMatches);
1426 // Compile raw template data
1427 $this->compileRawTemplateData($templateMatches);
1429 // Are there some raw templates left for loading?
1430 $this->loadExtraRawTemplates();
1432 // Are some raw templates found and loaded?
1433 if (count($this->rawTemplates) > 0) {
1434 // Insert all raw templates
1435 $this->insertRawTemplates();
1437 // Remove the raw template content as well
1438 $this->setRawTemplateData('');
1440 } // END - if($templateMatches ...
1444 * Loads a given view helper (by name)
1446 * @param $helperName The helper's name
1449 protected function loadViewHelper ($helperName) {
1450 // Is this view helper loaded?
1451 if (!isset($this->helpers[$helperName])) {
1452 // Create a class name
1453 $className = self::convertToClassName($helperName) . 'ViewHelper';
1455 // Generate new instance
1456 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1459 // Return the requested instance
1460 return $this->helpers[$helperName];
1464 * Transfers the content of this template engine to a given response instance
1466 * @param $responseInstance An instance of a Responseable class
1469 public function transferToResponse (Responseable $responseInstance) {
1470 // Get the content and set it in response class
1471 $responseInstance->writeToBody($this->getCompiledData());
1475 * "Compiles" a variable by replacing {?var?} with it's content
1477 * @param $rawCode Raw code to compile
1478 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1479 * @return $rawCode Compile code with inserted variable value
1481 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1482 // Find the variables
1483 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1484 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1486 // Compile all variables
1487 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1488 foreach ($varMatches[0] as $match) {
1489 // Add variable tags around it
1490 $varCode = '{?' . $match . '?}';
1493 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1495 // Is the variable found in code? (safes some calls)
1496 if (strpos($rawCode, $varCode) !== false) {
1498 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1500 // Use $match as new value or $value from read variable?
1501 if ($setMatchAsCode === true) {
1503 $rawCode = str_replace($varCode, $match, $rawCode);
1505 // Read the variable
1506 $value = $this->readVariable($match);
1509 $rawCode = str_replace($varCode, $value, $rawCode);
1514 // Return the compiled data
1515 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1520 * Getter for variable group array
1522 * @return $variableGroups All variable groups
1524 public final function getVariableGroups () {
1525 return $this->variableGroups;
1529 * Renames a variable in code and in stack
1531 * @param $oldName Old name of variable
1532 * @param $newName New name of variable
1535 public function renameVariable ($oldName, $newName) {
1536 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1537 // Get raw template code
1538 $rawData = $this->getRawTemplateData();
1541 $rawData = str_replace($oldName, $newName, $rawData);
1543 // Set the code back
1544 $this->setRawTemplateData($rawData);
1548 * Renders the given XML content
1550 * @param $content Valid XML content or if not set the current loaded raw content
1552 * @throws XmlParserException If an XML error was found
1554 public function renderXmlContent ($content = NULL) {
1555 // Is the content set?
1556 if (is_null($content)) {
1557 // Get current content
1558 $content = $this->getRawTemplateData();
1561 // Get a XmlParser instance
1562 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1564 // Check if XML compacting is enabled
1565 if ($this->isXmlCompactingEnabled()) {
1566 // Yes, so get a decorator class for transparent compacting
1567 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1570 // Parse the XML document
1571 $parserInstance->parseXmlContent($content);
1575 * Enables or disables language support
1577 * @param $languageSupport New language support setting
1580 public final function enableLanguageSupport ($languageSupport = true) {
1581 $this->languageSupport = (bool) $languageSupport;
1585 * Checks whether language support is enabled
1587 * @return $languageSupport Whether language support is enabled or disabled
1589 public final function isLanguageSupportEnabled () {
1590 return $this->languageSupport;
1594 * Enables or disables XML compacting
1596 * @param $xmlCompacting New XML compacting setting
1599 public final function enableXmlCompacting ($xmlCompacting = true) {
1600 $this->xmlCompacting = (bool) $xmlCompacting;
1604 * Checks whether XML compacting is enabled
1606 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1608 public final function isXmlCompactingEnabled () {
1609 return $this->xmlCompacting;
1613 * Removes all commentd, tabs and new-line characters to compact the content
1615 * @param $uncompactedContent The uncompacted content
1616 * @return $compactedContent The compacted content
1618 public function compactContent ($uncompactedContent) {
1619 // First, remove all tab/new-line/revert characters
1620 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1622 // Then regex all comments like <!-- //--> away
1623 preg_match_all($this->regExpComments, $compactedContent, $matches);
1625 // Do we have entries?
1626 if (isset($matches[0][0])) {
1628 foreach ($matches[0] as $match) {
1630 $compactedContent = str_replace($match, '', $compactedContent);
1634 // Set the content again
1635 $this->setRawTemplateData($compactedContent);
1637 // Return compacted content
1638 return $compactedContent;