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\Handler\Stream\IoHandler;
10 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
11 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
12 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
13 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
14 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
15 use Org\Mxchange\CoreFramework\Response\Responseable;
16 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
19 use \InvalidArgumentException;
23 * A generic template engine
25 * @author Roland Haeder <webmaster@shipsimu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
46 * The file I/O instance for the template loader
48 private $fileIoInstance = NULL;
51 * The local path name where all templates and sub folders for special
52 * templates are stored. We will internally determine the language plus
53 * "html" for web templates or "emails" for email templates
55 private $templateBasePath = '';
60 private $templateType = 'html';
63 * The extension for web and email templates (not compiled templates)
65 private $templateExtension = '.tpl';
68 * The extension for code templates (not compiled templates)
70 private $codeExtension = '.ctp';
73 * Path relative to $templateBasePath and language code for compiled code-templates
75 private $compileOutputPath = 'templates/_compiled/';
78 * The path name for all templates
80 private $genericBasePath = 'templates/';
83 * The raw (maybe uncompiled) template
85 private $rawTemplateData = '';
88 * Template data with compiled-in variables
90 private $compiledData = '';
93 * The last loaded template's file instance (SplFileInfo)
95 private $lastTemplate = NULL;
98 * The variable stack for the templates
100 private $varStack = array();
103 * Loaded templates for recursive protection and detection
105 private $loadedTemplates = array();
108 * Compiled templates for recursive protection and detection
110 private $compiledTemplates = array();
113 * Loaded raw template data
115 private $loadedRawData = NULL;
118 * Raw templates which are linked in code templates
120 private $rawTemplates = NULL;
123 * A regular expression for variable=value pairs
125 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
128 * A regular expression for filtering out code tags
130 * E.g.: {?template:variable=value;var2=value2;[...]?}
132 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
135 * A regular expression to find template comments like <!-- Comment here //-->
137 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
142 private $helpers = array();
145 * Current variable group
147 private $currGroup = 'general';
150 * All template groups except "general"
152 private $variableGroups = array();
157 private $codeBegin = '<?php';
162 private $codeEnd = '?>';
165 * Language support is enabled by default
167 private $languageSupport = true;
170 * XML compacting is disabled by default
172 private $xmlCompacting = false;
174 // Exception codes for the template engine
175 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
176 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
177 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
178 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
181 * Protected constructor
183 * @param $className Name of the class
186 protected function __construct ($className) {
187 // Call parent constructor
188 parent::__construct($className);
190 // Init file I/O instance
191 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
194 $this->setFileIoInstance($ioInstance);
198 * Search for a variable in the stack
200 * @param $variableName The variable we are looking for
201 * @param $variableGroup Optional variable group to look in
202 * @return $index false means not found, >=0 means found on a specific index
204 private function getVariableIndex (string $variableName, string $variableGroup = NULL) {
205 // Replace all dashes to underscores to match variables with configuration entries
206 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
208 // First everything is not found
211 // If the stack is NULL, use the current group
212 if (is_null($variableGroup)) {
214 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
215 $variableGroup = $this->currGroup;
218 // Is the group there?
219 if ($this->isVarStackSet($variableGroup)) {
221 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
222 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
223 // Is the entry found?
224 if ($currEntry['name'] == $variableName) {
226 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
233 // Return the current position
238 * Checks whether the given variable group is set
240 * @param $variableGroup Variable group to check
241 * @return $isSet Whether the given variable group is set
243 protected final function isVarStackSet (string $variableGroup) {
245 $isSet = isset($this->varStack[$variableGroup]);
252 * Getter for given variable group
254 * @param $variableGroup Variable group to check
255 * @return $varStack Found variable group
257 public final function getVarStack (string $variableGroup) {
258 return $this->varStack[$variableGroup];
262 * Setter for given variable group
264 * @param $variableGroup Variable group to check
265 * @param $varStack Variable stack to check
268 protected final function setVarStack (string $variableGroup, array $varStack) {
269 $this->varStack[$variableGroup] = $varStack;
273 * Return a content of a variable or null if not found
275 * @param $variableName The variable we are looking for
276 * @param $variableGroup Optional variable group to look in
277 * @return $content Content of the variable or null if not found
279 protected function readVariable (string $variableName, string $variableGroup = NULL) {
280 // Replace all dashes to underscores to match variables with configuration entries
281 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
283 // First everything is not found
286 // If the stack is NULL, use the current group
287 if (is_null($variableGroup)) {
289 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
290 $variableGroup = $this->currGroup;
293 // Get variable index
294 $found = $this->getVariableIndex($variableName, $variableGroup);
296 // Is the variable found?
297 if ($found !== false) {
299 $content = $this->getVariableValue($variableGroup, $found);
302 // Return the current position
303 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
308 * Add a variable to the stack
310 * @param $variableName Name of variable to add
311 * @param $value Value we want to store in the variable
314 private function addVariable (string $variableName, $value) {
315 // Set general variable group
316 $this->setVariableGroup('general');
318 // Add it to the stack
319 $this->addGroupVariable($variableName, $value);
323 * Returns all variables of current group or empty array
325 * @return $result Whether array of found variables or empty array
327 private function readCurrentGroup () {
328 // Default is not found
331 // Is the group there?
332 if ($this->isVarStackSet($this->currGroup)) {
334 $result = $this->getVarStack($this->currGroup);
342 * Settter for variable group
344 * @param $groupName Name of variable group
345 * @param $add Whether add this group
348 public function setVariableGroup (string $groupName, bool $add = true) {
350 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
351 $this->currGroup = $groupName;
353 // Skip group 'general'
354 if (($groupName != 'general') && ($add === true)) {
355 $this->variableGroups[$groupName] = 'OK';
361 * Adds a variable to current group
363 * @param $variableName Variable to set
364 * @param $value Value to store in variable
367 public function addGroupVariable (string $variableName, $value) {
368 // Replace all dashes to underscores to match variables with configuration entries
369 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
372 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
374 // Get current variables in group
375 $currVars = $this->readCurrentGroup();
377 // Append our variable
378 array_push($currVars, $this->generateVariableArray($variableName, $value));
380 // Add it to the stack
381 $this->setVarStack($this->currGroup, $currVars);
385 * Getter for variable value, throws a NoVariableException if the variable is not found
387 * @param $variableGroup Variable group to use
388 * @param $index Index in variable array
389 * @return $value Value to set
391 private function getVariableValue (string $variableGroup, int $index) {
393 return $this->varStack[$variableGroup][$index]['value'];
397 * Modify an entry on the stack
399 * @param $variableName The variable we are looking for
400 * @param $value The value we want to store in the variable
402 * @throws NoVariableException If the given variable is not found
404 private function modifyVariable (string $variableName, $value) {
405 // Replace all dashes to underscores to match variables with configuration entries
406 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
408 // Get index for variable
409 $index = $this->getVariableIndex($variableName);
411 // Is the variable set?
412 if ($index === false) {
413 // Unset variables cannot be modified
414 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
418 $this->setVariableValue($this->currGroup, $index, $value);
422 * Sets a variable value for given variable group and index
424 * @param $variableGroup Variable group to use
425 * @param $index Index in variable array
426 * @param $value Value to set
429 private function setVariableValue (string $variableGroup, int $index, $value) {
430 $this->varStack[$variableGroup][$index]['value'] = $value;
434 * Sets a variable within given group. This method does detect if the
435 * variable is already set. If so, the variable got modified, otherwise
438 * @param $variableGroup Variable group to use
439 * @param $variableName Variable to set
440 * @param $value Value to set
443 protected function setVariable (string $variableGroup, string $variableName, $value) {
444 // Replace all dashes to underscores to match variables with configuration entries
445 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
447 // Get index for variable
448 $index = $this->getVariableIndex($variableName);
450 // Is the variable set?
451 if ($index === false) {
452 // Is the stack there?
453 if (!isset($this->varStack[$variableGroup])) {
454 // Then initialize it here
455 $this->varStack[$variableGroup] = array();
459 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
462 $this->setVariableValue($this->currGroup, $index, $value);
467 * "Generates" (better returns) an array for all variables for given
468 * variable/value pay.
470 * @param $variableName Variable to set
471 * @param $value Value to set
472 * @return $varData Variable data array
474 private function generateVariableArray (string $variableName, $value) {
475 // Replace all dashes to underscores to match variables with configuration entries
476 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
478 // Generate the temporary array
480 'name' => $variableName,
489 * Setter for template type. Only 'html', 'emails' and 'compiled' should
492 * @param $templateType The current template's type
495 protected final function setTemplateType (string $templateType) {
496 $this->templateType = $templateType;
500 * Getter for template type
502 * @return $templateType The current template's type
504 public final function getTemplateType () {
505 return $this->templateType;
509 * Setter for the last loaded template's file instance
511 * @param $template The last loaded template
514 private final function setLastTemplate (SplFileInfo $fileInstance) {
515 $this->lastTemplate = $fileInstance;
519 * Getter for the last loaded template's file instance
521 * @return $template The last loaded template
523 private final function getLastTemplate () {
524 return $this->lastTemplate;
528 * Setter for base path
530 * @param $templateBasePath The relative base path for all templates
533 protected final function setTemplateBasePath (string $templateBasePath) {
535 $this->templateBasePath = $templateBasePath;
539 * Getter for base path
541 * @return $templateBasePath The relative base path for all templates
543 public final function getTemplateBasePath () {
545 return $this->templateBasePath;
549 * Getter for generic base path
551 * @return $templateBasePath The relative base path for all templates
553 public final function getGenericBasePath () {
555 return $this->genericBasePath;
559 * Setter for template extension
561 * @param $templateExtension The file extension for all uncompiled
565 protected final function setRawTemplateExtension (string $templateExtension) {
567 $this->templateExtension = $templateExtension;
571 * Setter for code template extension
573 * @param $codeExtension The file extension for all uncompiled
577 protected final function setCodeTemplateExtension (string $codeExtension) {
579 $this->codeExtension = $codeExtension;
583 * Getter for template extension
585 * @return $templateExtension The file extension for all uncompiled
588 public final function getRawTemplateExtension () {
590 return $this->templateExtension;
594 * Getter for code-template extension
596 * @return $codeExtension The file extension for all code-
599 public final function getCodeTemplateExtension () {
601 return $this->codeExtension;
605 * Setter for path of compiled templates
607 * @param $compileOutputPath The local base path for all compiled
611 protected final function setCompileOutputPath (string $compileOutputPath) {
613 $this->compileOutputPath = $compileOutputPath;
617 * Unsets the given offset in the variable group
619 * @param $index Index to unset
620 * @param $variableGroup Variable group (default: currGroup)
623 protected final function unsetVariableStackOffset (int $index, string $variableGroup = NULL) {
624 // Is the variable group not set?
625 if (is_null($variableGroup)) {
626 // Then set it to current
627 $variableGroup = $this->currGroup;
630 // Is the entry there?
631 if (!isset($this->varStack[$variableGroup][$index])) {
632 // Abort here, we need fixing!
633 $this->debugInstance();
637 unset($this->varStack[$variableGroup][$index]);
641 * Private setter for raw template data
643 * @param $rawTemplateData The raw data from the template
646 protected final function setRawTemplateData (string $rawTemplateData) {
647 // And store it in this class
648 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
649 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
650 $this->rawTemplateData = $rawTemplateData;
654 * Getter for raw template data
656 * @return $rawTemplateData The raw data from the template
658 public final function getRawTemplateData () {
659 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->rawTemplateData) . ' Bytes read.');
660 return $this->rawTemplateData;
664 * Private setter for compiled templates
666 * @param $compiledData Compiled template data
669 private final function setCompiledData (string $compiledData) {
670 // And store it in this class
671 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($compiledData) . ' Bytes set.');
672 $this->compiledData = $compiledData;
676 * Getter for compiled templates, must be public for e.g. Mailer classes.
678 * @return $compiledData Compiled template data
680 public final function getCompiledData () {
681 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->compiledData) . ' Bytes read.');
682 return $this->compiledData;
686 * Private loader for all template types
688 * @param $templateName The template we shall load
689 * @param $extOther An other extension to use
691 * @throws FileNotFoundException If the template was not found
693 protected function loadTemplate (string $templateName, string $extOther = '') {
694 // Get extension for the template if empty
695 if (empty($extOther)) {
696 // None provided, so get the raw one
697 $ext = $this->getRawTemplateExtension();
704 * Construct the FQFN for the template without language as language is
705 * now entirely done by php_intl. These old thing with language-based
706 * template paths comes from an older time.
708 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
709 $this->getTemplateBasePath(),
710 $this->getGenericBasePath(),
711 $this->getTemplateType(),
713 (string) $templateName,
719 // Load the raw template data
720 $this->loadRawTemplateData($fileInstance);
721 } catch (FileNotFoundException $e) {
722 // If we shall load a code-template we need to switch the file extension
723 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
724 // Switch over to the code-template extension and try it again
725 $ext = $this->getCodeTemplateExtension();
728 $this->loadTemplate($templateName, $ext);
731 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
738 * A private loader for raw template names
740 * @param $fileInstance An instance of a SplFileInfo class
743 private function loadRawTemplateData (SplFileInfo $fileInstance) {
744 // Load the raw template
745 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: fileInstance=' . $fileInstance);
746 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
748 // Store the template's contents into this class
749 $this->setRawTemplateData($rawTemplateData);
751 // Remember the template's file instance
752 $this->setLastTemplate($fileInstance);
756 * Try to assign an extracted template variable as a "content" or 'config'
759 * @param $variableName The variable's name (shall be content or config)
761 * @param $variableName The variable we want to assign
764 private function assignTemplateVariable (string $variableName, $var) {
765 // Replace all dashes to underscores to match variables with configuration entries
766 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',var=' . $var);
767 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
769 // Is it not a config variable?
770 if ($variableName != 'config') {
771 // Regular template variables
772 $this->assignVariable($variableName, '');
774 // Configuration variables
775 $this->assignConfigVariable($var);
780 * Extract variables from a given raw data stream
782 * @param $rawData The raw template data we shall analyze
785 private function extractVariablesFromRawData (string $rawData) {
786 // Search for variables
787 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
788 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
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: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 (string $code, string $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: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(StringUtils::convertDashesToUnderscores($var));
980 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: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: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: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: 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:varMatches=' . print_r($varMatches, true));
1032 // Assign all variables
1033 $this->assignAllVariables($varMatches);
1036 // Compile the loaded template
1037 $this->compileCode($code, $template);
1040 // Insert all templates
1041 $this->insertAllTemplates($templateMatches);
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: 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: 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 // Set the content back
1090 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content after=' . strlen($content) . ' (' . md5($content) . ')');
1091 $this->setRawTemplateData($content);
1095 * Load a specified HTML template into the engine
1097 * @param $template The web template we shall load which is located in
1101 public function loadHtmlTemplate (string $template) {
1102 // Set template type
1103 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1105 // Load the special template
1106 $this->loadTemplate($template);
1110 * Assign (add) a given variable with a value
1112 * @param $variableName The variable we are looking for
1113 * @param $value The value we want to store in the variable
1115 * @throws InvalidArgumentException If the variable name is left empty
1117 public final function assignVariable (string $variableName, $value) {
1118 // Validate parameter
1119 if (empty($variableName)) {
1120 // Throw an exception
1121 throw new InvalidArgumentException('Parameter "variableName" is empty');
1124 // Replace all dashes to underscores to match variables with configuration entries
1125 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1127 // First search for the variable if it was already added
1128 $index = $this->getVariableIndex($variableName);
1131 if ($index === false) {
1132 // Add it to the stack
1133 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1134 $this->addVariable($variableName, $value);
1135 } elseif (!empty($value)) {
1136 // Modify the stack entry
1137 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1138 $this->modifyVariable($variableName, $value);
1143 * Removes a given variable
1145 * @param $variableName The variable we are looking for
1146 * @param $variableGroup Name of variable group (default: 'general')
1149 public final function removeVariable (string $variableName, string $variableGroup = 'general') {
1150 // First search for the variable if it was already added
1151 $index = $this->getVariableIndex($variableName, $variableGroup);
1154 if ($index !== false) {
1155 // Remove this variable
1156 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1157 $this->unsetVariableStackOffset($index, $variableGroup);
1162 * Assigns the last loaded raw template content with a given variable
1164 * @param $templateName Name of the template we want to assign
1165 * @param $variableName Name of the variable we want to assign
1168 public function assignTemplateWithVariable (string $templateName, string $variableName) {
1169 // Get the content from last loaded raw template
1170 $content = $this->getRawTemplateData();
1172 // Assign the variable
1173 $this->assignVariable($variableName, $content);
1175 // Purge raw content
1176 $this->setRawTemplateData('');
1180 * Assign a given congfiguration variable with a value
1182 * @param $variableName The configuration variable we want to assign
1185 public function assignConfigVariable (string $variableName) {
1186 // Replace all dashes to underscores to match variables with configuration entries
1187 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1189 // Sweet and simple...
1190 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1191 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1195 * Assigns a lot variables into the stack of currently loaded template.
1196 * This method should only be used in very rare circumstances, e.g. when
1197 * you have to copy a whole set of variables into the template engine.
1198 * Before you use this method, please make sure you have considered all
1199 * other possiblities.
1201 * @param $variables An array with variables to be assigned
1204 public function assignMultipleVariables (array $variables) {
1206 foreach ($variables as $name => $value) {
1207 // Set variable with name for 'config' group
1208 $this->assignVariable($name, $value);
1213 * Assigns all the application data with template variables
1217 public function assignApplicationData () {
1218 // Get application instance
1219 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1221 // Get long name and assign it
1222 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1224 // Get short name and assign it
1225 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1227 // Get version number and assign it
1228 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1230 // Assign extra application-depending data
1231 $applicationInstance->assignExtraTemplateData($this);
1235 * Load a specified code template into the engine
1237 * @param $template The code template we shall load which is
1238 * located in 'code' by default
1241 public function loadCodeTemplate (string $template) {
1242 // Set template type
1243 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1245 // Load the special template
1246 $this->loadTemplate($template);
1250 * Load a specified email template into the engine
1252 * @param $template The email template we shall load which is
1253 * located in 'emails' by default
1256 public function loadEmailTemplate (string $template) {
1257 // Set template type
1258 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1260 // Load the special template
1261 $this->loadTemplate($template);
1265 * Compiles configuration place-holders in all variables. This 'walks'
1266 * through the variable group 'general'. It interprets all values from that
1267 * variables as configuration entries after compiling them.
1271 public final function compileConfigInVariables () {
1272 // Do we have the stack?
1273 if (!$this->isVarStackSet('general')) {
1274 // Abort here silently
1275 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Aborted, variable stack general not found!');
1279 // Iterate through all general variables
1280 foreach ($this->getVarStack('general') as $index => $currVariable) {
1281 // Compile the value
1282 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1285 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currVariable['name'] . ',value=' . $value);
1287 // Remove it from stack
1288 $this->removeVariable($currVariable['name'], 'general');
1289 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1291 // Is it a configuration key?
1292 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1293 // The value itself is a configuration entry
1294 $this->assignConfigVariable($value);
1296 // Re-assign the value directly
1297 $this->assignVariable($currVariable['name'], $value);
1303 * Compile all variables by inserting their respective values
1306 * @todo Make this code some nicer...
1308 public final function compileVariables () {
1309 // Initialize the $content array
1310 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1313 // Iterate through all general variables
1314 foreach ($this->getVarStack('general') as $currVariable) {
1315 // Transfer it's name/value combination to the $content array
1316 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1317 $dummy[$currVariable['name']] = $currVariable['value'];
1320 // Set the new variable (don't remove the second dollar!)
1321 $$validVar = $dummy;
1323 // Remove some variables
1325 unset($currVariable);
1327 // Run the compilation three times to get content from helper classes in
1330 // Finalize the compilation of template variables
1331 $this->finalizeVariableCompilation();
1333 // Prepare the eval() command for comiling the template
1334 $eval = sprintf('$result = "%s";',
1335 addslashes($this->getRawTemplateData())
1338 // This loop does remove the backslashes (\) in PHP parameters
1339 while (strpos($eval, $this->codeBegin) !== false) {
1340 // Get left part before "<?"
1341 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1343 // Get all from right of "<?"
1344 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1346 // Cut middle part out and remove escapes
1347 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1348 $evalMiddle = stripslashes($evalMiddle);
1350 // Remove the middle part from right one
1351 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1353 // And put all together
1354 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1357 // Prepare PHP code for eval() command
1358 $eval = str_replace(
1367 // Run the constructed command. This will "compile" all variables in
1370 // Goes something wrong?
1371 if ((!isset($result)) || (empty($result))) {
1372 // Output eval command
1373 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1375 // Output backtrace here
1376 $this->debugBackTrace();
1379 // Set raw template data
1380 $this->setRawTemplateData($result);
1384 // Final variable assignment
1385 $this->finalizeVariableCompilation();
1387 // Set the new content
1388 $this->setCompiledData($this->getRawTemplateData());
1392 * Compile all required templates into the current loaded one
1395 * @throws UnexpectedTemplateTypeException If the template type is
1397 * @throws InvalidArrayCountException If an unexpected array
1398 * count has been found
1400 public function compileTemplate () {
1401 // Get code type to make things shorter
1402 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1404 // We will only work with template type "code" from configuration
1405 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1407 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1410 // Get the raw data.
1411 $rawData = $this->getRawTemplateData();
1413 // Remove double spaces and trim leading/trailing spaces
1414 $rawData = trim(str_replace(' ', ' ', $rawData));
1416 // Search for raw variables
1417 $this->extractVariablesFromRawData($rawData);
1419 // Search for code-tags which are {? ?}
1420 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1423 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:templateMatches=' . print_r($templateMatches , true));
1425 // Analyze the matches array
1426 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1427 // Entries are found:
1429 // The main analysis
1430 $this->analyzeTemplate($templateMatches);
1432 // Compile raw template data
1433 $this->compileRawTemplateData($templateMatches);
1435 // Are there some raw templates left for loading?
1436 $this->loadExtraRawTemplates();
1438 // Are some raw templates found and loaded?
1439 if (count($this->rawTemplates) > 0) {
1440 // Insert all raw templates
1441 $this->insertRawTemplates();
1443 // Remove the raw template content as well
1444 $this->setRawTemplateData('');
1450 * Loads a given view helper (by name)
1452 * @param $helperName The helper's name
1455 protected function loadViewHelper (string $helperName) {
1456 // Is this view helper loaded?
1457 if (!isset($this->helpers[$helperName])) {
1458 // Create a class name
1459 $className = self::convertToClassName($helperName) . 'ViewHelper';
1461 // Generate new instance
1462 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1465 // Return the requested instance
1466 return $this->helpers[$helperName];
1470 * Transfers the content of this template engine to a given response instance
1472 * @param $responseInstance An instance of a Responseable class
1475 public function transferToResponse (Responseable $responseInstance) {
1476 // Get the content and set it in response class
1477 $responseInstance->writeToBody($this->getCompiledData());
1481 * "Compiles" a variable by replacing {?var?} with it's content
1483 * @param $rawCode Raw code to compile
1484 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1485 * @return $rawCode Compile code with inserted variable value
1487 public function compileRawCode (string $rawCode, bool $setMatchAsCode = false) {
1488 // Find the variables
1489 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1490 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1492 // Compile all variables
1493 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:<pre>' . print_r($varMatches, true) . '</pre>');
1494 foreach ($varMatches[0] as $match) {
1495 // Add variable tags around it
1496 $varCode = '{?' . $match . '?}';
1499 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varCode=' . $varCode);
1501 // Is the variable found in code? (safes some calls)
1502 if (strpos($rawCode, $varCode) !== false) {
1504 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1506 // Use $match as new value or $value from read variable?
1507 if ($setMatchAsCode === true) {
1509 $rawCode = str_replace($varCode, $match, $rawCode);
1511 // Read the variable
1512 $value = $this->readVariable($match);
1515 $rawCode = str_replace($varCode, $value, $rawCode);
1520 // Return the compiled data
1521 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1526 * Getter for variable group array
1528 * @return $variableGroups All variable groups
1530 public final function getVariableGroups () {
1531 return $this->variableGroups;
1535 * Renames a variable in code and in stack
1537 * @param $oldName Old name of variable
1538 * @param $newName New name of variable
1541 public function renameVariable (string $oldName, string $newName) {
1542 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: oldName=' . $oldName . ', newName=' . $newName);
1543 // Get raw template code
1544 $rawData = $this->getRawTemplateData();
1547 $rawData = str_replace($oldName, $newName, $rawData);
1549 // Set the code back
1550 $this->setRawTemplateData($rawData);
1554 * Renders the given XML content
1556 * @param $content Valid XML content or if not set the current loaded raw content
1558 * @throws XmlParserException If an XML error was found
1560 public function renderXmlContent (string $content = NULL) {
1561 // Is the content set?
1562 if (is_null($content)) {
1563 // Get current content
1564 $content = $this->getRawTemplateData();
1567 // Get a XmlParser instance
1568 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1570 // Check if XML compacting is enabled
1571 if ($this->isXmlCompactingEnabled()) {
1572 // Yes, so get a decorator class for transparent compacting
1573 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1576 // Parse the XML document
1577 $parserInstance->parseXmlContent($content);
1581 * Enables or disables language support
1583 * @param $languageSupport New language support setting
1586 public final function enableLanguageSupport (bool $languageSupport = true) {
1587 $this->languageSupport = $languageSupport;
1591 * Checks whether language support is enabled
1593 * @return $languageSupport Whether language support is enabled or disabled
1595 public final function isLanguageSupportEnabled () {
1596 return $this->languageSupport;
1600 * Enables or disables XML compacting
1602 * @param $xmlCompacting New XML compacting setting
1605 public final function enableXmlCompacting (bool $xmlCompacting = true) {
1606 $this->xmlCompacting = $xmlCompacting;
1610 * Checks whether XML compacting is enabled
1612 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1614 public final function isXmlCompactingEnabled () {
1615 return $this->xmlCompacting;
1619 * Private getter for file IO instance
1621 * @return $fileIoInstance An instance to the file I/O sub-system
1623 protected final function getFileIoInstance () {
1624 return $this->fileIoInstance;
1628 * Setter for file I/O instance
1630 * @param $fileIoInstance An instance to the file I/O sub-system
1633 public final function setFileIoInstance (IoHandler $fileIoInstance) {
1634 $this->fileIoInstance = $fileIoInstance;
1638 * Removes all commentd, tabs and new-line characters to compact the content
1640 * @param $uncompactedContent The uncompacted content
1641 * @return $compactedContent The compacted content
1643 public function compactContent (string $uncompactedContent) {
1644 // First, remove all tab/new-line/revert characters
1645 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1647 // Then regex all comments like <!-- //--> away
1648 preg_match_all($this->regExpComments, $compactedContent, $matches);
1650 // Do we have entries?
1651 if (isset($matches[0][0])) {
1653 foreach ($matches[0] as $match) {
1655 $compactedContent = str_replace($match, '', $compactedContent);
1659 // Set the content again
1660 $this->setRawTemplateData($compactedContent);
1662 // Return compacted content
1663 return $compactedContent;