3 namespace CoreFramework\Template\Engine;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Generic\EmptyVariableException;
8 use CoreFramework\Manager\ManageableApplication;
9 use CoreFramework\Object\BaseFrameworkSystem;
10 use CoreFramework\Response\Responseable;
13 * A generic template engine
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 class BaseTemplateEngine extends BaseFrameworkSystem {
36 * The local path name where all templates and sub folders for special
37 * templates are stored. We will internally determine the language plus
38 * "html" for web templates or "emails" for email templates
40 private $templateBasePath = '';
45 private $templateType = 'html';
48 * The extension for web and email templates (not compiled templates)
50 private $templateExtension = '.tpl';
53 * The extension for code templates (not compiled templates)
55 private $codeExtension = '.ctp';
58 * Path relative to $templateBasePath and language code for compiled code-templates
60 private $compileOutputPath = 'templates/_compiled/';
63 * The path name for all templates
65 private $genericBasePath = 'templates/';
68 * The raw (maybe uncompiled) template
70 private $rawTemplateData = '';
73 * Template data with compiled-in variables
75 private $compiledData = '';
78 * The last loaded template's FQFN for debugging the engine
80 private $lastTemplate = '';
83 * The variable stack for the templates
85 private $varStack = array();
88 * Loaded templates for recursive protection and detection
90 private $loadedTemplates = array();
93 * Compiled templates for recursive protection and detection
95 private $compiledTemplates = array();
98 * Loaded raw template data
100 private $loadedRawData = NULL;
103 * Raw templates which are linked in code templates
105 private $rawTemplates = NULL;
108 * A regular expression for variable=value pairs
110 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
113 * A regular expression for filtering out code tags
115 * E.g.: {?template:variable=value;var2=value2;[...]?}
117 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
120 * A regular expression to find template comments like <!-- Comment here //-->
122 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
127 private $helpers = array();
130 * Current variable group
132 private $currGroup = 'general';
135 * All template groups except "general"
137 private $variableGroups = array();
142 private $codeBegin = '<?php';
147 private $codeEnd = '?>';
150 * Language support is enabled by default
152 private $languageSupport = TRUE;
155 * XML compacting is disabled by default
157 private $xmlCompacting = FALSE;
159 // Exception codes for the template engine
160 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
161 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
162 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
163 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
166 * Protected constructor
168 * @param $className Name of the class
171 protected function __construct ($className) {
172 // Call parent constructor
173 parent::__construct($className);
175 // Init file I/O instance
176 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
179 $this->setFileIoInstance($ioInstance);
183 * Search for a variable in the stack
185 * @param $variableName The variable we are looking for
186 * @param $variableGroup Optional variable group to look in
187 * @return $index FALSE means not found, >=0 means found on a specific index
189 private function getVariableIndex ($variableName, $variableGroup = NULL) {
190 // Replace all dashes to underscores to match variables with configuration entries
191 $variableName = trim(self::convertDashesToUnderscores($variableName));
193 // First everything is not found
196 // If the stack is NULL, use the current group
197 if (is_null($variableGroup)) {
199 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
200 $variableGroup = $this->currGroup;
203 // Is the group there?
204 if ($this->isVarStackSet($variableGroup)) {
206 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
207 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
208 // Is the entry found?
209 if ($currEntry['name'] == $variableName) {
211 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
218 // Return the current position
223 * Checks whether the given variable group is set
225 * @param $variableGroup Variable group to check
226 * @return $isSet Whether the given variable group is set
228 protected final function isVarStackSet ($variableGroup) {
230 $isSet = isset($this->varStack[$variableGroup]);
237 * Getter for given variable group
239 * @param $variableGroup Variable group to check
240 * @return $varStack Found variable group
242 public final function getVarStack ($variableGroup) {
243 return $this->varStack[$variableGroup];
247 * Setter for given variable group
249 * @param $variableGroup Variable group to check
250 * @param $varStack Variable stack to check
253 protected final function setVarStack ($variableGroup, array $varStack) {
254 $this->varStack[$variableGroup] = $varStack;
258 * Return a content of a variable or null if not found
260 * @param $variableName The variable we are looking for
261 * @param $variableGroup Optional variable group to look in
262 * @return $content Content of the variable or null if not found
264 protected function readVariable ($variableName, $variableGroup = NULL) {
265 // Replace all dashes to underscores to match variables with configuration entries
266 $variableName = trim(self::convertDashesToUnderscores($variableName));
268 // First everything is not found
271 // If the stack is NULL, use the current group
272 if (is_null($variableGroup)) {
274 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
275 $variableGroup = $this->currGroup;
278 // Get variable index
279 $found = $this->getVariableIndex($variableName, $variableGroup);
281 // Is the variable found?
282 if ($found !== FALSE) {
284 $content = $this->getVariableValue($variableGroup, $found);
287 // Return the current position
288 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
293 * Add a variable to the stack
295 * @param $variableName Name of variable to add
296 * @param $value Value we want to store in the variable
299 private function addVariable ($variableName, $value) {
300 // Set general variable group
301 $this->setVariableGroup('general');
303 // Add it to the stack
304 $this->addGroupVariable($variableName, $value);
308 * Returns all variables of current group or empty array
310 * @return $result Whether array of found variables or empty array
312 private function readCurrentGroup () {
313 // Default is not found
316 // Is the group there?
317 if ($this->isVarStackSet($this->currGroup)) {
319 $result = $this->getVarStack($this->currGroup);
327 * Settter for variable group
329 * @param $groupName Name of variable group
330 * @param $add Whether add this group
333 public function setVariableGroup ($groupName, $add = TRUE) {
335 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
336 $this->currGroup = $groupName;
338 // Skip group 'general'
339 if (($groupName != 'general') && ($add === TRUE)) {
340 $this->variableGroups[$groupName] = 'OK';
346 * Adds a variable to current group
348 * @param $variableName Variable to set
349 * @param $value Value to store in variable
352 public function addGroupVariable ($variableName, $value) {
353 // Replace all dashes to underscores to match variables with configuration entries
354 $variableName = trim(self::convertDashesToUnderscores($variableName));
357 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
359 // Get current variables in group
360 $currVars = $this->readCurrentGroup();
362 // Append our variable
363 array_push($currVars, $this->generateVariableArray($variableName, $value));
365 // Add it to the stack
366 $this->setVarStack($this->currGroup, $currVars);
370 * Getter for variable value, throws a NoVariableException if the variable is not found
372 * @param $variableGroup Variable group to use
373 * @param $index Index in variable array
374 * @return $value Value to set
376 private function getVariableValue ($variableGroup, $index) {
378 return $this->varStack[$variableGroup][$index]['value'];
382 * Modify an entry on the stack
384 * @param $variableName The variable we are looking for
385 * @param $value The value we want to store in the variable
387 * @throws NoVariableException If the given variable is not found
389 private function modifyVariable ($variableName, $value) {
390 // Replace all dashes to underscores to match variables with configuration entries
391 $variableName = trim(self::convertDashesToUnderscores($variableName));
393 // Get index for variable
394 $index = $this->getVariableIndex($variableName);
396 // Is the variable set?
397 if ($index === FALSE) {
398 // Unset variables cannot be modified
399 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
403 $this->setVariableValue($this->currGroup, $index, $value);
407 * Sets a variable value for given variable group and index
409 * @param $variableGroup Variable group to use
410 * @param $index Index in variable array
411 * @param $value Value to set
414 private function setVariableValue ($variableGroup, $index, $value) {
415 $this->varStack[$variableGroup][$index]['value'] = $value;
419 * Sets a variable within given group. This method does detect if the
420 * variable is already set. If so, the variable got modified, otherwise
423 * @param $variableGroup Variable group to use
424 * @param $variableName Variable to set
425 * @param $value Value to set
428 protected function setVariable ($variableGroup, $variableName, $value) {
429 // Replace all dashes to underscores to match variables with configuration entries
430 $variableName = trim(self::convertDashesToUnderscores($variableName));
432 // Get index for variable
433 $index = $this->getVariableIndex($variableName);
435 // Is the variable set?
436 if ($index === FALSE) {
437 // Is the stack there?
438 if (!isset($this->varStack[$variableGroup])) {
439 // Then initialize it here
440 $this->varStack[$variableGroup] = array();
444 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
447 $this->setVariableValue($this->currGroup, $index, $value);
452 * "Generates" (better returns) an array for all variables for given
453 * variable/value pay.
455 * @param $variableName Variable to set
456 * @param $value Value to set
457 * @return $varData Variable data array
459 private function generateVariableArray ($variableName, $value) {
460 // Replace all dashes to underscores to match variables with configuration entries
461 $variableName = trim(self::convertDashesToUnderscores($variableName));
463 // Generate the temporary array
465 'name' => $variableName,
474 * Setter for template type. Only 'html', 'emails' and 'compiled' should
477 * @param $templateType The current template's type
480 protected final function setTemplateType ($templateType) {
481 $this->templateType = (string) $templateType;
485 * Getter for template type
487 * @return $templateType The current template's type
489 public final function getTemplateType () {
490 return $this->templateType;
494 * Setter for the last loaded template's FQFN
496 * @param $template The last loaded template
499 private final function setLastTemplate ($template) {
500 $this->lastTemplate = (string) $template;
504 * Getter for the last loaded template's FQFN
506 * @return $template The last loaded template
508 private final function getLastTemplate () {
509 return $this->lastTemplate;
513 * Setter for base path
515 * @param $templateBasePath The relative base path for all templates
518 protected final function setTemplateBasePath ($templateBasePath) {
520 $this->templateBasePath = (string) $templateBasePath;
524 * Getter for base path
526 * @return $templateBasePath The relative base path for all templates
528 public final function getTemplateBasePath () {
530 return $this->templateBasePath;
534 * Getter for generic base path
536 * @return $templateBasePath The relative base path for all templates
538 public final function getGenericBasePath () {
540 return $this->genericBasePath;
544 * Setter for template extension
546 * @param $templateExtension The file extension for all uncompiled
550 protected final function setRawTemplateExtension ($templateExtension) {
552 $this->templateExtension = (string) $templateExtension;
556 * Setter for code template extension
558 * @param $codeExtension The file extension for all uncompiled
562 protected final function setCodeTemplateExtension ($codeExtension) {
564 $this->codeExtension = (string) $codeExtension;
568 * Getter for template extension
570 * @return $templateExtension The file extension for all uncompiled
573 public final function getRawTemplateExtension () {
575 return $this->templateExtension;
579 * Getter for code-template extension
581 * @return $codeExtension The file extension for all code-
584 public final function getCodeTemplateExtension () {
586 return $this->codeExtension;
590 * Setter for path of compiled templates
592 * @param $compileOutputPath The local base path for all compiled
596 protected final function setCompileOutputPath ($compileOutputPath) {
598 $this->compileOutputPath = (string) $compileOutputPath;
602 * Unsets the given offset in the variable group
604 * @param $index Index to unset
605 * @param $variableGroup Variable group (default: currGroup)
608 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
609 // Is the variable group not set?
610 if (is_null($variableGroup)) {
611 // Then set it to current
612 $variableGroup = $this->currGroup;
615 // Is the entry there?
616 if (!isset($this->varStack[$variableGroup][$index])) {
617 // Abort here, we need fixing!
618 $this->debugInstance();
622 unset($this->varStack[$variableGroup][$index]);
626 * Private setter for raw template data
628 * @param $rawTemplateData The raw data from the template
631 protected final function setRawTemplateData ($rawTemplateData) {
632 // And store it in this class
633 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
634 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
635 $this->rawTemplateData = (string) $rawTemplateData;
639 * Getter for raw template data
641 * @return $rawTemplateData The raw data from the template
643 public final function getRawTemplateData () {
644 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
645 return $this->rawTemplateData;
649 * Private setter for compiled templates
653 private final function setCompiledData ($compiledData) {
654 // And store it in this class
655 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
656 $this->compiledData = (string) $compiledData;
660 * Getter for compiled templates, must be public for e.g. Mailer classes.
662 * @return $compiledData Compiled template data
664 public final function getCompiledData () {
665 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
666 return $this->compiledData;
670 * Private loader for all template types
672 * @param $template The template we shall load
673 * @param $extOther An other extension to use
675 * @throws FileNotFoundException If the template was not found
677 protected function loadTemplate ($template, $extOther = '') {
678 // Get extension for the template if empty
679 if (empty($extOther)) {
680 // None provided, so get the raw one
681 $ext = $this->getRawTemplateExtension();
684 $ext = (string) $extOther;
688 * Construct the FQFN for the template without language as language is
689 * now entirely done by php_intl. These old thing with language-based
690 * template paths comes from an older time.
692 $fqfn = sprintf('%s%s%s%s/%s%s',
693 $this->getConfigInstance()->getConfigEntry('base_path'),
694 $this->getTemplateBasePath(),
695 $this->getGenericBasePath(),
696 $this->getTemplateType(),
703 // Load the raw template data
704 $this->loadRawTemplateData($fqfn);
705 } catch (FileNotFoundException $e) {
706 // If we shall load a code-template we need to switch the file extension
707 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
708 // Switch over to the code-template extension and try it again
709 $ext = $this->getCodeTemplateExtension();
712 $this->loadTemplate($template, $ext);
715 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
722 * A private loader for raw template names
724 * @param $fqfn The full-qualified file name for a template
727 private function loadRawTemplateData ($fqfn) {
728 // Some debug code to look on the file which is being loaded
729 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
731 // Load the raw template
732 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
734 // Store the template's contents into this class
735 $this->setRawTemplateData($rawTemplateData);
737 // Remember the template's FQFN
738 $this->setLastTemplate($fqfn);
742 * Try to assign an extracted template variable as a "content" or 'config'
745 * @param $variableName The variable's name (shall be content or config)
747 * @param $variableName The variable we want to assign
750 private function assignTemplateVariable ($variableName, $var) {
751 // Replace all dashes to underscores to match variables with configuration entries
752 $variableName = trim(self::convertDashesToUnderscores($variableName));
755 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
757 // Is it not a config variable?
758 if ($variableName != 'config') {
759 // Regular template variables
760 $this->assignVariable($variableName, '');
762 // Configuration variables
763 $this->assignConfigVariable($var);
768 * Extract variables from a given raw data stream
770 * @param $rawData The raw template data we shall analyze
773 private function extractVariablesFromRawData ($rawData) {
775 $rawData = (string) $rawData;
777 // Search for variables
778 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
781 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
783 // Did we find some variables?
784 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
785 // Initialize all missing variables
786 foreach ($variableMatches[3] as $key => $var) {
788 $variableName = $variableMatches[1][$key];
790 // Workarround: Do not assign empty variables
792 // Try to assign it, empty strings are being ignored
793 $this->assignTemplateVariable($variableName, $var);
800 * Main analysis of the loaded template
802 * @param $templateMatches Found template place-holders, see below
805 *---------------------------------
806 * Structure of $templateMatches:
807 *---------------------------------
808 * [0] => Array - An array with all full matches
809 * [1] => Array - An array with left part (before the ':') of a match
810 * [2] => Array - An array with right part of a match including ':'
811 * [3] => Array - An array with right part of a match excluding ':'
813 private function analyzeTemplate (array $templateMatches) {
814 // Backup raw template data
815 $backup = $this->getRawTemplateData();
817 // Initialize some arrays
818 if (is_null($this->loadedRawData)) {
820 $this->loadedRawData = array();
821 $this->rawTemplates = array();
824 // Load all requested templates
825 foreach ($templateMatches[1] as $template) {
826 // Load and compile only templates which we have not yet loaded
827 // RECURSIVE PROTECTION! BE CAREFUL HERE!
828 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
830 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
832 // Template not found, but maybe variable assigned?
833 if ($this->getVariableIndex($template) !== FALSE) {
834 // Use that content here
835 $this->loadedRawData[$template] = $this->readVariable($template);
837 // Recursive protection:
838 array_push($this->loadedTemplates, $template);
840 // Then try to search for code-templates
842 // Load the code template and remember it's contents
843 $this->loadCodeTemplate($template);
844 $this->loadedRawData[$template] = $this->getRawTemplateData();
846 // Remember this template for recursion detection
847 // RECURSIVE PROTECTION!
848 array_push($this->loadedTemplates, $template);
849 } catch (FileNotFoundException $e) {
850 // Even this is not done... :/
851 array_push($this->rawTemplates, $template);
857 // Restore the raw template data
858 $this->setRawTemplateData($backup);
862 * Compile a given raw template code and remember it for later usage
864 * @param $code The raw template code
865 * @param $template The template's name
868 private function compileCode ($code, $template) {
869 // Is this template already compiled?
870 if (in_array($template, $this->compiledTemplates)) {
875 // Remember this template being compiled
876 array_push($this->compiledTemplates, $template);
878 // Compile the loaded code in five steps:
880 // 1. Backup current template data
881 $backup = $this->getRawTemplateData();
883 // 2. Set the current template's raw data as the new content
884 $this->setRawTemplateData($code);
886 // 3. Compile the template data
887 $this->compileTemplate();
889 // 4. Remember it's contents
890 $this->loadedRawData[$template] = $this->getRawTemplateData();
892 // 5. Restore the previous raw content from backup variable
893 $this->setRawTemplateData($backup);
897 * Insert all given and loaded templates by running through all loaded
898 * codes and searching for their place-holder in the main template
900 * @param $templateMatches See method analyzeTemplate()
903 private function insertAllTemplates (array $templateMatches) {
904 // Run through all loaded codes
905 foreach ($this->loadedRawData as $template => $code) {
907 // Search for the template
908 $foundIndex = array_search($template, $templateMatches[1]);
910 // Lookup the matching template replacement
911 if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
913 // Get the current raw template
914 $rawData = $this->getRawTemplateData();
916 // Replace the space holder with the template code
917 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
919 // Set the new raw data
920 $this->setRawTemplateData($rawData);
926 * Load all extra raw templates
930 private function loadExtraRawTemplates () {
931 // Are there some raw templates we need to load?
932 if (count($this->rawTemplates) > 0) {
933 // Try to load all raw templates
934 foreach ($this->rawTemplates as $key => $template) {
937 $this->loadHtmlTemplate($template);
939 // Remember it's contents
940 $this->rawTemplates[$template] = $this->getRawTemplateData();
942 // Remove it from the loader list
943 unset($this->rawTemplates[$key]);
945 // Remember this template for recursion detection
946 // RECURSIVE PROTECTION!
947 array_push($this->loadedTemplates, $template);
948 } catch (FileNotFoundException $e) {
949 // This template was never found. We silently ignore it
950 unset($this->rawTemplates[$key]);
957 * Assign all found template variables
959 * @param $varMatches An array full of variable/value pairs.
961 * @todo Unfinished work or don't die here.
963 private function assignAllVariables (array $varMatches) {
965 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
967 // Search for all variables
968 foreach ($varMatches[1] as $key => $var) {
969 // Replace all dashes to underscores to match variables with configuration entries
970 $var = trim(self::convertDashesToUnderscores($var));
973 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
975 // Detect leading equals
976 if (substr($varMatches[2][$key], 0, 1) == '=') {
977 // Remove and cast it
978 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
981 // Do we have some quotes left and right side? Then it is free text
982 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
983 // Free string detected! Which we can assign directly
984 $this->assignVariable($var, $varMatches[3][$key]);
985 } elseif (!empty($varMatches[2][$key])) {
986 // @TODO Non-string found so we need some deeper analysis...
987 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
993 * Compiles all loaded raw templates
995 * @param $templateMatches See method analyzeTemplate() for details
998 private function compileRawTemplateData (array $templateMatches) {
1000 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1002 // Are some code-templates found which we need to compile?
1003 if (count($this->loadedRawData) > 0) {
1004 // Then compile all!
1005 foreach ($this->loadedRawData as $template => $code) {
1007 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1009 // Is this template already compiled?
1010 if (in_array($template, $this->compiledTemplates)) {
1012 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1016 // Search for the template
1017 $foundIndex = array_search($template, $templateMatches[1]);
1019 // Lookup the matching variable data
1020 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1021 // Split it up with another reg. exp. into variable=value pairs
1022 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1023 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1025 // Assign all variables
1026 $this->assignAllVariables($varMatches);
1027 } // END - if (isset($templateMatches ...
1029 // Compile the loaded template
1030 $this->compileCode($code, $template);
1031 } // END - foreach ($this->loadedRawData ...
1033 // Insert all templates
1034 $this->insertAllTemplates($templateMatches);
1035 } // END - if (count($this->loadedRawData) ...
1039 * Inserts all raw templates into their respective variables
1043 private function insertRawTemplates () {
1044 // Load all templates
1045 foreach ($this->rawTemplates as $template => $content) {
1046 // Set the template as a variable with the content
1047 $this->assignVariable($template, $content);
1052 * Finalizes the compilation of all template variables
1056 private function finalizeVariableCompilation () {
1058 $content = $this->getRawTemplateData();
1059 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1061 // Do we have the stack?
1062 if (!$this->isVarStackSet('general')) {
1063 // Abort here silently
1064 // @TODO This silent abort should be logged, maybe.
1068 // Walk through all variables
1069 foreach ($this->getVarStack('general') as $currEntry) {
1070 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1071 // Replace all [$var] or {?$var?} with the content
1072 // @TODO Old behaviour, will become obsolete!
1073 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1075 // @TODO Yet another old way
1076 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1078 // The new behaviour
1079 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1082 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1084 // Set the content back
1085 $this->setRawTemplateData($content);
1089 * Load a specified HTML template into the engine
1091 * @param $template The web template we shall load which is located in
1095 public function loadHtmlTemplate ($template) {
1096 // Set template type
1097 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1099 // Load the special template
1100 $this->loadTemplate($template);
1104 * Assign (add) a given variable with a value
1106 * @param $variableName The variable we are looking for
1107 * @param $value The value we want to store in the variable
1109 * @throws EmptyVariableException If the variable name is left empty
1111 public final function assignVariable ($variableName, $value) {
1112 // Replace all dashes to underscores to match variables with configuration entries
1113 $variableName = trim(self::convertDashesToUnderscores($variableName));
1115 // Empty variable found?
1116 if (empty($variableName)) {
1117 // Throw an exception
1118 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1121 // First search for the variable if it was already added
1122 $index = $this->getVariableIndex($variableName);
1125 if ($index === FALSE) {
1126 // Add it to the stack
1127 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1128 $this->addVariable($variableName, $value);
1129 } elseif (!empty($value)) {
1130 // Modify the stack entry
1131 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1132 $this->modifyVariable($variableName, $value);
1137 * Removes a given variable
1139 * @param $variableName The variable we are looking for
1140 * @param $variableGroup Name of variable group (default: 'general')
1143 public final function removeVariable ($variableName, $variableGroup = 'general') {
1144 // First search for the variable if it was already added
1145 $index = $this->getVariableIndex($variableName, $variableGroup);
1148 if ($index !== FALSE) {
1149 // Remove this variable
1150 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1151 $this->unsetVariableStackOffset($index, $variableGroup);
1156 * Assigns the last loaded raw template content with a given variable
1158 * @param $templateName Name of the template we want to assign
1159 * @param $variableName Name of the variable we want to assign
1162 public function assignTemplateWithVariable ($templateName, $variableName) {
1163 // Get the content from last loaded raw template
1164 $content = $this->getRawTemplateData();
1166 // Assign the variable
1167 $this->assignVariable($variableName, $content);
1169 // Purge raw content
1170 $this->setRawTemplateData('');
1174 * Assign a given congfiguration variable with a value
1176 * @param $variableName The configuration variable we want to assign
1179 public function assignConfigVariable ($variableName) {
1180 // Replace all dashes to underscores to match variables with configuration entries
1181 $variableName = trim(self::convertDashesToUnderscores($variableName));
1183 // Sweet and simple...
1184 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1185 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1189 * Assigns a lot variables into the stack of currently loaded template.
1190 * This method should only be used in very rare circumstances, e.g. when
1191 * you have to copy a whole set of variables into the template engine.
1192 * Before you use this method, please make sure you have considered all
1193 * other possiblities.
1195 * @param $variables An array with variables to be assigned
1198 public function assignMultipleVariables (array $variables) {
1200 foreach ($variables as $name => $value) {
1201 // Set variable with name for 'config' group
1202 $this->assignVariable($name, $value);
1207 * Assigns all the application data with template variables
1209 * @param $applicationInstance A manageable application instance
1212 public function assignApplicationData (ManageableApplication $applicationInstance) {
1213 // Get long name and assign it
1214 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1216 // Get short name and assign it
1217 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1219 // Get version number and assign it
1220 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1222 // Assign extra application-depending data
1223 $applicationInstance->assignExtraTemplateData($this);
1227 * Load a specified code template into the engine
1229 * @param $template The code template we shall load which is
1230 * located in 'code' by default
1233 public function loadCodeTemplate ($template) {
1234 // Set template type
1235 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type'));
1237 // Load the special template
1238 $this->loadTemplate($template);
1242 * Load a specified email template into the engine
1244 * @param $template The email template we shall load which is
1245 * located in 'emails' by default
1248 public function loadEmailTemplate ($template) {
1249 // Set template type
1250 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1252 // Load the special template
1253 $this->loadTemplate($template);
1257 * Compiles configuration place-holders in all variables. This 'walks'
1258 * through the variable group 'general'. It interprets all values from that
1259 * variables as configuration entries after compiling them.
1263 public final function compileConfigInVariables () {
1264 // Do we have the stack?
1265 if (!$this->isVarStackSet('general')) {
1266 // Abort here silently
1267 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1271 // Iterate through all general variables
1272 foreach ($this->getVarStack('general') as $index => $currVariable) {
1273 // Compile the value
1274 $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1277 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1279 // Remove it from stack
1280 $this->removeVariable($currVariable['name'], 'general');
1281 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1283 // Is it a configuration key?
1284 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1285 // The value itself is a configuration entry
1286 $this->assignConfigVariable($value);
1288 // Re-assign the value directly
1289 $this->assignVariable($currVariable['name'], $value);
1295 * Compile all variables by inserting their respective values
1298 * @todo Make this code some nicer...
1300 public final function compileVariables () {
1301 // Initialize the $content array
1302 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1305 // Iterate through all general variables
1306 foreach ($this->getVarStack('general') as $currVariable) {
1307 // Transfer it's name/value combination to the $content array
1308 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1309 $dummy[$currVariable['name']] = $currVariable['value'];
1312 // Set the new variable (don't remove the second dollar!)
1313 $$validVar = $dummy;
1315 // Remove some variables
1317 unset($currVariable);
1319 // Run the compilation three times to get content from helper classes in
1322 // Finalize the compilation of template variables
1323 $this->finalizeVariableCompilation();
1325 // Prepare the eval() command for comiling the template
1326 $eval = sprintf('$result = "%s";',
1327 addslashes($this->getRawTemplateData())
1330 // This loop does remove the backslashes (\) in PHP parameters
1331 while (strpos($eval, $this->codeBegin) !== FALSE) {
1332 // Get left part before "<?"
1333 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1335 // Get all from right of "<?"
1336 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1338 // Cut middle part out and remove escapes
1339 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1340 $evalMiddle = stripslashes($evalMiddle);
1342 // Remove the middle part from right one
1343 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1345 // And put all together
1346 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1349 // Prepare PHP code for eval() command
1350 $eval = str_replace(
1359 // Run the constructed command. This will "compile" all variables in
1362 // Goes something wrong?
1363 if ((!isset($result)) || (empty($result))) {
1364 // Output eval command
1365 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1367 // Output backtrace here
1368 $this->debugBackTrace();
1371 // Set raw template data
1372 $this->setRawTemplateData($result);
1376 // Final variable assignment
1377 $this->finalizeVariableCompilation();
1379 // Set the new content
1380 $this->setCompiledData($this->getRawTemplateData());
1384 * Compile all required templates into the current loaded one
1387 * @throws UnexpectedTemplateTypeException If the template type is
1389 * @throws InvalidArrayCountException If an unexpected array
1390 * count has been found
1392 public function compileTemplate () {
1393 // Get code type to make things shorter
1394 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type');
1396 // We will only work with template type "code" from configuration
1397 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1399 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1402 // Get the raw data.
1403 $rawData = $this->getRawTemplateData();
1405 // Remove double spaces and trim leading/trailing spaces
1406 $rawData = trim(str_replace(' ', ' ', $rawData));
1408 // Search for raw variables
1409 $this->extractVariablesFromRawData($rawData);
1411 // Search for code-tags which are {? ?}
1412 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1415 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1417 // Analyze the matches array
1418 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1419 // Entries are found:
1421 // The main analysis
1422 $this->analyzeTemplate($templateMatches);
1424 // Compile raw template data
1425 $this->compileRawTemplateData($templateMatches);
1427 // Are there some raw templates left for loading?
1428 $this->loadExtraRawTemplates();
1430 // Are some raw templates found and loaded?
1431 if (count($this->rawTemplates) > 0) {
1432 // Insert all raw templates
1433 $this->insertRawTemplates();
1435 // Remove the raw template content as well
1436 $this->setRawTemplateData('');
1438 } // END - if($templateMatches ...
1442 * Loads a given view helper (by name)
1444 * @param $helperName The helper's name
1447 protected function loadViewHelper ($helperName) {
1448 // Is this view helper loaded?
1449 if (!isset($this->helpers[$helperName])) {
1450 // Create a class name
1451 $className = self::convertToClassName($helperName) . 'ViewHelper';
1453 // Generate new instance
1454 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1457 // Return the requested instance
1458 return $this->helpers[$helperName];
1462 * Transfers the content of this template engine to a given response instance
1464 * @param $responseInstance An instance of a Responseable class
1467 public function transferToResponse (Responseable $responseInstance) {
1468 // Get the content and set it in response class
1469 $responseInstance->writeToBody($this->getCompiledData());
1473 * "Compiles" a variable by replacing {?var?} with it's content
1475 * @param $rawCode Raw code to compile
1476 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1477 * @return $rawCode Compile code with inserted variable value
1479 public function compileRawCode ($rawCode, $setMatchAsCode=FALSE) {
1480 // Find the variables
1481 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1482 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1484 // Compile all variables
1485 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, TRUE) . '</pre>');
1486 foreach ($varMatches[0] as $match) {
1487 // Add variable tags around it
1488 $varCode = '{?' . $match . '?}';
1491 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1493 // Is the variable found in code? (safes some calls)
1494 if (strpos($rawCode, $varCode) !== FALSE) {
1496 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1498 // Use $match as new value or $value from read variable?
1499 if ($setMatchAsCode === TRUE) {
1501 $rawCode = str_replace($varCode, $match, $rawCode);
1503 // Read the variable
1504 $value = $this->readVariable($match);
1507 $rawCode = str_replace($varCode, $value, $rawCode);
1512 // Return the compiled data
1513 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1518 * Getter for variable group array
1520 * @return $variableGroups All variable groups
1522 public final function getVariableGroups () {
1523 return $this->variableGroups;
1527 * Renames a variable in code and in stack
1529 * @param $oldName Old name of variable
1530 * @param $newName New name of variable
1533 public function renameVariable ($oldName, $newName) {
1534 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1535 // Get raw template code
1536 $rawData = $this->getRawTemplateData();
1539 $rawData = str_replace($oldName, $newName, $rawData);
1541 // Set the code back
1542 $this->setRawTemplateData($rawData);
1546 * Renders the given XML content
1548 * @param $content Valid XML content or if not set the current loaded raw content
1550 * @throws XmlParserException If an XML error was found
1552 public function renderXmlContent ($content = NULL) {
1553 // Is the content set?
1554 if (is_null($content)) {
1555 // Get current content
1556 $content = $this->getRawTemplateData();
1559 // Get a XmlParser instance
1560 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1562 // Check if XML compacting is enabled
1563 if ($this->isXmlCompactingEnabled()) {
1564 // Yes, so get a decorator class for transparent compacting
1565 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1568 // Parse the XML document
1569 $parserInstance->parseXmlContent($content);
1573 * Enables or disables language support
1575 * @param $languageSupport New language support setting
1578 public final function enableLanguageSupport ($languageSupport = TRUE) {
1579 $this->languageSupport = (bool) $languageSupport;
1583 * Checks whether language support is enabled
1585 * @return $languageSupport Whether language support is enabled or disabled
1587 public final function isLanguageSupportEnabled () {
1588 return $this->languageSupport;
1592 * Enables or disables XML compacting
1594 * @param $xmlCompacting New XML compacting setting
1597 public final function enableXmlCompacting ($xmlCompacting = TRUE) {
1598 $this->xmlCompacting = (bool) $xmlCompacting;
1602 * Checks whether XML compacting is enabled
1604 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1606 public final function isXmlCompactingEnabled () {
1607 return $this->xmlCompacting;
1611 * Removes all commentd, tabs and new-line characters to compact the content
1613 * @param $uncompactedContent The uncompacted content
1614 * @return $compactedContent The compacted content
1616 public function compactContent ($uncompactedContent) {
1617 // First, remove all tab/new-line/revert characters
1618 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1620 // Then regex all comments like <!-- //--> away
1621 preg_match_all($this->regExpComments, $compactedContent, $matches);
1623 // Do we have entries?
1624 if (isset($matches[0][0])) {
1626 foreach ($matches[0] as $match) {
1628 $compactedContent = str_replace($match, '', $compactedContent);
1632 // Set the content again
1633 $this->setRawTemplateData($compactedContent);
1635 // Return compacted content
1636 return $compactedContent;