3 namespace CoreFramework\TemplateEngine;
5 // Import framework stuff
6 use CoreFramework\Manager\ManageableApplication;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 * A generic template engine
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class BaseTemplateEngine extends BaseFrameworkSystem {
33 * The local path name where all templates and sub folders for special
34 * templates are stored. We will internally determine the language plus
35 * "html" for web templates or "emails" for email templates
37 private $templateBasePath = '';
42 private $templateType = 'html';
45 * The extension for web and email templates (not compiled templates)
47 private $templateExtension = '.tpl';
50 * The extension for code templates (not compiled templates)
52 private $codeExtension = '.ctp';
55 * Path relative to $templateBasePath and language code for compiled code-templates
57 private $compileOutputPath = 'templates/_compiled/';
60 * The path name for all templates
62 private $genericBasePath = 'templates/';
65 * The raw (maybe uncompiled) template
67 private $rawTemplateData = '';
70 * Template data with compiled-in variables
72 private $compiledData = '';
75 * The last loaded template's FQFN for debugging the engine
77 private $lastTemplate = '';
80 * The variable stack for the templates
82 private $varStack = array();
85 * Loaded templates for recursive protection and detection
87 private $loadedTemplates = array();
90 * Compiled templates for recursive protection and detection
92 private $compiledTemplates = array();
95 * Loaded raw template data
97 private $loadedRawData = NULL;
100 * Raw templates which are linked in code templates
102 private $rawTemplates = NULL;
105 * A regular expression for variable=value pairs
107 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
110 * A regular expression for filtering out code tags
112 * E.g.: {?template:variable=value;var2=value2;[...]?}
114 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
117 * A regular expression to find template comments like <!-- Comment here //-->
119 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
124 private $helpers = array();
127 * Current variable group
129 private $currGroup = 'general';
132 * All template groups except "general"
134 private $variableGroups = array();
139 private $codeBegin = '<?php';
144 private $codeEnd = '?>';
147 * Language support is enabled by default
149 private $languageSupport = TRUE;
152 * XML compacting is disabled by default
154 private $xmlCompacting = FALSE;
156 // Exception codes for the template engine
157 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
158 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
159 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
160 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
163 * Protected constructor
165 * @param $className Name of the class
168 protected function __construct ($className) {
169 // Call parent constructor
170 parent::__construct($className);
172 // Init file I/O instance
173 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
176 $this->setFileIoInstance($ioInstance);
180 * Search for a variable in the stack
182 * @param $variableName The variable we are looking for
183 * @param $variableGroup Optional variable group to look in
184 * @return $index FALSE means not found, >=0 means found on a specific index
186 private function getVariableIndex ($variableName, $variableGroup = NULL) {
187 // Replace all dashes to underscores to match variables with configuration entries
188 $variableName = trim(self::convertDashesToUnderscores($variableName));
190 // First everything is not found
193 // If the stack is NULL, use the current group
194 if (is_null($variableGroup)) {
196 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
197 $variableGroup = $this->currGroup;
200 // Is the group there?
201 if ($this->isVarStackSet($variableGroup)) {
203 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
204 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
205 // Is the entry found?
206 if ($currEntry['name'] == $variableName) {
208 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.':FOUND!');
215 // Return the current position
220 * Checks whether the given variable group is set
222 * @param $variableGroup Variable group to check
223 * @return $isSet Whether the given variable group is set
225 protected final function isVarStackSet ($variableGroup) {
227 $isSet = isset($this->varStack[$variableGroup]);
234 * Getter for given variable group
236 * @param $variableGroup Variable group to check
237 * @return $varStack Found variable group
239 public final function getVarStack ($variableGroup) {
240 return $this->varStack[$variableGroup];
244 * Setter for given variable group
246 * @param $variableGroup Variable group to check
247 * @param $varStack Variable stack to check
250 protected final function setVarStack ($variableGroup, array $varStack) {
251 $this->varStack[$variableGroup] = $varStack;
255 * Return a content of a variable or null if not found
257 * @param $variableName The variable we are looking for
258 * @param $variableGroup Optional variable group to look in
259 * @return $content Content of the variable or null if not found
261 protected function readVariable ($variableName, $variableGroup = NULL) {
262 // Replace all dashes to underscores to match variables with configuration entries
263 $variableName = trim(self::convertDashesToUnderscores($variableName));
265 // First everything is not found
268 // If the stack is NULL, use the current group
269 if (is_null($variableGroup)) {
271 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
272 $variableGroup = $this->currGroup;
275 // Get variable index
276 $found = $this->getVariableIndex($variableName, $variableGroup);
278 // Is the variable found?
279 if ($found !== FALSE) {
281 $content = $this->getVariableValue($variableGroup, $found);
284 // Return the current position
285 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
290 * Add a variable to the stack
292 * @param $variableName Name of variable to add
293 * @param $value Value we want to store in the variable
296 private function addVariable ($variableName, $value) {
297 // Set general variable group
298 $this->setVariableGroup('general');
300 // Add it to the stack
301 $this->addGroupVariable($variableName, $value);
305 * Returns all variables of current group or empty array
307 * @return $result Whether array of found variables or empty array
309 private function readCurrentGroup () {
310 // Default is not found
313 // Is the group there?
314 if ($this->isVarStackSet($this->currGroup)) {
316 $result = $this->getVarStack($this->currGroup);
324 * Settter for variable group
326 * @param $groupName Name of variable group
327 * @param $add Whether add this group
330 public function setVariableGroup ($groupName, $add = TRUE) {
332 //* DEBIG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
333 $this->currGroup = $groupName;
335 // Skip group 'general'
336 if (($groupName != 'general') && ($add === TRUE)) {
337 $this->variableGroups[$groupName] = 'OK';
343 * Adds a variable to current group
345 * @param $variableName Variable to set
346 * @param $value Value to store in variable
349 public function addGroupVariable ($variableName, $value) {
350 // Replace all dashes to underscores to match variables with configuration entries
351 $variableName = trim(self::convertDashesToUnderscores($variableName));
354 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
356 // Get current variables in group
357 $currVars = $this->readCurrentGroup();
359 // Append our variable
360 array_push($currVars, $this->generateVariableArray($variableName, $value));
362 // Add it to the stack
363 $this->setVarStack($this->currGroup, $currVars);
367 * Getter for variable value, throws a NoVariableException if the variable is not found
369 * @param $variableGroup Variable group to use
370 * @param $index Index in variable array
371 * @return $value Value to set
373 private function getVariableValue ($variableGroup, $index) {
375 return $this->varStack[$variableGroup][$index]['value'];
379 * Modify an entry on the stack
381 * @param $variableName The variable we are looking for
382 * @param $value The value we want to store in the variable
384 * @throws NoVariableException If the given variable is not found
386 private function modifyVariable ($variableName, $value) {
387 // Replace all dashes to underscores to match variables with configuration entries
388 $variableName = trim(self::convertDashesToUnderscores($variableName));
390 // Get index for variable
391 $index = $this->getVariableIndex($variableName);
393 // Is the variable set?
394 if ($index === FALSE) {
395 // Unset variables cannot be modified
396 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
400 $this->setVariableValue($this->currGroup, $index, $value);
404 * Sets a variable value for given variable group and index
406 * @param $variableGroup Variable group to use
407 * @param $index Index in variable array
408 * @param $value Value to set
411 private function setVariableValue ($variableGroup, $index, $value) {
412 $this->varStack[$variableGroup][$index]['value'] = $value;
416 * Sets a variable within given group. This method does detect if the
417 * variable is already set. If so, the variable got modified, otherwise
420 * @param $variableGroup Variable group to use
421 * @param $variableName Variable to set
422 * @param $value Value to set
425 protected function setVariable ($variableGroup, $variableName, $value) {
426 // Replace all dashes to underscores to match variables with configuration entries
427 $variableName = trim(self::convertDashesToUnderscores($variableName));
429 // Get index for variable
430 $index = $this->getVariableIndex($variableName);
432 // Is the variable set?
433 if ($index === FALSE) {
434 // Is the stack there?
435 if (!isset($this->varStack[$variableGroup])) {
436 // Then initialize it here
437 $this->varStack[$variableGroup] = array();
441 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
444 $this->setVariableValue($this->currGroup, $index, $value);
449 * "Generates" (better returns) an array for all variables for given
450 * variable/value pay.
452 * @param $variableName Variable to set
453 * @param $value Value to set
454 * @return $varData Variable data array
456 private function generateVariableArray ($variableName, $value) {
457 // Replace all dashes to underscores to match variables with configuration entries
458 $variableName = trim(self::convertDashesToUnderscores($variableName));
460 // Generate the temporary array
462 'name' => $variableName,
471 * Setter for template type. Only 'html', 'emails' and 'compiled' should
474 * @param $templateType The current template's type
477 protected final function setTemplateType ($templateType) {
478 $this->templateType = (string) $templateType;
482 * Getter for template type
484 * @return $templateType The current template's type
486 public final function getTemplateType () {
487 return $this->templateType;
491 * Setter for the last loaded template's FQFN
493 * @param $template The last loaded template
496 private final function setLastTemplate ($template) {
497 $this->lastTemplate = (string) $template;
501 * Getter for the last loaded template's FQFN
503 * @return $template The last loaded template
505 private final function getLastTemplate () {
506 return $this->lastTemplate;
510 * Setter for base path
512 * @param $templateBasePath The relative base path for all templates
515 protected final function setTemplateBasePath ($templateBasePath) {
517 $this->templateBasePath = (string) $templateBasePath;
521 * Getter for base path
523 * @return $templateBasePath The relative base path for all templates
525 public final function getTemplateBasePath () {
527 return $this->templateBasePath;
531 * Getter for generic base path
533 * @return $templateBasePath The relative base path for all templates
535 public final function getGenericBasePath () {
537 return $this->genericBasePath;
541 * Setter for template extension
543 * @param $templateExtension The file extension for all uncompiled
547 protected final function setRawTemplateExtension ($templateExtension) {
549 $this->templateExtension = (string) $templateExtension;
553 * Setter for code template extension
555 * @param $codeExtension The file extension for all uncompiled
559 protected final function setCodeTemplateExtension ($codeExtension) {
561 $this->codeExtension = (string) $codeExtension;
565 * Getter for template extension
567 * @return $templateExtension The file extension for all uncompiled
570 public final function getRawTemplateExtension () {
572 return $this->templateExtension;
576 * Getter for code-template extension
578 * @return $codeExtension The file extension for all code-
581 public final function getCodeTemplateExtension () {
583 return $this->codeExtension;
587 * Setter for path of compiled templates
589 * @param $compileOutputPath The local base path for all compiled
593 protected final function setCompileOutputPath ($compileOutputPath) {
595 $this->compileOutputPath = (string) $compileOutputPath;
599 * Unsets the given offset in the variable group
601 * @param $index Index to unset
602 * @param $variableGroup Variable group (default: currGroup)
605 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
606 // Is the variable group not set?
607 if (is_null($variableGroup)) {
608 // Then set it to current
609 $variableGroup = $this->currGroup;
612 // Is the entry there?
613 if (!isset($this->varStack[$variableGroup][$index])) {
614 // Abort here, we need fixing!
615 $this->debugInstance();
619 unset($this->varStack[$variableGroup][$index]);
623 * Private setter for raw template data
625 * @param $rawTemplateData The raw data from the template
628 protected final function setRawTemplateData ($rawTemplateData) {
629 // And store it in this class
630 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
631 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
632 $this->rawTemplateData = (string) $rawTemplateData;
636 * Getter for raw template data
638 * @return $rawTemplateData The raw data from the template
640 public final function getRawTemplateData () {
641 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
642 return $this->rawTemplateData;
646 * Private setter for compiled templates
650 private final function setCompiledData ($compiledData) {
651 // And store it in this class
652 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
653 $this->compiledData = (string) $compiledData;
657 * Getter for compiled templates, must be public for e.g. Mailer classes.
659 * @return $compiledData Compiled template data
661 public final function getCompiledData () {
662 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
663 return $this->compiledData;
667 * Private loader for all template types
669 * @param $template The template we shall load
670 * @param $extOther An other extension to use
672 * @throws FileNotFoundException If the template was not found
674 protected function loadTemplate ($template, $extOther = '') {
675 // Get extension for the template if empty
676 if (empty($extOther)) {
677 // None provided, so get the raw one
678 $ext = $this->getRawTemplateExtension();
681 $ext = (string) $extOther;
685 * Construct the FQFN for the template without language as language is
686 * now entirely done by php_intl. These old thing with language-based
687 * template paths comes from an older time.
689 $fqfn = sprintf('%s%s%s%s/%s%s',
690 $this->getConfigInstance()->getConfigEntry('base_path'),
691 $this->getTemplateBasePath(),
692 $this->getGenericBasePath(),
693 $this->getTemplateType(),
700 // Load the raw template data
701 $this->loadRawTemplateData($fqfn);
702 } catch (FileNotFoundException $e) {
703 // If we shall load a code-template we need to switch the file extension
704 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
705 // Switch over to the code-template extension and try it again
706 $ext = $this->getCodeTemplateExtension();
709 $this->loadTemplate($template, $ext);
712 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
719 * A private loader for raw template names
721 * @param $fqfn The full-qualified file name for a template
724 private function loadRawTemplateData ($fqfn) {
725 // Some debug code to look on the file which is being loaded
726 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
728 // Load the raw template
729 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
731 // Store the template's contents into this class
732 $this->setRawTemplateData($rawTemplateData);
734 // Remember the template's FQFN
735 $this->setLastTemplate($fqfn);
739 * Try to assign an extracted template variable as a "content" or 'config'
742 * @param $variableName The variable's name (shall be content or config)
744 * @param $variableName The variable we want to assign
747 private function assignTemplateVariable ($variableName, $var) {
748 // Replace all dashes to underscores to match variables with configuration entries
749 $variableName = trim(self::convertDashesToUnderscores($variableName));
752 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
754 // Is it not a config variable?
755 if ($variableName != 'config') {
756 // Regular template variables
757 $this->assignVariable($variableName, '');
759 // Configuration variables
760 $this->assignConfigVariable($var);
765 * Extract variables from a given raw data stream
767 * @param $rawData The raw template data we shall analyze
770 private function extractVariablesFromRawData ($rawData) {
772 $rawData = (string) $rawData;
774 // Search for variables
775 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
778 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
780 // Did we find some variables?
781 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
782 // Initialize all missing variables
783 foreach ($variableMatches[3] as $key => $var) {
785 $variableName = $variableMatches[1][$key];
787 // Workarround: Do not assign empty variables
789 // Try to assign it, empty strings are being ignored
790 $this->assignTemplateVariable($variableName, $var);
797 * Main analysis of the loaded template
799 * @param $templateMatches Found template place-holders, see below
802 *---------------------------------
803 * Structure of $templateMatches:
804 *---------------------------------
805 * [0] => Array - An array with all full matches
806 * [1] => Array - An array with left part (before the ':') of a match
807 * [2] => Array - An array with right part of a match including ':'
808 * [3] => Array - An array with right part of a match excluding ':'
810 private function analyzeTemplate (array $templateMatches) {
811 // Backup raw template data
812 $backup = $this->getRawTemplateData();
814 // Initialize some arrays
815 if (is_null($this->loadedRawData)) {
817 $this->loadedRawData = array();
818 $this->rawTemplates = array();
821 // Load all requested templates
822 foreach ($templateMatches[1] as $template) {
823 // Load and compile only templates which we have not yet loaded
824 // RECURSIVE PROTECTION! BE CAREFUL HERE!
825 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
827 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
829 // Template not found, but maybe variable assigned?
830 if ($this->getVariableIndex($template) !== FALSE) {
831 // Use that content here
832 $this->loadedRawData[$template] = $this->readVariable($template);
834 // Recursive protection:
835 array_push($this->loadedTemplates, $template);
837 // Then try to search for code-templates
839 // Load the code template and remember it's contents
840 $this->loadCodeTemplate($template);
841 $this->loadedRawData[$template] = $this->getRawTemplateData();
843 // Remember this template for recursion detection
844 // RECURSIVE PROTECTION!
845 array_push($this->loadedTemplates, $template);
846 } catch (FileNotFoundException $e) {
847 // Even this is not done... :/
848 array_push($this->rawTemplates, $template);
854 // Restore the raw template data
855 $this->setRawTemplateData($backup);
859 * Compile a given raw template code and remember it for later usage
861 * @param $code The raw template code
862 * @param $template The template's name
865 private function compileCode ($code, $template) {
866 // Is this template already compiled?
867 if (in_array($template, $this->compiledTemplates)) {
872 // Remember this template being compiled
873 array_push($this->compiledTemplates, $template);
875 // Compile the loaded code in five steps:
877 // 1. Backup current template data
878 $backup = $this->getRawTemplateData();
880 // 2. Set the current template's raw data as the new content
881 $this->setRawTemplateData($code);
883 // 3. Compile the template data
884 $this->compileTemplate();
886 // 4. Remember it's contents
887 $this->loadedRawData[$template] = $this->getRawTemplateData();
889 // 5. Restore the previous raw content from backup variable
890 $this->setRawTemplateData($backup);
894 * Insert all given and loaded templates by running through all loaded
895 * codes and searching for their place-holder in the main template
897 * @param $templateMatches See method analyzeTemplate()
900 private function insertAllTemplates (array $templateMatches) {
901 // Run through all loaded codes
902 foreach ($this->loadedRawData as $template => $code) {
904 // Search for the template
905 $foundIndex = array_search($template, $templateMatches[1]);
907 // Lookup the matching template replacement
908 if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
910 // Get the current raw template
911 $rawData = $this->getRawTemplateData();
913 // Replace the space holder with the template code
914 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
916 // Set the new raw data
917 $this->setRawTemplateData($rawData);
923 * Load all extra raw templates
927 private function loadExtraRawTemplates () {
928 // Are there some raw templates we need to load?
929 if (count($this->rawTemplates) > 0) {
930 // Try to load all raw templates
931 foreach ($this->rawTemplates as $key => $template) {
934 $this->loadHtmlTemplate($template);
936 // Remember it's contents
937 $this->rawTemplates[$template] = $this->getRawTemplateData();
939 // Remove it from the loader list
940 unset($this->rawTemplates[$key]);
942 // Remember this template for recursion detection
943 // RECURSIVE PROTECTION!
944 array_push($this->loadedTemplates, $template);
945 } catch (FileNotFoundException $e) {
946 // This template was never found. We silently ignore it
947 unset($this->rawTemplates[$key]);
954 * Assign all found template variables
956 * @param $varMatches An array full of variable/value pairs.
958 * @todo Unfinished work or don't die here.
960 private function assignAllVariables (array $varMatches) {
962 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
964 // Search for all variables
965 foreach ($varMatches[1] as $key => $var) {
966 // Replace all dashes to underscores to match variables with configuration entries
967 $var = trim(self::convertDashesToUnderscores($var));
970 self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
972 // Detect leading equals
973 if (substr($varMatches[2][$key], 0, 1) == '=') {
974 // Remove and cast it
975 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
978 // Do we have some quotes left and right side? Then it is free text
979 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
980 // Free string detected! Which we can assign directly
981 $this->assignVariable($var, $varMatches[3][$key]);
982 } elseif (!empty($varMatches[2][$key])) {
983 // @TODO Non-string found so we need some deeper analysis...
984 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
990 * Compiles all loaded raw templates
992 * @param $templateMatches See method analyzeTemplate() for details
995 private function compileRawTemplateData (array $templateMatches) {
997 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
999 // Are some code-templates found which we need to compile?
1000 if (count($this->loadedRawData) > 0) {
1001 // Then compile all!
1002 foreach ($this->loadedRawData as $template => $code) {
1004 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1006 // Is this template already compiled?
1007 if (in_array($template, $this->compiledTemplates)) {
1009 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1013 // Search for the template
1014 $foundIndex = array_search($template, $templateMatches[1]);
1016 // Lookup the matching variable data
1017 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1018 // Split it up with another reg. exp. into variable=value pairs
1019 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1020 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1022 // Assign all variables
1023 $this->assignAllVariables($varMatches);
1024 } // END - if (isset($templateMatches ...
1026 // Compile the loaded template
1027 $this->compileCode($code, $template);
1028 } // END - foreach ($this->loadedRawData ...
1030 // Insert all templates
1031 $this->insertAllTemplates($templateMatches);
1032 } // END - if (count($this->loadedRawData) ...
1036 * Inserts all raw templates into their respective variables
1040 private function insertRawTemplates () {
1041 // Load all templates
1042 foreach ($this->rawTemplates as $template => $content) {
1043 // Set the template as a variable with the content
1044 $this->assignVariable($template, $content);
1049 * Finalizes the compilation of all template variables
1053 private function finalizeVariableCompilation () {
1055 $content = $this->getRawTemplateData();
1056 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1058 // Do we have the stack?
1059 if (!$this->isVarStackSet('general')) {
1060 // Abort here silently
1061 // @TODO This silent abort should be logged, maybe.
1065 // Walk through all variables
1066 foreach ($this->getVarStack('general') as $currEntry) {
1067 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1068 // Replace all [$var] or {?$var?} with the content
1069 // @TODO Old behaviour, will become obsolete!
1070 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1072 // @TODO Yet another old way
1073 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1075 // The new behaviour
1076 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1079 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1081 // Set the content back
1082 $this->setRawTemplateData($content);
1086 * Load a specified HTML template into the engine
1088 * @param $template The web template we shall load which is located in
1092 public function loadHtmlTemplate ($template) {
1093 // Set template type
1094 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1096 // Load the special template
1097 $this->loadTemplate($template);
1101 * Assign (add) a given variable with a value
1103 * @param $variableName The variable we are looking for
1104 * @param $value The value we want to store in the variable
1106 * @throws EmptyVariableException If the variable name is left empty
1108 public final function assignVariable ($variableName, $value) {
1109 // Replace all dashes to underscores to match variables with configuration entries
1110 $variableName = trim(self::convertDashesToUnderscores($variableName));
1112 // Empty variable found?
1113 if (empty($variableName)) {
1114 // Throw an exception
1115 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1118 // First search for the variable if it was already added
1119 $index = $this->getVariableIndex($variableName);
1122 if ($index === FALSE) {
1123 // Add it to the stack
1124 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1125 $this->addVariable($variableName, $value);
1126 } elseif (!empty($value)) {
1127 // Modify the stack entry
1128 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1129 $this->modifyVariable($variableName, $value);
1134 * Removes a given variable
1136 * @param $variableName The variable we are looking for
1137 * @param $variableGroup Name of variable group (default: 'general')
1140 public final function removeVariable ($variableName, $variableGroup = 'general') {
1141 // First search for the variable if it was already added
1142 $index = $this->getVariableIndex($variableName, $variableGroup);
1145 if ($index !== FALSE) {
1146 // Remove this variable
1147 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1148 $this->unsetVariableStackOffset($index, $variableGroup);
1153 * Assigns the last loaded raw template content with a given variable
1155 * @param $templateName Name of the template we want to assign
1156 * @param $variableName Name of the variable we want to assign
1159 public function assignTemplateWithVariable ($templateName, $variableName) {
1160 // Get the content from last loaded raw template
1161 $content = $this->getRawTemplateData();
1163 // Assign the variable
1164 $this->assignVariable($variableName, $content);
1166 // Purge raw content
1167 $this->setRawTemplateData('');
1171 * Assign a given congfiguration variable with a value
1173 * @param $variableName The configuration variable we want to assign
1176 public function assignConfigVariable ($variableName) {
1177 // Replace all dashes to underscores to match variables with configuration entries
1178 $variableName = trim(self::convertDashesToUnderscores($variableName));
1180 // Sweet and simple...
1181 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1182 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1186 * Assigns a lot variables into the stack of currently loaded template.
1187 * This method should only be used in very rare circumstances, e.g. when
1188 * you have to copy a whole set of variables into the template engine.
1189 * Before you use this method, please make sure you have considered all
1190 * other possiblities.
1192 * @param $variables An array with variables to be assigned
1195 public function assignMultipleVariables (array $variables) {
1197 foreach ($variables as $name => $value) {
1198 // Set variable with name for 'config' group
1199 $this->assignVariable($name, $value);
1204 * Assigns all the application data with template variables
1206 * @param $applicationInstance A manageable application instance
1209 public function assignApplicationData (ManageableApplication $applicationInstance) {
1210 // Get long name and assign it
1211 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1213 // Get short name and assign it
1214 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1216 // Get version number and assign it
1217 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1219 // Assign extra application-depending data
1220 $applicationInstance->assignExtraTemplateData($this);
1224 * Load a specified code template into the engine
1226 * @param $template The code template we shall load which is
1227 * located in 'code' by default
1230 public function loadCodeTemplate ($template) {
1231 // Set template type
1232 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type'));
1234 // Load the special template
1235 $this->loadTemplate($template);
1239 * Load a specified email template into the engine
1241 * @param $template The email template we shall load which is
1242 * located in 'emails' by default
1245 public function loadEmailTemplate ($template) {
1246 // Set template type
1247 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1249 // Load the special template
1250 $this->loadTemplate($template);
1254 * Compiles configuration place-holders in all variables. This 'walks'
1255 * through the variable group 'general'. It interprets all values from that
1256 * variables as configuration entries after compiling them.
1260 public final function compileConfigInVariables () {
1261 // Do we have the stack?
1262 if (!$this->isVarStackSet('general')) {
1263 // Abort here silently
1264 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1268 // Iterate through all general variables
1269 foreach ($this->getVarStack('general') as $index => $currVariable) {
1270 // Compile the value
1271 $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1274 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1276 // Remove it from stack
1277 $this->removeVariable($currVariable['name'], 'general');
1278 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1280 // Is it a configuration key?
1281 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1282 // The value itself is a configuration entry
1283 $this->assignConfigVariable($value);
1285 // Re-assign the value directly
1286 $this->assignVariable($currVariable['name'], $value);
1292 * Compile all variables by inserting their respective values
1295 * @todo Make this code some nicer...
1297 public final function compileVariables () {
1298 // Initialize the $content array
1299 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1302 // Iterate through all general variables
1303 foreach ($this->getVarStack('general') as $currVariable) {
1304 // Transfer it's name/value combination to the $content array
1305 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1306 $dummy[$currVariable['name']] = $currVariable['value'];
1309 // Set the new variable (don't remove the second dollar!)
1310 $$validVar = $dummy;
1312 // Remove some variables
1314 unset($currVariable);
1316 // Run the compilation three times to get content from helper classes in
1319 // Finalize the compilation of template variables
1320 $this->finalizeVariableCompilation();
1322 // Prepare the eval() command for comiling the template
1323 $eval = sprintf('$result = "%s";',
1324 addslashes($this->getRawTemplateData())
1327 // This loop does remove the backslashes (\) in PHP parameters
1328 while (strpos($eval, $this->codeBegin) !== FALSE) {
1329 // Get left part before "<?"
1330 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1332 // Get all from right of "<?"
1333 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1335 // Cut middle part out and remove escapes
1336 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1337 $evalMiddle = stripslashes($evalMiddle);
1339 // Remove the middle part from right one
1340 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1342 // And put all together
1343 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1346 // Prepare PHP code for eval() command
1347 $eval = str_replace(
1356 // Run the constructed command. This will "compile" all variables in
1359 // Goes something wrong?
1360 if ((!isset($result)) || (empty($result))) {
1361 // Output eval command
1362 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1364 // Output backtrace here
1365 $this->debugBackTrace();
1368 // Set raw template data
1369 $this->setRawTemplateData($result);
1373 // Final variable assignment
1374 $this->finalizeVariableCompilation();
1376 // Set the new content
1377 $this->setCompiledData($this->getRawTemplateData());
1381 * Compile all required templates into the current loaded one
1384 * @throws UnexpectedTemplateTypeException If the template type is
1386 * @throws InvalidArrayCountException If an unexpected array
1387 * count has been found
1389 public function compileTemplate () {
1390 // Get code type to make things shorter
1391 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type');
1393 // We will only work with template type "code" from configuration
1394 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1396 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1399 // Get the raw data.
1400 $rawData = $this->getRawTemplateData();
1402 // Remove double spaces and trim leading/trailing spaces
1403 $rawData = trim(str_replace(' ', ' ', $rawData));
1405 // Search for raw variables
1406 $this->extractVariablesFromRawData($rawData);
1408 // Search for code-tags which are {? ?}
1409 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1412 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1414 // Analyze the matches array
1415 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1416 // Entries are found:
1418 // The main analysis
1419 $this->analyzeTemplate($templateMatches);
1421 // Compile raw template data
1422 $this->compileRawTemplateData($templateMatches);
1424 // Are there some raw templates left for loading?
1425 $this->loadExtraRawTemplates();
1427 // Are some raw templates found and loaded?
1428 if (count($this->rawTemplates) > 0) {
1429 // Insert all raw templates
1430 $this->insertRawTemplates();
1432 // Remove the raw template content as well
1433 $this->setRawTemplateData('');
1435 } // END - if($templateMatches ...
1439 * Loads a given view helper (by name)
1441 * @param $helperName The helper's name
1444 protected function loadViewHelper ($helperName) {
1445 // Is this view helper loaded?
1446 if (!isset($this->helpers[$helperName])) {
1447 // Create a class name
1448 $className = self::convertToClassName($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 $variableGroups All variable groups
1519 public final function getVariableGroups () {
1520 return $this->variableGroups;
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 XML compacting is 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;