3 * A generic template engine
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseTemplateEngine extends BaseFrameworkSystem {
26 * The local path name where all templates and sub folders for special
27 * templates are stored. We will internally determine the language plus
28 * "html" for web templates or "emails" for email templates
30 private $templateBasePath = '';
35 private $templateType = 'html';
38 * The extension for web and email templates (not compiled templates)
40 private $templateExtension = '.tpl';
43 * The extension for code templates (not compiled templates)
45 private $codeExtension = '.ctp';
48 * Path relative to $templateBasePath and language code for compiled code-templates
50 private $compileOutputPath = 'templates/_compiled/';
53 * The path name for all templates
55 private $genericBasePath = 'templates/';
58 * The raw (maybe uncompiled) template
60 private $rawTemplateData = '';
63 * Template data with compiled-in variables
65 private $compiledData = '';
68 * The last loaded template's FQFN for debugging the engine
70 private $lastTemplate = '';
73 * The variable stack for the templates
75 private $varStack = array();
78 * Loaded templates for recursive protection and detection
80 private $loadedTemplates = array();
83 * Compiled templates for recursive protection and detection
85 private $compiledTemplates = array();
88 * Loaded raw template data
90 private $loadedRawData = NULL;
93 * Raw templates which are linked in code templates
95 private $rawTemplates = NULL;
98 * A regular expression for variable=value pairs
100 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
103 * A regular expression for filtering out code tags
105 * E.g.: {?template:variable=value;var2=value2;[...]?}
107 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
110 * A regular expression to find template comments like <!-- Comment here //-->
112 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
117 private $helpers = array();
120 * Current variable group
122 private $currGroup = 'general';
125 * All template groups except "general"
127 private $varGroups = array();
132 private $codeBegin = '<?php';
137 private $codeEnd = '?>';
140 * Language support is enabled by default
142 private $languageSupport = TRUE;
145 * XML compacting is disabled by default
147 private $xmlCompacting = FALSE;
149 // Exception codes for the template engine
150 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
151 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
152 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
153 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
156 * Protected constructor
158 * @param $className Name of the class
161 protected function __construct ($className) {
162 // Call parent constructor
163 parent::__construct($className);
165 // Init file I/O instance
166 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
169 $this->setFileIoInstance($ioInstance);
173 * Search for a variable in the stack
175 * @param $variableName The variable we are looking for
176 * @param $variableGroup Optional variable group to look in
177 * @return $index FALSE means not found, >=0 means found on a specific index
179 private function getVariableIndex ($variableName, $variableGroup = NULL) {
180 // Replace all dashes to underscores to match variables with configuration entries
181 $variableName = trim($this->convertDashesToUnderscores($variableName));
183 // First everything is not found
186 // If the stack is NULL, use the current group
187 if (is_null($variableGroup)) {
189 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
190 $variableGroup = $this->currGroup;
193 // Is the group there?
194 if ($this->isVarStackSet($variableGroup)) {
196 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
197 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
198 // Is the entry found?
199 if ($currEntry['name'] == $variableName) {
201 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':FOUND!');
208 // Return the current position
213 * Checks whether the given variable group is set
215 * @param $variableGroup Variable group to check
216 * @return $isSet Whether the given variable group is set
218 protected final function isVarStackSet ($variableGroup) {
220 $isSet = isset($this->varStack[$variableGroup]);
227 * Getter for given variable group
229 * @param $variableGroup Variable group to check
230 * @return $varStack Found variable group
232 public final function getVarStack ($variableGroup) {
233 return $this->varStack[$variableGroup];
237 * Setter for given variable group
239 * @param $variableGroup Variable group to check
240 * @param $varStack Variable stack to check
243 protected final function setVarStack ($variableGroup, array $varStack) {
244 $this->varStack[$variableGroup] = $varStack;
248 * Return a content of a variable or null if not found
250 * @param $variableName The variable we are looking for
251 * @param $variableGroup Optional variable group to look in
252 * @return $content Content of the variable or null if not found
254 protected function readVariable ($variableName, $variableGroup = NULL) {
255 // Replace all dashes to underscores to match variables with configuration entries
256 $variableName = trim($this->convertDashesToUnderscores($variableName));
258 // First everything is not found
261 // If the stack is NULL, use the current group
262 if (is_null($variableGroup)) {
264 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
265 $variableGroup = $this->currGroup;
268 // Get variable index
269 $found = $this->getVariableIndex($variableName, $variableGroup);
271 // Is the variable found?
272 if ($found !== FALSE) {
274 $content = $this->getVariableValue($variableGroup, $found);
277 // Return the current position
278 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
283 * Add a variable to the stack
285 * @param $variableName Name of variable to add
286 * @param $value Value we want to store in the variable
289 private function addVariable ($variableName, $value) {
290 // Set general variable group
291 $this->setVariableGroup('general');
293 // Add it to the stack
294 $this->addGroupVariable($variableName, $value);
298 * Returns all variables of current group or empty array
300 * @return $result Whether array of found variables or empty array
302 private function readCurrentGroup () {
303 // Default is not found
306 // Is the group there?
307 if ($this->isVarStackSet($this->currGroup)) {
309 $result = $this->getVarStack($this->currGroup);
317 * Settter for variable group
319 * @param $groupName Name of variable group
320 * @param $add Whether add this group
323 public function setVariableGroup ($groupName, $add = TRUE) {
325 //* DEBIG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
326 $this->currGroup = $groupName;
328 // Skip group 'general'
329 if (($groupName != 'general') && ($add === TRUE)) {
330 $this->varGroups[$groupName] = 'OK';
336 * Adds a variable to current group
338 * @param $variableName Variable to set
339 * @param $value Value to store in variable
342 public function addGroupVariable ($variableName, $value) {
343 // Replace all dashes to underscores to match variables with configuration entries
344 $variableName = trim($this->convertDashesToUnderscores($variableName));
347 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
349 // Get current variables in group
350 $currVars = $this->readCurrentGroup();
352 // Append our variable
353 array_push($currVars, $this->generateVariableArray($variableName, $value));
355 // Add it to the stack
356 $this->setVarStack($this->currGroup, $currVars);
360 * Getter for variable value, throws a NoVariableException if the variable is not found
362 * @param $varGroup Variable group to use
363 * @param $index Index in variable array
364 * @return $value Value to set
366 private function getVariableValue ($varGroup, $index) {
368 return $this->varStack[$varGroup][$index]['value'];
372 * Modify an entry on the stack
374 * @param $variableName The variable we are looking for
375 * @param $value The value we want to store in the variable
377 * @throws NoVariableException If the given variable is not found
379 private function modifyVariable ($variableName, $value) {
380 // Replace all dashes to underscores to match variables with configuration entries
381 $variableName = trim($this->convertDashesToUnderscores($variableName));
383 // Get index for variable
384 $index = $this->getVariableIndex($variableName);
386 // Is the variable set?
387 if ($index === FALSE) {
388 // Unset variables cannot be modified
389 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
393 $this->setVariableValue($this->currGroup, $index, $value);
397 * Sets a variable value for given variable group and index
399 * @param $varGroup Variable group to use
400 * @param $index Index in variable array
401 * @param $value Value to set
404 private function setVariableValue ($varGroup, $index, $value) {
405 $this->varStack[$varGroup][$index]['value'] = $value;
409 * Sets a variable within given group. This method does detect if the
410 * variable is already set. If so, the variable got modified, otherwise
413 * @param $varGroup Variable group to use
414 * @param $variableName Variable to set
415 * @param $value Value to set
418 protected function setVariable ($varGroup, $variableName, $value) {
419 // Replace all dashes to underscores to match variables with configuration entries
420 $variableName = trim($this->convertDashesToUnderscores($variableName));
422 // Get index for variable
423 $index = $this->getVariableIndex($variableName);
425 // Is the variable set?
426 if ($index === FALSE) {
427 // Is the stack there?
428 if (!isset($this->varStack[$varGroup])) {
429 // Then initialize it here
430 $this->varStack[$varGroup] = array();
434 array_push($this->varStack[$varGroup], $this->generateVariableArray($variableName, $value));
437 $this->setVariableValue($this->currGroup, $index, $value);
442 * "Generates" (better returns) an array for all variables for given
443 * variable/value pay.
445 * @param $variableName Variable to set
446 * @param $value Value to set
447 * @return $varData Variable data array
449 private function generateVariableArray ($variableName, $value) {
450 // Replace all dashes to underscores to match variables with configuration entries
451 $variableName = trim($this->convertDashesToUnderscores($variableName));
453 // Generate the temporary array
455 'name' => $variableName,
464 * Setter for template type. Only 'html', 'emails' and 'compiled' should
467 * @param $templateType The current template's type
470 protected final function setTemplateType ($templateType) {
471 $this->templateType = (string) $templateType;
475 * Setter for the last loaded template's FQFN
477 * @param $template The last loaded template
480 private final function setLastTemplate ($template) {
481 $this->lastTemplate = (string) $template;
485 * Getter for the last loaded template's FQFN
487 * @return $template The last loaded template
489 private final function getLastTemplate () {
490 return $this->lastTemplate;
494 * Setter for base path
496 * @param $templateBasePath The relative base path for all templates
499 public final function setTemplateBasePath ($templateBasePath) {
501 $this->templateBasePath = (string) $templateBasePath;
505 * Getter for base path
507 * @return $templateBasePath The relative base path for all templates
509 public final function getTemplateBasePath () {
511 return $this->templateBasePath;
515 * Getter for generic base path
517 * @return $templateBasePath The relative base path for all templates
519 public final function getGenericBasePath () {
521 return $this->genericBasePath;
525 * Setter for template extension
527 * @param $templateExtension The file extension for all uncompiled
531 public final function setRawTemplateExtension ($templateExtension) {
533 $this->templateExtension = (string) $templateExtension;
537 * Setter for code template extension
539 * @param $codeExtension The file extension for all uncompiled
543 public final function setCodeTemplateExtension ($codeExtension) {
545 $this->codeExtension = (string) $codeExtension;
549 * Getter for template extension
551 * @return $templateExtension The file extension for all uncompiled
554 public final function getRawTemplateExtension () {
556 return $this->templateExtension;
560 * Getter for code-template extension
562 * @return $codeExtension The file extension for all code-
565 public final function getCodeTemplateExtension () {
567 return $this->codeExtension;
571 * Setter for path of compiled templates
573 * @param $compileOutputPath The local base path for all compiled
577 public final function setCompileOutputPath ($compileOutputPath) {
579 $this->compileOutputPath = (string) $compileOutputPath;
583 * Getter for template type
585 * @return $templateType The current template's type
587 public final function getTemplateType () {
588 return $this->templateType;
592 * Unsets the given offset in the variable group
594 * @param $index Index to unset
595 * @param $variableGroup Variable group (default: currGroup)
598 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
599 // Is the variable group not set?
600 if (is_null($variableGroup)) {
601 // Then set it to current
602 $variableGroup = $this->currGroup;
605 // Is the entry there?
606 if (!isset($this->varStack[$variableGroup][$index])) {
607 // Abort here, we need fixing!
608 $this->debugInstance();
612 unset($this->varStack[$variableGroup][$index]);
616 * Private setter for raw template data
618 * @param $rawTemplateData The raw data from the template
621 protected final function setRawTemplateData ($rawTemplateData) {
622 // And store it in this class
623 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
624 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
625 $this->rawTemplateData = (string) $rawTemplateData;
629 * Getter for raw template data
631 * @return $rawTemplateData The raw data from the template
633 public final function getRawTemplateData () {
634 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
635 return $this->rawTemplateData;
639 * Private setter for compiled templates
643 private final function setCompiledData ($compiledData) {
644 // And store it in this class
645 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
646 $this->compiledData = (string) $compiledData;
650 * Getter for compiled templates
652 * @return $compiledData Compiled template data
654 public final function getCompiledData () {
655 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
656 return $this->compiledData;
660 * Private loader for all template types
662 * @param $template The template we shall load
663 * @param $extOther An other extension to use
665 * @throws FileIoException If the template was not found
667 protected function loadTemplate ($template, $extOther = '') {
668 // Get extension for the template if empty
669 if (empty($extOther)) {
670 // None provided, so get the raw one
671 $ext = $this->getRawTemplateExtension();
674 $ext = (string) $extOther;
677 // Is language support enabled?
678 if ($this->isLanguageSupportEnabled()) {
679 // Construct the FQFN for the template by honoring the current language
680 $fqfn = sprintf('%s%s%s%s/%s/%s%s',
681 $this->getConfigInstance()->getConfigEntry('base_path'),
682 $this->getTemplateBasePath(),
683 $this->getGenericBasePath(),
684 $this->getLanguageInstance()->getLanguageCode(),
685 $this->getTemplateType(),
690 // Construct the FQFN for the template without language
691 $fqfn = sprintf('%s%s%s%s/%s%s',
692 $this->getConfigInstance()->getConfigEntry('base_path'),
693 $this->getTemplateBasePath(),
694 $this->getGenericBasePath(),
695 $this->getTemplateType(),
703 // Load the raw template data
704 $this->loadRawTemplateData($fqfn);
705 } catch (FileIoException $e) {
706 // If we shall load a code-template we need to switch the file extension
707 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_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 FileIoException($fqfn, FrameworkFileInputPointer::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 // Get a input/output instance from the middleware
729 $ioInstance = $this->getFileIoInstance();
731 // Some debug code to look on the file which is being loaded
732 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
734 // Load the raw template
735 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
737 // Store the template's contents into this class
738 $this->setRawTemplateData($rawTemplateData);
740 // Remember the template's FQFN
741 $this->setLastTemplate($fqfn);
745 * Try to assign an extracted template variable as a "content" or 'config'
748 * @param $varName The variable's name (shall be content or config)
750 * @param $variableName The variable we want to assign
753 private function assignTemplateVariable ($varName, $var) {
754 // Replace all dashes to underscores to match variables with configuration entries
755 $variableName = trim($this->convertDashesToUnderscores($variableName));
758 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: varName=' . $varName . ',variableName=' . $variableName);
760 // Is it not a config variable?
761 if ($varName != 'config') {
762 // Regular template variables
763 $this->assignVariable($variableName, '');
765 // Configuration variables
766 $this->assignConfigVariable($variableName);
771 * Extract variables from a given raw data stream
773 * @param $rawData The raw template data we shall analyze
776 private function extractVariablesFromRawData ($rawData) {
778 $rawData = (string) $rawData;
780 // Search for variables
781 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
784 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
786 // Did we find some variables?
787 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
788 // Initialize all missing variables
789 foreach ($variableMatches[3] as $key => $var) {
791 $varName = $variableMatches[1][$key];
793 // Workarround: Do not assign empty variables
795 // Try to assign it, empty strings are being ignored
796 $this->assignTemplateVariable($varName, $var);
803 * Main analysis of the loaded template
805 * @param $templateMatches Found template place-holders, see below
808 *---------------------------------
809 * Structure of $templateMatches:
810 *---------------------------------
811 * [0] => Array - An array with all full matches
812 * [1] => Array - An array with left part (before the ':') of a match
813 * [2] => Array - An array with right part of a match including ':'
814 * [3] => Array - An array with right part of a match excluding ':'
816 private function analyzeTemplate (array $templateMatches) {
817 // Backup raw template data
818 $backup = $this->getRawTemplateData();
820 // Initialize some arrays
821 if (is_null($this->loadedRawData)) {
823 $this->loadedRawData = array();
824 $this->rawTemplates = array();
827 // Load all requested templates
828 foreach ($templateMatches[1] as $template) {
829 // Load and compile only templates which we have not yet loaded
830 // RECURSIVE PROTECTION! BE CAREFUL HERE!
831 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
833 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
835 // Template not found, but maybe variable assigned?
836 if ($this->getVariableIndex($template, 'config') !== FALSE) {
837 // Use that content here
838 $this->loadedRawData[$template] = $this->readVariable($template, 'config');
840 // Recursive protection:
841 array_push($this->loadedTemplates, $template);
842 } elseif ($this->getVariableIndex($template) !== FALSE) {
843 // Use that content here
844 $this->loadedRawData[$template] = $this->readVariable($template);
846 // Recursive protection:
847 array_push($this->loadedTemplates, $template);
849 // Then try to search for code-templates
851 // Load the code template and remember it's contents
852 $this->loadCodeTemplate($template);
853 $this->loadedRawData[$template] = $this->getRawTemplateData();
855 // Remember this template for recursion detection
856 // RECURSIVE PROTECTION!
857 array_push($this->loadedTemplates, $template);
858 } catch (FileIoException $e) {
859 // Even this is not done... :/
860 array_push($this->rawTemplates, $template);
866 // Restore the raw template data
867 $this->setRawTemplateData($backup);
871 * Compile a given raw template code and remember it for later usage
873 * @param $code The raw template code
874 * @param $template The template's name
877 private function compileCode ($code, $template) {
878 // Is this template already compiled?
879 if (in_array($template, $this->compiledTemplates)) {
884 // Remember this template being compiled
885 array_push($this->compiledTemplates, $template);
887 // Compile the loaded code in five steps:
889 // 1. Backup current template data
890 $backup = $this->getRawTemplateData();
892 // 2. Set the current template's raw data as the new content
893 $this->setRawTemplateData($code);
895 // 3. Compile the template data
896 $this->compileTemplate();
898 // 4. Remember it's contents
899 $this->loadedRawData[$template] = $this->getRawTemplateData();
901 // 5. Restore the previous raw content from backup variable
902 $this->setRawTemplateData($backup);
906 * Insert all given and loaded templates by running through all loaded
907 * codes and searching for their place-holder in the main template
909 * @param $templateMatches See method analyzeTemplate()
912 private function insertAllTemplates (array $templateMatches) {
913 // Run through all loaded codes
914 foreach ($this->loadedRawData as $template => $code) {
916 // Search for the template
917 $foundIndex = array_search($template, $templateMatches[1]);
919 // Lookup the matching template replacement
920 if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
922 // Get the current raw template
923 $rawData = $this->getRawTemplateData();
925 // Replace the space holder with the template code
926 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
928 // Set the new raw data
929 $this->setRawTemplateData($rawData);
935 * Load all extra raw templates
939 private function loadExtraRawTemplates () {
940 // Are there some raw templates we need to load?
941 if (count($this->rawTemplates) > 0) {
942 // Try to load all raw templates
943 foreach ($this->rawTemplates as $key => $template) {
946 $this->loadWebTemplate($template);
948 // Remember it's contents
949 $this->rawTemplates[$template] = $this->getRawTemplateData();
951 // Remove it from the loader list
952 unset($this->rawTemplates[$key]);
954 // Remember this template for recursion detection
955 // RECURSIVE PROTECTION!
956 array_push($this->loadedTemplates, $template);
957 } catch (FileIoException $e) {
958 // This template was never found. We silently ignore it
959 unset($this->rawTemplates[$key]);
966 * Assign all found template variables
968 * @param $varMatches An array full of variable/value pairs.
970 * @todo Unfinished work or don't die here.
972 private function assignAllVariables (array $varMatches) {
974 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
976 // Search for all variables
977 foreach ($varMatches[1] as $key => $var) {
978 // Replace all dashes to underscores to match variables with configuration entries
979 $var = trim($this->convertDashesToUnderscores($var));
982 self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
984 // Detect leading equals
985 if (substr($varMatches[2][$key], 0, 1) == '=') {
986 // Remove and cast it
987 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
990 // Do we have some quotes left and right side? Then it is free text
991 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
992 // Free string detected! Which we can assign directly
993 $this->assignVariable($var, $varMatches[3][$key]);
994 } elseif (!empty($varMatches[2][$key])) {
995 // @TODO Non-string found so we need some deeper analysis...
996 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
1002 * Compiles all loaded raw templates
1004 * @param $templateMatches See method analyzeTemplate() for details
1007 private function compileRawTemplateData (array $templateMatches) {
1009 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1011 // Are some code-templates found which we need to compile?
1012 if (count($this->loadedRawData) > 0) {
1013 // Then compile all!
1014 foreach ($this->loadedRawData as $template => $code) {
1016 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1018 // Is this template already compiled?
1019 if (in_array($template, $this->compiledTemplates)) {
1021 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1025 // Search for the template
1026 $foundIndex = array_search($template, $templateMatches[1]);
1028 // Lookup the matching variable data
1029 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1030 // Split it up with another reg. exp. into variable=value pairs
1031 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1032 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1034 // Assign all variables
1035 $this->assignAllVariables($varMatches);
1036 } // END - if (isset($templateMatches ...
1038 // Compile the loaded template
1039 $this->compileCode($code, $template);
1040 } // END - foreach ($this->loadedRawData ...
1042 // Insert all templates
1043 $this->insertAllTemplates($templateMatches);
1044 } // END - if (count($this->loadedRawData) ...
1048 * Inserts all raw templates into their respective variables
1052 private function insertRawTemplates () {
1053 // Load all templates
1054 foreach ($this->rawTemplates as $template => $content) {
1055 // Set the template as a variable with the content
1056 $this->assignVariable($template, $content);
1061 * Finalizes the compilation of all template variables
1065 private function finalizeVariableCompilation () {
1067 $content = $this->getRawTemplateData();
1068 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1070 // Do we have the stack?
1071 if (!$this->isVarStackSet('general')) {
1072 // Abort here silently
1073 // @TODO This silent abort should be logged, maybe.
1077 // Walk through all variables
1078 foreach ($this->getVarStack('general') as $currEntry) {
1079 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1080 // Replace all [$var] or {?$var?} with the content
1081 // @TODO Old behaviour, will become obsolete!
1082 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1084 // @TODO Yet another old way
1085 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1087 // The new behaviour
1088 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1091 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1093 // Set the content back
1094 $this->setRawTemplateData($content);
1098 * Load a specified web template into the engine
1100 * @param $template The web template we shall load which is located in
1104 public function loadWebTemplate ($template) {
1105 // Set template type
1106 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
1108 // Load the special template
1109 $this->loadTemplate($template);
1113 * Assign (add) a given variable with a value
1115 * @param $variableName The variable we are looking for
1116 * @param $value The value we want to store in the variable
1118 * @throws EmptyVariableException If the variable name is left empty
1120 public final function assignVariable ($variableName, $value) {
1121 // Replace all dashes to underscores to match variables with configuration entries
1122 $variableName = trim($this->convertDashesToUnderscores($variableName));
1124 // Empty variable found?
1125 if (empty($variableName)) {
1126 // Throw an exception
1127 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1130 // First search for the variable if it was already added
1131 $index = $this->getVariableIndex($variableName);
1134 if ($index === FALSE) {
1135 // Add it to the stack
1136 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1137 $this->addVariable($variableName, $value);
1138 } elseif (!empty($value)) {
1139 // Modify the stack entry
1140 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1141 $this->modifyVariable($variableName, $value);
1146 * Removes a given variable
1148 * @param $variableName The variable we are looking for
1149 * @param $variableGroup Name of variable group (default: 'general')
1152 public final function removeVariable ($variableName, $variableGroup = 'general') {
1153 // First search for the variable if it was already added
1154 $index = $this->getVariableIndex($variableName, $variableGroup);
1157 if ($index !== FALSE) {
1158 // Remove this variable
1159 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1160 $this->unsetVariableStackOffset($index, $variableGroup);
1165 * Assigns the last loaded raw template content with a given variable
1167 * @param $templateName Name of the template we want to assign
1168 * @param $variableName Name of the variable we want to assign
1171 public function assignTemplateWithVariable ($templateName, $variableName) {
1172 // Get the content from last loaded raw template
1173 $content = $this->getRawTemplateData();
1175 // Assign the variable
1176 $this->assignVariable($variableName, $content);
1178 // Purge raw content
1179 $this->setRawTemplateData('');
1183 * Assign a given congfiguration variable with a value
1185 * @param $variableName The configuration variable we want to assign
1188 public function assignConfigVariable ($variableName) {
1189 // Replace all dashes to underscores to match variables with configuration entries
1190 $variableName = trim($this->convertDashesToUnderscores($variableName));
1192 // Sweet and simple...
1193 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1194 $this->setVariable('config', $variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1198 * Injects an array of config variables into the stack of currently loaded
1199 * template. This method should only be used in very rare circumstances,
1200 * e.g. when you have to copy a whole set of variables into the template
1201 * engine. Before you use this method, please make sure you have considered
1202 * all other possiblities.
1204 * @param $variables An array with variables to be injected
1207 public function injectConfigVariables (array $variables) {
1209 foreach ($variables as $name => $value) {
1210 // Set variable with name for 'config' group
1211 $this->setVariable('config', $name, $value);
1216 * Assigns all the application data with template variables
1218 * @param $applicationInstance A manageable application instance
1221 public function assignApplicationData (ManageableApplication $applicationInstance) {
1222 // Get long name and assign it
1223 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1225 // Get short name and assign it
1226 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1228 // Get version number and assign it
1229 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1231 // Assign extra application-depending data
1232 $applicationInstance->assignExtraTemplateData($this);
1236 * Load a specified code template into the engine
1238 * @param $template The code template we shall load which is
1239 * located in 'code' by default
1242 public function loadCodeTemplate ($template) {
1243 // Set template type
1244 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1246 // Load the special template
1247 $this->loadTemplate($template);
1251 * Compiles configuration place-holders in all variables. This 'walks'
1252 * through the variable group 'general'. It interprets all values from that
1253 * variables as configuration entries after compiling them.
1257 public final function compileConfigInVariables () {
1258 // Do we have the stack?
1259 if (!$this->isVarStackSet('general')) {
1260 // Abort here silently
1261 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1265 // Iterate through all general variables
1266 foreach ($this->getVarStack('general') as $index => $currVariable) {
1267 // Compile the value
1268 $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1271 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1273 // Remove it from stack
1274 $this->removeVariable($currVariable['name'], 'general');
1275 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1277 // Is it a configuration key?
1278 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1279 // The value itself is a configuration entry
1280 $this->assignConfigVariable($value);
1282 // Re-assign the value directly
1283 $this->setVariable('config', $currVariable['name'], $value);
1289 * Compile all variables by inserting their respective values
1292 * @todo Make this code some nicer...
1294 public final function compileVariables () {
1295 // Initialize the $content array
1296 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1299 // Iterate through all general variables
1300 foreach ($this->getVarStack('general') as $currVariable) {
1301 // Transfer it's name/value combination to the $content array
1302 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1303 $dummy[$currVariable['name']] = $currVariable['value'];
1306 // Set the new variable (don't remove the second dollar!)
1307 $$validVar = $dummy;
1309 // Remove some variables
1311 unset($currVariable);
1313 // Run the compilation three times to get content from helper classes in
1316 // Finalize the compilation of template variables
1317 $this->finalizeVariableCompilation();
1319 // Prepare the eval() command for comiling the template
1320 $eval = sprintf('$result = "%s";',
1321 addslashes($this->getRawTemplateData())
1324 // This loop does remove the backslashes (\) in PHP parameters
1325 while (strpos($eval, $this->codeBegin) !== FALSE) {
1326 // Get left part before "<?"
1327 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1329 // Get all from right of "<?"
1330 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1332 // Cut middle part out and remove escapes
1333 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1334 $evalMiddle = stripslashes($evalMiddle);
1336 // Remove the middle part from right one
1337 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1339 // And put all together
1340 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1343 // Prepare PHP code for eval() command
1344 $eval = str_replace(
1353 // Run the constructed command. This will "compile" all variables in
1356 // Goes something wrong?
1357 if ((!isset($result)) || (empty($result))) {
1358 // Output eval command
1359 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1361 // Output backtrace here
1362 $this->debugBackTrace();
1365 // Set raw template data
1366 $this->setRawTemplateData($result);
1370 // Final variable assignment
1371 $this->finalizeVariableCompilation();
1373 // Set the new content
1374 $this->setCompiledData($this->getRawTemplateData());
1378 * Compile all required templates into the current loaded one
1381 * @throws UnexpectedTemplateTypeException If the template type is
1383 * @throws InvalidArrayCountException If an unexpected array
1384 * count has been found
1386 public function compileTemplate () {
1387 // Get code type to make things shorter
1388 $codeType = $this->getConfigInstance()->getConfigEntry('code_template_type');
1390 // We will only work with template type "code" from configuration
1391 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1393 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1396 // Get the raw data.
1397 $rawData = $this->getRawTemplateData();
1399 // Remove double spaces and trim leading/trailing spaces
1400 $rawData = trim(str_replace(' ', ' ', $rawData));
1402 // Search for raw variables
1403 $this->extractVariablesFromRawData($rawData);
1405 // Search for code-tags which are {? ?}
1406 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1409 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1411 // Analyze the matches array
1412 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1413 // Entries are found:
1415 // The main analysis
1416 $this->analyzeTemplate($templateMatches);
1418 // Compile raw template data
1419 $this->compileRawTemplateData($templateMatches);
1421 // Are there some raw templates left for loading?
1422 $this->loadExtraRawTemplates();
1424 // Are some raw templates found and loaded?
1425 if (count($this->rawTemplates) > 0) {
1426 // Insert all raw templates
1427 $this->insertRawTemplates();
1429 // Remove the raw template content as well
1430 $this->setRawTemplateData('');
1432 } // END - if($templateMatches ...
1436 * Loads a given view helper (by name)
1438 * @param $helperName The helper's name
1441 protected function loadViewHelper ($helperName) {
1442 // Make first character upper case, rest low
1443 $helperName = $this->convertToClassName($helperName);
1445 // Is this view helper loaded?
1446 if (!isset($this->helpers[$helperName])) {
1447 // Create a class name
1448 $className = $helperName . 'ViewHelper';
1450 // Generate new instance
1451 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1454 // Return the requested instance
1455 return $this->helpers[$helperName];
1459 * Transfers the content of this template engine to a given response instance
1461 * @param $responseInstance An instance of a response class
1464 public function transferToResponse (Responseable $responseInstance) {
1465 // Get the content and set it in response class
1466 $responseInstance->writeToBody($this->getCompiledData());
1470 * "Compiles" a variable by replacing {?var?} with it's content
1472 * @param $rawCode Raw code to compile
1473 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1474 * @return $rawCode Compile code with inserted variable value
1476 public function compileRawCode ($rawCode, $setMatchAsCode=FALSE) {
1477 // Find the variables
1478 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1479 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1481 // Compile all variables
1482 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, TRUE) . '</pre>');
1483 foreach ($varMatches[0] as $match) {
1484 // Add variable tags around it
1485 $varCode = '{?' . $match . '?}';
1488 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1490 // Is the variable found in code? (safes some calls)
1491 if (strpos($rawCode, $varCode) !== FALSE) {
1493 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1495 // Use $match as new value or $value from read variable?
1496 if ($setMatchAsCode === TRUE) {
1498 $rawCode = str_replace($varCode, $match, $rawCode);
1500 // Read the variable
1501 $value = $this->readVariable($match);
1504 $rawCode = str_replace($varCode, $value, $rawCode);
1509 // Return the compiled data
1510 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1515 * Getter for variable group array
1517 * @return $vargroups All variable groups
1519 public final function getVariableGroups () {
1520 return $this->varGroups;
1524 * Renames a variable in code and in stack
1526 * @param $oldName Old name of variable
1527 * @param $newName New name of variable
1530 public function renameVariable ($oldName, $newName) {
1531 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1532 // Get raw template code
1533 $rawData = $this->getRawTemplateData();
1536 $rawData = str_replace($oldName, $newName, $rawData);
1538 // Set the code back
1539 $this->setRawTemplateData($rawData);
1543 * Renders the given XML content
1545 * @param $content Valid XML content or if not set the current loaded raw content
1547 * @throws XmlParserException If an XML error was found
1549 public function renderXmlContent ($content = NULL) {
1550 // Is the content set?
1551 if (is_null($content)) {
1552 // Get current content
1553 $content = $this->getRawTemplateData();
1556 // Get a XmlParser instance
1557 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1559 // Check if we have XML compacting enabled
1560 if ($this->isXmlCompactingEnabled()) {
1561 // Yes, so get a decorator class for transparent compacting
1562 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1565 // Parse the XML document
1566 $parserInstance->parseXmlContent($content);
1570 * Enables or disables language support
1572 * @param $languageSupport New language support setting
1575 public final function enableLanguageSupport ($languageSupport = TRUE) {
1576 $this->languageSupport = (bool) $languageSupport;
1580 * Checks whether language support is enabled
1582 * @return $languageSupport Whether language support is enabled or disabled
1584 public final function isLanguageSupportEnabled () {
1585 return $this->languageSupport;
1589 * Enables or disables XML compacting
1591 * @param $xmlCompacting New XML compacting setting
1594 public final function enableXmlCompacting ($xmlCompacting = TRUE) {
1595 $this->xmlCompacting = (bool) $xmlCompacting;
1599 * Checks whether XML compacting is enabled
1601 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1603 public final function isXmlCompactingEnabled () {
1604 return $this->xmlCompacting;
1608 * Removes all commentd, tabs and new-line characters to compact the content
1610 * @param $uncompactedContent The uncompacted content
1611 * @return $compactedContent The compacted content
1613 public function compactContent ($uncompactedContent) {
1614 // First, remove all tab/new-line/revert characters
1615 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1617 // Then regex all comments like <!-- //--> away
1618 preg_match_all($this->regExpComments, $compactedContent, $matches);
1620 // Do we have entries?
1621 if (isset($matches[0][0])) {
1623 foreach ($matches[0] as $match) {
1625 $compactedContent = str_replace($match, '', $compactedContent);
1629 // Set the content again
1630 $this->setRawTemplateData($compactedContent);
1632 // Return compacted content
1633 return $compactedContent;