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\Response\Responseable;
15 use \InvalidArgumentException;
19 * A generic template engine
21 * @author Roland Haeder <webmaster@shipsimu.org>
23 <<<<<<< HEAD:framework/main/classes/template/class_BaseTemplateEngine.php
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
26 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
27 >>>>>>> Some updates::inc/main/classes/template/class_BaseTemplateEngine.php
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
46 * The local path name where all templates and sub folders for special
47 * templates are stored. We will internally determine the language plus
48 * "html" for web templates or "emails" for email templates
50 private $templateBasePath = '';
55 private $templateType = 'html';
58 * The extension for web and email templates (not compiled templates)
60 private $templateExtension = '.tpl';
63 * The extension for code templates (not compiled templates)
65 private $codeExtension = '.ctp';
68 * Path relative to $templateBasePath and language code for compiled code-templates
70 private $compileOutputPath = 'templates/_compiled/';
73 * The path name for all templates
75 private $genericBasePath = 'templates/';
78 * The raw (maybe uncompiled) template
80 private $rawTemplateData = '';
83 * Template data with compiled-in variables
85 private $compiledData = '';
88 * The last loaded template's file instance (SplFileInfo)
90 private $lastTemplate = NULL;
93 * The variable stack for the templates
95 private $varStack = array();
98 * Loaded templates for recursive protection and detection
100 private $loadedTemplates = array();
103 * Compiled templates for recursive protection and detection
105 private $compiledTemplates = array();
108 * Loaded raw template data
110 private $loadedRawData = NULL;
113 * Raw templates which are linked in code templates
115 private $rawTemplates = NULL;
118 * A regular expression for variable=value pairs
120 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
123 * A regular expression for filtering out code tags
125 * E.g.: {?template:variable=value;var2=value2;[...]?}
127 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
130 * A regular expression to find template comments like <!-- Comment here //-->
132 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
137 private $helpers = array();
140 * Current variable group
142 private $currGroup = 'general';
145 * All template groups except "general"
147 private $variableGroups = array();
152 private $codeBegin = '<?php';
157 private $codeEnd = '?>';
160 * Language support is enabled by default
162 private $languageSupport = true;
165 * XML compacting is disabled by default
167 private $xmlCompacting = false;
169 // Exception codes for the template engine
170 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
171 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
172 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
173 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
176 * Protected constructor
178 * @param $className Name of the class
181 protected function __construct ($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 ($variableName, $variableGroup = NULL) {
200 // Replace all dashes to underscores to match variables with configuration entries
201 $variableName = trim(self::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 ($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 ($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 ($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 ($variableName, $variableGroup = NULL) {
275 // Replace all dashes to underscores to match variables with configuration entries
276 $variableName = trim(self::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 ($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 ($groupName, $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 ($variableName, $value) {
363 // Replace all dashes to underscores to match variables with configuration entries
364 $variableName = trim(self::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 ($variableGroup, $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 ($variableName, $value) {
400 // Replace all dashes to underscores to match variables with configuration entries
401 $variableName = trim(self::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 ($variableGroup, $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 ($variableGroup, $variableName, $value) {
439 // Replace all dashes to underscores to match variables with configuration entries
440 $variableName = trim(self::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] = array();
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 ($variableName, $value) {
470 // Replace all dashes to underscores to match variables with configuration entries
471 $variableName = trim(self::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 ($templateType) {
491 $this->templateType = (string) $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 ($templateBasePath) {
530 $this->templateBasePath = (string) $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 ($templateExtension) {
562 $this->templateExtension = (string) $templateExtension;
566 * Setter for code template extension
568 * @param $codeExtension The file extension for all uncompiled
572 protected final function setCodeTemplateExtension ($codeExtension) {
574 $this->codeExtension = (string) $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 ($compileOutputPath) {
608 $this->compileOutputPath = (string) $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 ($index, $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 ($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 = (string) $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[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
655 return $this->rawTemplateData;
659 * Private setter for compiled templates
663 private final function setCompiledData ($compiledData) {
664 // And store it in this class
665 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
666 $this->compiledData = (string) $compiledData;
670 * Getter for compiled templates, must be public for e.g. Mailer classes.
672 * @return $compiledData Compiled template data
674 public final function getCompiledData () {
675 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
676 return $this->compiledData;
680 * Private loader for all template types
682 * @param $templateName The template we shall load
683 * @param $extOther An other extension to use
685 * @throws FileNotFoundException If the template was not found
687 protected function loadTemplate ($templateName, $extOther = '') {
688 // Get extension for the template if empty
689 if (empty($extOther)) {
690 // None provided, so get the raw one
691 $ext = $this->getRawTemplateExtension();
694 $ext = (string) $extOther;
698 * Construct the FQFN for the template without language as language is
699 * now entirely done by php_intl. These old thing with language-based
700 * template paths comes from an older time.
702 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
703 $this->getTemplateBasePath(),
704 $this->getGenericBasePath(),
705 $this->getTemplateType(),
707 (string) $templateName,
713 // Load the raw template data
714 $this->loadRawTemplateData($fileInstance);
715 } catch (FileNotFoundException $e) {
716 // If we shall load a code-template we need to switch the file extension
717 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
718 // Switch over to the code-template extension and try it again
719 $ext = $this->getCodeTemplateExtension();
722 $this->loadTemplate($templateName, $ext);
725 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
732 * A private loader for raw template names
734 * @param $fileInstance An instance of a SplFileInfo class
737 private function loadRawTemplateData (SplFileInfo $fileInstance) {
738 // Some debug code to look on the file which is being loaded
739 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: fileInstance=' . $fileInstance);
741 // Load the raw template
742 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
744 // Store the template's contents into this class
745 $this->setRawTemplateData($rawTemplateData);
747 // Remember the template's file instance
748 $this->setLastTemplate($fileInstance);
752 * Try to assign an extracted template variable as a "content" or 'config'
755 * @param $variableName The variable's name (shall be content or config)
757 * @param $variableName The variable we want to assign
760 private function assignTemplateVariable ($variableName, $var) {
761 // Replace all dashes to underscores to match variables with configuration entries
762 $variableName = trim(self::convertDashesToUnderscores($variableName));
765 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
767 // Is it not a config variable?
768 if ($variableName != 'config') {
769 // Regular template variables
770 $this->assignVariable($variableName, '');
772 // Configuration variables
773 $this->assignConfigVariable($var);
778 * Extract variables from a given raw data stream
780 * @param $rawData The raw template data we shall analyze
783 private function extractVariablesFromRawData ($rawData) {
785 $rawData = (string) $rawData;
787 // Search for variables
788 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
791 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
793 // Did we find some variables?
794 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
795 // Initialize all missing variables
796 foreach ($variableMatches[3] as $key => $var) {
798 $variableName = $variableMatches[1][$key];
800 // Workarround: Do not assign empty variables
802 // Try to assign it, empty strings are being ignored
803 $this->assignTemplateVariable($variableName, $var);
810 * Main analysis of the loaded template
812 * @param $templateMatches Found template place-holders, see below
815 *---------------------------------
816 * Structure of $templateMatches:
817 *---------------------------------
818 * [0] => Array - An array with all full matches
819 * [1] => Array - An array with left part (before the ':') of a match
820 * [2] => Array - An array with right part of a match including ':'
821 * [3] => Array - An array with right part of a match excluding ':'
823 private function analyzeTemplate (array $templateMatches) {
824 // Backup raw template data
825 $backup = $this->getRawTemplateData();
827 // Initialize some arrays
828 if (is_null($this->loadedRawData)) {
830 $this->loadedRawData = array();
831 $this->rawTemplates = array();
834 // Load all requested templates
835 foreach ($templateMatches[1] as $template) {
836 // Load and compile only templates which we have not yet loaded
837 // RECURSIVE PROTECTION! BE CAREFUL HERE!
838 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
840 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
842 // Template not found, but maybe variable assigned?
843 if ($this->getVariableIndex($template) !== false) {
844 // Use that content here
845 $this->loadedRawData[$template] = $this->readVariable($template);
847 // Recursive protection:
848 array_push($this->loadedTemplates, $template);
850 // Then try to search for code-templates
852 // Load the code template and remember it's contents
853 $this->loadCodeTemplate($template);
854 $this->loadedRawData[$template] = $this->getRawTemplateData();
856 // Remember this template for recursion detection
857 // RECURSIVE PROTECTION!
858 array_push($this->loadedTemplates, $template);
859 } catch (FileNotFoundException $e) {
860 // Even this is not done... :/
861 array_push($this->rawTemplates, $template);
867 // Restore the raw template data
868 $this->setRawTemplateData($backup);
872 * Compile a given raw template code and remember it for later usage
874 * @param $code The raw template code
875 * @param $template The template's name
878 private function compileCode ($code, $template) {
879 // Is this template already compiled?
880 if (in_array($template, $this->compiledTemplates)) {
885 // Remember this template being compiled
886 array_push($this->compiledTemplates, $template);
888 // Compile the loaded code in five steps:
890 // 1. Backup current template data
891 $backup = $this->getRawTemplateData();
893 // 2. Set the current template's raw data as the new content
894 $this->setRawTemplateData($code);
896 // 3. Compile the template data
897 $this->compileTemplate();
899 // 4. Remember it's contents
900 $this->loadedRawData[$template] = $this->getRawTemplateData();
902 // 5. Restore the previous raw content from backup variable
903 $this->setRawTemplateData($backup);
907 * Insert all given and loaded templates by running through all loaded
908 * codes and searching for their place-holder in the main template
910 * @param $templateMatches See method analyzeTemplate()
913 private function insertAllTemplates (array $templateMatches) {
914 // Run through all loaded codes
915 foreach ($this->loadedRawData as $template => $code) {
917 // Search for the template
918 $foundIndex = array_search($template, $templateMatches[1]);
920 // Lookup the matching template replacement
921 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
923 // Get the current raw template
924 $rawData = $this->getRawTemplateData();
926 // Replace the space holder with the template code
927 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
929 // Set the new raw data
930 $this->setRawTemplateData($rawData);
936 * Load all extra raw templates
940 private function loadExtraRawTemplates () {
941 // Are there some raw templates we need to load?
942 if (count($this->rawTemplates) > 0) {
943 // Try to load all raw templates
944 foreach ($this->rawTemplates as $key => $template) {
947 $this->loadHtmlTemplate($template);
949 // Remember it's contents
950 $this->rawTemplates[$template] = $this->getRawTemplateData();
952 // Remove it from the loader list
953 unset($this->rawTemplates[$key]);
955 // Remember this template for recursion detection
956 // RECURSIVE PROTECTION!
957 array_push($this->loadedTemplates, $template);
958 } catch (FileNotFoundException $e) {
959 // This template was never found. We silently ignore it
960 unset($this->rawTemplates[$key]);
967 * Assign all found template variables
969 * @param $varMatches An array full of variable/value pairs.
971 * @todo Unfinished work or don't die here.
973 private function assignAllVariables (array $varMatches) {
975 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
977 // Search for all variables
978 foreach ($varMatches[1] as $key => $var) {
979 // Replace all dashes to underscores to match variables with configuration entries
980 $var = trim(self::convertDashesToUnderscores($var));
983 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
985 // Detect leading equals
986 if (substr($varMatches[2][$key], 0, 1) == '=') {
987 // Remove and cast it
988 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
991 // Do we have some quotes left and right side? Then it is free text
992 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
993 // Free string detected! Which we can assign directly
994 $this->assignVariable($var, $varMatches[3][$key]);
995 } elseif (!empty($varMatches[2][$key])) {
996 // @TODO Non-string found so we need some deeper analysis...
997 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
1003 * Compiles all loaded raw templates
1005 * @param $templateMatches See method analyzeTemplate() for details
1008 private function compileRawTemplateData (array $templateMatches) {
1010 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1012 // Are some code-templates found which we need to compile?
1013 if (count($this->loadedRawData) > 0) {
1014 // Then compile all!
1015 foreach ($this->loadedRawData as $template => $code) {
1017 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1019 // Is this template already compiled?
1020 if (in_array($template, $this->compiledTemplates)) {
1022 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1026 // Search for the template
1027 $foundIndex = array_search($template, $templateMatches[1]);
1029 // Lookup the matching variable data
1030 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1031 // Split it up with another reg. exp. into variable=value pairs
1032 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1033 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1035 // Assign all variables
1036 $this->assignAllVariables($varMatches);
1037 } // END - if (isset($templateMatches ...
1039 // Compile the loaded template
1040 $this->compileCode($code, $template);
1041 } // END - foreach ($this->loadedRawData ...
1043 // Insert all templates
1044 $this->insertAllTemplates($templateMatches);
1045 } // END - if (count($this->loadedRawData) ...
1049 * Inserts all raw templates into their respective variables
1053 private function insertRawTemplates () {
1054 // Load all templates
1055 foreach ($this->rawTemplates as $template => $content) {
1056 // Set the template as a variable with the content
1057 $this->assignVariable($template, $content);
1062 * Finalizes the compilation of all template variables
1066 private function finalizeVariableCompilation () {
1068 $content = $this->getRawTemplateData();
1069 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1071 // Do we have the stack?
1072 if (!$this->isVarStackSet('general')) {
1073 // Abort here silently
1074 // @TODO This silent abort should be logged, maybe.
1078 // Walk through all variables
1079 foreach ($this->getVarStack('general') as $currEntry) {
1080 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1081 // Replace all [$var] or {?$var?} with the content
1082 // @TODO Old behaviour, will become obsolete!
1083 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1085 // @TODO Yet another old way
1086 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1088 // The new behaviour
1089 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1092 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1094 // Set the content back
1095 $this->setRawTemplateData($content);
1099 * Load a specified HTML template into the engine
1101 * @param $template The web template we shall load which is located in
1105 public function loadHtmlTemplate ($template) {
1106 // Set template type
1107 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1109 // Load the special template
1110 $this->loadTemplate($template);
1114 * Assign (add) a given variable with a value
1116 * @param $variableName The variable we are looking for
1117 * @param $value The value we want to store in the variable
1119 * @throws InvalidArgumentException If the variable name is left empty
1121 public final function assignVariable ($variableName, $value) {
1122 // Replace all dashes to underscores to match variables with configuration entries
1123 $variableName = trim(self::convertDashesToUnderscores($variableName));
1125 // Empty variable found?
1126 if (empty($variableName)) {
1127 // Throw an exception
1128 throw new InvalidArgumentException('Parameter "variableName" is empty');
1131 // First search for the variable if it was already added
1132 $index = $this->getVariableIndex($variableName);
1135 if ($index === false) {
1136 // Add it to the stack
1137 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1138 $this->addVariable($variableName, $value);
1139 } elseif (!empty($value)) {
1140 // Modify the stack entry
1141 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1142 $this->modifyVariable($variableName, $value);
1147 * Removes a given variable
1149 * @param $variableName The variable we are looking for
1150 * @param $variableGroup Name of variable group (default: 'general')
1153 public final function removeVariable ($variableName, $variableGroup = 'general') {
1154 // First search for the variable if it was already added
1155 $index = $this->getVariableIndex($variableName, $variableGroup);
1158 if ($index !== false) {
1159 // Remove this variable
1160 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1161 $this->unsetVariableStackOffset($index, $variableGroup);
1166 * Assigns the last loaded raw template content with a given variable
1168 * @param $templateName Name of the template we want to assign
1169 * @param $variableName Name of the variable we want to assign
1172 public function assignTemplateWithVariable ($templateName, $variableName) {
1173 // Get the content from last loaded raw template
1174 $content = $this->getRawTemplateData();
1176 // Assign the variable
1177 $this->assignVariable($variableName, $content);
1179 // Purge raw content
1180 $this->setRawTemplateData('');
1184 * Assign a given congfiguration variable with a value
1186 * @param $variableName The configuration variable we want to assign
1189 public function assignConfigVariable ($variableName) {
1190 // Replace all dashes to underscores to match variables with configuration entries
1191 $variableName = trim(self::convertDashesToUnderscores($variableName));
1193 // Sweet and simple...
1194 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1195 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1199 * Assigns a lot variables into the stack of currently loaded template.
1200 * This method should only be used in very rare circumstances, e.g. when
1201 * you have to copy a whole set of variables into the template engine.
1202 * Before you use this method, please make sure you have considered all
1203 * other possiblities.
1205 * @param $variables An array with variables to be assigned
1208 public function assignMultipleVariables (array $variables) {
1210 foreach ($variables as $name => $value) {
1211 // Set variable with name for 'config' group
1212 $this->assignVariable($name, $value);
1217 * Assigns all the application data with template variables
1219 * @param $applicationInstance A manageable application instance
1222 public function assignApplicationData (ManageableApplication $applicationInstance) {
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;