3 namespace CoreFramework\Template\Engine;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Manager\ManageableApplication;
8 use CoreFramework\Object\BaseFrameworkSystem;
11 * A generic template engine
13 * @author Roland Haeder <webmaster@shipsimu.org>
15 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
16 * @license GNU GPL 3.0 or any newer version
17 * @link http://www.shipsimu.org
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 class BaseTemplateEngine extends BaseFrameworkSystem {
34 * The local path name where all templates and sub folders for special
35 * templates are stored. We will internally determine the language plus
36 * "html" for web templates or "emails" for email templates
38 private $templateBasePath = '';
43 private $templateType = 'html';
46 * The extension for web and email templates (not compiled templates)
48 private $templateExtension = '.tpl';
51 * The extension for code templates (not compiled templates)
53 private $codeExtension = '.ctp';
56 * Path relative to $templateBasePath and language code for compiled code-templates
58 private $compileOutputPath = 'templates/_compiled/';
61 * The path name for all templates
63 private $genericBasePath = 'templates/';
66 * The raw (maybe uncompiled) template
68 private $rawTemplateData = '';
71 * Template data with compiled-in variables
73 private $compiledData = '';
76 * The last loaded template's FQFN for debugging the engine
78 private $lastTemplate = '';
81 * The variable stack for the templates
83 private $varStack = array();
86 * Loaded templates for recursive protection and detection
88 private $loadedTemplates = array();
91 * Compiled templates for recursive protection and detection
93 private $compiledTemplates = array();
96 * Loaded raw template data
98 private $loadedRawData = NULL;
101 * Raw templates which are linked in code templates
103 private $rawTemplates = NULL;
106 * A regular expression for variable=value pairs
108 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
111 * A regular expression for filtering out code tags
113 * E.g.: {?template:variable=value;var2=value2;[...]?}
115 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
118 * A regular expression to find template comments like <!-- Comment here //-->
120 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
125 private $helpers = array();
128 * Current variable group
130 private $currGroup = 'general';
133 * All template groups except "general"
135 private $variableGroups = array();
140 private $codeBegin = '<?php';
145 private $codeEnd = '?>';
148 * Language support is enabled by default
150 private $languageSupport = TRUE;
153 * XML compacting is disabled by default
155 private $xmlCompacting = FALSE;
157 // Exception codes for the template engine
158 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
159 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
160 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
161 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
164 * Protected constructor
166 * @param $className Name of the class
169 protected function __construct ($className) {
170 // Call parent constructor
171 parent::__construct($className);
173 // Init file I/O instance
174 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
177 $this->setFileIoInstance($ioInstance);
181 * Search for a variable in the stack
183 * @param $variableName The variable we are looking for
184 * @param $variableGroup Optional variable group to look in
185 * @return $index FALSE means not found, >=0 means found on a specific index
187 private function getVariableIndex ($variableName, $variableGroup = NULL) {
188 // Replace all dashes to underscores to match variables with configuration entries
189 $variableName = trim(self::convertDashesToUnderscores($variableName));
191 // First everything is not found
194 // If the stack is NULL, use the current group
195 if (is_null($variableGroup)) {
197 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
198 $variableGroup = $this->currGroup;
201 // Is the group there?
202 if ($this->isVarStackSet($variableGroup)) {
204 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
205 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
206 // Is the entry found?
207 if ($currEntry['name'] == $variableName) {
209 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
216 // Return the current position
221 * Checks whether the given variable group is set
223 * @param $variableGroup Variable group to check
224 * @return $isSet Whether the given variable group is set
226 protected final function isVarStackSet ($variableGroup) {
228 $isSet = isset($this->varStack[$variableGroup]);
235 * Getter for given variable group
237 * @param $variableGroup Variable group to check
238 * @return $varStack Found variable group
240 public final function getVarStack ($variableGroup) {
241 return $this->varStack[$variableGroup];
245 * Setter for given variable group
247 * @param $variableGroup Variable group to check
248 * @param $varStack Variable stack to check
251 protected final function setVarStack ($variableGroup, array $varStack) {
252 $this->varStack[$variableGroup] = $varStack;
256 * Return a content of a variable or null if not found
258 * @param $variableName The variable we are looking for
259 * @param $variableGroup Optional variable group to look in
260 * @return $content Content of the variable or null if not found
262 protected function readVariable ($variableName, $variableGroup = NULL) {
263 // Replace all dashes to underscores to match variables with configuration entries
264 $variableName = trim(self::convertDashesToUnderscores($variableName));
266 // First everything is not found
269 // If the stack is NULL, use the current group
270 if (is_null($variableGroup)) {
272 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
273 $variableGroup = $this->currGroup;
276 // Get variable index
277 $found = $this->getVariableIndex($variableName, $variableGroup);
279 // Is the variable found?
280 if ($found !== FALSE) {
282 $content = $this->getVariableValue($variableGroup, $found);
285 // Return the current position
286 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
291 * Add a variable to the stack
293 * @param $variableName Name of variable to add
294 * @param $value Value we want to store in the variable
297 private function addVariable ($variableName, $value) {
298 // Set general variable group
299 $this->setVariableGroup('general');
301 // Add it to the stack
302 $this->addGroupVariable($variableName, $value);
306 * Returns all variables of current group or empty array
308 * @return $result Whether array of found variables or empty array
310 private function readCurrentGroup () {
311 // Default is not found
314 // Is the group there?
315 if ($this->isVarStackSet($this->currGroup)) {
317 $result = $this->getVarStack($this->currGroup);
325 * Settter for variable group
327 * @param $groupName Name of variable group
328 * @param $add Whether add this group
331 public function setVariableGroup ($groupName, $add = TRUE) {
333 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
334 $this->currGroup = $groupName;
336 // Skip group 'general'
337 if (($groupName != 'general') && ($add === TRUE)) {
338 $this->variableGroups[$groupName] = 'OK';
344 * Adds a variable to current group
346 * @param $variableName Variable to set
347 * @param $value Value to store in variable
350 public function addGroupVariable ($variableName, $value) {
351 // Replace all dashes to underscores to match variables with configuration entries
352 $variableName = trim(self::convertDashesToUnderscores($variableName));
355 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
357 // Get current variables in group
358 $currVars = $this->readCurrentGroup();
360 // Append our variable
361 array_push($currVars, $this->generateVariableArray($variableName, $value));
363 // Add it to the stack
364 $this->setVarStack($this->currGroup, $currVars);
368 * Getter for variable value, throws a NoVariableException if the variable is not found
370 * @param $variableGroup Variable group to use
371 * @param $index Index in variable array
372 * @return $value Value to set
374 private function getVariableValue ($variableGroup, $index) {
376 return $this->varStack[$variableGroup][$index]['value'];
380 * Modify an entry on the stack
382 * @param $variableName The variable we are looking for
383 * @param $value The value we want to store in the variable
385 * @throws NoVariableException If the given variable is not found
387 private function modifyVariable ($variableName, $value) {
388 // Replace all dashes to underscores to match variables with configuration entries
389 $variableName = trim(self::convertDashesToUnderscores($variableName));
391 // Get index for variable
392 $index = $this->getVariableIndex($variableName);
394 // Is the variable set?
395 if ($index === FALSE) {
396 // Unset variables cannot be modified
397 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
401 $this->setVariableValue($this->currGroup, $index, $value);
405 * Sets a variable value for given variable group and index
407 * @param $variableGroup Variable group to use
408 * @param $index Index in variable array
409 * @param $value Value to set
412 private function setVariableValue ($variableGroup, $index, $value) {
413 $this->varStack[$variableGroup][$index]['value'] = $value;
417 * Sets a variable within given group. This method does detect if the
418 * variable is already set. If so, the variable got modified, otherwise
421 * @param $variableGroup Variable group to use
422 * @param $variableName Variable to set
423 * @param $value Value to set
426 protected function setVariable ($variableGroup, $variableName, $value) {
427 // Replace all dashes to underscores to match variables with configuration entries
428 $variableName = trim(self::convertDashesToUnderscores($variableName));
430 // Get index for variable
431 $index = $this->getVariableIndex($variableName);
433 // Is the variable set?
434 if ($index === FALSE) {
435 // Is the stack there?
436 if (!isset($this->varStack[$variableGroup])) {
437 // Then initialize it here
438 $this->varStack[$variableGroup] = array();
442 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
445 $this->setVariableValue($this->currGroup, $index, $value);
450 * "Generates" (better returns) an array for all variables for given
451 * variable/value pay.
453 * @param $variableName Variable to set
454 * @param $value Value to set
455 * @return $varData Variable data array
457 private function generateVariableArray ($variableName, $value) {
458 // Replace all dashes to underscores to match variables with configuration entries
459 $variableName = trim(self::convertDashesToUnderscores($variableName));
461 // Generate the temporary array
463 'name' => $variableName,
472 * Setter for template type. Only 'html', 'emails' and 'compiled' should
475 * @param $templateType The current template's type
478 protected final function setTemplateType ($templateType) {
479 $this->templateType = (string) $templateType;
483 * Getter for template type
485 * @return $templateType The current template's type
487 public final function getTemplateType () {
488 return $this->templateType;
492 * Setter for the last loaded template's FQFN
494 * @param $template The last loaded template
497 private final function setLastTemplate ($template) {
498 $this->lastTemplate = (string) $template;
502 * Getter for the last loaded template's FQFN
504 * @return $template The last loaded template
506 private final function getLastTemplate () {
507 return $this->lastTemplate;
511 * Setter for base path
513 * @param $templateBasePath The relative base path for all templates
516 protected final function setTemplateBasePath ($templateBasePath) {
518 $this->templateBasePath = (string) $templateBasePath;
522 * Getter for base path
524 * @return $templateBasePath The relative base path for all templates
526 public final function getTemplateBasePath () {
528 return $this->templateBasePath;
532 * Getter for generic base path
534 * @return $templateBasePath The relative base path for all templates
536 public final function getGenericBasePath () {
538 return $this->genericBasePath;
542 * Setter for template extension
544 * @param $templateExtension The file extension for all uncompiled
548 protected final function setRawTemplateExtension ($templateExtension) {
550 $this->templateExtension = (string) $templateExtension;
554 * Setter for code template extension
556 * @param $codeExtension The file extension for all uncompiled
560 protected final function setCodeTemplateExtension ($codeExtension) {
562 $this->codeExtension = (string) $codeExtension;
566 * Getter for template extension
568 * @return $templateExtension The file extension for all uncompiled
571 public final function getRawTemplateExtension () {
573 return $this->templateExtension;
577 * Getter for code-template extension
579 * @return $codeExtension The file extension for all code-
582 public final function getCodeTemplateExtension () {
584 return $this->codeExtension;
588 * Setter for path of compiled templates
590 * @param $compileOutputPath The local base path for all compiled
594 protected final function setCompileOutputPath ($compileOutputPath) {
596 $this->compileOutputPath = (string) $compileOutputPath;
600 * Unsets the given offset in the variable group
602 * @param $index Index to unset
603 * @param $variableGroup Variable group (default: currGroup)
606 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
607 // Is the variable group not set?
608 if (is_null($variableGroup)) {
609 // Then set it to current
610 $variableGroup = $this->currGroup;
613 // Is the entry there?
614 if (!isset($this->varStack[$variableGroup][$index])) {
615 // Abort here, we need fixing!
616 $this->debugInstance();
620 unset($this->varStack[$variableGroup][$index]);
624 * Private setter for raw template data
626 * @param $rawTemplateData The raw data from the template
629 protected final function setRawTemplateData ($rawTemplateData) {
630 // And store it in this class
631 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
632 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
633 $this->rawTemplateData = (string) $rawTemplateData;
637 * Getter for raw template data
639 * @return $rawTemplateData The raw data from the template
641 public final function getRawTemplateData () {
642 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
643 return $this->rawTemplateData;
647 * Private setter for compiled templates
651 private final function setCompiledData ($compiledData) {
652 // And store it in this class
653 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
654 $this->compiledData = (string) $compiledData;
658 * Getter for compiled templates, must be public for e.g. Mailer classes.
660 * @return $compiledData Compiled template data
662 public final function getCompiledData () {
663 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
664 return $this->compiledData;
668 * Private loader for all template types
670 * @param $template The template we shall load
671 * @param $extOther An other extension to use
673 * @throws FileNotFoundException If the template was not found
675 protected function loadTemplate ($template, $extOther = '') {
676 // Get extension for the template if empty
677 if (empty($extOther)) {
678 // None provided, so get the raw one
679 $ext = $this->getRawTemplateExtension();
682 $ext = (string) $extOther;
686 * Construct the FQFN for the template without language as language is
687 * now entirely done by php_intl. These old thing with language-based
688 * template paths comes from an older time.
690 $fqfn = sprintf('%s%s%s%s/%s%s',
691 $this->getConfigInstance()->getConfigEntry('base_path'),
692 $this->getTemplateBasePath(),
693 $this->getGenericBasePath(),
694 $this->getTemplateType(),
701 // Load the raw template data
702 $this->loadRawTemplateData($fqfn);
703 } catch (FileNotFoundException $e) {
704 // If we shall load a code-template we need to switch the file extension
705 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
706 // Switch over to the code-template extension and try it again
707 $ext = $this->getCodeTemplateExtension();
710 $this->loadTemplate($template, $ext);
713 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
720 * A private loader for raw template names
722 * @param $fqfn The full-qualified file name for a template
725 private function loadRawTemplateData ($fqfn) {
726 // Some debug code to look on the file which is being loaded
727 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
729 // Load the raw template
730 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
732 // Store the template's contents into this class
733 $this->setRawTemplateData($rawTemplateData);
735 // Remember the template's FQFN
736 $this->setLastTemplate($fqfn);
740 * Try to assign an extracted template variable as a "content" or 'config'
743 * @param $variableName The variable's name (shall be content or config)
745 * @param $variableName The variable we want to assign
748 private function assignTemplateVariable ($variableName, $var) {
749 // Replace all dashes to underscores to match variables with configuration entries
750 $variableName = trim(self::convertDashesToUnderscores($variableName));
753 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
755 // Is it not a config variable?
756 if ($variableName != 'config') {
757 // Regular template variables
758 $this->assignVariable($variableName, '');
760 // Configuration variables
761 $this->assignConfigVariable($var);
766 * Extract variables from a given raw data stream
768 * @param $rawData The raw template data we shall analyze
771 private function extractVariablesFromRawData ($rawData) {
773 $rawData = (string) $rawData;
775 // Search for variables
776 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
779 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
781 // Did we find some variables?
782 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
783 // Initialize all missing variables
784 foreach ($variableMatches[3] as $key => $var) {
786 $variableName = $variableMatches[1][$key];
788 // Workarround: Do not assign empty variables
790 // Try to assign it, empty strings are being ignored
791 $this->assignTemplateVariable($variableName, $var);
798 * Main analysis of the loaded template
800 * @param $templateMatches Found template place-holders, see below
803 *---------------------------------
804 * Structure of $templateMatches:
805 *---------------------------------
806 * [0] => Array - An array with all full matches
807 * [1] => Array - An array with left part (before the ':') of a match
808 * [2] => Array - An array with right part of a match including ':'
809 * [3] => Array - An array with right part of a match excluding ':'
811 private function analyzeTemplate (array $templateMatches) {
812 // Backup raw template data
813 $backup = $this->getRawTemplateData();
815 // Initialize some arrays
816 if (is_null($this->loadedRawData)) {
818 $this->loadedRawData = array();
819 $this->rawTemplates = array();
822 // Load all requested templates
823 foreach ($templateMatches[1] as $template) {
824 // Load and compile only templates which we have not yet loaded
825 // RECURSIVE PROTECTION! BE CAREFUL HERE!
826 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
828 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
830 // Template not found, but maybe variable assigned?
831 if ($this->getVariableIndex($template) !== FALSE) {
832 // Use that content here
833 $this->loadedRawData[$template] = $this->readVariable($template);
835 // Recursive protection:
836 array_push($this->loadedTemplates, $template);
838 // Then try to search for code-templates
840 // Load the code template and remember it's contents
841 $this->loadCodeTemplate($template);
842 $this->loadedRawData[$template] = $this->getRawTemplateData();
844 // Remember this template for recursion detection
845 // RECURSIVE PROTECTION!
846 array_push($this->loadedTemplates, $template);
847 } catch (FileNotFoundException $e) {
848 // Even this is not done... :/
849 array_push($this->rawTemplates, $template);
855 // Restore the raw template data
856 $this->setRawTemplateData($backup);
860 * Compile a given raw template code and remember it for later usage
862 * @param $code The raw template code
863 * @param $template The template's name
866 private function compileCode ($code, $template) {
867 // Is this template already compiled?
868 if (in_array($template, $this->compiledTemplates)) {
873 // Remember this template being compiled
874 array_push($this->compiledTemplates, $template);
876 // Compile the loaded code in five steps:
878 // 1. Backup current template data
879 $backup = $this->getRawTemplateData();
881 // 2. Set the current template's raw data as the new content
882 $this->setRawTemplateData($code);
884 // 3. Compile the template data
885 $this->compileTemplate();
887 // 4. Remember it's contents
888 $this->loadedRawData[$template] = $this->getRawTemplateData();
890 // 5. Restore the previous raw content from backup variable
891 $this->setRawTemplateData($backup);
895 * Insert all given and loaded templates by running through all loaded
896 * codes and searching for their place-holder in the main template
898 * @param $templateMatches See method analyzeTemplate()
901 private function insertAllTemplates (array $templateMatches) {
902 // Run through all loaded codes
903 foreach ($this->loadedRawData as $template => $code) {
905 // Search for the template
906 $foundIndex = array_search($template, $templateMatches[1]);
908 // Lookup the matching template replacement
909 if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
911 // Get the current raw template
912 $rawData = $this->getRawTemplateData();
914 // Replace the space holder with the template code
915 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
917 // Set the new raw data
918 $this->setRawTemplateData($rawData);
924 * Load all extra raw templates
928 private function loadExtraRawTemplates () {
929 // Are there some raw templates we need to load?
930 if (count($this->rawTemplates) > 0) {
931 // Try to load all raw templates
932 foreach ($this->rawTemplates as $key => $template) {
935 $this->loadHtmlTemplate($template);
937 // Remember it's contents
938 $this->rawTemplates[$template] = $this->getRawTemplateData();
940 // Remove it from the loader list
941 unset($this->rawTemplates[$key]);
943 // Remember this template for recursion detection
944 // RECURSIVE PROTECTION!
945 array_push($this->loadedTemplates, $template);
946 } catch (FileNotFoundException $e) {
947 // This template was never found. We silently ignore it
948 unset($this->rawTemplates[$key]);
955 * Assign all found template variables
957 * @param $varMatches An array full of variable/value pairs.
959 * @todo Unfinished work or don't die here.
961 private function assignAllVariables (array $varMatches) {
963 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
965 // Search for all variables
966 foreach ($varMatches[1] as $key => $var) {
967 // Replace all dashes to underscores to match variables with configuration entries
968 $var = trim(self::convertDashesToUnderscores($var));
971 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
973 // Detect leading equals
974 if (substr($varMatches[2][$key], 0, 1) == '=') {
975 // Remove and cast it
976 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
979 // Do we have some quotes left and right side? Then it is free text
980 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
981 // Free string detected! Which we can assign directly
982 $this->assignVariable($var, $varMatches[3][$key]);
983 } elseif (!empty($varMatches[2][$key])) {
984 // @TODO Non-string found so we need some deeper analysis...
985 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
991 * Compiles all loaded raw templates
993 * @param $templateMatches See method analyzeTemplate() for details
996 private function compileRawTemplateData (array $templateMatches) {
998 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1000 // Are some code-templates found which we need to compile?
1001 if (count($this->loadedRawData) > 0) {
1002 // Then compile all!
1003 foreach ($this->loadedRawData as $template => $code) {
1005 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1007 // Is this template already compiled?
1008 if (in_array($template, $this->compiledTemplates)) {
1010 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1014 // Search for the template
1015 $foundIndex = array_search($template, $templateMatches[1]);
1017 // Lookup the matching variable data
1018 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1019 // Split it up with another reg. exp. into variable=value pairs
1020 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1021 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1023 // Assign all variables
1024 $this->assignAllVariables($varMatches);
1025 } // END - if (isset($templateMatches ...
1027 // Compile the loaded template
1028 $this->compileCode($code, $template);
1029 } // END - foreach ($this->loadedRawData ...
1031 // Insert all templates
1032 $this->insertAllTemplates($templateMatches);
1033 } // END - if (count($this->loadedRawData) ...
1037 * Inserts all raw templates into their respective variables
1041 private function insertRawTemplates () {
1042 // Load all templates
1043 foreach ($this->rawTemplates as $template => $content) {
1044 // Set the template as a variable with the content
1045 $this->assignVariable($template, $content);
1050 * Finalizes the compilation of all template variables
1054 private function finalizeVariableCompilation () {
1056 $content = $this->getRawTemplateData();
1057 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1059 // Do we have the stack?
1060 if (!$this->isVarStackSet('general')) {
1061 // Abort here silently
1062 // @TODO This silent abort should be logged, maybe.
1066 // Walk through all variables
1067 foreach ($this->getVarStack('general') as $currEntry) {
1068 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1069 // Replace all [$var] or {?$var?} with the content
1070 // @TODO Old behaviour, will become obsolete!
1071 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1073 // @TODO Yet another old way
1074 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1076 // The new behaviour
1077 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1080 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1082 // Set the content back
1083 $this->setRawTemplateData($content);
1087 * Load a specified HTML template into the engine
1089 * @param $template The web template we shall load which is located in
1093 public function loadHtmlTemplate ($template) {
1094 // Set template type
1095 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1097 // Load the special template
1098 $this->loadTemplate($template);
1102 * Assign (add) a given variable with a value
1104 * @param $variableName The variable we are looking for
1105 * @param $value The value we want to store in the variable
1107 * @throws EmptyVariableException If the variable name is left empty
1109 public final function assignVariable ($variableName, $value) {
1110 // Replace all dashes to underscores to match variables with configuration entries
1111 $variableName = trim(self::convertDashesToUnderscores($variableName));
1113 // Empty variable found?
1114 if (empty($variableName)) {
1115 // Throw an exception
1116 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1119 // First search for the variable if it was already added
1120 $index = $this->getVariableIndex($variableName);
1123 if ($index === FALSE) {
1124 // Add it to the stack
1125 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1126 $this->addVariable($variableName, $value);
1127 } elseif (!empty($value)) {
1128 // Modify the stack entry
1129 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1130 $this->modifyVariable($variableName, $value);
1135 * Removes a given variable
1137 * @param $variableName The variable we are looking for
1138 * @param $variableGroup Name of variable group (default: 'general')
1141 public final function removeVariable ($variableName, $variableGroup = 'general') {
1142 // First search for the variable if it was already added
1143 $index = $this->getVariableIndex($variableName, $variableGroup);
1146 if ($index !== FALSE) {
1147 // Remove this variable
1148 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1149 $this->unsetVariableStackOffset($index, $variableGroup);
1154 * Assigns the last loaded raw template content with a given variable
1156 * @param $templateName Name of the template we want to assign
1157 * @param $variableName Name of the variable we want to assign
1160 public function assignTemplateWithVariable ($templateName, $variableName) {
1161 // Get the content from last loaded raw template
1162 $content = $this->getRawTemplateData();
1164 // Assign the variable
1165 $this->assignVariable($variableName, $content);
1167 // Purge raw content
1168 $this->setRawTemplateData('');
1172 * Assign a given congfiguration variable with a value
1174 * @param $variableName The configuration variable we want to assign
1177 public function assignConfigVariable ($variableName) {
1178 // Replace all dashes to underscores to match variables with configuration entries
1179 $variableName = trim(self::convertDashesToUnderscores($variableName));
1181 // Sweet and simple...
1182 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1183 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1187 * Assigns a lot variables into the stack of currently loaded template.
1188 * This method should only be used in very rare circumstances, e.g. when
1189 * you have to copy a whole set of variables into the template engine.
1190 * Before you use this method, please make sure you have considered all
1191 * other possiblities.
1193 * @param $variables An array with variables to be assigned
1196 public function assignMultipleVariables (array $variables) {
1198 foreach ($variables as $name => $value) {
1199 // Set variable with name for 'config' group
1200 $this->assignVariable($name, $value);
1205 * Assigns all the application data with template variables
1207 * @param $applicationInstance A manageable application instance
1210 public function assignApplicationData (ManageableApplication $applicationInstance) {
1211 // Get long name and assign it
1212 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1214 // Get short name and assign it
1215 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1217 // Get version number and assign it
1218 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1220 // Assign extra application-depending data
1221 $applicationInstance->assignExtraTemplateData($this);
1225 * Load a specified code template into the engine
1227 * @param $template The code template we shall load which is
1228 * located in 'code' by default
1231 public function loadCodeTemplate ($template) {
1232 // Set template type
1233 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type'));
1235 // Load the special template
1236 $this->loadTemplate($template);
1240 * Load a specified email template into the engine
1242 * @param $template The email template we shall load which is
1243 * located in 'emails' by default
1246 public function loadEmailTemplate ($template) {
1247 // Set template type
1248 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1250 // Load the special template
1251 $this->loadTemplate($template);
1255 * Compiles configuration place-holders in all variables. This 'walks'
1256 * through the variable group 'general'. It interprets all values from that
1257 * variables as configuration entries after compiling them.
1261 public final function compileConfigInVariables () {
1262 // Do we have the stack?
1263 if (!$this->isVarStackSet('general')) {
1264 // Abort here silently
1265 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1269 // Iterate through all general variables
1270 foreach ($this->getVarStack('general') as $index => $currVariable) {
1271 // Compile the value
1272 $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1275 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1277 // Remove it from stack
1278 $this->removeVariable($currVariable['name'], 'general');
1279 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1281 // Is it a configuration key?
1282 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1283 // The value itself is a configuration entry
1284 $this->assignConfigVariable($value);
1286 // Re-assign the value directly
1287 $this->assignVariable($currVariable['name'], $value);
1293 * Compile all variables by inserting their respective values
1296 * @todo Make this code some nicer...
1298 public final function compileVariables () {
1299 // Initialize the $content array
1300 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1303 // Iterate through all general variables
1304 foreach ($this->getVarStack('general') as $currVariable) {
1305 // Transfer it's name/value combination to the $content array
1306 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1307 $dummy[$currVariable['name']] = $currVariable['value'];
1310 // Set the new variable (don't remove the second dollar!)
1311 $$validVar = $dummy;
1313 // Remove some variables
1315 unset($currVariable);
1317 // Run the compilation three times to get content from helper classes in
1320 // Finalize the compilation of template variables
1321 $this->finalizeVariableCompilation();
1323 // Prepare the eval() command for comiling the template
1324 $eval = sprintf('$result = "%s";',
1325 addslashes($this->getRawTemplateData())
1328 // This loop does remove the backslashes (\) in PHP parameters
1329 while (strpos($eval, $this->codeBegin) !== FALSE) {
1330 // Get left part before "<?"
1331 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1333 // Get all from right of "<?"
1334 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1336 // Cut middle part out and remove escapes
1337 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1338 $evalMiddle = stripslashes($evalMiddle);
1340 // Remove the middle part from right one
1341 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1343 // And put all together
1344 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1347 // Prepare PHP code for eval() command
1348 $eval = str_replace(
1357 // Run the constructed command. This will "compile" all variables in
1360 // Goes something wrong?
1361 if ((!isset($result)) || (empty($result))) {
1362 // Output eval command
1363 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1365 // Output backtrace here
1366 $this->debugBackTrace();
1369 // Set raw template data
1370 $this->setRawTemplateData($result);
1374 // Final variable assignment
1375 $this->finalizeVariableCompilation();
1377 // Set the new content
1378 $this->setCompiledData($this->getRawTemplateData());
1382 * Compile all required templates into the current loaded one
1385 * @throws UnexpectedTemplateTypeException If the template type is
1387 * @throws InvalidArrayCountException If an unexpected array
1388 * count has been found
1390 public function compileTemplate () {
1391 // Get code type to make things shorter
1392 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type');
1394 // We will only work with template type "code" from configuration
1395 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1397 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . self::getResponseTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1400 // Get the raw data.
1401 $rawData = $this->getRawTemplateData();
1403 // Remove double spaces and trim leading/trailing spaces
1404 $rawData = trim(str_replace(' ', ' ', $rawData));
1406 // Search for raw variables
1407 $this->extractVariablesFromRawData($rawData);
1409 // Search for code-tags which are {? ?}
1410 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1413 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1415 // Analyze the matches array
1416 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1417 // Entries are found:
1419 // The main analysis
1420 $this->analyzeTemplate($templateMatches);
1422 // Compile raw template data
1423 $this->compileRawTemplateData($templateMatches);
1425 // Are there some raw templates left for loading?
1426 $this->loadExtraRawTemplates();
1428 // Are some raw templates found and loaded?
1429 if (count($this->rawTemplates) > 0) {
1430 // Insert all raw templates
1431 $this->insertRawTemplates();
1433 // Remove the raw template content as well
1434 $this->setRawTemplateData('');
1436 } // END - if($templateMatches ...
1440 * Loads a given view helper (by name)
1442 * @param $helperName The helper's name
1445 protected function loadViewHelper ($helperName) {
1446 // Is this view helper loaded?
1447 if (!isset($this->helpers[$helperName])) {
1448 // Create a class name
1449 $className = self::convertToClassName($helperName) . 'ViewHelper';
1451 // Generate new instance
1452 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1455 // Return the requested instance
1456 return $this->helpers[$helperName];
1460 * Transfers the content of this template engine to a given response instance
1462 * @param $responseInstance An instance of a Responsable class
1465 public function transferToResponse (Responseable $responseInstance) {
1466 // Get the content and set it in response class
1467 $responseInstance->writeToBody($this->getCompiledData());
1471 * "Compiles" a variable by replacing {?var?} with it's content
1473 * @param $rawCode Raw code to compile
1474 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1475 * @return $rawCode Compile code with inserted variable value
1477 public function compileRawCode ($rawCode, $setMatchAsCode=FALSE) {
1478 // Find the variables
1479 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1480 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1482 // Compile all variables
1483 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, TRUE) . '</pre>');
1484 foreach ($varMatches[0] as $match) {
1485 // Add variable tags around it
1486 $varCode = '{?' . $match . '?}';
1489 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1491 // Is the variable found in code? (safes some calls)
1492 if (strpos($rawCode, $varCode) !== FALSE) {
1494 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1496 // Use $match as new value or $value from read variable?
1497 if ($setMatchAsCode === TRUE) {
1499 $rawCode = str_replace($varCode, $match, $rawCode);
1501 // Read the variable
1502 $value = $this->readVariable($match);
1505 $rawCode = str_replace($varCode, $value, $rawCode);
1510 // Return the compiled data
1511 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1516 * Getter for variable group array
1518 * @return $variableGroups All variable groups
1520 public final function getVariableGroups () {
1521 return $this->variableGroups;
1525 * Renames a variable in code and in stack
1527 * @param $oldName Old name of variable
1528 * @param $newName New name of variable
1531 public function renameVariable ($oldName, $newName) {
1532 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1533 // Get raw template code
1534 $rawData = $this->getRawTemplateData();
1537 $rawData = str_replace($oldName, $newName, $rawData);
1539 // Set the code back
1540 $this->setRawTemplateData($rawData);
1544 * Renders the given XML content
1546 * @param $content Valid XML content or if not set the current loaded raw content
1548 * @throws XmlParserException If an XML error was found
1550 public function renderXmlContent ($content = NULL) {
1551 // Is the content set?
1552 if (is_null($content)) {
1553 // Get current content
1554 $content = $this->getRawTemplateData();
1557 // Get a XmlParser instance
1558 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1560 // Check if XML compacting is enabled
1561 if ($this->isXmlCompactingEnabled()) {
1562 // Yes, so get a decorator class for transparent compacting
1563 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1566 // Parse the XML document
1567 $parserInstance->parseXmlContent($content);
1571 * Enables or disables language support
1573 * @param $languageSupport New language support setting
1576 public final function enableLanguageSupport ($languageSupport = TRUE) {
1577 $this->languageSupport = (bool) $languageSupport;
1581 * Checks whether language support is enabled
1583 * @return $languageSupport Whether language support is enabled or disabled
1585 public final function isLanguageSupportEnabled () {
1586 return $this->languageSupport;
1590 * Enables or disables XML compacting
1592 * @param $xmlCompacting New XML compacting setting
1595 public final function enableXmlCompacting ($xmlCompacting = TRUE) {
1596 $this->xmlCompacting = (bool) $xmlCompacting;
1600 * Checks whether XML compacting is enabled
1602 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1604 public final function isXmlCompactingEnabled () {
1605 return $this->xmlCompacting;
1609 * Removes all commentd, tabs and new-line characters to compact the content
1611 * @param $uncompactedContent The uncompacted content
1612 * @return $compactedContent The compacted content
1614 public function compactContent ($uncompactedContent) {
1615 // First, remove all tab/new-line/revert characters
1616 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1618 // Then regex all comments like <!-- //--> away
1619 preg_match_all($this->regExpComments, $compactedContent, $matches);
1621 // Do we have entries?
1622 if (isset($matches[0][0])) {
1624 foreach ($matches[0] as $match) {
1626 $compactedContent = str_replace($match, '', $compactedContent);
1630 // Set the content again
1631 $this->setRawTemplateData($compactedContent);
1633 // Return compacted content
1634 return $compactedContent;