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\Object\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
10 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
11 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
12 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
13 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
14 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
15 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
16 use Org\Mxchange\CoreFramework\Response\Responseable;
17 use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
18 use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
21 use \InvalidArgumentException;
25 * A generic template engine
27 * @author Roland Haeder <webmaster@shipsimu.org>
29 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
30 * @license GNU GPL 3.0 or any newer version
31 * @link http://www.shipsimu.org
33 * This program is free software: you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation, either version 3 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program. If not, see <http://www.gnu.org/licenses/>.
46 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
50 // Exception codes for the template engine
51 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
52 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
53 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
54 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
57 * The local path name where all templates and sub folders for special
58 * templates are stored. We will internally determine the language plus
59 * "html" for web templates or "emails" for email templates
61 private $templateBasePath = '';
66 private $templateType = 'html';
69 * The extension for web and email templates (not compiled templates)
71 private $templateExtension = '.tpl';
74 * The extension for code templates (not compiled templates)
76 private $codeExtension = '.ctp';
79 * Path relative to $templateBasePath and language code for compiled code-templates
81 private $compileOutputPath = 'templates/_compiled/';
84 * The path name for all templates
86 private $genericBasePath = 'templates/';
89 * The raw (maybe uncompiled) template
91 private $rawTemplateData = '';
94 * Template data with compiled-in variables
96 private $compiledData = '';
99 * The last loaded template's file instance (SplFileInfo)
101 private $lastTemplate = NULL;
104 * The variable stack for the templates
106 private $varStack = [];
109 * Loaded templates for recursive protection and detection
111 private $loadedTemplates = [];
114 * Compiled templates for recursive protection and detection
116 private $compiledTemplates = [];
119 * Loaded raw template data
121 private $loadedRawData = NULL;
124 * Raw templates which are linked in code templates
126 private $rawTemplates = NULL;
129 * A regular expression for variable=value pairs
131 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
134 * A regular expression for filtering out code tags
136 * E.g.: {?template:variable=value;var2=value2;[...]?}
138 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
141 * A regular expression to find template comments like <!-- Comment here //-->
143 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
148 private $helpers = [];
151 * Current variable group
153 private $currGroup = 'general';
156 * All template groups except "general"
158 private $variableGroups = [];
163 private $codeBegin = '<?php';
168 private $codeEnd = '?>';
171 * Language support is enabled by default
173 private $languageSupport = true;
176 * Protected constructor
178 * @param $className Name of the class
181 protected function __construct (string $className) {
182 // Call parent constructor
183 parent::__construct($className);
185 // Init file I/O instance
186 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
189 $this->setFileIoInstance($ioInstance);
193 * Search for a variable in the stack
195 * @param $variableName The variable we are looking for
196 * @param $variableGroup Optional variable group to look in
197 * @return $index false means not found, >=0 means found on a specific index
199 private function getVariableIndex (string $variableName, string $variableGroup = NULL) {
200 // Replace all dashes to underscores to match variables with configuration entries
201 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
203 // First everything is not found
206 // If the stack is NULL, use the current group
207 if (is_null($variableGroup)) {
209 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
210 $variableGroup = $this->currGroup;
213 // Is the group there?
214 if ($this->isVarStackSet($variableGroup)) {
216 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
217 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
218 // Is the entry found?
219 if ($currEntry['name'] == $variableName) {
221 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
228 // Return the current position
233 * Checks whether the given variable group is set
235 * @param $variableGroup Variable group to check
236 * @return $isSet Whether the given variable group is set
238 protected final function isVarStackSet (string $variableGroup) {
240 $isSet = isset($this->varStack[$variableGroup]);
247 * Getter for given variable group
249 * @param $variableGroup Variable group to check
250 * @return $varStack Found variable group
252 public final function getVarStack (string $variableGroup) {
253 return $this->varStack[$variableGroup];
257 * Setter for given variable group
259 * @param $variableGroup Variable group to check
260 * @param $varStack Variable stack to check
263 protected final function setVarStack (string $variableGroup, array $varStack) {
264 $this->varStack[$variableGroup] = $varStack;
268 * Return a content of a variable or null if not found
270 * @param $variableName The variable we are looking for
271 * @param $variableGroup Optional variable group to look in
272 * @return $content Content of the variable or null if not found
274 protected function readVariable (string $variableName, string $variableGroup = NULL) {
275 // Replace all dashes to underscores to match variables with configuration entries
276 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
278 // First everything is not found
281 // If the stack is NULL, use the current group
282 if (is_null($variableGroup)) {
284 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
285 $variableGroup = $this->currGroup;
288 // Get variable index
289 $found = $this->getVariableIndex($variableName, $variableGroup);
291 // Is the variable found?
292 if ($found !== false) {
294 $content = $this->getVariableValue($variableGroup, $found);
297 // Return the current position
298 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
303 * Add a variable to the stack
305 * @param $variableName Name of variable to add
306 * @param $value Value we want to store in the variable
309 private function addVariable (string $variableName, $value) {
310 // Set general variable group
311 $this->setVariableGroup('general');
313 // Add it to the stack
314 $this->addGroupVariable($variableName, $value);
318 * Returns all variables of current group or empty array
320 * @return $result Whether array of found variables or empty array
322 private function readCurrentGroup () {
323 // Default is not found
326 // Is the group there?
327 if ($this->isVarStackSet($this->currGroup)) {
329 $result = $this->getVarStack($this->currGroup);
337 * Settter for variable group
339 * @param $groupName Name of variable group
340 * @param $add Whether add this group
343 public function setVariableGroup (string $groupName, bool $add = true) {
345 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
346 $this->currGroup = $groupName;
348 // Skip group 'general'
349 if (($groupName != 'general') && ($add === true)) {
350 $this->variableGroups[$groupName] = 'OK';
356 * Adds a variable to current group
358 * @param $variableName Variable to set
359 * @param $value Value to store in variable
362 public function addGroupVariable (string $variableName, $value) {
363 // Replace all dashes to underscores to match variables with configuration entries
364 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
367 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
369 // Get current variables in group
370 $currVars = $this->readCurrentGroup();
372 // Append our variable
373 array_push($currVars, $this->generateVariableArray($variableName, $value));
375 // Add it to the stack
376 $this->setVarStack($this->currGroup, $currVars);
380 * Getter for variable value, throws a NoVariableException if the variable is not found
382 * @param $variableGroup Variable group to use
383 * @param $index Index in variable array
384 * @return $value Value to set
386 private function getVariableValue (string $variableGroup, int $index) {
388 return $this->varStack[$variableGroup][$index]['value'];
392 * Modify an entry on the stack
394 * @param $variableName The variable we are looking for
395 * @param $value The value we want to store in the variable
397 * @throws NoVariableException If the given variable is not found
399 private function modifyVariable (string $variableName, $value) {
400 // Replace all dashes to underscores to match variables with configuration entries
401 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
403 // Get index for variable
404 $index = $this->getVariableIndex($variableName);
406 // Is the variable set?
407 if ($index === false) {
408 // Unset variables cannot be modified
409 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
413 $this->setVariableValue($this->currGroup, $index, $value);
417 * Sets a variable value for given variable group and index
419 * @param $variableGroup Variable group to use
420 * @param $index Index in variable array
421 * @param $value Value to set
424 private function setVariableValue (string $variableGroup, int $index, $value) {
425 $this->varStack[$variableGroup][$index]['value'] = $value;
429 * Sets a variable within given group. This method does detect if the
430 * variable is already set. If so, the variable got modified, otherwise
433 * @param $variableGroup Variable group to use
434 * @param $variableName Variable to set
435 * @param $value Value to set
438 protected function setVariable (string $variableGroup, string $variableName, $value) {
439 // Replace all dashes to underscores to match variables with configuration entries
440 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
442 // Get index for variable
443 $index = $this->getVariableIndex($variableName);
445 // Is the variable set?
446 if ($index === false) {
447 // Is the stack there?
448 if (!isset($this->varStack[$variableGroup])) {
449 // Then initialize it here
450 $this->varStack[$variableGroup] = [];
454 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
457 $this->setVariableValue($this->currGroup, $index, $value);
462 * "Generates" (better returns) an array for all variables for given
463 * variable/value pay.
465 * @param $variableName Variable to set
466 * @param $value Value to set
467 * @return $varData Variable data array
469 private function generateVariableArray (string $variableName, $value) {
470 // Replace all dashes to underscores to match variables with configuration entries
471 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
473 // Generate the temporary array
475 'name' => $variableName,
484 * Setter for template type. Only 'html', 'emails' and 'compiled' should
487 * @param $templateType The current template's type
490 protected final function setTemplateType (string $templateType) {
491 $this->templateType = $templateType;
495 * Getter for template type
497 * @return $templateType The current template's type
499 public final function getTemplateType () {
500 return $this->templateType;
504 * Setter for the last loaded template's file instance
506 * @param $template The last loaded template
509 private final function setLastTemplate (SplFileInfo $fileInstance) {
510 $this->lastTemplate = $fileInstance;
514 * Getter for the last loaded template's file instance
516 * @return $template The last loaded template
518 private final function getLastTemplate () {
519 return $this->lastTemplate;
523 * Setter for base path
525 * @param $templateBasePath The relative base path for all templates
528 protected final function setTemplateBasePath (string $templateBasePath) {
530 $this->templateBasePath = $templateBasePath;
534 * Getter for base path
536 * @return $templateBasePath The relative base path for all templates
538 public final function getTemplateBasePath () {
540 return $this->templateBasePath;
544 * Getter for generic base path
546 * @return $templateBasePath The relative base path for all templates
548 public final function getGenericBasePath () {
550 return $this->genericBasePath;
554 * Setter for template extension
556 * @param $templateExtension The file extension for all uncompiled
560 protected final function setRawTemplateExtension (string $templateExtension) {
562 $this->templateExtension = $templateExtension;
566 * Setter for code template extension
568 * @param $codeExtension The file extension for all uncompiled
572 protected final function setCodeTemplateExtension (string $codeExtension) {
574 $this->codeExtension = $codeExtension;
578 * Getter for template extension
580 * @return $templateExtension The file extension for all uncompiled
583 public final function getRawTemplateExtension () {
585 return $this->templateExtension;
589 * Getter for code-template extension
591 * @return $codeExtension The file extension for all code-
594 public final function getCodeTemplateExtension () {
596 return $this->codeExtension;
600 * Setter for path of compiled templates
602 * @param $compileOutputPath The local base path for all compiled
606 protected final function setCompileOutputPath (string $compileOutputPath) {
608 $this->compileOutputPath = $compileOutputPath;
612 * Unsets the given offset in the variable group
614 * @param $index Index to unset
615 * @param $variableGroup Variable group (default: currGroup)
618 protected final function unsetVariableStackOffset (int $index, string $variableGroup = NULL) {
619 // Is the variable group not set?
620 if (is_null($variableGroup)) {
621 // Then set it to current
622 $variableGroup = $this->currGroup;
625 // Is the entry there?
626 if (!isset($this->varStack[$variableGroup][$index])) {
627 // Abort here, we need fixing!
628 $this->debugInstance();
632 unset($this->varStack[$variableGroup][$index]);
636 * Private setter for raw template data
638 * @param $rawTemplateData The raw data from the template
641 protected final function setRawTemplateData (string $rawTemplateData) {
642 // And store it in this class
643 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
644 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
645 $this->rawTemplateData = $rawTemplateData;
649 * Getter for raw template data
651 * @return $rawTemplateData The raw data from the template
653 public final function getRawTemplateData () {
654 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->rawTemplateData) . ' Bytes read.');
655 return $this->rawTemplateData;
659 * Private setter for compiled templates
661 * @param $compiledData Compiled template data
664 private final function setCompiledData (string $compiledData) {
665 // And store it in this class
666 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($compiledData) . ' Bytes set.');
667 $this->compiledData = $compiledData;
671 * Getter for compiled templates, must be public for e.g. Mailer classes.
673 * @return $compiledData Compiled template data
675 public final function getCompiledData () {
676 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: ' . strlen($this->compiledData) . ' Bytes read.');
677 return $this->compiledData;
681 * Private loader for all template types
683 * @param $templateName The template we shall load
684 * @param $extOther An other extension to use
686 * @throws FileNotFoundException If the template was not found
688 protected function loadTemplate (string $templateName, string $extOther = '') {
689 // Get extension for the template if empty
690 if (empty($extOther)) {
691 // None provided, so get the raw one
692 $ext = $this->getRawTemplateExtension();
699 * Construct the FQFN for the template without language as language is
700 * now entirely done by php_intl. These old thing with language-based
701 * template paths comes from an older time.
703 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
704 $this->getTemplateBasePath(),
705 $this->getGenericBasePath(),
706 $this->getTemplateType(),
708 (string) $templateName,
714 // Load the raw template data
715 $this->loadRawTemplateData($fileInstance);
716 } catch (FileNotFoundException $e) {
717 // If we shall load a code-template we need to switch the file extension
718 if (($this->getTemplateType() != FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
719 // Switch over to the code-template extension and try it again
720 $ext = $this->getCodeTemplateExtension();
723 $this->loadTemplate($templateName, $ext);
726 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
733 * A private loader for raw template names
735 * @param $fileInstance An instance of a SplFileInfo class
738 private function loadRawTemplateData (SplFileInfo $fileInstance) {
739 // Load the raw template
740 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: fileInstance=' . $fileInstance);
741 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
743 // Store the template's contents into this class
744 $this->setRawTemplateData($rawTemplateData);
746 // Remember the template's file instance
747 $this->setLastTemplate($fileInstance);
751 * Try to assign an extracted template variable as a "content" or 'config'
754 * @param $variableName The variable's name (shall be content or config)
756 * @param $variableName The variable we want to assign
759 private function assignTemplateVariable (string $variableName, $var) {
760 // Replace all dashes to underscores to match variables with configuration entries
761 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',var=' . $var);
762 $variableName = trim(StringUtils::convertDashesToUnderscores($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 (string $rawData) {
781 // Search for variables
782 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
783 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
785 // Did we find some variables?
786 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
787 // Initialize all missing variables
788 foreach ($variableMatches[3] as $key => $var) {
790 $variableName = $variableMatches[1][$key];
792 // Workarround: Do not assign empty variables
794 // Try to assign it, empty strings are being ignored
795 $this->assignTemplateVariable($variableName, $var);
802 * Main analysis of the loaded template
804 * @param $templateMatches Found template place-holders, see below
807 *---------------------------------
808 * Structure of $templateMatches:
809 *---------------------------------
810 * [0] => Array - An array with all full matches
811 * [1] => Array - An array with left part (before the ':') of a match
812 * [2] => Array - An array with right part of a match including ':'
813 * [3] => Array - An array with right part of a match excluding ':'
815 private function analyzeTemplate (array $templateMatches) {
816 // Backup raw template data
817 $backup = $this->getRawTemplateData();
819 // Initialize some arrays
820 if (is_null($this->loadedRawData)) {
822 $this->loadedRawData = [];
823 $this->rawTemplates = [];
826 // Load all requested templates
827 foreach ($templateMatches[1] as $template) {
828 // Load and compile only templates which we have not yet loaded
829 // RECURSIVE PROTECTION! BE CAREFUL HERE!
830 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
832 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:template=' . $template);
834 // Template not found, but maybe variable assigned?
835 if ($this->getVariableIndex($template) !== false) {
836 // Use that content here
837 $this->loadedRawData[$template] = $this->readVariable($template);
839 // Recursive protection:
840 array_push($this->loadedTemplates, $template);
842 // Then try to search for code-templates
844 // Load the code template and remember it's contents
845 $this->loadCodeTemplate($template);
846 $this->loadedRawData[$template] = $this->getRawTemplateData();
848 // Remember this template for recursion detection
849 // RECURSIVE PROTECTION!
850 array_push($this->loadedTemplates, $template);
851 } catch (FileNotFoundException $e) {
852 // Even this is not done... :/
853 array_push($this->rawTemplates, $template);
859 // Restore the raw template data
860 $this->setRawTemplateData($backup);
864 * Compile a given raw template code and remember it for later usage
866 * @param $code The raw template code
867 * @param $template The template's name
870 private function compileCode (string $code, string $template) {
871 // Is this template already compiled?
872 if (in_array($template, $this->compiledTemplates)) {
877 // Remember this template being compiled
878 array_push($this->compiledTemplates, $template);
880 // Compile the loaded code in five steps:
882 // 1. Backup current template data
883 $backup = $this->getRawTemplateData();
885 // 2. Set the current template's raw data as the new content
886 $this->setRawTemplateData($code);
888 // 3. Compile the template data
889 $this->compileTemplate();
891 // 4. Remember it's contents
892 $this->loadedRawData[$template] = $this->getRawTemplateData();
894 // 5. Restore the previous raw content from backup variable
895 $this->setRawTemplateData($backup);
899 * Insert all given and loaded templates by running through all loaded
900 * codes and searching for their place-holder in the main template
902 * @param $templateMatches See method analyzeTemplate()
905 private function insertAllTemplates (array $templateMatches) {
906 // Run through all loaded codes
907 foreach ($this->loadedRawData as $template => $code) {
909 // Search for the template
910 $foundIndex = array_search($template, $templateMatches[1]);
912 // Lookup the matching template replacement
913 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
915 // Get the current raw template
916 $rawData = $this->getRawTemplateData();
918 // Replace the space holder with the template code
919 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
921 // Set the new raw data
922 $this->setRawTemplateData($rawData);
928 * Load all extra raw templates
932 private function loadExtraRawTemplates () {
933 // Are there some raw templates we need to load?
934 if (count($this->rawTemplates) > 0) {
935 // Try to load all raw templates
936 foreach ($this->rawTemplates as $key => $template) {
939 $this->loadHtmlTemplate($template);
941 // Remember it's contents
942 $this->rawTemplates[$template] = $this->getRawTemplateData();
944 // Remove it from the loader list
945 unset($this->rawTemplates[$key]);
947 // Remember this template for recursion detection
948 // RECURSIVE PROTECTION!
949 array_push($this->loadedTemplates, $template);
950 } catch (FileNotFoundException $e) {
951 // This template was never found. We silently ignore it
952 unset($this->rawTemplates[$key]);
959 * Assign all found template variables
961 * @param $varMatches An array full of variable/value pairs.
963 * @todo Unfinished work or don't die here.
965 private function assignAllVariables (array $varMatches) {
967 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches()=' . count($varMatches));
969 // Search for all variables
970 foreach ($varMatches[1] as $key => $var) {
971 // Replace all dashes to underscores to match variables with configuration entries
972 $var = trim(StringUtils::convertDashesToUnderscores($var));
975 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:key=' . $key . ',var=' . $var);
977 // Detect leading equals
978 if (substr($varMatches[2][$key], 0, 1) == '=') {
979 // Remove and cast it
980 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
983 // Do we have some quotes left and right side? Then it is free text
984 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
985 // Free string detected! Which we can assign directly
986 $this->assignVariable($var, $varMatches[3][$key]);
987 } elseif (!empty($varMatches[2][$key])) {
988 // @TODO Non-string found so we need some deeper analysis...
989 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
995 * Compiles all loaded raw templates
997 * @param $templateMatches See method analyzeTemplate() for details
1000 private function compileRawTemplateData (array $templateMatches) {
1002 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:loadedRawData()= ' .count($this->loadedRawData));
1004 // Are some code-templates found which we need to compile?
1005 if (count($this->loadedRawData) > 0) {
1006 // Then compile all!
1007 foreach ($this->loadedRawData as $template => $code) {
1009 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1011 // Is this template already compiled?
1012 if (in_array($template, $this->compiledTemplates)) {
1014 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Template ' . $template . ' already compiled. SKIPPED!');
1018 // Search for the template
1019 $foundIndex = array_search($template, $templateMatches[1]);
1021 // Lookup the matching variable data
1022 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1023 // Split it up with another reg. exp. into variable=value pairs
1024 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1025 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches=' . print_r($varMatches, true));
1027 // Assign all variables
1028 $this->assignAllVariables($varMatches);
1031 // Compile the loaded template
1032 $this->compileCode($code, $template);
1035 // Insert all templates
1036 $this->insertAllTemplates($templateMatches);
1041 * Inserts all raw templates into their respective variables
1045 private function insertRawTemplates () {
1046 // Load all templates
1047 foreach ($this->rawTemplates as $template => $content) {
1048 // Set the template as a variable with the content
1049 $this->assignVariable($template, $content);
1054 * Finalizes the compilation of all template variables
1058 private function finalizeVariableCompilation () {
1060 $content = $this->getRawTemplateData();
1061 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content before=' . strlen($content) . ' (' . md5($content) . ')');
1063 // Do we have the stack?
1064 if (!$this->isVarStackSet('general')) {
1065 // Abort here silently
1066 // @TODO This silent abort should be logged, maybe.
1070 // Walk through all variables
1071 foreach ($this->getVarStack('general') as $currEntry) {
1072 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1073 // Replace all [$var] or {?$var?} with the content
1074 // @TODO Old behaviour, will become obsolete!
1075 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1077 // @TODO Yet another old way
1078 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1080 // The new behaviour
1081 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1084 // Set the content back
1085 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content after=' . strlen($content) . ' (' . md5($content) . ')');
1086 $this->setRawTemplateData($content);
1090 * Load a specified HTML template into the engine
1092 * @param $template The web template we shall load which is located in
1096 public function loadHtmlTemplate (string $template) {
1097 // Set template type
1098 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('html_template_type'));
1100 // Load the special template
1101 $this->loadTemplate($template);
1105 * Assign (add) a given variable with a value
1107 * @param $variableName The variable we are looking for
1108 * @param $value The value we want to store in the variable
1110 * @throws InvalidArgumentException If the variable name is left empty
1112 public final function assignVariable (string $variableName, $value) {
1113 // Validate parameter
1114 if (empty($variableName)) {
1115 // Throw an exception
1116 throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
1119 // Replace all dashes to underscores to match variables with configuration entries
1120 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1122 // First search for the variable if it was already added
1123 $index = $this->getVariableIndex($variableName);
1126 if ($index === false) {
1127 // Add it to the stack
1128 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1129 $this->addVariable($variableName, $value);
1130 } elseif (!empty($value)) {
1131 // Modify the stack entry
1132 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1133 $this->modifyVariable($variableName, $value);
1138 * Removes a given variable
1140 * @param $variableName The variable we are looking for
1141 * @param $variableGroup Name of variable group (default: 'general')
1144 public final function removeVariable (string $variableName, string $variableGroup = 'general') {
1145 // First search for the variable if it was already added
1146 $index = $this->getVariableIndex($variableName, $variableGroup);
1149 if ($index !== false) {
1150 // Remove this variable
1151 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1152 $this->unsetVariableStackOffset($index, $variableGroup);
1157 * Assigns the last loaded raw template content with a given variable
1159 * @param $templateName Name of the template we want to assign
1160 * @param $variableName Name of the variable we want to assign
1163 public function assignTemplateWithVariable (string $templateName, string $variableName) {
1164 // Get the content from last loaded raw template
1165 $content = $this->getRawTemplateData();
1167 // Assign the variable
1168 $this->assignVariable($variableName, $content);
1170 // Purge raw content
1171 $this->setRawTemplateData('');
1175 * Assign a given congfiguration variable with a value
1177 * @param $variableName The configuration variable we want to assign
1180 public function assignConfigVariable (string $variableName) {
1181 // Replace all dashes to underscores to match variables with configuration entries
1182 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1184 // Sweet and simple...
1185 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',getConfigEntry()=' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
1186 $this->assignVariable($variableName, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
1190 * Assigns a lot variables into the stack of currently loaded template.
1191 * This method should only be used in very rare circumstances, e.g. when
1192 * you have to copy a whole set of variables into the template engine.
1193 * Before you use this method, please make sure you have considered all
1194 * other possiblities.
1196 * @param $variables An array with variables to be assigned
1199 public function assignMultipleVariables (array $variables) {
1201 foreach ($variables as $name => $value) {
1202 // Set variable with name for 'config' group
1203 $this->assignVariable($name, $value);
1208 * Assigns all the application data with template variables
1212 public function assignApplicationData () {
1213 // Get application instance
1214 $applicationInstance = ApplicationHelper::getSelfInstance();
1216 // Get long name and assign it
1217 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1219 // Get short name and assign it
1220 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1222 // Get version number and assign it
1223 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1225 // Assign extra application-depending data
1226 $applicationInstance->assignExtraTemplateData($this);
1230 * Load a specified code template into the engine
1232 * @param $template The code template we shall load which is
1233 * located in 'code' by default
1236 public function loadCodeTemplate (string $template) {
1237 // Set template type
1238 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1240 // Load the special template
1241 $this->loadTemplate($template);
1245 * Load a specified email template into the engine
1247 * @param $template The email template we shall load which is
1248 * located in 'emails' by default
1251 public function loadEmailTemplate (string $template) {
1252 // Set template type
1253 $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('email_template_type'));
1255 // Load the special template
1256 $this->loadTemplate($template);
1260 * Compiles configuration place-holders in all variables. This 'walks'
1261 * through the variable group 'general'. It interprets all values from that
1262 * variables as configuration entries after compiling them.
1266 public final function compileConfigInVariables () {
1267 // Do we have the stack?
1268 if (!$this->isVarStackSet('general')) {
1269 // Abort here silently
1270 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Aborted, variable stack general not found!');
1274 // Iterate through all general variables
1275 foreach ($this->getVarStack('general') as $index => $currVariable) {
1276 // Compile the value
1277 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1280 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currVariable['name'] . ',value=' . $value);
1282 // Remove it from stack
1283 $this->removeVariable($currVariable['name'], 'general');
1284 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1286 // Is it a configuration key?
1287 if (FrameworkBootstrap::getConfigurationInstance()->isConfigurationEntrySet($value)) {
1288 // The value itself is a configuration entry
1289 $this->assignConfigVariable($value);
1291 // Re-assign the value directly
1292 $this->assignVariable($currVariable['name'], $value);
1298 * Compile all variables by inserting their respective values
1301 * @todo Make this code some nicer...
1303 public final function compileVariables () {
1304 // Initialize the $content array
1305 $validVar = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('tpl_valid_var');
1308 // Iterate through all general variables
1309 foreach ($this->getVarStack('general') as $currVariable) {
1310 // Transfer it's name/value combination to the $content array
1311 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1312 $dummy[$currVariable['name']] = $currVariable['value'];
1315 // Set the new variable (don't remove the second dollar!)
1316 $$validVar = $dummy;
1318 // Remove some variables
1320 unset($currVariable);
1322 // Run the compilation three times to get content from helper classes in
1325 // Finalize the compilation of template variables
1326 $this->finalizeVariableCompilation();
1328 // Prepare the eval() command for comiling the template
1329 $eval = sprintf('$result = "%s";',
1330 addslashes($this->getRawTemplateData())
1333 // This loop does remove the backslashes (\) in PHP parameters
1334 while (strpos($eval, $this->codeBegin) !== false) {
1335 // Get left part before "<?"
1336 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1338 // Get all from right of "<?"
1339 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1341 // Cut middle part out and remove escapes
1342 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1343 $evalMiddle = stripslashes($evalMiddle);
1345 // Remove the middle part from right one
1346 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1348 // And put all together
1349 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1352 // Prepare PHP code for eval() command
1353 $eval = str_replace(
1362 // Run the constructed command. This will "compile" all variables in
1365 // Goes something wrong?
1366 if ((!isset($result)) || (empty($result))) {
1367 // Output eval command
1368 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1370 // Output backtrace here
1371 $this->debugBackTrace();
1374 // Set raw template data
1375 $this->setRawTemplateData($result);
1379 // Final variable assignment
1380 $this->finalizeVariableCompilation();
1382 // Set the new content
1383 $this->setCompiledData($this->getRawTemplateData());
1387 * Compile all required templates into the current loaded one
1390 * @throws UnexpectedTemplateTypeException If the template type is
1392 * @throws InvalidArrayCountException If an unexpected array
1393 * count has been found
1395 public function compileTemplate () {
1396 // Get code type to make things shorter
1397 $codeType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1399 // We will only work with template type "code" from configuration
1400 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1402 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1405 // Get the raw data.
1406 $rawData = $this->getRawTemplateData();
1408 // Remove double spaces and trim leading/trailing spaces
1409 $rawData = trim(str_replace(' ', ' ', $rawData));
1411 // Search for raw variables
1412 $this->extractVariablesFromRawData($rawData);
1414 // Search for code-tags which are {? ?}
1415 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1418 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:templateMatches=' . print_r($templateMatches , true));
1420 // Analyze the matches array
1421 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1422 // Entries are found:
1424 // The main analysis
1425 $this->analyzeTemplate($templateMatches);
1427 // Compile raw template data
1428 $this->compileRawTemplateData($templateMatches);
1430 // Are there some raw templates left for loading?
1431 $this->loadExtraRawTemplates();
1433 // Are some raw templates found and loaded?
1434 if (count($this->rawTemplates) > 0) {
1435 // Insert all raw templates
1436 $this->insertRawTemplates();
1438 // Remove the raw template content as well
1439 $this->setRawTemplateData('');
1445 * Loads a given view helper (by name)
1447 * @param $helperName The helper's name
1450 protected function loadViewHelper (string $helperName) {
1451 // Is this view helper loaded?
1452 if (!isset($this->helpers[$helperName])) {
1453 // Create a class name
1454 $className = StringUtils::convertToClassName($helperName) . 'ViewHelper';
1456 // Generate new instance
1457 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1460 // Return the requested instance
1461 return $this->helpers[$helperName];
1465 * Transfers the content of this template engine to a given response instance
1467 * @param $responseInstance An instance of a Responseable class
1470 public function transferToResponse (Responseable $responseInstance) {
1471 // Get the content and set it in response class
1472 $responseInstance->writeToBody($this->getCompiledData());
1476 * "Compiles" a variable by replacing {?var?} with it's content
1478 * @param $rawCode Raw code to compile
1479 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1480 * @return $rawCode Compile code with inserted variable value
1482 public function compileRawCode (string $rawCode, bool $setMatchAsCode = false) {
1483 // Find the variables
1484 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1485 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1487 // Compile all variables
1488 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:<pre>' . print_r($varMatches, true) . '</pre>');
1489 foreach ($varMatches[0] as $match) {
1490 // Add variable tags around it
1491 $varCode = '{?' . $match . '?}';
1494 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varCode=' . $varCode);
1496 // Is the variable found in code? (safes some calls)
1497 if (strpos($rawCode, $varCode) !== false) {
1499 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1501 // Use $match as new value or $value from read variable?
1502 if ($setMatchAsCode === true) {
1504 $rawCode = str_replace($varCode, $match, $rawCode);
1506 // Read the variable
1507 $value = $this->readVariable($match);
1510 $rawCode = str_replace($varCode, $value, $rawCode);
1515 // Return the compiled data
1516 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1521 * Getter for variable group array
1523 * @return $variableGroups All variable groups
1525 public final function getVariableGroups () {
1526 return $this->variableGroups;
1530 * Renames a variable in code and in stack
1532 * @param $oldName Old name of variable
1533 * @param $newName New name of variable
1536 public function renameVariable (string $oldName, string $newName) {
1537 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: oldName=' . $oldName . ', newName=' . $newName);
1538 // Get raw template code
1539 $rawData = $this->getRawTemplateData();
1542 $rawData = str_replace($oldName, $newName, $rawData);
1544 // Set the code back
1545 $this->setRawTemplateData($rawData);
1549 * Enables or disables language support
1551 * @param $languageSupport New language support setting
1554 public final function enableLanguageSupport (bool $languageSupport = true) {
1555 $this->languageSupport = $languageSupport;
1559 * Checks whether language support is enabled
1561 * @return $languageSupport Whether language support is enabled or disabled
1563 public final function isLanguageSupportEnabled () {
1564 return $this->languageSupport;
1568 * Removes all commentd, tabs and new-line characters to compact the content
1570 * @param $uncompactedContent The uncompacted content
1571 * @return $compactedContent The compacted content
1573 public function compactContent (string $uncompactedContent) {
1574 // First, remove all tab/new-line/revert characters
1575 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1577 // Then regex all comments like <!-- //--> away
1578 preg_match_all($this->regExpComments, $compactedContent, $matches);
1580 // Do we have entries?
1581 if (isset($matches[0][0])) {
1583 foreach ($matches[0] as $match) {
1585 $compactedContent = str_replace($match, '', $compactedContent);
1589 // Set the content again
1590 $this->setRawTemplateData($compactedContent);
1592 // Return compacted content
1593 return $compactedContent;