3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.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_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
112 private $helpers = array();
115 * Current variable group
117 private $currGroup = 'general';
120 * All template groups except "general"
122 private $varGroups = array();
127 private $codeBegin = '<?php';
132 private $codeEnd = '?>';
135 * Language support is enabled by default
137 private $languageSupport = true;
140 * XML compacting is disabled by default
142 private $xmlCompacting = false;
144 // Exception codes for the template engine
145 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
146 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
147 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
148 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
151 * Protected constructor
153 * @param $className Name of the class
156 protected function __construct ($className) {
157 // Call parent constructor
158 parent::__construct($className);
160 // Init file I/O instance
161 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
164 $this->setFileIoInstance($ioInstance);
168 * Search for a variable in the stack
170 * @param $variableName The variable we are looking for
171 * @param $variableGroup Optional variable group to look in
172 * @return $index FALSE means not found, >=0 means found on a specific index
174 private function getVariableIndex ($variableName, $variableGroup = NULL) {
175 // Replace all dashes to underscores to match variables with configuration entries
176 $variableName = trim($this->convertDashesToUnderscores($variableName));
178 // First everything is not found
181 // If the stack is null, use the current group
182 if (is_null($variableGroup)) {
184 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
185 $variableGroup = $this->currGroup;
188 // Is the group there?
189 if ($this->isVarStackSet($variableGroup)) {
191 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
192 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
193 // Is the entry found?
194 if ($currEntry['name'] == $variableName) {
196 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':FOUND!');
203 // Return the current position
208 * Checks whether the given variable group is set
210 * @param $variableGroup Variable group to check
211 * @return $isSet Whether the given variable group is set
213 protected final function isVarStackSet ($variableGroup) {
215 $isSet = isset($this->varStack[$variableGroup]);
222 * Getter for given variable group
224 * @param $variableGroup Variable group to check
225 * @return $varStack Found variable group
227 public final function getVarStack ($variableGroup) {
228 return $this->varStack[$variableGroup];
232 * Setter for given variable group
234 * @param $variableGroup Variable group to check
235 * @param $varStack Variable stack to check
238 protected final function setVarStack ($variableGroup, array $varStack) {
239 $this->varStack[$variableGroup] = $varStack;
243 * Return a content of a variable or null if not found
245 * @param $variableName The variable we are looking for
246 * @param $variableGroup Optional variable group to look in
247 * @return $content Content of the variable or null if not found
249 protected function readVariable ($variableName, $variableGroup = NULL) {
250 // Replace all dashes to underscores to match variables with configuration entries
251 $variableName = trim($this->convertDashesToUnderscores($variableName));
253 // First everything is not found
256 // If the stack is null, use the current group
257 if (is_null($variableGroup)) {
259 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
260 $variableGroup = $this->currGroup;
263 // Get variable index
264 $found = $this->getVariableIndex($variableName, $variableGroup);
266 // Is the variable found?
267 if ($found !== false) {
269 $content = $this->getVariableValue($variableGroup, $found);
272 // Return the current position
273 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
278 * Add a variable to the stack
280 * @param $variableName Name of variable to add
281 * @param $value Value we want to store in the variable
284 private function addVariable ($variableName, $value) {
285 // Set general variable group
286 $this->setVariableGroup('general');
288 // Add it to the stack
289 $this->addGroupVariable($variableName, $value);
293 * Returns all variables of current group or empty array
295 * @return $result Whether array of found variables or empty array
297 private function readCurrentGroup () {
298 // Default is not found
301 // Is the group there?
302 if ($this->isVarStackSet($this->currGroup)) {
304 $result = $this->getVarStack($this->currGroup);
312 * Settter for variable group
314 * @param $groupName Name of variable group
315 * @param $add Whether add this group
318 public function setVariableGroup ($groupName, $add = true) {
320 //* DEBIG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
321 $this->currGroup = $groupName;
323 // Skip group 'general'
324 if (($groupName != 'general') && ($add === true)) {
325 $this->varGroups[$groupName] = 'OK';
331 * Adds a variable to current group
333 * @param $variableName Variable to set
334 * @param $value Value to store in variable
337 public function addGroupVariable ($variableName, $value) {
338 // Replace all dashes to underscores to match variables with configuration entries
339 $variableName = trim($this->convertDashesToUnderscores($variableName));
342 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
344 // Get current variables in group
345 $currVars = $this->readCurrentGroup();
347 // Append our variable
348 $currVars[] = $this->generateVariableArray($variableName, $value);
350 // Add it to the stack
351 $this->setVarStack($this->currGroup, $currVars);
355 * Getter for variable value, throws a NoVariableException if the variable is not found
357 * @param $varGroup Variable group to use
358 * @param $index Index in variable array
359 * @return $value Value to set
361 private function getVariableValue ($varGroup, $index) {
363 return $this->varStack[$varGroup][$index]['value'];
367 * Modify an entry on the stack
369 * @param $variableName The variable we are looking for
370 * @param $value The value we want to store in the variable
372 * @throws NoVariableException If the given variable is not found
374 private function modifyVariable ($variableName, $value) {
375 // Replace all dashes to underscores to match variables with configuration entries
376 $variableName = trim($this->convertDashesToUnderscores($variableName));
378 // Get index for variable
379 $index = $this->getVariableIndex($variableName);
381 // Is the variable set?
382 if ($index === false) {
383 // Unset variables cannot be modified
384 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
388 $this->setVariableValue($this->currGroup, $index, $value);
392 * Sets a variable value for given variable group and index
394 * @param $varGroup Variable group to use
395 * @param $index Index in variable array
396 * @param $value Value to set
399 private function setVariableValue ($varGroup, $index, $value) {
400 $this->varStack[$varGroup][$index]['value'] = $value;
404 * Sets a variable within given group. This method does detect if the
405 * variable is already set. If so, the variable got modified, otherwise
408 * @param $varGroup Variable group to use
409 * @param $variableName Variable to set
410 * @param $value Value to set
413 protected function setVariable ($varGroup, $variableName, $value) {
414 // Replace all dashes to underscores to match variables with configuration entries
415 $variableName = trim($this->convertDashesToUnderscores($variableName));
417 // Get index for variable
418 $index = $this->getVariableIndex($variableName);
420 // Is the variable set?
421 if ($index === false) {
423 $this->varStack[$varGroup][] = $this->generateVariableArray($variableName, $value);
426 $this->setVariableValue($this->currGroup, $index, $value);
431 * "Generates" (better returns) an array for all variables for given
432 * variable/value pay.
434 * @param $variableName Variable to set
435 * @param $value Value to set
436 * @return $varData Variable data array
438 private function generateVariableArray ($variableName, $value) {
439 // Replace all dashes to underscores to match variables with configuration entries
440 $variableName = trim($this->convertDashesToUnderscores($variableName));
442 // Generate the temporary array
444 'name' => $variableName,
453 * Setter for template type. Only 'html', 'emails' and 'compiled' should
456 * @param $templateType The current template's type
459 protected final function setTemplateType ($templateType) {
460 $this->templateType = (string) $templateType;
464 * Setter for the last loaded template's FQFN
466 * @param $template The last loaded template
469 private final function setLastTemplate ($template) {
470 $this->lastTemplate = (string) $template;
474 * Getter for the last loaded template's FQFN
476 * @return $template The last loaded template
478 private final function getLastTemplate () {
479 return $this->lastTemplate;
483 * Setter for base path
485 * @param $templateBasePath The relative base path for all templates
488 public final function setTemplateBasePath ($templateBasePath) {
490 $this->templateBasePath = (string) $templateBasePath;
494 * Getter for base path
496 * @return $templateBasePath The relative base path for all templates
498 public final function getTemplateBasePath () {
500 return $this->templateBasePath;
504 * Getter for generic base path
506 * @return $templateBasePath The relative base path for all templates
508 public final function getGenericBasePath () {
510 return $this->genericBasePath;
514 * Setter for template extension
516 * @param $templateExtension The file extension for all uncompiled
520 public final function setRawTemplateExtension ($templateExtension) {
522 $this->templateExtension = (string) $templateExtension;
526 * Setter for code template extension
528 * @param $codeExtension The file extension for all uncompiled
532 public final function setCodeTemplateExtension ($codeExtension) {
534 $this->codeExtension = (string) $codeExtension;
538 * Getter for template extension
540 * @return $templateExtension The file extension for all uncompiled
543 public final function getRawTemplateExtension () {
545 return $this->templateExtension;
549 * Getter for code-template extension
551 * @return $codeExtension The file extension for all code-
554 public final function getCodeTemplateExtension () {
556 return $this->codeExtension;
560 * Setter for path of compiled templates
562 * @param $compileOutputPath The local base path for all compiled
566 public final function setCompileOutputPath ($compileOutputPath) {
568 $this->compileOutputPath = (string) $compileOutputPath;
572 * Getter for template type
574 * @return $templateType The current template's type
576 public final function getTemplateType () {
577 return $this->templateType;
581 * Assign (add) a given variable with a value
583 * @param $variableName The variable we are looking for
584 * @param $value The value we want to store in the variable
586 * @throws EmptyVariableException If the variable name is left empty
588 public final function assignVariable ($variableName, $value) {
589 // Replace all dashes to underscores to match variables with configuration entries
590 $variableName = trim($this->convertDashesToUnderscores($variableName));
592 // Empty variable found?
593 if (empty($variableName)) {
594 // Throw an exception
595 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
598 // First search for the variable if it was already added
599 $index = $this->getVariableIndex($variableName);
602 if ($index === false) {
603 // Add it to the stack
604 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
605 $this->addVariable($variableName, $value);
606 } elseif (!empty($value)) {
607 // Modify the stack entry
608 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
609 $this->modifyVariable($variableName, $value);
614 * Removes a given variable
616 * @param $variableName The variable we are looking for
617 * @param $variableGroup Name of variable group (default: 'general')
620 public final function removeVariable ($variableName, $variableGroup = 'general') {
621 // First search for the variable if it was already added
622 $index = $this->getVariableIndex($variableName, $variableGroup);
625 if ($index !== false) {
626 // Remove this variable
627 $this->unsetVariableStackOffset($index, $variableGroup);
632 * Unsets the given offset in the variable group
634 * @param $index Index to unset
635 * @param $variableGroup Variable group (default: currGroup)
638 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
639 // Is the variable group not set?
640 if (is_null($variableGroup)) {
641 // Then set it to current
642 $variableGroup = $this->currGroup;
645 // Is the entry there?
646 if (!isset($this->varStack[$variableGroup][$index])) {
647 // Abort here, we need fixing!
648 $this->debugInstance();
652 unset($this->varStack[$variableGroup][$index]);
656 * Private setter for raw template data
658 * @param $rawTemplateData The raw data from the template
661 protected final function setRawTemplateData ($rawTemplateData) {
662 // And store it in this class
663 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
664 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
665 $this->rawTemplateData = (string) $rawTemplateData;
669 * Getter for raw template data
671 * @return $rawTemplateData The raw data from the template
673 public final function getRawTemplateData () {
674 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': ' . strlen($this->rawTemplateData) . ' Bytes read.');
675 return $this->rawTemplateData;
679 * Private setter for compiled templates
683 private final function setCompiledData ($compiledData) {
684 // And store it in this class
685 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': ' . strlen($compiledData) . ' Bytes set.');
686 $this->compiledData = (string) $compiledData;
690 * Getter for compiled templates
692 * @return $compiledData Compiled template data
694 public final function getCompiledData () {
695 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': ' . strlen($this->compiledData) . ' Bytes read.');
696 return $this->compiledData;
700 * Private loader for all template types
702 * @param $template The template we shall load
703 * @param $extOther An other extension to use
705 * @throws FileIoException If the template was not found
707 protected function loadTemplate ($template, $extOther = '') {
708 // Get extension for the template if empty
709 if (empty($extOther)) {
710 // None provided, so get the raw one
711 $ext = $this->getRawTemplateExtension();
714 $ext = (string) $extOther;
717 // Is language support enabled?
718 if ($this->isLanguageSupportEnabled()) {
719 // Construct the FQFN for the template by honoring the current language
720 $fqfn = sprintf("%s%s%s%s/%s/%s%s",
721 $this->getConfigInstance()->getConfigEntry('base_path'),
722 $this->getTemplateBasePath(),
723 $this->getGenericBasePath(),
724 $this->getLanguageInstance()->getLanguageCode(),
725 $this->getTemplateType(),
730 // Construct the FQFN for the template without language
731 $fqfn = sprintf("%s%s%s%s/%s%s",
732 $this->getConfigInstance()->getConfigEntry('base_path'),
733 $this->getTemplateBasePath(),
734 $this->getGenericBasePath(),
735 $this->getTemplateType(),
743 // Load the raw template data
744 $this->loadRawTemplateData($fqfn);
745 } catch (FileIoException $e) {
746 // If we shall load a code-template we need to switch the file extension
747 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
748 // Switch over to the code-template extension and try it again
749 $ext = $this->getCodeTemplateExtension();
752 $this->loadTemplate($template, $ext);
755 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
762 * A private loader for raw template names
764 * @param $fqfn The full-qualified file name for a template
767 private function loadRawTemplateData ($fqfn) {
768 // Get a input/output instance from the middleware
769 $ioInstance = $this->getFileIoInstance();
771 // Some debug code to look on the file which is being loaded
772 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': FQFN=' . $fqfn);
774 // Load the raw template
775 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
777 // Store the template's contents into this class
778 $this->setRawTemplateData($rawTemplateData);
780 // Remember the template's FQFN
781 $this->setLastTemplate($fqfn);
785 * Try to assign an extracted template variable as a "content" or 'config'
788 * @param $varName The variable's name (shall be content or config)
790 * @param $variableName The variable we want to assign
793 private function assignTemplateVariable ($varName, $var) {
794 // Replace all dashes to underscores to match variables with configuration entries
795 $variableName = trim($this->convertDashesToUnderscores($variableName));
798 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': varName=' . $varName . ',variableName=' . $variableName);
800 // Is it not a config variable?
801 if ($varName != 'config') {
802 // Regular template variables
803 $this->assignVariable($variableName, '');
805 // Configuration variables
806 $this->assignConfigVariable($variableName);
811 * Extract variables from a given raw data stream
813 * @param $rawData The raw template data we shall analyze
816 private function extractVariablesFromRawData ($rawData) {
818 $rawData = (string) $rawData;
820 // Search for variables
821 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
824 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
826 // Did we find some variables?
827 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
828 // Initialize all missing variables
829 foreach ($variableMatches[3] as $key => $var) {
831 $varName = $variableMatches[1][$key];
833 // Workarround: Do not assign empty variables
835 // Try to assign it, empty strings are being ignored
836 $this->assignTemplateVariable($varName, $var);
843 * Main analysis of the loaded template
845 * @param $templateMatches Found template place-holders, see below
848 *---------------------------------
849 * Structure of $templateMatches:
850 *---------------------------------
851 * [0] => Array - An array with all full matches
852 * [1] => Array - An array with left part (before the ':') of a match
853 * [2] => Array - An array with right part of a match including ':'
854 * [3] => Array - An array with right part of a match excluding ':'
856 private function analyzeTemplate (array $templateMatches) {
857 // Backup raw template data
858 $backup = $this->getRawTemplateData();
860 // Initialize some arrays
861 if (is_null($this->loadedRawData)) {
863 $this->loadedRawData = array();
864 $this->rawTemplates = array();
867 // Load all requested templates
868 foreach ($templateMatches[1] as $template) {
869 // Load and compile only templates which we have not yet loaded
870 // RECURSIVE PROTECTION! BE CAREFUL HERE!
871 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
873 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':template=' . $template);
875 // Template not found, but maybe variable assigned?
876 if ($this->getVariableIndex($template, 'config') !== false) {
877 // Use that content here
878 $this->loadedRawData[$template] = $this->readVariable($template, 'config');
880 // Recursive protection:
881 $this->loadedTemplates[] = $template;
882 } elseif ($this->getVariableIndex($template) !== false) {
883 // Use that content here
884 $this->loadedRawData[$template] = $this->readVariable($template);
886 // Recursive protection:
887 $this->loadedTemplates[] = $template;
889 // Then try to search for code-templates
891 // Load the code template and remember it's contents
892 $this->loadCodeTemplate($template);
893 $this->loadedRawData[$template] = $this->getRawTemplateData();
895 // Remember this template for recursion detection
896 // RECURSIVE PROTECTION!
897 $this->loadedTemplates[] = $template;
898 } catch (FileIoException $e) {
899 // Even this is not done... :/
900 $this->rawTemplates[] = $template;
906 // Restore the raw template data
907 $this->setRawTemplateData($backup);
911 * Compile a given raw template code and remember it for later usage
913 * @param $code The raw template code
914 * @param $template The template's name
917 private function compileCode ($code, $template) {
918 // Is this template already compiled?
919 if (in_array($template, $this->compiledTemplates)) {
924 // Remember this template being compiled
925 $this->compiledTemplates[] = $template;
927 // Compile the loaded code in five steps:
929 // 1. Backup current template data
930 $backup = $this->getRawTemplateData();
932 // 2. Set the current template's raw data as the new content
933 $this->setRawTemplateData($code);
935 // 3. Compile the template data
936 $this->compileTemplate();
938 // 4. Remember it's contents
939 $this->loadedRawData[$template] = $this->getRawTemplateData();
941 // 5. Restore the previous raw content from backup variable
942 $this->setRawTemplateData($backup);
946 * Insert all given and loaded templates by running through all loaded
947 * codes and searching for their place-holder in the main template
949 * @param $templateMatches See method analyzeTemplate()
952 private function insertAllTemplates (array $templateMatches) {
953 // Run through all loaded codes
954 foreach ($this->loadedRawData as $template => $code) {
956 // Search for the template
957 $foundIndex = array_search($template, $templateMatches[1]);
959 // Lookup the matching template replacement
960 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
962 // Get the current raw template
963 $rawData = $this->getRawTemplateData();
965 // Replace the space holder with the template code
966 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
968 // Set the new raw data
969 $this->setRawTemplateData($rawData);
975 * Load all extra raw templates
979 private function loadExtraRawTemplates () {
980 // Are there some raw templates we need to load?
981 if (count($this->rawTemplates) > 0) {
982 // Try to load all raw templates
983 foreach ($this->rawTemplates as $key => $template) {
986 $this->loadWebTemplate($template);
988 // Remember it's contents
989 $this->rawTemplates[$template] = $this->getRawTemplateData();
991 // Remove it from the loader list
992 unset($this->rawTemplates[$key]);
994 // Remember this template for recursion detection
995 // RECURSIVE PROTECTION!
996 $this->loadedTemplates[] = $template;
997 } catch (FileIoException $e) {
998 // This template was never found. We silently ignore it
999 unset($this->rawTemplates[$key]);
1006 * Assign all found template variables
1008 * @param $varMatches An array full of variable/value pairs.
1010 * @todo Unfinished work or don't die here.
1012 private function assignAllVariables (array $varMatches) {
1014 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':varMatches()=' . count($varMatches));
1016 // Search for all variables
1017 foreach ($varMatches[1] as $key => $var) {
1018 // Replace all dashes to underscores to match variables with configuration entries
1019 $var = trim($this->convertDashesToUnderscores($var));
1022 self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':key=' . $key . ',var=' . $var);
1024 // Detect leading equals
1025 if (substr($varMatches[2][$key], 0, 1) == '=') {
1026 // Remove and cast it
1027 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
1030 // Do we have some quotes left and right side? Then it is free text
1031 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
1032 // Free string detected! Which we can assign directly
1033 $this->assignVariable($var, $varMatches[3][$key]);
1034 } elseif (!empty($varMatches[2][$key])) {
1035 // @TODO Non-string found so we need some deeper analysis...
1036 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
1042 * Compiles all loaded raw templates
1044 * @param $templateMatches See method analyzeTemplate() for details
1047 private function compileRawTemplateData (array $templateMatches) {
1049 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':loadedRawData()= ' .count($this->loadedRawData));
1051 // Are some code-templates found which we need to compile?
1052 if (count($this->loadedRawData) > 0) {
1053 // Then compile all!
1054 foreach ($this->loadedRawData as $template => $code) {
1056 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1058 // Is this template already compiled?
1059 if (in_array($template, $this->compiledTemplates)) {
1061 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': Template ' . $template . ' already compiled. SKIPPED!');
1065 // Search for the template
1066 $foundIndex = array_search($template, $templateMatches[1]);
1068 // Lookup the matching variable data
1069 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1070 // Split it up with another reg. exp. into variable=value pairs
1071 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1072 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':varMatches=' . print_r($varMatches, true));
1074 // Assign all variables
1075 $this->assignAllVariables($varMatches);
1076 } // END - if (isset($templateMatches ...
1078 // Compile the loaded template
1079 $this->compileCode($code, $template);
1080 } // END - foreach ($this->loadedRawData ...
1082 // Insert all templates
1083 $this->insertAllTemplates($templateMatches);
1084 } // END - if (count($this->loadedRawData) ...
1088 * Inserts all raw templates into their respective variables
1092 private function insertRawTemplates () {
1093 // Load all templates
1094 foreach ($this->rawTemplates as $template => $content) {
1095 // Set the template as a variable with the content
1096 $this->assignVariable($template, $content);
1101 * Finalizes the compilation of all template variables
1105 private function finalizeVariableCompilation () {
1107 $content = $this->getRawTemplateData();
1108 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': content before=' . strlen($content) . ' (' . md5($content) . ')');
1110 // Do we have the stack?
1111 if (!$this->isVarStackSet('general')) {
1112 // Abort here silently
1113 // @TODO This silent abort should be logged, maybe.
1117 // Walk through all variables
1118 foreach ($this->getVarStack('general') as $currEntry) {
1119 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1120 // Replace all [$var] or {?$var?} with the content
1121 // @TODO Old behaviour, will become obsolete!
1122 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1124 // @TODO Yet another old way
1125 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1127 // The new behaviour
1128 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1131 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': content after=' . strlen($content) . ' (' . md5($content) . ')');
1133 // Set the content back
1134 $this->setRawTemplateData($content);
1138 * Load a specified web template into the engine
1140 * @param $template The web template we shall load which is located in
1144 public function loadWebTemplate ($template) {
1145 // Set template type
1146 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
1148 // Load the special template
1149 $this->loadTemplate($template);
1153 * Assign a given congfiguration variable with a value
1155 * @param $variableName The configuration variable we want to assign
1158 public function assignConfigVariable ($variableName) {
1159 // Replace all dashes to underscores to match variables with configuration entries
1160 $variableName = trim($this->convertDashesToUnderscores($variableName));
1162 // Sweet and simple...
1163 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1164 $this->setVariable('config', $variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1168 * Load a specified code template into the engine
1170 * @param $template The code template we shall load which is
1171 * located in 'code' by default
1174 public function loadCodeTemplate ($template) {
1175 // Set template type
1176 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1178 // Load the special template
1179 $this->loadTemplate($template);
1183 * Compiles configuration place-holders in all variables. This 'walks'
1184 * through the variable group 'general'. It interprets all values from that
1185 * variables as configuration entries after compiling them.
1189 public final function compileConfigInVariables () {
1190 // Do we have the stack?
1191 if (!$this->isVarStackSet('general')) {
1192 // Abort here silently
1193 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': Aborted, variable stack general not found!');
1197 // Iterate through all general variables
1198 foreach ($this->getVarStack('general') as $index => $currVariable) {
1199 // Compile the value
1200 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1203 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': name=' . $currVariable['name'] . ',value=' . $value);
1205 // Remove it from stack
1206 $this->removeVariable($currVariable['name'], 'general');
1208 // Re-assign the variable
1209 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1210 $this->assignConfigVariable($value);
1215 * Compile all variables by inserting their respective values
1218 * @todo Make this code some nicer...
1220 public final function compileVariables () {
1221 // Initialize the $content array
1222 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1225 // Iterate through all general variables
1226 foreach ($this->getVarStack('general') as $currVariable) {
1227 // Transfer it's name/value combination to the $content array
1228 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1229 $dummy[$currVariable['name']] = $currVariable['value'];
1232 // Set the new variable (don't remove the second dollar!)
1233 $$validVar = $dummy;
1235 // Remove some variables
1237 unset($currVariable);
1239 // Run the compilation three times to get content from helper classes in
1242 // Finalize the compilation of template variables
1243 $this->finalizeVariableCompilation();
1245 // Prepare the eval() command for comiling the template
1246 $eval = sprintf("\$result = \"%s\";",
1247 addslashes($this->getRawTemplateData())
1250 // This loop does remove the backslashes (\) in PHP parameters
1251 while (strpos($eval, $this->codeBegin) !== false) {
1252 // Get left part before "<?"
1253 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1255 // Get all from right of "<?"
1256 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1258 // Cut middle part out and remove escapes
1259 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1260 $evalMiddle = stripslashes($evalMiddle);
1262 // Remove the middle part from right one
1263 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1265 // And put all together
1266 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1269 // Prepare PHP code for eval() command
1270 $eval = str_replace(
1279 // Run the constructed command. This will "compile" all variables in
1282 // Goes something wrong?
1283 if ((!isset($result)) || (empty($result))) {
1284 // Output eval command
1285 self::createDebugInstance(__CLASS__)->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1287 // Output backtrace here
1288 $this->debugBackTrace();
1291 // Set raw template data
1292 $this->setRawTemplateData($result);
1296 // Final variable assignment
1297 $this->finalizeVariableCompilation();
1299 // Set the new content
1300 $this->setCompiledData($this->getRawTemplateData());
1304 * Compile all required templates into the current loaded one
1307 * @throws UnexpectedTemplateTypeException If the template type is
1309 * @throws InvalidArrayCountException If an unexpected array
1310 * count has been found
1312 public function compileTemplate () {
1313 // Get code type to make things shorter
1314 $codeType = $this->getConfigInstance()->getConfigEntry('code_template_type');
1316 // We will only work with template type "code" from configuration
1317 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1319 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1322 // Get the raw data.
1323 $rawData = $this->getRawTemplateData();
1325 // Remove double spaces and trim leading/trailing spaces
1326 $rawData = trim(str_replace(' ', ' ', $rawData));
1328 // Search for raw variables
1329 $this->extractVariablesFromRawData($rawData);
1331 // Search for code-tags which are {? ?}
1332 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1335 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':templateMatches=' . print_r($templateMatches , true));
1337 // Analyze the matches array
1338 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1339 // Entries are found:
1341 // The main analysis
1342 $this->analyzeTemplate($templateMatches);
1344 // Compile raw template data
1345 $this->compileRawTemplateData($templateMatches);
1347 // Are there some raw templates left for loading?
1348 $this->loadExtraRawTemplates();
1350 // Are some raw templates found and loaded?
1351 if (count($this->rawTemplates) > 0) {
1352 // Insert all raw templates
1353 $this->insertRawTemplates();
1355 // Remove the raw template content as well
1356 $this->setRawTemplateData('');
1358 } // END - if($templateMatches ...
1362 * Loads a given view helper (by name)
1364 * @param $helperName The helper's name
1367 protected function loadViewHelper ($helperName) {
1368 // Make first character upper case, rest low
1369 $helperName = $this->convertToClassName($helperName);
1371 // Is this view helper loaded?
1372 if (!isset($this->helpers[$helperName])) {
1373 // Create a class name
1374 $className = $helperName . 'ViewHelper';
1376 // Generate new instance
1377 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1380 // Return the requested instance
1381 return $this->helpers[$helperName];
1385 * Assigns the last loaded raw template content with a given variable
1387 * @param $templateName Name of the template we want to assign
1388 * @param $variableName Name of the variable we want to assign
1391 public function assignTemplateWithVariable ($templateName, $variableName) {
1392 // Get the content from last loaded raw template
1393 $content = $this->getRawTemplateData();
1395 // Assign the variable
1396 $this->assignVariable($variableName, $content);
1398 // Purge raw content
1399 $this->setRawTemplateData('');
1403 * Transfers the content of this template engine to a given response instance
1405 * @param $responseInstance An instance of a response class
1408 public function transferToResponse (Responseable $responseInstance) {
1409 // Get the content and set it in response class
1410 $responseInstance->writeToBody($this->getCompiledData());
1414 * Assigns all the application data with template variables
1416 * @param $applicationInstance A manageable application instance
1419 public function assignApplicationData (ManageableApplication $applicationInstance) {
1420 // Get long name and assign it
1421 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1423 // Get short name and assign it
1424 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1426 // Get version number and assign it
1427 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1429 // Assign extra application-depending data
1430 $applicationInstance->assignExtraTemplateData($this);
1434 * "Compiles" a variable by replacing {?var?} with it's content
1436 * @param $rawCode Raw code to compile
1437 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1438 * @return $rawCode Compile code with inserted variable value
1440 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1441 // Find the variables
1442 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1443 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1445 // Compile all variables
1446 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':<pre>' . print_r($varMatches, true) . '</pre>');
1447 foreach ($varMatches[0] as $match) {
1448 // Add variable tags around it
1449 $varCode = '{?' . $match . '?}';
1452 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':varCode=' . $varCode);
1454 // Is the variable found in code? (safes some calls)
1455 if (strpos($rawCode, $varCode) !== false) {
1457 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1459 // Use $match as new value or $value from read variable?
1460 if ($setMatchAsCode === true) {
1462 $rawCode = str_replace($varCode, $match, $rawCode);
1464 // Read the variable
1465 $value = $this->readVariable($match);
1468 $rawCode = str_replace($varCode, $value, $rawCode);
1473 // Return the compiled data
1474 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ':rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1479 * Getter for variable group array
1481 * @return $vargroups All variable groups
1483 public final function getVariableGroups () {
1484 return $this->varGroups;
1488 * Renames a variable in code and in stack
1490 * @param $oldName Old name of variable
1491 * @param $newName New name of variable
1494 public function renameVariable ($oldName, $newName) {
1495 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__ . ': oldName=' . $oldName . ', newName=' . $newName);
1496 // Get raw template code
1497 $rawData = $this->getRawTemplateData();
1500 $rawData = str_replace($oldName, $newName, $rawData);
1502 // Set the code back
1503 $this->setRawTemplateData($rawData);
1507 * Renders the given XML content
1509 * @param $content Valid XML content or if not set the current loaded raw content
1511 * @throws XmlParserException If an XML error was found
1513 public function renderXmlContent ($content = NULL) {
1514 // Is the content set?
1515 if (is_null($content)) {
1516 // Get current content
1517 $content = $this->getRawTemplateData();
1520 // Get a XmlParser instance
1521 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1523 // Check if we have XML compacting enabled
1524 if ($this->isXmlCompactingEnabled()) {
1525 // Yes, so get a decorator class for transparent compacting
1526 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1529 // Parse the XML document
1530 $parserInstance->parseXmlContent($content);
1534 * Enables or disables language support
1536 * @param $languageSupport New language support setting
1539 public final function enableLanguageSupport ($languageSupport = true) {
1540 $this->languageSupport = (bool) $languageSupport;
1544 * Checks whether language support is enabled
1546 * @return $languageSupport Whether language support is enabled or disabled
1548 public final function isLanguageSupportEnabled () {
1549 return $this->languageSupport;
1553 * Enables or disables XML compacting
1555 * @param $xmlCompacting New XML compacting setting
1558 public final function enableXmlCompacting ($xmlCompacting = true) {
1559 $this->xmlCompacting = (bool) $xmlCompacting;
1563 * Checks whether XML compacting is enabled
1565 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1567 public final function isXmlCompactingEnabled () {
1568 return $this->xmlCompacting;
1572 * Removes all commentd, tabs and new-line characters to compact the content
1574 * @param $uncompactedContent The uncompacted content
1575 * @return $compactedContent The compacted content
1577 public function compactContent ($uncompactedContent) {
1578 // First, remove all tab/new-line/revert characters
1579 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1581 // Then regex all comments like <!-- //--> away
1582 preg_match_all('/<!--[\w\W]*?(\/\/){0,1}-->/', $compactedContent, $matches);
1584 // Do we have entries?
1585 if (isset($matches[0][0])) {
1587 foreach ($matches[0] as $match) {
1589 $compactedContent = str_replace($match, '', $compactedContent);
1593 // Set the content again
1594 $this->setRawTemplateData($compactedContent);
1596 // Return compacted content
1597 return $compactedContent;