3 namespace Org\Mxchange\CoreFramework\Template\Engine;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
10 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
11 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
12 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
13 use Org\Mxchange\CoreFramework\Response\Responseable;
14 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
17 use \InvalidArgumentException;
21 * A generic template engine
23 * @author Roland Haeder <webmaster@shipsimu.org>
25 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.shipsimu.org
29 * This program is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
44 * The local path name where all templates and sub folders for special
45 * templates are stored. We will internally determine the language plus
46 * "html" for web templates or "emails" for email templates
48 private $templateBasePath = '';
53 private $templateType = 'html';
56 * The extension for web and email templates (not compiled templates)
58 private $templateExtension = '.tpl';
61 * The extension for code templates (not compiled templates)
63 private $codeExtension = '.ctp';
66 * Path relative to $templateBasePath and language code for compiled code-templates
68 private $compileOutputPath = 'templates/_compiled/';
71 * The path name for all templates
73 private $genericBasePath = 'templates/';
76 * The raw (maybe uncompiled) template
78 private $rawTemplateData = '';
81 * Template data with compiled-in variables
83 private $compiledData = '';
86 * The last loaded template's file instance (SplFileInfo)
88 private $lastTemplate = NULL;
91 * The variable stack for the templates
93 private $varStack = array();
96 * Loaded templates for recursive protection and detection
98 private $loadedTemplates = array();
101 * Compiled templates for recursive protection and detection
103 private $compiledTemplates = array();
106 * Loaded raw template data
108 private $loadedRawData = NULL;
111 * Raw templates which are linked in code templates
113 private $rawTemplates = NULL;
116 * A regular expression for variable=value pairs
118 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
121 * A regular expression for filtering out code tags
123 * E.g.: {?template:variable=value;var2=value2;[...]?}
125 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
128 * A regular expression to find template comments like <!-- Comment here //-->
130 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
135 private $helpers = array();
138 * Current variable group
140 private $currGroup = 'general';
143 * All template groups except "general"
145 private $variableGroups = array();
150 private $codeBegin = '<?php';
155 private $codeEnd = '?>';
158 * Language support is enabled by default
160 private $languageSupport = true;
163 * XML compacting is disabled by default
165 private $xmlCompacting = false;
167 // Exception codes for the template engine
168 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
169 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
170 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
171 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
174 * Protected constructor
176 * @param $className Name of the class
179 protected function __construct ($className) {
180 // Call parent constructor
181 parent::__construct($className);
183 // Init file I/O instance
184 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
187 $this->setFileIoInstance($ioInstance);
191 * Search for a variable in the stack
193 * @param $variableName The variable we are looking for
194 * @param $variableGroup Optional variable group to look in
195 * @return $index false means not found, >=0 means found on a specific index
197 private function getVariableIndex ($variableName, $variableGroup = NULL) {
198 // Replace all dashes to underscores to match variables with configuration entries
199 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
201 // First everything is not found
204 // If the stack is NULL, use the current group
205 if (is_null($variableGroup)) {
207 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
208 $variableGroup = $this->currGroup;
211 // Is the group there?
212 if ($this->isVarStackSet($variableGroup)) {
214 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
215 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
216 // Is the entry found?
217 if ($currEntry['name'] == $variableName) {
219 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
226 // Return the current position
231 * Checks whether the given variable group is set
233 * @param $variableGroup Variable group to check
234 * @return $isSet Whether the given variable group is set
236 protected final function isVarStackSet ($variableGroup) {
238 $isSet = isset($this->varStack[$variableGroup]);
245 * Getter for given variable group
247 * @param $variableGroup Variable group to check
248 * @return $varStack Found variable group
250 public final function getVarStack ($variableGroup) {
251 return $this->varStack[$variableGroup];
255 * Setter for given variable group
257 * @param $variableGroup Variable group to check
258 * @param $varStack Variable stack to check
261 protected final function setVarStack ($variableGroup, array $varStack) {
262 $this->varStack[$variableGroup] = $varStack;
266 * Return a content of a variable or null if not found
268 * @param $variableName The variable we are looking for
269 * @param $variableGroup Optional variable group to look in
270 * @return $content Content of the variable or null if not found
272 protected function readVariable ($variableName, $variableGroup = NULL) {
273 // Replace all dashes to underscores to match variables with configuration entries
274 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
276 // First everything is not found
279 // If the stack is NULL, use the current group
280 if (is_null($variableGroup)) {
282 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
283 $variableGroup = $this->currGroup;
286 // Get variable index
287 $found = $this->getVariableIndex($variableName, $variableGroup);
289 // Is the variable found?
290 if ($found !== false) {
292 $content = $this->getVariableValue($variableGroup, $found);
295 // Return the current position
296 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
301 * Add a variable to the stack
303 * @param $variableName Name of variable to add
304 * @param $value Value we want to store in the variable
307 private function addVariable ($variableName, $value) {
308 // Set general variable group
309 $this->setVariableGroup('general');
311 // Add it to the stack
312 $this->addGroupVariable($variableName, $value);
316 * Returns all variables of current group or empty array
318 * @return $result Whether array of found variables or empty array
320 private function readCurrentGroup () {
321 // Default is not found
324 // Is the group there?
325 if ($this->isVarStackSet($this->currGroup)) {
327 $result = $this->getVarStack($this->currGroup);
335 * Settter for variable group
337 * @param $groupName Name of variable group
338 * @param $add Whether add this group
341 public function setVariableGroup ($groupName, $add = true) {
343 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
344 $this->currGroup = $groupName;
346 // Skip group 'general'
347 if (($groupName != 'general') && ($add === true)) {
348 $this->variableGroups[$groupName] = 'OK';
354 * Adds a variable to current group
356 * @param $variableName Variable to set
357 * @param $value Value to store in variable
360 public function addGroupVariable ($variableName, $value) {
361 // Replace all dashes to underscores to match variables with configuration entries
362 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
365 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
367 // Get current variables in group
368 $currVars = $this->readCurrentGroup();
370 // Append our variable
371 array_push($currVars, $this->generateVariableArray($variableName, $value));
373 // Add it to the stack
374 $this->setVarStack($this->currGroup, $currVars);
378 * Getter for variable value, throws a NoVariableException if the variable is not found
380 * @param $variableGroup Variable group to use
381 * @param $index Index in variable array
382 * @return $value Value to set
384 private function getVariableValue ($variableGroup, $index) {
386 return $this->varStack[$variableGroup][$index]['value'];
390 * Modify an entry on the stack
392 * @param $variableName The variable we are looking for
393 * @param $value The value we want to store in the variable
395 * @throws NoVariableException If the given variable is not found
397 private function modifyVariable ($variableName, $value) {
398 // Replace all dashes to underscores to match variables with configuration entries
399 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
401 // Get index for variable
402 $index = $this->getVariableIndex($variableName);
404 // Is the variable set?
405 if ($index === false) {
406 // Unset variables cannot be modified
407 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
411 $this->setVariableValue($this->currGroup, $index, $value);
415 * Sets a variable value for given variable group and index
417 * @param $variableGroup Variable group to use
418 * @param $index Index in variable array
419 * @param $value Value to set
422 private function setVariableValue ($variableGroup, $index, $value) {
423 $this->varStack[$variableGroup][$index]['value'] = $value;
427 * Sets a variable within given group. This method does detect if the
428 * variable is already set. If so, the variable got modified, otherwise
431 * @param $variableGroup Variable group to use
432 * @param $variableName Variable to set
433 * @param $value Value to set
436 protected function setVariable ($variableGroup, $variableName, $value) {
437 // Replace all dashes to underscores to match variables with configuration entries
438 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
440 // Get index for variable
441 $index = $this->getVariableIndex($variableName);
443 // Is the variable set?
444 if ($index === false) {
445 // Is the stack there?
446 if (!isset($this->varStack[$variableGroup])) {
447 // Then initialize it here
448 $this->varStack[$variableGroup] = array();
452 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
455 $this->setVariableValue($this->currGroup, $index, $value);
460 * "Generates" (better returns) an array for all variables for given
461 * variable/value pay.
463 * @param $variableName Variable to set
464 * @param $value Value to set
465 * @return $varData Variable data array
467 private function generateVariableArray ($variableName, $value) {
468 // Replace all dashes to underscores to match variables with configuration entries
469 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
471 // Generate the temporary array
473 'name' => $variableName,
482 * Setter for template type. Only 'html', 'emails' and 'compiled' should
485 * @param $templateType The current template's type
488 protected final function setTemplateType ($templateType) {
489 $this->templateType = (string) $templateType;
493 * Getter for template type
495 * @return $templateType The current template's type
497 public final function getTemplateType () {
498 return $this->templateType;
502 * Setter for the last loaded template's file instance
504 * @param $template The last loaded template
507 private final function setLastTemplate (SplFileInfo $fileInstance) {
508 $this->lastTemplate = $fileInstance;
512 * Getter for the last loaded template's file instance
514 * @return $template The last loaded template
516 private final function getLastTemplate () {
517 return $this->lastTemplate;
521 * Setter for base path
523 * @param $templateBasePath The relative base path for all templates
526 protected final function setTemplateBasePath ($templateBasePath) {
528 $this->templateBasePath = (string) $templateBasePath;
532 * Getter for base path
534 * @return $templateBasePath The relative base path for all templates
536 public final function getTemplateBasePath () {
538 return $this->templateBasePath;
542 * Getter for generic base path
544 * @return $templateBasePath The relative base path for all templates
546 public final function getGenericBasePath () {
548 return $this->genericBasePath;
552 * Setter for template extension
554 * @param $templateExtension The file extension for all uncompiled
558 protected final function setRawTemplateExtension ($templateExtension) {
560 $this->templateExtension = (string) $templateExtension;
564 * Setter for code template extension
566 * @param $codeExtension The file extension for all uncompiled
570 protected final function setCodeTemplateExtension ($codeExtension) {
572 $this->codeExtension = (string) $codeExtension;
576 * Getter for template extension
578 * @return $templateExtension The file extension for all uncompiled
581 public final function getRawTemplateExtension () {
583 return $this->templateExtension;
587 * Getter for code-template extension
589 * @return $codeExtension The file extension for all code-
592 public final function getCodeTemplateExtension () {
594 return $this->codeExtension;
598 * Setter for path of compiled templates
600 * @param $compileOutputPath The local base path for all compiled
604 protected final function setCompileOutputPath ($compileOutputPath) {
606 $this->compileOutputPath = (string) $compileOutputPath;
610 * Unsets the given offset in the variable group
612 * @param $index Index to unset
613 * @param $variableGroup Variable group (default: currGroup)
616 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
617 // Is the variable group not set?
618 if (is_null($variableGroup)) {
619 // Then set it to current
620 $variableGroup = $this->currGroup;
623 // Is the entry there?
624 if (!isset($this->varStack[$variableGroup][$index])) {
625 // Abort here, we need fixing!
626 $this->debugInstance();
630 unset($this->varStack[$variableGroup][$index]);
634 * Private setter for raw template data
636 * @param $rawTemplateData The raw data from the template
639 protected final function setRawTemplateData ($rawTemplateData) {
640 // And store it in this class
641 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
642 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
643 $this->rawTemplateData = (string) $rawTemplateData;
647 * Getter for raw template data
649 * @return $rawTemplateData The raw data from the template
651 public final function getRawTemplateData () {
652 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
653 return $this->rawTemplateData;
657 * Private setter for compiled templates
661 private final function setCompiledData ($compiledData) {
662 // And store it in this class
663 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
664 $this->compiledData = (string) $compiledData;
668 * Getter for compiled templates, must be public for e.g. Mailer classes.
670 * @return $compiledData Compiled template data
672 public final function getCompiledData () {
673 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
674 return $this->compiledData;
678 * Private loader for all template types
680 * @param $templateName The template we shall load
681 * @param $extOther An other extension to use
683 * @throws FileNotFoundException If the template was not found
685 protected function loadTemplate ($templateName, $extOther = '') {
686 // Get extension for the template if empty
687 if (empty($extOther)) {
688 // None provided, so get the raw one
689 $ext = $this->getRawTemplateExtension();
692 $ext = (string) $extOther;
696 * Construct the FQFN for the template without language as language is
697 * now entirely done by php_intl. These old thing with language-based
698 * template paths comes from an older time.
700 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
701 $this->getTemplateBasePath(),
702 $this->getGenericBasePath(),
703 $this->getTemplateType(),
705 (string) $templateName,
711 // Load the raw template data
712 $this->loadRawTemplateData($fileInstance);
713 } catch (FileNotFoundException $e) {
714 // If we shall load a code-template we need to switch the file extension
715 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
716 // Switch over to the code-template extension and try it again
717 $ext = $this->getCodeTemplateExtension();
720 $this->loadTemplate($templateName, $ext);
723 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
730 * A private loader for raw template names
732 * @param $fileInstance An instance of a SplFileInfo class
735 private function loadRawTemplateData (SplFileInfo $fileInstance) {
736 // Some debug code to look on the file which is being loaded
737 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: fileInstance=' . $fileInstance);
739 // Load the raw template
740 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
742 // Store the template's contents into this class
743 $this->setRawTemplateData($rawTemplateData);
745 // Remember the template's file instance
746 $this->setLastTemplate($fileInstance);
750 * Try to assign an extracted template variable as a "content" or 'config'
753 * @param $variableName The variable's name (shall be content or config)
755 * @param $variableName The variable we want to assign
758 private function assignTemplateVariable ($variableName, $var) {
759 // Replace all dashes to underscores to match variables with configuration entries
760 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
763 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
765 // Is it not a config variable?
766 if ($variableName != 'config') {
767 // Regular template variables
768 $this->assignVariable($variableName, '');
770 // Configuration variables
771 $this->assignConfigVariable($var);
776 * Extract variables from a given raw data stream
778 * @param $rawData The raw template data we shall analyze
781 private function extractVariablesFromRawData ($rawData) {
783 $rawData = (string) $rawData;
785 // Search for variables
786 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
789 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
791 // Did we find some variables?
792 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
793 // Initialize all missing variables
794 foreach ($variableMatches[3] as $key => $var) {
796 $variableName = $variableMatches[1][$key];
798 // Workarround: Do not assign empty variables
800 // Try to assign it, empty strings are being ignored
801 $this->assignTemplateVariable($variableName, $var);
808 * Main analysis of the loaded template
810 * @param $templateMatches Found template place-holders, see below
813 *---------------------------------
814 * Structure of $templateMatches:
815 *---------------------------------
816 * [0] => Array - An array with all full matches
817 * [1] => Array - An array with left part (before the ':') of a match
818 * [2] => Array - An array with right part of a match including ':'
819 * [3] => Array - An array with right part of a match excluding ':'
821 private function analyzeTemplate (array $templateMatches) {
822 // Backup raw template data
823 $backup = $this->getRawTemplateData();
825 // Initialize some arrays
826 if (is_null($this->loadedRawData)) {
828 $this->loadedRawData = array();
829 $this->rawTemplates = array();
832 // Load all requested templates
833 foreach ($templateMatches[1] as $template) {
834 // Load and compile only templates which we have not yet loaded
835 // RECURSIVE PROTECTION! BE CAREFUL HERE!
836 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
838 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
840 // Template not found, but maybe variable assigned?
841 if ($this->getVariableIndex($template) !== false) {
842 // Use that content here
843 $this->loadedRawData[$template] = $this->readVariable($template);
845 // Recursive protection:
846 array_push($this->loadedTemplates, $template);
848 // Then try to search for code-templates
850 // Load the code template and remember it's contents
851 $this->loadCodeTemplate($template);
852 $this->loadedRawData[$template] = $this->getRawTemplateData();
854 // Remember this template for recursion detection
855 // RECURSIVE PROTECTION!
856 array_push($this->loadedTemplates, $template);
857 } catch (FileNotFoundException $e) {
858 // Even this is not done... :/
859 array_push($this->rawTemplates, $template);
865 // Restore the raw template data
866 $this->setRawTemplateData($backup);
870 * Compile a given raw template code and remember it for later usage
872 * @param $code The raw template code
873 * @param $template The template's name
876 private function compileCode ($code, $template) {
877 // Is this template already compiled?
878 if (in_array($template, $this->compiledTemplates)) {
883 // Remember this template being compiled
884 array_push($this->compiledTemplates, $template);
886 // Compile the loaded code in five steps:
888 // 1. Backup current template data
889 $backup = $this->getRawTemplateData();
891 // 2. Set the current template's raw data as the new content
892 $this->setRawTemplateData($code);
894 // 3. Compile the template data
895 $this->compileTemplate();
897 // 4. Remember it's contents
898 $this->loadedRawData[$template] = $this->getRawTemplateData();
900 // 5. Restore the previous raw content from backup variable
901 $this->setRawTemplateData($backup);
905 * Insert all given and loaded templates by running through all loaded
906 * codes and searching for their place-holder in the main template
908 * @param $templateMatches See method analyzeTemplate()
911 private function insertAllTemplates (array $templateMatches) {
912 // Run through all loaded codes
913 foreach ($this->loadedRawData as $template => $code) {
915 // Search for the template
916 $foundIndex = array_search($template, $templateMatches[1]);
918 // Lookup the matching template replacement
919 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
921 // Get the current raw template
922 $rawData = $this->getRawTemplateData();
924 // Replace the space holder with the template code
925 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
927 // Set the new raw data
928 $this->setRawTemplateData($rawData);
934 * Load all extra raw templates
938 private function loadExtraRawTemplates () {
939 // Are there some raw templates we need to load?
940 if (count($this->rawTemplates) > 0) {
941 // Try to load all raw templates
942 foreach ($this->rawTemplates as $key => $template) {
945 $this->loadHtmlTemplate($template);
947 // Remember it's contents
948 $this->rawTemplates[$template] = $this->getRawTemplateData();
950 // Remove it from the loader list
951 unset($this->rawTemplates[$key]);
953 // Remember this template for recursion detection
954 // RECURSIVE PROTECTION!
955 array_push($this->loadedTemplates, $template);
956 } catch (FileNotFoundException $e) {
957 // This template was never found. We silently ignore it
958 unset($this->rawTemplates[$key]);
965 * Assign all found template variables
967 * @param $varMatches An array full of variable/value pairs.
969 * @todo Unfinished work or don't die here.
971 private function assignAllVariables (array $varMatches) {
973 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
975 // Search for all variables
976 foreach ($varMatches[1] as $key => $var) {
977 // Replace all dashes to underscores to match variables with configuration entries
978 $var = trim(StringUtils::convertDashesToUnderscores($var));
981 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
983 // Detect leading equals
984 if (substr($varMatches[2][$key], 0, 1) == '=') {
985 // Remove and cast it
986 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
989 // Do we have some quotes left and right side? Then it is free text
990 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
991 // Free string detected! Which we can assign directly
992 $this->assignVariable($var, $varMatches[3][$key]);
993 } elseif (!empty($varMatches[2][$key])) {
994 // @TODO Non-string found so we need some deeper analysis...
995 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
1001 * Compiles all loaded raw templates
1003 * @param $templateMatches See method analyzeTemplate() for details
1006 private function compileRawTemplateData (array $templateMatches) {
1008 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1010 // Are some code-templates found which we need to compile?
1011 if (count($this->loadedRawData) > 0) {
1012 // Then compile all!
1013 foreach ($this->loadedRawData as $template => $code) {
1015 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1017 // Is this template already compiled?
1018 if (in_array($template, $this->compiledTemplates)) {
1020 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1024 // Search for the template
1025 $foundIndex = array_search($template, $templateMatches[1]);
1027 // Lookup the matching variable data
1028 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1029 // Split it up with another reg. exp. into variable=value pairs
1030 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1031 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1033 // Assign all variables
1034 $this->assignAllVariables($varMatches);
1035 } // END - if (isset($templateMatches ...
1037 // Compile the loaded template
1038 $this->compileCode($code, $template);
1039 } // END - foreach ($this->loadedRawData ...
1041 // Insert all templates
1042 $this->insertAllTemplates($templateMatches);
1043 } // END - if (count($this->loadedRawData) ...
1047 * Inserts all raw templates into their respective variables
1051 private function insertRawTemplates () {
1052 // Load all templates
1053 foreach ($this->rawTemplates as $template => $content) {
1054 // Set the template as a variable with the content
1055 $this->assignVariable($template, $content);
1060 * Finalizes the compilation of all template variables
1064 private function finalizeVariableCompilation () {
1066 $content = $this->getRawTemplateData();
1067 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1069 // Do we have the stack?
1070 if (!$this->isVarStackSet('general')) {
1071 // Abort here silently
1072 // @TODO This silent abort should be logged, maybe.
1076 // Walk through all variables
1077 foreach ($this->getVarStack('general') as $currEntry) {
1078 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1079 // Replace all [$var] or {?$var?} with the content
1080 // @TODO Old behaviour, will become obsolete!
1081 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1083 // @TODO Yet another old way
1084 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1086 // The new behaviour
1087 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1090 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1092 // Set the content back
1093 $this->setRawTemplateData($content);
1097 * Load a specified HTML template into the engine
1099 * @param $template The web template we shall load which is located in
1103 public function loadHtmlTemplate ($template) {
1104 // Set template type
1105 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1107 // Load the special template
1108 $this->loadTemplate($template);
1112 * Assign (add) a given variable with a value
1114 * @param $variableName The variable we are looking for
1115 * @param $value The value we want to store in the variable
1117 * @throws InvalidArgumentException If the variable name is left empty
1119 public final function assignVariable ($variableName, $value) {
1120 // Replace all dashes to underscores to match variables with configuration entries
1121 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1123 // Empty variable found?
1124 if (empty($variableName)) {
1125 // Throw an exception
1126 throw new InvalidArgumentException('Parameter "variableName" is empty');
1129 // First search for the variable if it was already added
1130 $index = $this->getVariableIndex($variableName);
1133 if ($index === false) {
1134 // Add it to the stack
1135 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1136 $this->addVariable($variableName, $value);
1137 } elseif (!empty($value)) {
1138 // Modify the stack entry
1139 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1140 $this->modifyVariable($variableName, $value);
1145 * Removes a given variable
1147 * @param $variableName The variable we are looking for
1148 * @param $variableGroup Name of variable group (default: 'general')
1151 public final function removeVariable ($variableName, $variableGroup = 'general') {
1152 // First search for the variable if it was already added
1153 $index = $this->getVariableIndex($variableName, $variableGroup);
1156 if ($index !== false) {
1157 // Remove this variable
1158 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1159 $this->unsetVariableStackOffset($index, $variableGroup);
1164 * Assigns the last loaded raw template content with a given variable
1166 * @param $templateName Name of the template we want to assign
1167 * @param $variableName Name of the variable we want to assign
1170 public function assignTemplateWithVariable ($templateName, $variableName) {
1171 // Get the content from last loaded raw template
1172 $content = $this->getRawTemplateData();
1174 // Assign the variable
1175 $this->assignVariable($variableName, $content);
1177 // Purge raw content
1178 $this->setRawTemplateData('');
1182 * Assign a given congfiguration variable with a value
1184 * @param $variableName The configuration variable we want to assign
1187 public function assignConfigVariable ($variableName) {
1188 // Replace all dashes to underscores to match variables with configuration entries
1189 $variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
1191 // Sweet and simple...
1192 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1193 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1197 * Assigns a lot variables into the stack of currently loaded template.
1198 * This method should only be used in very rare circumstances, e.g. when
1199 * you have to copy a whole set of variables into the template engine.
1200 * Before you use this method, please make sure you have considered all
1201 * other possiblities.
1203 * @param $variables An array with variables to be assigned
1206 public function assignMultipleVariables (array $variables) {
1208 foreach ($variables as $name => $value) {
1209 // Set variable with name for 'config' group
1210 $this->assignVariable($name, $value);
1215 * Assigns all the application data with template variables
1219 public function assignApplicationData () {
1220 // Get application instance
1221 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1223 // Get long name and assign it
1224 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1226 // Get short name and assign it
1227 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1229 // Get version number and assign it
1230 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1232 // Assign extra application-depending data
1233 $applicationInstance->assignExtraTemplateData($this);
1237 * Load a specified code template into the engine
1239 * @param $template The code template we shall load which is
1240 * located in 'code' by default
1243 public function loadCodeTemplate ($template) {
1244 // Set template type
1245 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1247 // Load the special template
1248 $this->loadTemplate($template);
1252 * Load a specified email template into the engine
1254 * @param $template The email template we shall load which is
1255 * located in 'emails' by default
1258 public function loadEmailTemplate ($template) {
1259 // Set template type
1260 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1262 // Load the special template
1263 $this->loadTemplate($template);
1267 * Compiles configuration place-holders in all variables. This 'walks'
1268 * through the variable group 'general'. It interprets all values from that
1269 * variables as configuration entries after compiling them.
1273 public final function compileConfigInVariables () {
1274 // Do we have the stack?
1275 if (!$this->isVarStackSet('general')) {
1276 // Abort here silently
1277 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1281 // Iterate through all general variables
1282 foreach ($this->getVarStack('general') as $index => $currVariable) {
1283 // Compile the value
1284 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1287 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1289 // Remove it from stack
1290 $this->removeVariable($currVariable['name'], 'general');
1291 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1293 // Is it a configuration key?
1294 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1295 // The value itself is a configuration entry
1296 $this->assignConfigVariable($value);
1298 // Re-assign the value directly
1299 $this->assignVariable($currVariable['name'], $value);
1305 * Compile all variables by inserting their respective values
1308 * @todo Make this code some nicer...
1310 public final function compileVariables () {
1311 // Initialize the $content array
1312 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1315 // Iterate through all general variables
1316 foreach ($this->getVarStack('general') as $currVariable) {
1317 // Transfer it's name/value combination to the $content array
1318 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1319 $dummy[$currVariable['name']] = $currVariable['value'];
1322 // Set the new variable (don't remove the second dollar!)
1323 $$validVar = $dummy;
1325 // Remove some variables
1327 unset($currVariable);
1329 // Run the compilation three times to get content from helper classes in
1332 // Finalize the compilation of template variables
1333 $this->finalizeVariableCompilation();
1335 // Prepare the eval() command for comiling the template
1336 $eval = sprintf('$result = "%s";',
1337 addslashes($this->getRawTemplateData())
1340 // This loop does remove the backslashes (\) in PHP parameters
1341 while (strpos($eval, $this->codeBegin) !== false) {
1342 // Get left part before "<?"
1343 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1345 // Get all from right of "<?"
1346 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1348 // Cut middle part out and remove escapes
1349 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1350 $evalMiddle = stripslashes($evalMiddle);
1352 // Remove the middle part from right one
1353 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1355 // And put all together
1356 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1359 // Prepare PHP code for eval() command
1360 $eval = str_replace(
1369 // Run the constructed command. This will "compile" all variables in
1372 // Goes something wrong?
1373 if ((!isset($result)) || (empty($result))) {
1374 // Output eval command
1375 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1377 // Output backtrace here
1378 $this->debugBackTrace();
1381 // Set raw template data
1382 $this->setRawTemplateData($result);
1386 // Final variable assignment
1387 $this->finalizeVariableCompilation();
1389 // Set the new content
1390 $this->setCompiledData($this->getRawTemplateData());
1394 * Compile all required templates into the current loaded one
1397 * @throws UnexpectedTemplateTypeException If the template type is
1399 * @throws InvalidArrayCountException If an unexpected array
1400 * count has been found
1402 public function compileTemplate () {
1403 // Get code type to make things shorter
1404 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1406 // We will only work with template type "code" from configuration
1407 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1409 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1412 // Get the raw data.
1413 $rawData = $this->getRawTemplateData();
1415 // Remove double spaces and trim leading/trailing spaces
1416 $rawData = trim(str_replace(' ', ' ', $rawData));
1418 // Search for raw variables
1419 $this->extractVariablesFromRawData($rawData);
1421 // Search for code-tags which are {? ?}
1422 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1425 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1427 // Analyze the matches array
1428 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1429 // Entries are found:
1431 // The main analysis
1432 $this->analyzeTemplate($templateMatches);
1434 // Compile raw template data
1435 $this->compileRawTemplateData($templateMatches);
1437 // Are there some raw templates left for loading?
1438 $this->loadExtraRawTemplates();
1440 // Are some raw templates found and loaded?
1441 if (count($this->rawTemplates) > 0) {
1442 // Insert all raw templates
1443 $this->insertRawTemplates();
1445 // Remove the raw template content as well
1446 $this->setRawTemplateData('');
1448 } // END - if($templateMatches ...
1452 * Loads a given view helper (by name)
1454 * @param $helperName The helper's name
1457 protected function loadViewHelper ($helperName) {
1458 // Is this view helper loaded?
1459 if (!isset($this->helpers[$helperName])) {
1460 // Create a class name
1461 $className = self::convertToClassName($helperName) . 'ViewHelper';
1463 // Generate new instance
1464 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1467 // Return the requested instance
1468 return $this->helpers[$helperName];
1472 * Transfers the content of this template engine to a given response instance
1474 * @param $responseInstance An instance of a Responseable class
1477 public function transferToResponse (Responseable $responseInstance) {
1478 // Get the content and set it in response class
1479 $responseInstance->writeToBody($this->getCompiledData());
1483 * "Compiles" a variable by replacing {?var?} with it's content
1485 * @param $rawCode Raw code to compile
1486 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1487 * @return $rawCode Compile code with inserted variable value
1489 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1490 // Find the variables
1491 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1492 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1494 // Compile all variables
1495 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1496 foreach ($varMatches[0] as $match) {
1497 // Add variable tags around it
1498 $varCode = '{?' . $match . '?}';
1501 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1503 // Is the variable found in code? (safes some calls)
1504 if (strpos($rawCode, $varCode) !== false) {
1506 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1508 // Use $match as new value or $value from read variable?
1509 if ($setMatchAsCode === true) {
1511 $rawCode = str_replace($varCode, $match, $rawCode);
1513 // Read the variable
1514 $value = $this->readVariable($match);
1517 $rawCode = str_replace($varCode, $value, $rawCode);
1522 // Return the compiled data
1523 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1528 * Getter for variable group array
1530 * @return $variableGroups All variable groups
1532 public final function getVariableGroups () {
1533 return $this->variableGroups;
1537 * Renames a variable in code and in stack
1539 * @param $oldName Old name of variable
1540 * @param $newName New name of variable
1543 public function renameVariable ($oldName, $newName) {
1544 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1545 // Get raw template code
1546 $rawData = $this->getRawTemplateData();
1549 $rawData = str_replace($oldName, $newName, $rawData);
1551 // Set the code back
1552 $this->setRawTemplateData($rawData);
1556 * Renders the given XML content
1558 * @param $content Valid XML content or if not set the current loaded raw content
1560 * @throws XmlParserException If an XML error was found
1562 public function renderXmlContent ($content = NULL) {
1563 // Is the content set?
1564 if (is_null($content)) {
1565 // Get current content
1566 $content = $this->getRawTemplateData();
1569 // Get a XmlParser instance
1570 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1572 // Check if XML compacting is enabled
1573 if ($this->isXmlCompactingEnabled()) {
1574 // Yes, so get a decorator class for transparent compacting
1575 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1578 // Parse the XML document
1579 $parserInstance->parseXmlContent($content);
1583 * Enables or disables language support
1585 * @param $languageSupport New language support setting
1588 public final function enableLanguageSupport ($languageSupport = true) {
1589 $this->languageSupport = (bool) $languageSupport;
1593 * Checks whether language support is enabled
1595 * @return $languageSupport Whether language support is enabled or disabled
1597 public final function isLanguageSupportEnabled () {
1598 return $this->languageSupport;
1602 * Enables or disables XML compacting
1604 * @param $xmlCompacting New XML compacting setting
1607 public final function enableXmlCompacting ($xmlCompacting = true) {
1608 $this->xmlCompacting = (bool) $xmlCompacting;
1612 * Checks whether XML compacting is enabled
1614 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1616 public final function isXmlCompactingEnabled () {
1617 return $this->xmlCompacting;
1621 * Removes all commentd, tabs and new-line characters to compact the content
1623 * @param $uncompactedContent The uncompacted content
1624 * @return $compactedContent The compacted content
1626 public function compactContent ($uncompactedContent) {
1627 // First, remove all tab/new-line/revert characters
1628 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1630 // Then regex all comments like <!-- //--> away
1631 preg_match_all($this->regExpComments, $compactedContent, $matches);
1633 // Do we have entries?
1634 if (isset($matches[0][0])) {
1636 foreach ($matches[0] as $match) {
1638 $compactedContent = str_replace($match, '', $compactedContent);
1642 // Set the content again
1643 $this->setRawTemplateData($compactedContent);
1645 // Return compacted content
1646 return $compactedContent;