3 namespace CoreFramework\Template\Engine;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use CoreFramework\Factory\ObjectFactory;
9 use CoreFramework\Filesystem\FileNotFoundException;
10 use CoreFramework\Generic\EmptyVariableException;
11 use CoreFramework\Manager\ManageableApplication;
12 use CoreFramework\Object\BaseFrameworkSystem;
13 use CoreFramework\Response\Responseable;
16 * A generic template engine
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class BaseTemplateEngine extends BaseFrameworkSystem {
39 * The local path name where all templates and sub folders for special
40 * templates are stored. We will internally determine the language plus
41 * "html" for web templates or "emails" for email templates
43 private $templateBasePath = '';
48 private $templateType = 'html';
51 * The extension for web and email templates (not compiled templates)
53 private $templateExtension = '.tpl';
56 * The extension for code templates (not compiled templates)
58 private $codeExtension = '.ctp';
61 * Path relative to $templateBasePath and language code for compiled code-templates
63 private $compileOutputPath = 'templates/_compiled/';
66 * The path name for all templates
68 private $genericBasePath = 'templates/';
71 * The raw (maybe uncompiled) template
73 private $rawTemplateData = '';
76 * Template data with compiled-in variables
78 private $compiledData = '';
81 * The last loaded template's FQFN for debugging the engine
83 private $lastTemplate = '';
86 * The variable stack for the templates
88 private $varStack = array();
91 * Loaded templates for recursive protection and detection
93 private $loadedTemplates = array();
96 * Compiled templates for recursive protection and detection
98 private $compiledTemplates = array();
101 * Loaded raw template data
103 private $loadedRawData = NULL;
106 * Raw templates which are linked in code templates
108 private $rawTemplates = NULL;
111 * A regular expression for variable=value pairs
113 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
116 * A regular expression for filtering out code tags
118 * E.g.: {?template:variable=value;var2=value2;[...]?}
120 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
123 * A regular expression to find template comments like <!-- Comment here //-->
125 private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
130 private $helpers = array();
133 * Current variable group
135 private $currGroup = 'general';
138 * All template groups except "general"
140 private $variableGroups = array();
145 private $codeBegin = '<?php';
150 private $codeEnd = '?>';
153 * Language support is enabled by default
155 private $languageSupport = true;
158 * XML compacting is disabled by default
160 private $xmlCompacting = false;
162 // Exception codes for the template engine
163 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
164 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
165 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
166 const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
169 * Protected constructor
171 * @param $className Name of the class
174 protected function __construct ($className) {
175 // Call parent constructor
176 parent::__construct($className);
178 // Init file I/O instance
179 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
182 $this->setFileIoInstance($ioInstance);
186 * Search for a variable in the stack
188 * @param $variableName The variable we are looking for
189 * @param $variableGroup Optional variable group to look in
190 * @return $index false means not found, >=0 means found on a specific index
192 private function getVariableIndex ($variableName, $variableGroup = NULL) {
193 // Replace all dashes to underscores to match variables with configuration entries
194 $variableName = trim(self::convertDashesToUnderscores($variableName));
196 // First everything is not found
199 // If the stack is NULL, use the current group
200 if (is_null($variableGroup)) {
202 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
203 $variableGroup = $this->currGroup;
206 // Is the group there?
207 if ($this->isVarStackSet($variableGroup)) {
209 foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
210 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
211 // Is the entry found?
212 if ($currEntry['name'] == $variableName) {
214 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
221 // Return the current position
226 * Checks whether the given variable group is set
228 * @param $variableGroup Variable group to check
229 * @return $isSet Whether the given variable group is set
231 protected final function isVarStackSet ($variableGroup) {
233 $isSet = isset($this->varStack[$variableGroup]);
240 * Getter for given variable group
242 * @param $variableGroup Variable group to check
243 * @return $varStack Found variable group
245 public final function getVarStack ($variableGroup) {
246 return $this->varStack[$variableGroup];
250 * Setter for given variable group
252 * @param $variableGroup Variable group to check
253 * @param $varStack Variable stack to check
256 protected final function setVarStack ($variableGroup, array $varStack) {
257 $this->varStack[$variableGroup] = $varStack;
261 * Return a content of a variable or null if not found
263 * @param $variableName The variable we are looking for
264 * @param $variableGroup Optional variable group to look in
265 * @return $content Content of the variable or null if not found
267 protected function readVariable ($variableName, $variableGroup = NULL) {
268 // Replace all dashes to underscores to match variables with configuration entries
269 $variableName = trim(self::convertDashesToUnderscores($variableName));
271 // First everything is not found
274 // If the stack is NULL, use the current group
275 if (is_null($variableGroup)) {
277 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
278 $variableGroup = $this->currGroup;
281 // Get variable index
282 $found = $this->getVariableIndex($variableName, $variableGroup);
284 // Is the variable found?
285 if ($found !== false) {
287 $content = $this->getVariableValue($variableGroup, $found);
290 // Return the current position
291 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
296 * Add a variable to the stack
298 * @param $variableName Name of variable to add
299 * @param $value Value we want to store in the variable
302 private function addVariable ($variableName, $value) {
303 // Set general variable group
304 $this->setVariableGroup('general');
306 // Add it to the stack
307 $this->addGroupVariable($variableName, $value);
311 * Returns all variables of current group or empty array
313 * @return $result Whether array of found variables or empty array
315 private function readCurrentGroup () {
316 // Default is not found
319 // Is the group there?
320 if ($this->isVarStackSet($this->currGroup)) {
322 $result = $this->getVarStack($this->currGroup);
330 * Settter for variable group
332 * @param $groupName Name of variable group
333 * @param $add Whether add this group
336 public function setVariableGroup ($groupName, $add = true) {
338 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
339 $this->currGroup = $groupName;
341 // Skip group 'general'
342 if (($groupName != 'general') && ($add === true)) {
343 $this->variableGroups[$groupName] = 'OK';
349 * Adds a variable to current group
351 * @param $variableName Variable to set
352 * @param $value Value to store in variable
355 public function addGroupVariable ($variableName, $value) {
356 // Replace all dashes to underscores to match variables with configuration entries
357 $variableName = trim(self::convertDashesToUnderscores($variableName));
360 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
362 // Get current variables in group
363 $currVars = $this->readCurrentGroup();
365 // Append our variable
366 array_push($currVars, $this->generateVariableArray($variableName, $value));
368 // Add it to the stack
369 $this->setVarStack($this->currGroup, $currVars);
373 * Getter for variable value, throws a NoVariableException if the variable is not found
375 * @param $variableGroup Variable group to use
376 * @param $index Index in variable array
377 * @return $value Value to set
379 private function getVariableValue ($variableGroup, $index) {
381 return $this->varStack[$variableGroup][$index]['value'];
385 * Modify an entry on the stack
387 * @param $variableName The variable we are looking for
388 * @param $value The value we want to store in the variable
390 * @throws NoVariableException If the given variable is not found
392 private function modifyVariable ($variableName, $value) {
393 // Replace all dashes to underscores to match variables with configuration entries
394 $variableName = trim(self::convertDashesToUnderscores($variableName));
396 // Get index for variable
397 $index = $this->getVariableIndex($variableName);
399 // Is the variable set?
400 if ($index === false) {
401 // Unset variables cannot be modified
402 throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
406 $this->setVariableValue($this->currGroup, $index, $value);
410 * Sets a variable value for given variable group and index
412 * @param $variableGroup Variable group to use
413 * @param $index Index in variable array
414 * @param $value Value to set
417 private function setVariableValue ($variableGroup, $index, $value) {
418 $this->varStack[$variableGroup][$index]['value'] = $value;
422 * Sets a variable within given group. This method does detect if the
423 * variable is already set. If so, the variable got modified, otherwise
426 * @param $variableGroup Variable group to use
427 * @param $variableName Variable to set
428 * @param $value Value to set
431 protected function setVariable ($variableGroup, $variableName, $value) {
432 // Replace all dashes to underscores to match variables with configuration entries
433 $variableName = trim(self::convertDashesToUnderscores($variableName));
435 // Get index for variable
436 $index = $this->getVariableIndex($variableName);
438 // Is the variable set?
439 if ($index === false) {
440 // Is the stack there?
441 if (!isset($this->varStack[$variableGroup])) {
442 // Then initialize it here
443 $this->varStack[$variableGroup] = array();
447 array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
450 $this->setVariableValue($this->currGroup, $index, $value);
455 * "Generates" (better returns) an array for all variables for given
456 * variable/value pay.
458 * @param $variableName Variable to set
459 * @param $value Value to set
460 * @return $varData Variable data array
462 private function generateVariableArray ($variableName, $value) {
463 // Replace all dashes to underscores to match variables with configuration entries
464 $variableName = trim(self::convertDashesToUnderscores($variableName));
466 // Generate the temporary array
468 'name' => $variableName,
477 * Setter for template type. Only 'html', 'emails' and 'compiled' should
480 * @param $templateType The current template's type
483 protected final function setTemplateType ($templateType) {
484 $this->templateType = (string) $templateType;
488 * Getter for template type
490 * @return $templateType The current template's type
492 public final function getTemplateType () {
493 return $this->templateType;
497 * Setter for the last loaded template's FQFN
499 * @param $template The last loaded template
502 private final function setLastTemplate ($template) {
503 $this->lastTemplate = (string) $template;
507 * Getter for the last loaded template's FQFN
509 * @return $template The last loaded template
511 private final function getLastTemplate () {
512 return $this->lastTemplate;
516 * Setter for base path
518 * @param $templateBasePath The relative base path for all templates
521 protected final function setTemplateBasePath ($templateBasePath) {
523 $this->templateBasePath = (string) $templateBasePath;
527 * Getter for base path
529 * @return $templateBasePath The relative base path for all templates
531 public final function getTemplateBasePath () {
533 return $this->templateBasePath;
537 * Getter for generic base path
539 * @return $templateBasePath The relative base path for all templates
541 public final function getGenericBasePath () {
543 return $this->genericBasePath;
547 * Setter for template extension
549 * @param $templateExtension The file extension for all uncompiled
553 protected final function setRawTemplateExtension ($templateExtension) {
555 $this->templateExtension = (string) $templateExtension;
559 * Setter for code template extension
561 * @param $codeExtension The file extension for all uncompiled
565 protected final function setCodeTemplateExtension ($codeExtension) {
567 $this->codeExtension = (string) $codeExtension;
571 * Getter for template extension
573 * @return $templateExtension The file extension for all uncompiled
576 public final function getRawTemplateExtension () {
578 return $this->templateExtension;
582 * Getter for code-template extension
584 * @return $codeExtension The file extension for all code-
587 public final function getCodeTemplateExtension () {
589 return $this->codeExtension;
593 * Setter for path of compiled templates
595 * @param $compileOutputPath The local base path for all compiled
599 protected final function setCompileOutputPath ($compileOutputPath) {
601 $this->compileOutputPath = (string) $compileOutputPath;
605 * Unsets the given offset in the variable group
607 * @param $index Index to unset
608 * @param $variableGroup Variable group (default: currGroup)
611 protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
612 // Is the variable group not set?
613 if (is_null($variableGroup)) {
614 // Then set it to current
615 $variableGroup = $this->currGroup;
618 // Is the entry there?
619 if (!isset($this->varStack[$variableGroup][$index])) {
620 // Abort here, we need fixing!
621 $this->debugInstance();
625 unset($this->varStack[$variableGroup][$index]);
629 * Private setter for raw template data
631 * @param $rawTemplateData The raw data from the template
634 protected final function setRawTemplateData ($rawTemplateData) {
635 // And store it in this class
636 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
637 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
638 $this->rawTemplateData = (string) $rawTemplateData;
642 * Getter for raw template data
644 * @return $rawTemplateData The raw data from the template
646 public final function getRawTemplateData () {
647 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
648 return $this->rawTemplateData;
652 * Private setter for compiled templates
656 private final function setCompiledData ($compiledData) {
657 // And store it in this class
658 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
659 $this->compiledData = (string) $compiledData;
663 * Getter for compiled templates, must be public for e.g. Mailer classes.
665 * @return $compiledData Compiled template data
667 public final function getCompiledData () {
668 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
669 return $this->compiledData;
673 * Private loader for all template types
675 * @param $templateName The template we shall load
676 * @param $extOther An other extension to use
678 * @throws FileNotFoundException If the template was not found
680 protected function loadTemplate ($templateName, $extOther = '') {
681 // Get extension for the template if empty
682 if (empty($extOther)) {
683 // None provided, so get the raw one
684 $ext = $this->getRawTemplateExtension();
687 $ext = (string) $extOther;
691 * Construct the FQFN for the template without language as language is
692 * now entirely done by php_intl. These old thing with language-based
693 * template paths comes from an older time.
695 $fqfn = sprintf('%s%s%s%s%s%s',
696 $this->getTemplateBasePath(),
697 $this->getGenericBasePath(),
698 $this->getTemplateType(),
700 (string) $templateName,
706 // Load the raw template data
707 $this->loadRawTemplateData($fqfn);
708 } catch (FileNotFoundException $e) {
709 // If we shall load a code-template we need to switch the file extension
710 if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
711 // Switch over to the code-template extension and try it again
712 $ext = $this->getCodeTemplateExtension();
715 $this->loadTemplate($templateName, $ext);
718 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
725 * A private loader for raw template names
727 * @param $fqfn The full-qualified file name for a template
730 private function loadRawTemplateData ($fqfn) {
731 // Some debug code to look on the file which is being loaded
732 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
734 // Load the raw template
735 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
737 // Store the template's contents into this class
738 $this->setRawTemplateData($rawTemplateData);
740 // Remember the template's FQFN
741 $this->setLastTemplate($fqfn);
745 * Try to assign an extracted template variable as a "content" or 'config'
748 * @param $variableName The variable's name (shall be content or config)
750 * @param $variableName The variable we want to assign
753 private function assignTemplateVariable ($variableName, $var) {
754 // Replace all dashes to underscores to match variables with configuration entries
755 $variableName = trim(self::convertDashesToUnderscores($variableName));
758 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
760 // Is it not a config variable?
761 if ($variableName != 'config') {
762 // Regular template variables
763 $this->assignVariable($variableName, '');
765 // Configuration variables
766 $this->assignConfigVariable($var);
771 * Extract variables from a given raw data stream
773 * @param $rawData The raw template data we shall analyze
776 private function extractVariablesFromRawData ($rawData) {
778 $rawData = (string) $rawData;
780 // Search for variables
781 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
784 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
786 // Did we find some variables?
787 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
788 // Initialize all missing variables
789 foreach ($variableMatches[3] as $key => $var) {
791 $variableName = $variableMatches[1][$key];
793 // Workarround: Do not assign empty variables
795 // Try to assign it, empty strings are being ignored
796 $this->assignTemplateVariable($variableName, $var);
803 * Main analysis of the loaded template
805 * @param $templateMatches Found template place-holders, see below
808 *---------------------------------
809 * Structure of $templateMatches:
810 *---------------------------------
811 * [0] => Array - An array with all full matches
812 * [1] => Array - An array with left part (before the ':') of a match
813 * [2] => Array - An array with right part of a match including ':'
814 * [3] => Array - An array with right part of a match excluding ':'
816 private function analyzeTemplate (array $templateMatches) {
817 // Backup raw template data
818 $backup = $this->getRawTemplateData();
820 // Initialize some arrays
821 if (is_null($this->loadedRawData)) {
823 $this->loadedRawData = array();
824 $this->rawTemplates = array();
827 // Load all requested templates
828 foreach ($templateMatches[1] as $template) {
829 // Load and compile only templates which we have not yet loaded
830 // RECURSIVE PROTECTION! BE CAREFUL HERE!
831 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
833 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
835 // Template not found, but maybe variable assigned?
836 if ($this->getVariableIndex($template) !== false) {
837 // Use that content here
838 $this->loadedRawData[$template] = $this->readVariable($template);
840 // Recursive protection:
841 array_push($this->loadedTemplates, $template);
843 // Then try to search for code-templates
845 // Load the code template and remember it's contents
846 $this->loadCodeTemplate($template);
847 $this->loadedRawData[$template] = $this->getRawTemplateData();
849 // Remember this template for recursion detection
850 // RECURSIVE PROTECTION!
851 array_push($this->loadedTemplates, $template);
852 } catch (FileNotFoundException $e) {
853 // Even this is not done... :/
854 array_push($this->rawTemplates, $template);
860 // Restore the raw template data
861 $this->setRawTemplateData($backup);
865 * Compile a given raw template code and remember it for later usage
867 * @param $code The raw template code
868 * @param $template The template's name
871 private function compileCode ($code, $template) {
872 // Is this template already compiled?
873 if (in_array($template, $this->compiledTemplates)) {
878 // Remember this template being compiled
879 array_push($this->compiledTemplates, $template);
881 // Compile the loaded code in five steps:
883 // 1. Backup current template data
884 $backup = $this->getRawTemplateData();
886 // 2. Set the current template's raw data as the new content
887 $this->setRawTemplateData($code);
889 // 3. Compile the template data
890 $this->compileTemplate();
892 // 4. Remember it's contents
893 $this->loadedRawData[$template] = $this->getRawTemplateData();
895 // 5. Restore the previous raw content from backup variable
896 $this->setRawTemplateData($backup);
900 * Insert all given and loaded templates by running through all loaded
901 * codes and searching for their place-holder in the main template
903 * @param $templateMatches See method analyzeTemplate()
906 private function insertAllTemplates (array $templateMatches) {
907 // Run through all loaded codes
908 foreach ($this->loadedRawData as $template => $code) {
910 // Search for the template
911 $foundIndex = array_search($template, $templateMatches[1]);
913 // Lookup the matching template replacement
914 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
916 // Get the current raw template
917 $rawData = $this->getRawTemplateData();
919 // Replace the space holder with the template code
920 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
922 // Set the new raw data
923 $this->setRawTemplateData($rawData);
929 * Load all extra raw templates
933 private function loadExtraRawTemplates () {
934 // Are there some raw templates we need to load?
935 if (count($this->rawTemplates) > 0) {
936 // Try to load all raw templates
937 foreach ($this->rawTemplates as $key => $template) {
940 $this->loadHtmlTemplate($template);
942 // Remember it's contents
943 $this->rawTemplates[$template] = $this->getRawTemplateData();
945 // Remove it from the loader list
946 unset($this->rawTemplates[$key]);
948 // Remember this template for recursion detection
949 // RECURSIVE PROTECTION!
950 array_push($this->loadedTemplates, $template);
951 } catch (FileNotFoundException $e) {
952 // This template was never found. We silently ignore it
953 unset($this->rawTemplates[$key]);
960 * Assign all found template variables
962 * @param $varMatches An array full of variable/value pairs.
964 * @todo Unfinished work or don't die here.
966 private function assignAllVariables (array $varMatches) {
968 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
970 // Search for all variables
971 foreach ($varMatches[1] as $key => $var) {
972 // Replace all dashes to underscores to match variables with configuration entries
973 $var = trim(self::convertDashesToUnderscores($var));
976 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
978 // Detect leading equals
979 if (substr($varMatches[2][$key], 0, 1) == '=') {
980 // Remove and cast it
981 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
984 // Do we have some quotes left and right side? Then it is free text
985 if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
986 // Free string detected! Which we can assign directly
987 $this->assignVariable($var, $varMatches[3][$key]);
988 } elseif (!empty($varMatches[2][$key])) {
989 // @TODO Non-string found so we need some deeper analysis...
990 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
996 * Compiles all loaded raw templates
998 * @param $templateMatches See method analyzeTemplate() for details
1001 private function compileRawTemplateData (array $templateMatches) {
1003 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1005 // Are some code-templates found which we need to compile?
1006 if (count($this->loadedRawData) > 0) {
1007 // Then compile all!
1008 foreach ($this->loadedRawData as $template => $code) {
1010 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1012 // Is this template already compiled?
1013 if (in_array($template, $this->compiledTemplates)) {
1015 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1019 // Search for the template
1020 $foundIndex = array_search($template, $templateMatches[1]);
1022 // Lookup the matching variable data
1023 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1024 // Split it up with another reg. exp. into variable=value pairs
1025 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1026 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1028 // Assign all variables
1029 $this->assignAllVariables($varMatches);
1030 } // END - if (isset($templateMatches ...
1032 // Compile the loaded template
1033 $this->compileCode($code, $template);
1034 } // END - foreach ($this->loadedRawData ...
1036 // Insert all templates
1037 $this->insertAllTemplates($templateMatches);
1038 } // END - if (count($this->loadedRawData) ...
1042 * Inserts all raw templates into their respective variables
1046 private function insertRawTemplates () {
1047 // Load all templates
1048 foreach ($this->rawTemplates as $template => $content) {
1049 // Set the template as a variable with the content
1050 $this->assignVariable($template, $content);
1055 * Finalizes the compilation of all template variables
1059 private function finalizeVariableCompilation () {
1061 $content = $this->getRawTemplateData();
1062 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1064 // Do we have the stack?
1065 if (!$this->isVarStackSet('general')) {
1066 // Abort here silently
1067 // @TODO This silent abort should be logged, maybe.
1071 // Walk through all variables
1072 foreach ($this->getVarStack('general') as $currEntry) {
1073 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1074 // Replace all [$var] or {?$var?} with the content
1075 // @TODO Old behaviour, will become obsolete!
1076 $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1078 // @TODO Yet another old way
1079 $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1081 // The new behaviour
1082 $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1085 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1087 // Set the content back
1088 $this->setRawTemplateData($content);
1092 * Load a specified HTML template into the engine
1094 * @param $template The web template we shall load which is located in
1098 public function loadHtmlTemplate ($template) {
1099 // Set template type
1100 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1102 // Load the special template
1103 $this->loadTemplate($template);
1107 * Assign (add) a given variable with a value
1109 * @param $variableName The variable we are looking for
1110 * @param $value The value we want to store in the variable
1112 * @throws EmptyVariableException If the variable name is left empty
1114 public final function assignVariable ($variableName, $value) {
1115 // Replace all dashes to underscores to match variables with configuration entries
1116 $variableName = trim(self::convertDashesToUnderscores($variableName));
1118 // Empty variable found?
1119 if (empty($variableName)) {
1120 // Throw an exception
1121 throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1124 // First search for the variable if it was already added
1125 $index = $this->getVariableIndex($variableName);
1128 if ($index === false) {
1129 // Add it to the stack
1130 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1131 $this->addVariable($variableName, $value);
1132 } elseif (!empty($value)) {
1133 // Modify the stack entry
1134 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1135 $this->modifyVariable($variableName, $value);
1140 * Removes a given variable
1142 * @param $variableName The variable we are looking for
1143 * @param $variableGroup Name of variable group (default: 'general')
1146 public final function removeVariable ($variableName, $variableGroup = 'general') {
1147 // First search for the variable if it was already added
1148 $index = $this->getVariableIndex($variableName, $variableGroup);
1151 if ($index !== false) {
1152 // Remove this variable
1153 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1154 $this->unsetVariableStackOffset($index, $variableGroup);
1159 * Assigns the last loaded raw template content with a given variable
1161 * @param $templateName Name of the template we want to assign
1162 * @param $variableName Name of the variable we want to assign
1165 public function assignTemplateWithVariable ($templateName, $variableName) {
1166 // Get the content from last loaded raw template
1167 $content = $this->getRawTemplateData();
1169 // Assign the variable
1170 $this->assignVariable($variableName, $content);
1172 // Purge raw content
1173 $this->setRawTemplateData('');
1177 * Assign a given congfiguration variable with a value
1179 * @param $variableName The configuration variable we want to assign
1182 public function assignConfigVariable ($variableName) {
1183 // Replace all dashes to underscores to match variables with configuration entries
1184 $variableName = trim(self::convertDashesToUnderscores($variableName));
1186 // Sweet and simple...
1187 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1188 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1192 * Assigns a lot variables into the stack of currently loaded template.
1193 * This method should only be used in very rare circumstances, e.g. when
1194 * you have to copy a whole set of variables into the template engine.
1195 * Before you use this method, please make sure you have considered all
1196 * other possiblities.
1198 * @param $variables An array with variables to be assigned
1201 public function assignMultipleVariables (array $variables) {
1203 foreach ($variables as $name => $value) {
1204 // Set variable with name for 'config' group
1205 $this->assignVariable($name, $value);
1210 * Assigns all the application data with template variables
1212 * @param $applicationInstance A manageable application instance
1215 public function assignApplicationData (ManageableApplication $applicationInstance) {
1216 // Get long name and assign it
1217 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1219 // Get short name and assign it
1220 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1222 // Get version number and assign it
1223 $this->assignVariable('app_version' , $applicationInstance->getAppVersion());
1225 // Assign extra application-depending data
1226 $applicationInstance->assignExtraTemplateData($this);
1230 * Load a specified code template into the engine
1232 * @param $template The code template we shall load which is
1233 * located in 'code' by default
1236 public function loadCodeTemplate ($template) {
1237 // Set template type
1238 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1240 // Load the special template
1241 $this->loadTemplate($template);
1245 * Load a specified email template into the engine
1247 * @param $template The email template we shall load which is
1248 * located in 'emails' by default
1251 public function loadEmailTemplate ($template) {
1252 // Set template type
1253 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1255 // Load the special template
1256 $this->loadTemplate($template);
1260 * Compiles configuration place-holders in all variables. This 'walks'
1261 * through the variable group 'general'. It interprets all values from that
1262 * variables as configuration entries after compiling them.
1266 public final function compileConfigInVariables () {
1267 // Do we have the stack?
1268 if (!$this->isVarStackSet('general')) {
1269 // Abort here silently
1270 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1274 // Iterate through all general variables
1275 foreach ($this->getVarStack('general') as $index => $currVariable) {
1276 // Compile the value
1277 $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1280 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1282 // Remove it from stack
1283 $this->removeVariable($currVariable['name'], 'general');
1284 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1286 // Is it a configuration key?
1287 if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1288 // The value itself is a configuration entry
1289 $this->assignConfigVariable($value);
1291 // Re-assign the value directly
1292 $this->assignVariable($currVariable['name'], $value);
1298 * Compile all variables by inserting their respective values
1301 * @todo Make this code some nicer...
1303 public final function compileVariables () {
1304 // Initialize the $content array
1305 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1308 // Iterate through all general variables
1309 foreach ($this->getVarStack('general') as $currVariable) {
1310 // Transfer it's name/value combination to the $content array
1311 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1312 $dummy[$currVariable['name']] = $currVariable['value'];
1315 // Set the new variable (don't remove the second dollar!)
1316 $$validVar = $dummy;
1318 // Remove some variables
1320 unset($currVariable);
1322 // Run the compilation three times to get content from helper classes in
1325 // Finalize the compilation of template variables
1326 $this->finalizeVariableCompilation();
1328 // Prepare the eval() command for comiling the template
1329 $eval = sprintf('$result = "%s";',
1330 addslashes($this->getRawTemplateData())
1333 // This loop does remove the backslashes (\) in PHP parameters
1334 while (strpos($eval, $this->codeBegin) !== false) {
1335 // Get left part before "<?"
1336 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1338 // Get all from right of "<?"
1339 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1341 // Cut middle part out and remove escapes
1342 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1343 $evalMiddle = stripslashes($evalMiddle);
1345 // Remove the middle part from right one
1346 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1348 // And put all together
1349 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1352 // Prepare PHP code for eval() command
1353 $eval = str_replace(
1362 // Run the constructed command. This will "compile" all variables in
1365 // Goes something wrong?
1366 if ((!isset($result)) || (empty($result))) {
1367 // Output eval command
1368 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1370 // Output backtrace here
1371 $this->debugBackTrace();
1374 // Set raw template data
1375 $this->setRawTemplateData($result);
1379 // Final variable assignment
1380 $this->finalizeVariableCompilation();
1382 // Set the new content
1383 $this->setCompiledData($this->getRawTemplateData());
1387 * Compile all required templates into the current loaded one
1390 * @throws UnexpectedTemplateTypeException If the template type is
1392 * @throws InvalidArrayCountException If an unexpected array
1393 * count has been found
1395 public function compileTemplate () {
1396 // Get code type to make things shorter
1397 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1399 // We will only work with template type "code" from configuration
1400 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1402 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1405 // Get the raw data.
1406 $rawData = $this->getRawTemplateData();
1408 // Remove double spaces and trim leading/trailing spaces
1409 $rawData = trim(str_replace(' ', ' ', $rawData));
1411 // Search for raw variables
1412 $this->extractVariablesFromRawData($rawData);
1414 // Search for code-tags which are {? ?}
1415 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1418 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1420 // Analyze the matches array
1421 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1422 // Entries are found:
1424 // The main analysis
1425 $this->analyzeTemplate($templateMatches);
1427 // Compile raw template data
1428 $this->compileRawTemplateData($templateMatches);
1430 // Are there some raw templates left for loading?
1431 $this->loadExtraRawTemplates();
1433 // Are some raw templates found and loaded?
1434 if (count($this->rawTemplates) > 0) {
1435 // Insert all raw templates
1436 $this->insertRawTemplates();
1438 // Remove the raw template content as well
1439 $this->setRawTemplateData('');
1441 } // END - if($templateMatches ...
1445 * Loads a given view helper (by name)
1447 * @param $helperName The helper's name
1450 protected function loadViewHelper ($helperName) {
1451 // Is this view helper loaded?
1452 if (!isset($this->helpers[$helperName])) {
1453 // Create a class name
1454 $className = self::convertToClassName($helperName) . 'ViewHelper';
1456 // Generate new instance
1457 $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1460 // Return the requested instance
1461 return $this->helpers[$helperName];
1465 * Transfers the content of this template engine to a given response instance
1467 * @param $responseInstance An instance of a Responseable class
1470 public function transferToResponse (Responseable $responseInstance) {
1471 // Get the content and set it in response class
1472 $responseInstance->writeToBody($this->getCompiledData());
1476 * "Compiles" a variable by replacing {?var?} with it's content
1478 * @param $rawCode Raw code to compile
1479 * @param $setMatchAsCode Sets $match if readVariable() returns empty result
1480 * @return $rawCode Compile code with inserted variable value
1482 public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1483 // Find the variables
1484 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1485 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1487 // Compile all variables
1488 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1489 foreach ($varMatches[0] as $match) {
1490 // Add variable tags around it
1491 $varCode = '{?' . $match . '?}';
1494 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1496 // Is the variable found in code? (safes some calls)
1497 if (strpos($rawCode, $varCode) !== false) {
1499 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1501 // Use $match as new value or $value from read variable?
1502 if ($setMatchAsCode === true) {
1504 $rawCode = str_replace($varCode, $match, $rawCode);
1506 // Read the variable
1507 $value = $this->readVariable($match);
1510 $rawCode = str_replace($varCode, $value, $rawCode);
1515 // Return the compiled data
1516 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1521 * Getter for variable group array
1523 * @return $variableGroups All variable groups
1525 public final function getVariableGroups () {
1526 return $this->variableGroups;
1530 * Renames a variable in code and in stack
1532 * @param $oldName Old name of variable
1533 * @param $newName New name of variable
1536 public function renameVariable ($oldName, $newName) {
1537 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1538 // Get raw template code
1539 $rawData = $this->getRawTemplateData();
1542 $rawData = str_replace($oldName, $newName, $rawData);
1544 // Set the code back
1545 $this->setRawTemplateData($rawData);
1549 * Renders the given XML content
1551 * @param $content Valid XML content or if not set the current loaded raw content
1553 * @throws XmlParserException If an XML error was found
1555 public function renderXmlContent ($content = NULL) {
1556 // Is the content set?
1557 if (is_null($content)) {
1558 // Get current content
1559 $content = $this->getRawTemplateData();
1562 // Get a XmlParser instance
1563 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1565 // Check if XML compacting is enabled
1566 if ($this->isXmlCompactingEnabled()) {
1567 // Yes, so get a decorator class for transparent compacting
1568 $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1571 // Parse the XML document
1572 $parserInstance->parseXmlContent($content);
1576 * Enables or disables language support
1578 * @param $languageSupport New language support setting
1581 public final function enableLanguageSupport ($languageSupport = true) {
1582 $this->languageSupport = (bool) $languageSupport;
1586 * Checks whether language support is enabled
1588 * @return $languageSupport Whether language support is enabled or disabled
1590 public final function isLanguageSupportEnabled () {
1591 return $this->languageSupport;
1595 * Enables or disables XML compacting
1597 * @param $xmlCompacting New XML compacting setting
1600 public final function enableXmlCompacting ($xmlCompacting = true) {
1601 $this->xmlCompacting = (bool) $xmlCompacting;
1605 * Checks whether XML compacting is enabled
1607 * @return $xmlCompacting Whether XML compacting is enabled or disabled
1609 public final function isXmlCompactingEnabled () {
1610 return $this->xmlCompacting;
1614 * Removes all commentd, tabs and new-line characters to compact the content
1616 * @param $uncompactedContent The uncompacted content
1617 * @return $compactedContent The compacted content
1619 public function compactContent ($uncompactedContent) {
1620 // First, remove all tab/new-line/revert characters
1621 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1623 // Then regex all comments like <!-- //--> away
1624 preg_match_all($this->regExpComments, $compactedContent, $matches);
1626 // Do we have entries?
1627 if (isset($matches[0][0])) {
1629 foreach ($matches[0] as $match) {
1631 $compactedContent = str_replace($match, '', $compactedContent);
1635 // Set the content again
1636 $this->setRawTemplateData($compactedContent);
1638 // Return compacted content
1639 return $compactedContent;