3 namespace Org\Mxchange\CoreFramework\Template\Engine;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
10 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
11 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
12 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
13 use Org\Mxchange\CoreFramework\Response\Responseable;
16 use \InvalidArgumentException;
20 * A generic template engine
22 * @author Roland Haeder <webmaster@shipsimu.org>
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
25 * @license GNU GPL 3.0 or any newer version
26 * @link http://www.shipsimu.org
28 * This program is free software: you can redistribute it and/or modify
29 * it under the terms of the GNU General Public License as published by
30 * the Free Software Foundation, either version 3 of the License, or
31 * (at your option) any later version.
33 * This program is distributed in the hope that it will be useful,
34 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 * GNU General Public License for more details.
38 * You should have received a copy of the GNU General Public License
39 * along with this program. If not, see <http://www.gnu.org/licenses/>.
41 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
43 * The local path name where all templates and sub folders for special
44 * templates are stored. We will internally determine the language plus
45 * "html" for web templates or "emails" for email templates
47 private $templateBasePath = '';
52 private $templateType = 'html';
55 * The extension for web and email templates (not compiled templates)
57 private $templateExtension = '.tpl';
60 * The extension for code templates (not compiled templates)
62 private $codeExtension = '.ctp';
65 * Path relative to $templateBasePath and language code for compiled code-templates
67 private $compileOutputPath = 'templates/_compiled/';
70 * The path name for all templates
72 private $genericBasePath = 'templates/';
75 * The raw (maybe uncompiled) template
77 private $rawTemplateData = '';
80 * Template data with compiled-in variables
82 private $compiledData = '';
85 * The last loaded template's file instance (SplFileInfo)
87 private $lastTemplate = NULL;
90 * The variable stack for the templates
92 private $varStack = array();
95 * Loaded templates for recursive protection and detection
97 private $loadedTemplates = array();
100 * Compiled templates for recursive protection and detection
102 private $compiledTemplates = array();
105 * Loaded raw template data
107 private $loadedRawData = NULL;
110 * Raw templates which are linked in code templates
112 private $rawTemplates = NULL;
115 * A regular expression for variable=value pairs
117 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
120 * A regular expression for filtering out code tags
122 * E.g.: {?template:variable=value;var2=value2;[...]?}
124 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
127 * A regular expression to find template comments like <!-- Comment here //-->
129 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
134 private $helpers = array();
137 * Current variable group
139 private $currGroup = 'general';
142 * All template groups except "general"
144 private $variableGroups = array();
149 private $codeBegin = '<?php';
154 private $codeEnd = '?>';
157 * Language support is enabled by default
159 private $languageSupport = true;
162 * XML compacting is disabled by default
164 private $xmlCompacting = false;
166 // Exception codes for the template engine
167 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
168 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
169 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
170 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
173 * Protected constructor
175 * @param $className Name of the class
178 protected function __construct ($className) {
179 // Call parent constructor
180 parent::__construct($className);
182 // Init file I/O instance
183 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
186 $this->setFileIoInstance($ioInstance);
190 * Search for a variable in the stack
192 * @param $variableName The variable we are looking for
193 * @param $variableGroup Optional variable group to look in
194 * @return $index false means not found, >=0 means found on a specific index
196 private function getVariableIndex ($variableName, $variableGroup = NULL) {
197 // Replace all dashes to underscores to match variables with configuration entries
198 $variableName = trim(self::convertDashesToUnderscores($variableName));
200 // First everything is not found
203 // If the stack is NULL, use the current group
204 if (is_null($variableGroup)) {
206 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
207 $variableGroup = $this->currGroup;
210 // Is the group there?
211 if ($this->isVarStackSet($variableGroup)) {
213 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
214 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
215 // Is the entry found?
216 if ($currEntry['name'] == $variableName) {
218 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
225 // Return the current position
230 * Checks whether the given variable group is set
232 * @param $variableGroup Variable group to check
233 * @return $isSet Whether the given variable group is set
235 protected final function isVarStackSet ($variableGroup) {
237 $isSet = isset($this->varStack[$variableGroup]);
244 * Getter for given variable group
246 * @param $variableGroup Variable group to check
247 * @return $varStack Found variable group
249 public final function getVarStack ($variableGroup) {
250 return $this->varStack[$variableGroup];
254 * Setter for given variable group
256 * @param $variableGroup Variable group to check
257 * @param $varStack Variable stack to check
260 protected final function setVarStack ($variableGroup, array $varStack) {
261 $this->varStack[$variableGroup] = $varStack;
265 * Return a content of a variable or null if not found
267 * @param $variableName The variable we are looking for
268 * @param $variableGroup Optional variable group to look in
269 * @return $content Content of the variable or null if not found
271 protected function readVariable ($variableName, $variableGroup = NULL) {
272 // Replace all dashes to underscores to match variables with configuration entries
273 $variableName = trim(self::convertDashesToUnderscores($variableName));
275 // First everything is not found
278 // If the stack is NULL, use the current group
279 if (is_null($variableGroup)) {
281 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
282 $variableGroup = $this->currGroup;
285 // Get variable index
286 $found = $this->getVariableIndex($variableName, $variableGroup);
288 // Is the variable found?
289 if ($found !== false) {
291 $content = $this->getVariableValue($variableGroup, $found);
294 // Return the current position
295 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
300 * Add a variable to the stack
302 * @param $variableName Name of variable to add
303 * @param $value Value we want to store in the variable
306 private function addVariable ($variableName, $value) {
307 // Set general variable group
308 $this->setVariableGroup('general');
310 // Add it to the stack
311 $this->addGroupVariable($variableName, $value);
315 * Returns all variables of current group or empty array
317 * @return $result Whether array of found variables or empty array
319 private function readCurrentGroup () {
320 // Default is not found
323 // Is the group there?
324 if ($this->isVarStackSet($this->currGroup)) {
326 $result = $this->getVarStack($this->currGroup);
334 * Settter for variable group
336 * @param $groupName Name of variable group
337 * @param $add Whether add this group
340 public function setVariableGroup ($groupName, $add = true) {
342 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
343 $this->currGroup = $groupName;
345 // Skip group 'general'
346 if (($groupName != 'general') && ($add === true)) {
347 $this->variableGroups[$groupName] = 'OK';
353 * Adds a variable to current group
355 * @param $variableName Variable to set
356 * @param $value Value to store in variable
359 public function addGroupVariable ($variableName, $value) {
360 // Replace all dashes to underscores to match variables with configuration entries
361 $variableName = trim(self::convertDashesToUnderscores($variableName));
364 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
366 // Get current variables in group
367 $currVars = $this->readCurrentGroup();
369 // Append our variable
370 array_push($currVars, $this->generateVariableArray($variableName, $value));
372 // Add it to the stack
373 $this->setVarStack($this->currGroup, $currVars);
377 * Getter for variable value, throws a NoVariableException if the variable is not found
379 * @param $variableGroup Variable group to use
380 * @param $index Index in variable array
381 * @return $value Value to set
383 private function getVariableValue ($variableGroup, $index) {
385 return $this->varStack[$variableGroup][$index]['value'];
389 * Modify an entry on the stack
391 * @param $variableName The variable we are looking for
392 * @param $value The value we want to store in the variable
394 * @throws NoVariableException If the given variable is not found
396 private function modifyVariable ($variableName, $value) {
397 // Replace all dashes to underscores to match variables with configuration entries
398 $variableName = trim(self::convertDashesToUnderscores($variableName));
400 // Get index for variable
401 $index = $this->getVariableIndex($variableName);
403 // Is the variable set?
404 if ($index === false) {
405 // Unset variables cannot be modified
406 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
410 $this->setVariableValue($this->currGroup, $index, $value);
414 * Sets a variable value for given variable group and index
416 * @param $variableGroup Variable group to use
417 * @param $index Index in variable array
418 * @param $value Value to set
421 private function setVariableValue ($variableGroup, $index, $value) {
422 $this->varStack[$variableGroup][$index]['value'] = $value;
426 * Sets a variable within given group. This method does detect if the
427 * variable is already set. If so, the variable got modified, otherwise
430 * @param $variableGroup Variable group to use
431 * @param $variableName Variable to set
432 * @param $value Value to set
435 protected function setVariable ($variableGroup, $variableName, $value) {
436 // Replace all dashes to underscores to match variables with configuration entries
437 $variableName = trim(self::convertDashesToUnderscores($variableName));
439 // Get index for variable
440 $index = $this->getVariableIndex($variableName);
442 // Is the variable set?
443 if ($index === false) {
444 // Is the stack there?
445 if (!isset($this->varStack[$variableGroup])) {
446 // Then initialize it here
447 $this->varStack[$variableGroup] = array();
451 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
454 $this->setVariableValue($this->currGroup, $index, $value);
459 * "Generates" (better returns) an array for all variables for given
460 * variable/value pay.
462 * @param $variableName Variable to set
463 * @param $value Value to set
464 * @return $varData Variable data array
466 private function generateVariableArray ($variableName, $value) {
467 // Replace all dashes to underscores to match variables with configuration entries
468 $variableName = trim(self::convertDashesToUnderscores($variableName));
470 // Generate the temporary array
472 'name' => $variableName,
481 * Setter for template type. Only 'html', 'emails' and 'compiled' should
484 * @param $templateType The current template's type
487 protected final function setTemplateType ($templateType) {
488 $this->templateType = (string) $templateType;
492 * Getter for template type
494 * @return $templateType The current template's type
496 public final function getTemplateType () {
497 return $this->templateType;
501 * Setter for the last loaded template's file instance
503 * @param $template The last loaded template
506 private final function setLastTemplate (SplFileInfo $fileInstance) {
507 $this->lastTemplate = $fileInstance;
511 * Getter for the last loaded template's file instance
513 * @return $template The last loaded template
515 private final function getLastTemplate () {
516 return $this->lastTemplate;
520 * Setter for base path
522 * @param $templateBasePath The relative base path for all templates
525 protected final function setTemplateBasePath ($templateBasePath) {
527 $this->templateBasePath = (string) $templateBasePath;
531 * Getter for base path
533 * @return $templateBasePath The relative base path for all templates
535 public final function getTemplateBasePath () {
537 return $this->templateBasePath;
541 * Getter for generic base path
543 * @return $templateBasePath The relative base path for all templates
545 public final function getGenericBasePath () {
547 return $this->genericBasePath;
551 * Setter for template extension
553 * @param $templateExtension The file extension for all uncompiled
557 protected final function setRawTemplateExtension ($templateExtension) {
559 $this->templateExtension = (string) $templateExtension;
563 * Setter for code template extension
565 * @param $codeExtension The file extension for all uncompiled
569 protected final function setCodeTemplateExtension ($codeExtension) {
571 $this->codeExtension = (string) $codeExtension;
575 * Getter for template extension
577 * @return $templateExtension The file extension for all uncompiled
580 public final function getRawTemplateExtension () {
582 return $this->templateExtension;
586 * Getter for code-template extension
588 * @return $codeExtension The file extension for all code-
591 public final function getCodeTemplateExtension () {
593 return $this->codeExtension;
597 * Setter for path of compiled templates
599 * @param $compileOutputPath The local base path for all compiled
603 protected final function setCompileOutputPath ($compileOutputPath) {
605 $this->compileOutputPath = (string) $compileOutputPath;
609 * Unsets the given offset in the variable group
611 * @param $index Index to unset
612 * @param $variableGroup Variable group (default: currGroup)
615 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
616 // Is the variable group not set?
617 if (is_null($variableGroup)) {
618 // Then set it to current
619 $variableGroup = $this->currGroup;
622 // Is the entry there?
623 if (!isset($this->varStack[$variableGroup][$index])) {
624 // Abort here, we need fixing!
625 $this->debugInstance();
629 unset($this->varStack[$variableGroup][$index]);
633 * Private setter for raw template data
635 * @param $rawTemplateData The raw data from the template
638 protected final function setRawTemplateData ($rawTemplateData) {
639 // And store it in this class
640 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
641 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
642 $this->rawTemplateData = (string) $rawTemplateData;
646 * Getter for raw template data
648 * @return $rawTemplateData The raw data from the template
650 public final function getRawTemplateData () {
651 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
652 return $this->rawTemplateData;
656 * Private setter for compiled templates
660 private final function setCompiledData ($compiledData) {
661 // And store it in this class
662 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
663 $this->compiledData = (string) $compiledData;
667 * Getter for compiled templates, must be public for e.g. Mailer classes.
669 * @return $compiledData Compiled template data
671 public final function getCompiledData () {
672 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
673 return $this->compiledData;
677 * Private loader for all template types
679 * @param $templateName The template we shall load
680 * @param $extOther An other extension to use
682 * @throws FileNotFoundException If the template was not found
684 protected function loadTemplate ($templateName, $extOther = '') {
685 // Get extension for the template if empty
686 if (empty($extOther)) {
687 // None provided, so get the raw one
688 $ext = $this->getRawTemplateExtension();
691 $ext = (string) $extOther;
695 * Construct the FQFN for the template without language as language is
696 * now entirely done by php_intl. These old thing with language-based
697 * template paths comes from an older time.
699 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
700 $this->getTemplateBasePath(),
701 $this->getGenericBasePath(),
702 $this->getTemplateType(),
704 (string) $templateName,
710 // Load the raw template data
711 $this->loadRawTemplateData($fileInstance);
712 } catch (FileNotFoundException $e) {
713 // If we shall load a code-template we need to switch the file extension
714 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
715 // Switch over to the code-template extension and try it again
716 $ext = $this->getCodeTemplateExtension();
719 $this->loadTemplate($templateName, $ext);
722 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
729 * A private loader for raw template names
731 * @param $fileInstance An instance of a SplFileInfo class
734 private function loadRawTemplateData (SplFileInfo $fileInstance) {
735 // Some debug code to look on the file which is being loaded
736 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: fileInstance=' . $fileInstance);
738 // Load the raw template
739 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
741 // Store the template's contents into this class
742 $this->setRawTemplateData($rawTemplateData);
744 // Remember the template's file instance
745 $this->setLastTemplate($fileInstance);
749 * Try to assign an extracted template variable as a "content" or 'config'
752 * @param $variableName The variable's name (shall be content or config)
754 * @param $variableName The variable we want to assign
757 private function assignTemplateVariable ($variableName, $var) {
758 // Replace all dashes to underscores to match variables with configuration entries
759 $variableName = trim(self::convertDashesToUnderscores($variableName));
762 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
764 // Is it not a config variable?
765 if ($variableName != 'config') {
766 // Regular template variables
767 $this->assignVariable($variableName, '');
769 // Configuration variables
770 $this->assignConfigVariable($var);
775 * Extract variables from a given raw data stream
777 * @param $rawData The raw template data we shall analyze
780 private function extractVariablesFromRawData ($rawData) {
782 $rawData = (string) $rawData;
784 // Search for variables
785 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
788 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
790 // Did we find some variables?
791 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
792 // Initialize all missing variables
793 foreach ($variableMatches[3] as $key => $var) {
795 $variableName = $variableMatches[1][$key];
797 // Workarround: Do not assign empty variables
799 // Try to assign it, empty strings are being ignored
800 $this->assignTemplateVariable($variableName, $var);
807 * Main analysis of the loaded template
809 * @param $templateMatches Found template place-holders, see below
812 *---------------------------------
813 * Structure of $templateMatches:
814 *---------------------------------
815 * [0] => Array - An array with all full matches
816 * [1] => Array - An array with left part (before the ':') of a match
817 * [2] => Array - An array with right part of a match including ':'
818 * [3] => Array - An array with right part of a match excluding ':'
820 private function analyzeTemplate (array $templateMatches) {
821 // Backup raw template data
822 $backup = $this->getRawTemplateData();
824 // Initialize some arrays
825 if (is_null($this->loadedRawData)) {
827 $this->loadedRawData = array();
828 $this->rawTemplates = array();
831 // Load all requested templates
832 foreach ($templateMatches[1] as $template) {
833 // Load and compile only templates which we have not yet loaded
834 // RECURSIVE PROTECTION! BE CAREFUL HERE!
835 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
837 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
839 // Template not found, but maybe variable assigned?
840 if ($this->getVariableIndex($template) !== false) {
841 // Use that content here
842 $this->loadedRawData[$template] = $this->readVariable($template);
844 // Recursive protection:
845 array_push($this->loadedTemplates, $template);
847 // Then try to search for code-templates
849 // Load the code template and remember it's contents
850 $this->loadCodeTemplate($template);
851 $this->loadedRawData[$template] = $this->getRawTemplateData();
853 // Remember this template for recursion detection
854 // RECURSIVE PROTECTION!
855 array_push($this->loadedTemplates, $template);
856 } catch (FileNotFoundException $e) {
857 // Even this is not done... :/
858 array_push($this->rawTemplates, $template);
864 // Restore the raw template data
865 $this->setRawTemplateData($backup);
869 * Compile a given raw template code and remember it for later usage
871 * @param $code The raw template code
872 * @param $template The template's name
875 private function compileCode ($code, $template) {
876 // Is this template already compiled?
877 if (in_array($template, $this->compiledTemplates)) {
882 // Remember this template being compiled
883 array_push($this->compiledTemplates, $template);
885 // Compile the loaded code in five steps:
887 // 1. Backup current template data
888 $backup = $this->getRawTemplateData();
890 // 2. Set the current template's raw data as the new content
891 $this->setRawTemplateData($code);
893 // 3. Compile the template data
894 $this->compileTemplate();
896 // 4. Remember it's contents
897 $this->loadedRawData[$template] = $this->getRawTemplateData();
899 // 5. Restore the previous raw content from backup variable
900 $this->setRawTemplateData($backup);
904 * Insert all given and loaded templates by running through all loaded
905 * codes and searching for their place-holder in the main template
907 * @param $templateMatches See method analyzeTemplate()
910 private function insertAllTemplates (array $templateMatches) {
911 // Run through all loaded codes
912 foreach ($this->loadedRawData as $template => $code) {
914 // Search for the template
915 $foundIndex = array_search($template, $templateMatches[1]);
917 // Lookup the matching template replacement
918 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
920 // Get the current raw template
921 $rawData = $this->getRawTemplateData();
923 // Replace the space holder with the template code
924 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
926 // Set the new raw data
927 $this->setRawTemplateData($rawData);
933 * Load all extra raw templates
937 private function loadExtraRawTemplates () {
938 // Are there some raw templates we need to load?
939 if (count($this->rawTemplates) > 0) {
940 // Try to load all raw templates
941 foreach ($this->rawTemplates as $key => $template) {
944 $this->loadHtmlTemplate($template);
946 // Remember it's contents
947 $this->rawTemplates[$template] = $this->getRawTemplateData();
949 // Remove it from the loader list
950 unset($this->rawTemplates[$key]);
952 // Remember this template for recursion detection
953 // RECURSIVE PROTECTION!
954 array_push($this->loadedTemplates, $template);
955 } catch (FileNotFoundException $e) {
956 // This template was never found. We silently ignore it
957 unset($this->rawTemplates[$key]);
964 * Assign all found template variables
966 * @param $varMatches An array full of variable/value pairs.
968 * @todo Unfinished work or don't die here.
970 private function assignAllVariables (array $varMatches) {
972 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
974 // Search for all variables
975 foreach ($varMatches[1] as $key => $var) {
976 // Replace all dashes to underscores to match variables with configuration entries
977 $var = trim(self::convertDashesToUnderscores($var));
980 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
982 // Detect leading equals
983 if (substr($varMatches[2][$key], 0, 1) == '=') {
984 // Remove and cast it
985 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
988 // Do we have some quotes left and right side? Then it is free text
989 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
990 // Free string detected! Which we can assign directly
991 $this->assignVariable($var, $varMatches[3][$key]);
992 } elseif (!empty($varMatches[2][$key])) {
993 // @TODO Non-string found so we need some deeper analysis...
994 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
1000 * Compiles all loaded raw templates
1002 * @param $templateMatches See method analyzeTemplate() for details
1005 private function compileRawTemplateData (array $templateMatches) {
1007 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1009 // Are some code-templates found which we need to compile?
1010 if (count($this->loadedRawData) > 0) {
1011 // Then compile all!
1012 foreach ($this->loadedRawData as $template => $code) {
1014 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1016 // Is this template already compiled?
1017 if (in_array($template, $this->compiledTemplates)) {
1019 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1023 // Search for the template
1024 $foundIndex = array_search($template, $templateMatches[1]);
1026 // Lookup the matching variable data
1027 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1028 // Split it up with another reg. exp. into variable=value pairs
1029 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1030 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1032 // Assign all variables
1033 $this->assignAllVariables($varMatches);
1034 } // END - if (isset($templateMatches ...
1036 // Compile the loaded template
1037 $this->compileCode($code, $template);
1038 } // END - foreach ($this->loadedRawData ...
1040 // Insert all templates
1041 $this->insertAllTemplates($templateMatches);
1042 } // END - if (count($this->loadedRawData) ...
1046 * Inserts all raw templates into their respective variables
1050 private function insertRawTemplates () {
1051 // Load all templates
1052 foreach ($this->rawTemplates as $template => $content) {
1053 // Set the template as a variable with the content
1054 $this->assignVariable($template, $content);
1059 * Finalizes the compilation of all template variables
1063 private function finalizeVariableCompilation () {
1065 $content = $this->getRawTemplateData();
1066 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1068 // Do we have the stack?
1069 if (!$this->isVarStackSet('general')) {
1070 // Abort here silently
1071 // @TODO This silent abort should be logged, maybe.
1075 // Walk through all variables
1076 foreach ($this->getVarStack('general') as $currEntry) {
1077 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1078 // Replace all [$var] or {?$var?} with the content
1079 // @TODO Old behaviour, will become obsolete!
1080 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1082 // @TODO Yet another old way
1083 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1085 // The new behaviour
1086 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1089 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1091 // Set the content back
1092 $this->setRawTemplateData($content);
1096 * Load a specified HTML template into the engine
1098 * @param $template The web template we shall load which is located in
1102 public function loadHtmlTemplate ($template) {
1103 // Set template type
1104 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1106 // Load the special template
1107 $this->loadTemplate($template);
1111 * Assign (add) a given variable with a value
1113 * @param $variableName The variable we are looking for
1114 * @param $value The value we want to store in the variable
1116 * @throws InvalidArgumentException If the variable name is left empty
1118 public final function assignVariable ($variableName, $value) {
1119 // Replace all dashes to underscores to match variables with configuration entries
1120 $variableName = trim(self::convertDashesToUnderscores($variableName));
1122 // Empty variable found?
1123 if (empty($variableName)) {
1124 // Throw an exception
1125 throw new InvalidArgumentException('Parameter "variableName" is empty');
1128 // First search for the variable if it was already added
1129 $index = $this->getVariableIndex($variableName);
1132 if ($index === false) {
1133 // Add it to the stack
1134 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1135 $this->addVariable($variableName, $value);
1136 } elseif (!empty($value)) {
1137 // Modify the stack entry
1138 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1139 $this->modifyVariable($variableName, $value);
1144 * Removes a given variable
1146 * @param $variableName The variable we are looking for
1147 * @param $variableGroup Name of variable group (default: 'general')
1150 public final function removeVariable ($variableName, $variableGroup = 'general') {
1151 // First search for the variable if it was already added
1152 $index = $this->getVariableIndex($variableName, $variableGroup);
1155 if ($index !== false) {
1156 // Remove this variable
1157 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1158 $this->unsetVariableStackOffset($index, $variableGroup);
1163 * Assigns the last loaded raw template content with a given variable
1165 * @param $templateName Name of the template we want to assign
1166 * @param $variableName Name of the variable we want to assign
1169 public function assignTemplateWithVariable ($templateName, $variableName) {
1170 // Get the content from last loaded raw template
1171 $content = $this->getRawTemplateData();
1173 // Assign the variable
1174 $this->assignVariable($variableName, $content);
1176 // Purge raw content
1177 $this->setRawTemplateData('');
1181 * Assign a given congfiguration variable with a value
1183 * @param $variableName The configuration variable we want to assign
1186 public function assignConfigVariable ($variableName) {
1187 // Replace all dashes to underscores to match variables with configuration entries
1188 $variableName = trim(self::convertDashesToUnderscores($variableName));
1190 // Sweet and simple...
1191 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1192 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1196 * Assigns a lot variables into the stack of currently loaded template.
1197 * This method should only be used in very rare circumstances, e.g. when
1198 * you have to copy a whole set of variables into the template engine.
1199 * Before you use this method, please make sure you have considered all
1200 * other possiblities.
1202 * @param $variables An array with variables to be assigned
1205 public function assignMultipleVariables (array $variables) {
1207 foreach ($variables as $name => $value) {
1208 // Set variable with name for 'config' group
1209 $this->assignVariable($name, $value);
1214 * Assigns all the application data with template variables
1218 public function assignApplicationData () {
1219 // Get application instance
1220 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1222 // Get long name and assign it
1223 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1225 // Get short name and assign it
1226 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1228 // Get version number and assign it
1229 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1231 // Assign extra application-depending data
1232 $applicationInstance->assignExtraTemplateData($this);
1236 * Load a specified code template into the engine
1238 * @param $template The code template we shall load which is
1239 * located in 'code' by default
1242 public function loadCodeTemplate ($template) {
1243 // Set template type
1244 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1246 // Load the special template
1247 $this->loadTemplate($template);
1251 * Load a specified email template into the engine
1253 * @param $template The email template we shall load which is
1254 * located in 'emails' by default
1257 public function loadEmailTemplate ($template) {
1258 // Set template type
1259 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1261 // Load the special template
1262 $this->loadTemplate($template);
1266 * Compiles configuration place-holders in all variables. This 'walks'
1267 * through the variable group 'general'. It interprets all values from that
1268 * variables as configuration entries after compiling them.
1272 public final function compileConfigInVariables () {
1273 // Do we have the stack?
1274 if (!$this->isVarStackSet('general')) {
1275 // Abort here silently
1276 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1280 // Iterate through all general variables
1281 foreach ($this->getVarStack('general') as $index => $currVariable) {
1282 // Compile the value
1283 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1286 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1288 // Remove it from stack
1289 $this->removeVariable($currVariable['name'], 'general');
1290 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1292 // Is it a configuration key?
1293 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1294 // The value itself is a configuration entry
1295 $this->assignConfigVariable($value);
1297 // Re-assign the value directly
1298 $this->assignVariable($currVariable['name'], $value);
1304 * Compile all variables by inserting their respective values
1307 * @todo Make this code some nicer...
1309 public final function compileVariables () {
1310 // Initialize the $content array
1311 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1314 // Iterate through all general variables
1315 foreach ($this->getVarStack('general') as $currVariable) {
1316 // Transfer it's name/value combination to the $content array
1317 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1318 $dummy[$currVariable['name']] = $currVariable['value'];
1321 // Set the new variable (don't remove the second dollar!)
1322 $$validVar = $dummy;
1324 // Remove some variables
1326 unset($currVariable);
1328 // Run the compilation three times to get content from helper classes in
1331 // Finalize the compilation of template variables
1332 $this->finalizeVariableCompilation();
1334 // Prepare the eval() command for comiling the template
1335 $eval = sprintf('$result = "%s";',
1336 addslashes($this->getRawTemplateData())
1339 // This loop does remove the backslashes (\) in PHP parameters
1340 while (strpos($eval, $this->codeBegin) !== false) {
1341 // Get left part before "<?"
1342 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1344 // Get all from right of "<?"
1345 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1347 // Cut middle part out and remove escapes
1348 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1349 $evalMiddle = stripslashes($evalMiddle);
1351 // Remove the middle part from right one
1352 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1354 // And put all together
1355 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1358 // Prepare PHP code for eval() command
1359 $eval = str_replace(
1368 // Run the constructed command. This will "compile" all variables in
1371 // Goes something wrong?
1372 if ((!isset($result)) || (empty($result))) {
1373 // Output eval command
1374 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1376 // Output backtrace here
1377 $this->debugBackTrace();
1380 // Set raw template data
1381 $this->setRawTemplateData($result);
1385 // Final variable assignment
1386 $this->finalizeVariableCompilation();
1388 // Set the new content
1389 $this->setCompiledData($this->getRawTemplateData());
1393 * Compile all required templates into the current loaded one
1396 * @throws UnexpectedTemplateTypeException If the template type is
1398 * @throws InvalidArrayCountException If an unexpected array
1399 * count has been found
1401 public function compileTemplate () {
1402 // Get code type to make things shorter
1403 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1405 // We will only work with template type "code" from configuration
1406 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1408 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1411 // Get the raw data.
1412 $rawData = $this->getRawTemplateData();
1414 // Remove double spaces and trim leading/trailing spaces
1415 $rawData = trim(str_replace(' ', ' ', $rawData));
1417 // Search for raw variables
1418 $this->extractVariablesFromRawData($rawData);
1420 // Search for code-tags which are {? ?}
1421 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1424 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1426 // Analyze the matches array
1427 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1428 // Entries are found:
1430 // The main analysis
1431 $this->analyzeTemplate($templateMatches);
1433 // Compile raw template data
1434 $this->compileRawTemplateData($templateMatches);
1436 // Are there some raw templates left for loading?
1437 $this->loadExtraRawTemplates();
1439 // Are some raw templates found and loaded?
1440 if (count($this->rawTemplates) > 0) {
1441 // Insert all raw templates
1442 $this->insertRawTemplates();
1444 // Remove the raw template content as well
1445 $this->setRawTemplateData('');
1447 } // END - if($templateMatches ...
1451 * Loads a given view helper (by name)
1453 * @param $helperName The helper's name
1456 protected function loadViewHelper ($helperName) {
1457 // Is this view helper loaded?
1458 if (!isset($this->helpers[$helperName])) {
1459 // Create a class name
1460 $className = self::convertToClassName($helperName) . 'ViewHelper';
1462 // Generate new instance
1463 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1466 // Return the requested instance
1467 return $this->helpers[$helperName];
1471 * Transfers the content of this template engine to a given response instance
1473 * @param $responseInstance An instance of a Responseable class
1476 public function transferToResponse (Responseable $responseInstance) {
1477 // Get the content and set it in response class
1478 $responseInstance->writeToBody($this->getCompiledData());
1482 * "Compiles" a variable by replacing {?var?} with it's content
1484 * @param $rawCode Raw code to compile
1485 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1486 * @return $rawCode Compile code with inserted variable value
1488 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1489 // Find the variables
1490 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1491 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1493 // Compile all variables
1494 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1495 foreach ($varMatches[0] as $match) {
1496 // Add variable tags around it
1497 $varCode = '{?' . $match . '?}';
1500 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1502 // Is the variable found in code? (safes some calls)
1503 if (strpos($rawCode, $varCode) !== false) {
1505 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1507 // Use $match as new value or $value from read variable?
1508 if ($setMatchAsCode === true) {
1510 $rawCode = str_replace($varCode, $match, $rawCode);
1512 // Read the variable
1513 $value = $this->readVariable($match);
1516 $rawCode = str_replace($varCode, $value, $rawCode);
1521 // Return the compiled data
1522 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1527 * Getter for variable group array
1529 * @return $variableGroups All variable groups
1531 public final function getVariableGroups () {
1532 return $this->variableGroups;
1536 * Renames a variable in code and in stack
1538 * @param $oldName Old name of variable
1539 * @param $newName New name of variable
1542 public function renameVariable ($oldName, $newName) {
1543 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1544 // Get raw template code
1545 $rawData = $this->getRawTemplateData();
1548 $rawData = str_replace($oldName, $newName, $rawData);
1550 // Set the code back
1551 $this->setRawTemplateData($rawData);
1555 * Renders the given XML content
1557 * @param $content Valid XML content or if not set the current loaded raw content
1559 * @throws XmlParserException If an XML error was found
1561 public function renderXmlContent ($content = NULL) {
1562 // Is the content set?
1563 if (is_null($content)) {
1564 // Get current content
1565 $content = $this->getRawTemplateData();
1568 // Get a XmlParser instance
1569 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1571 // Check if XML compacting is enabled
1572 if ($this->isXmlCompactingEnabled()) {
1573 // Yes, so get a decorator class for transparent compacting
1574 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1577 // Parse the XML document
1578 $parserInstance->parseXmlContent($content);
1582 * Enables or disables language support
1584 * @param $languageSupport New language support setting
1587 public final function enableLanguageSupport ($languageSupport = true) {
1588 $this->languageSupport = (bool) $languageSupport;
1592 * Checks whether language support is enabled
1594 * @return $languageSupport Whether language support is enabled or disabled
1596 public final function isLanguageSupportEnabled () {
1597 return $this->languageSupport;
1601 * Enables or disables XML compacting
1603 * @param $xmlCompacting New XML compacting setting
1606 public final function enableXmlCompacting ($xmlCompacting = true) {
1607 $this->xmlCompacting = (bool) $xmlCompacting;
1611 * Checks whether XML compacting is enabled
1613 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1615 public final function isXmlCompactingEnabled () {
1616 return $this->xmlCompacting;
1620 * Removes all commentd, tabs and new-line characters to compact the content
1622 * @param $uncompactedContent The uncompacted content
1623 * @return $compactedContent The compacted content
1625 public function compactContent ($uncompactedContent) {
1626 // First, remove all tab/new-line/revert characters
1627 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1629 // Then regex all comments like <!-- //--> away
1630 preg_match_all($this->regExpComments, $compactedContent, $matches);
1632 // Do we have entries?
1633 if (isset($matches[0][0])) {
1635 foreach ($matches[0] as $match) {
1637 $compactedContent = str_replace($match, '', $compactedContent);
1641 // Set the content again
1642 $this->setRawTemplateData($compactedContent);
1644 // Return compacted content
1645 return $compactedContent;