3 * A generic template engine
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseTemplateEngine extends BaseFrameworkSystem {
26 * The local path name where all templates and sub folders for special
27 * templates are stored. We will internally determine the language plus
28 * "html" for web templates or "emails" for email templates
30 private $basePath = "";
35 private $templateType = "html";
38 * The extension for web and email templates (not compiled templates)
40 private $templateExtension = ".tpl";
43 * The extension for code templates (not compiled templates)
45 private $codeExtension = ".ctp";
48 * Path relative to $basePath and language code for compiled code-templates
50 private $compileOutputPath = "templates/_compiled";
53 * The raw (maybe uncompiled) template
55 private $rawTemplateData = "";
58 * Template data with compiled-in variables
60 private $compiledData = "";
63 * The last loaded template's FQFN for debugging the engine
65 private $lastTemplate = "";
68 * The variable stack for the templates
70 private $varStack = array();
73 * Loaded templates for recursive protection and detection
75 private $loadedTemplates = array();
78 * Compiled templates for recursive protection and detection
80 private $compiledTemplates = array();
83 * Loaded raw template data
85 private $loadedRawData = null;
88 * Raw templates which are linked in code templates
90 private $rawTemplates = null;
93 * A regular expression for variable=value pairs
95 private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
98 * A regular expression for filtering out code tags
100 * E.g.: {?template:variable=value;var2=value2;[...]?}
102 private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
107 private $helpers = array();
110 * Current variable group
112 private $currGroup = 'general';
115 * All template groups except "general"
117 private $varGroups = array();
119 // Exception codes for the template engine
120 const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
121 const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
122 const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
125 * Protected constructor
127 * @param $className Name of the class
130 protected function __construct ($className) {
131 // Call parent constructor
132 parent::__construct($className);
135 $this->removeNumberFormaters();
136 $this->removeSystemArray();
140 * Search for a variable in the stack
142 * @param $var The variable we are looking for
143 * @return $idx FALSE means not found, >=0 means found on a specific index
145 private function isVariableAlreadySet ($var) {
146 // First everything is not found
149 // Is the group there?
150 if (isset($this->varStack[$this->currGroup])) {
152 foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
153 //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
154 // Is the entry found?
155 if ($currEntry['name'] == $var) {
157 //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
164 // Return the current position
169 * Return a content of a variable or null if not found
171 * @param $var The variable we are looking for
172 * @return $content Content of the variable or null if not found
174 protected function readVariable ($var) {
175 // First everything is not found
178 // Get variable index
179 $found = $this->isVariableAlreadySet($var);
181 // Is the variable found?
182 if ($found !== false) {
184 $found = $this->varStack[$this->currGroup][$found]['value'];
187 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
189 // Return the current position
194 * Add a variable to the stack
196 * @param $var The variable we are looking for
197 * @param $value The value we want to store in the variable
200 private function addVariable ($var, $value) {
201 // Set general variable group
202 $this->setVariableGroup('general');
204 // Add it to the stack
205 $this->addGroupVariable($var, $value);
209 * Returns all variables of current group or empty array
211 * @return $result Wether array of found variables or empty array
213 private function readCurrentGroup () {
214 // Default is not found
217 // Is the group there?
218 if (isset($this->varStack[$this->currGroup])) {
220 $result = $this->varStack[$this->currGroup];
228 * Settter for variable group
230 * @param $groupName Name of variable group
231 * @param $add Wether add this group
234 public function setVariableGroup ($groupName, $add = true) {
236 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
237 $this->currGroup = $groupName;
239 // Skip group 'general'
240 if (($groupName != 'general') && ($add === true)) {
241 $this->varGroups[$groupName] = 'OK';
247 * Adds a variable to current group
249 * @param $var Variable to set
250 * @param $value Value to store in variable
253 public function addGroupVariable ($var, $value) {
254 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
256 // Get current variables in group
257 $currVars = $this->readCurrentGroup();
259 // Append our variable
265 // Add it to the stack
266 $this->varStack[$this->currGroup] = $currVars;
270 * Modify an entry on the stack
272 * @param $var The variable we are looking for
273 * @param $value The value we want to store in the variable
276 private function modifyVariable ($var, $value) {
277 // Get index for variable
278 $idx = $this->isVariableAlreadySet($var);
280 // Is the variable set?
281 if ($idx !== false) {
283 $this->varStack[$this->currGroup][$idx]['value'] = $value;
288 * Setter for template type. Only "html", "emails" and "compiled" should
291 * @param $templateType The current template's type
294 private final function setTemplateType ($templateType) {
295 $this->templateType = (string) $templateType;
299 * Setter for the last loaded template's FQFN
301 * @param $template The last loaded template
304 private final function setLastTemplate ($template) {
305 $this->lastTemplate = (string) $template;
309 * Getter for the last loaded template's FQFN
311 * @return $template The last loaded template
313 private final function getLastTemplate () {
314 return $this->lastTemplate;
318 * Setter for base path
320 * @param $basePath The local base path for all templates
323 public final function setBasePath ($basePath) {
325 $this->basePath = (string) $basePath;
329 * Getter for base path
331 * @return $basePath The local base path for all templates
333 public final function getBasePath () {
335 return $this->basePath;
339 * Setter for template extension
341 * @param $templateExtension The file extension for all uncompiled
345 public final function setRawTemplateExtension ($templateExtension) {
347 $this->templateExtension = (string) $templateExtension;
351 * Setter for code template extension
353 * @param $codeExtension The file extension for all uncompiled
357 public final function setCodeTemplateExtension ($codeExtension) {
359 $this->codeExtension = (string) $codeExtension;
363 * Getter for template extension
365 * @return $templateExtension The file extension for all uncompiled
368 public final function getRawTemplateExtension () {
370 return $this->templateExtension;
374 * Getter for code-template extension
376 * @return $codeExtension The file extension for all code-
379 public final function getCodeTemplateExtension () {
381 return $this->codeExtension;
385 * Setter for path of compiled templates
387 * @param $compileOutputPath The local base path for all compiled
391 public final function setCompileOutputPath ($compileOutputPath) {
393 $this->compileOutputPath = (string) $compileOutputPath;
397 * Getter for template type
399 * @return $templateType The current template's type
401 public final function getTemplateType () {
402 return $this->templateType;
406 * Assign (add) a given variable with a value
408 * @param $var The variable we are looking for
409 * @param $value The value we want to store in the variable
411 * @throws EmptyVariableException If the variable name is left empty
413 public final function assignVariable ($var, $value) {
414 // Trim spaces of variable name
417 // Empty variable found?
419 // Throw an exception
420 throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
423 // First search for the variable if it was already added
424 $idx = $this->isVariableAlreadySet($var);
427 if ($idx === false) {
428 // Add it to the stack
429 //* DEBUG: */ echo "ADD: ".$var."<br />\n";
430 $this->addVariable($var, $value);
431 } elseif (!empty($value)) {
432 // Modify the stack entry
433 //* DEBUG: */ echo "MOD: ".$var."<br />\n";
434 $this->modifyVariable($var, $value);
439 * Removes a given variable
441 * @param $var The variable we are looking for
444 public final function removeVariable ($var) {
445 // First search for the variable if it was already added
446 $idx = $this->isVariableAlreadySet($var);
449 if ($idx !== false) {
450 // Remove this variable
451 $this->varStack->offsetUnset($idx);
456 * Private setter for raw template data
458 * @param $rawTemplateData The raw data from the template
461 protected final function setRawTemplateData ($rawTemplateData) {
462 // And store it in this class
463 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($rawTemplateData)." Bytes set.<br />\n";
464 //* DEBUG: */ echo $this->currGroup." variables: ".count($this->varStack[$this->currGroup]).", groups=".count($this->varStack)."<br />\n";
465 $this->rawTemplateData = (string) $rawTemplateData;
469 * Getter for raw template data
471 * @return $rawTemplateData The raw data from the template
473 public final function getRawTemplateData () {
474 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->rawTemplateData)." Bytes read.<br />\n";
475 return $this->rawTemplateData;
479 * Private setter for compiled templates
483 private final function setCompiledData ($compiledData) {
484 // And store it in this class
485 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($compiledData)." Bytes set.<br />\n";
486 $this->compiledData = (string) $compiledData;
490 * Getter for compiled templates
492 * @return $compiledData Compiled template data
494 public final function getCompiledData () {
495 //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->compiledData)." Bytes read.<br />\n";
496 return $this->compiledData;
500 * Private loader for all template types
502 * @param $template The template we shall load
505 private function loadTemplate ($template) {
506 // Get extension for the template
507 $ext = $this->getRawTemplateExtension();
509 // If we shall load a code-template we need to switch the file extension
510 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
511 // Switch over to the code-template extension
512 $ext = $this->getCodeTemplateExtension();
515 // Construct the FQFN for the template by honoring the current language
516 $fqfn = sprintf("%s%s/%s/%s%s",
517 $this->getBasePath(),
518 $this->getLanguageInstance()->getLanguageCode(),
519 $this->getTemplateType(),
524 // Load the raw template data
525 $this->loadRawTemplateData($fqfn);
529 * A private loader for raw template names
531 * @param $fqfn The full-qualified file name for a template
534 private function loadRawTemplateData ($fqfn) {
535 // Get a input/output instance from the middleware
536 $ioInstance = $this->getFileIoInstance();
538 // Some debug code to look on the file which is being loaded
539 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
541 // Load the raw template
542 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
544 // Store the template's contents into this class
545 $this->setRawTemplateData($rawTemplateData);
547 // Remember the template's FQFN
548 $this->setLastTemplate($fqfn);
552 * Try to assign an extracted template variable as a "content" or 'config'
555 * @param $varName The variable's name (shall be content orconfig) by
557 * @param $var The variable we want to assign
559 private function assignTemplateVariable ($varName, $var) {
560 // Is it not a config variable?
561 if ($varName != 'config') {
562 // Regular template variables
563 $this->assignVariable($var, "");
565 // Configuration variables
566 $this->assignConfigVariable($var);
571 * Extract variables from a given raw data stream
573 * @param $rawData The raw template data we shall analyze
576 private function extractVariablesFromRawData ($rawData) {
578 $rawData = (string) $rawData;
580 // Search for variables
581 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
583 // Did we find some variables?
584 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
585 // Initialize all missing variables
586 foreach ($variableMatches[3] as $key => $var) {
588 $varName = $variableMatches[1][$key];
590 // Workarround: Do not assign empty variables
592 // Try to assign it, empty strings are being ignored
593 $this->assignTemplateVariable($varName, $var);
600 * Main analysis of the loaded template
602 * @param $templateMatches Found template place-holders, see below
605 *---------------------------------
606 * Structure of $templateMatches:
607 *---------------------------------
608 * [0] => Array - An array with all full matches
609 * [1] => Array - An array with left part (before the ":") of a match
610 * [2] => Array - An array with right part of a match including ":"
611 * [3] => Array - An array with right part of a match excluding ":"
613 private function analyzeTemplate (array $templateMatches) {
614 // Backup raw template data
615 $backup = $this->getRawTemplateData();
617 // Initialize some arrays
618 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
620 // Load all requested templates
621 foreach ($templateMatches[1] as $template) {
623 // Load and compile only templates which we have not yet loaded
624 // RECURSIVE PROTECTION! BE CAREFUL HERE!
625 if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
627 // Template not found, but maybe variable assigned?
628 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
629 if ($this->isVariableAlreadySet($template) !== false) {
630 // Use that content here
631 $this->loadedRawData[$template] = $this->readVariable($template);
633 // Recursive protection:
634 $this->loadedTemplates[] = $template;
635 } elseif (isset($this->varStack['config'][$template])) {
636 // Use that content here
637 $this->loadedRawData[$template] = $this->varStack['config'][$template];
639 // Recursive protection:
640 $this->loadedTemplates[] = $template;
642 // Then try to search for code-templates
644 // Load the code template and remember it's contents
645 $this->loadCodeTemplate($template);
646 $this->loadedRawData[$template] = $this->getRawTemplateData();
648 // Remember this template for recursion detection
649 // RECURSIVE PROTECTION!
650 $this->loadedTemplates[] = $template;
651 } catch (FileNotFoundException $e) {
652 // Even this is not done... :/
653 $this->rawTemplates[] = $template;
654 } catch (FilePointerNotOpenedException $e) {
655 // Even this is not done... :/
656 $this->rawTemplates[] = $template;
662 // Restore the raw template data
663 $this->setRawTemplateData($backup);
667 * Compile a given raw template code and remember it for later usage
669 * @param $code The raw template code
670 * @param $template The template's name
673 private function compileCode ($code, $template) {
674 // Is this template already compiled?
675 if (in_array($template, $this->compiledTemplates)) {
680 // Remember this template being compiled
681 $this->compiledTemplates[] = $template;
683 // Compile the loaded code in five steps:
685 // 1. Backup current template data
686 $backup = $this->getRawTemplateData();
688 // 2. Set the current template's raw data as the new content
689 $this->setRawTemplateData($code);
691 // 3. Compile the template data
692 $this->compileTemplate();
694 // 4. Remember it's contents
695 $this->loadedRawData[$template] = $this->getRawTemplateData();
697 // 5. Restore the previous raw content from backup variable
698 $this->setRawTemplateData($backup);
702 * Insert all given and loaded templates by running through all loaded
703 * codes and searching for their place-holder in the main template
705 * @param $templateMatches See method analyzeTemplate()
708 private function insertAllTemplates (array $templateMatches) {
709 // Run through all loaded codes
710 foreach ($this->loadedRawData as $template => $code) {
712 // Search for the template
713 $foundIndex = array_search($template, $templateMatches[1]);
715 // Lookup the matching template replacement
716 if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
718 // Get the current raw template
719 $rawData = $this->getRawTemplateData();
721 // Replace the space holder with the template code
722 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
724 // Set the new raw data
725 $this->setRawTemplateData($rawData);
731 * Load all extra raw templates
735 private function loadExtraRawTemplates () {
736 // Are there some raw templates we need to load?
737 if (count($this->rawTemplates) > 0) {
738 // Try to load all raw templates
739 foreach ($this->rawTemplates as $key => $template) {
742 $this->loadWebTemplate($template);
744 // Remember it's contents
745 $this->rawTemplates[$template] = $this->getRawTemplateData();
747 // Remove it from the loader list
748 unset($this->rawTemplates[$key]);
750 // Remember this template for recursion detection
751 // RECURSIVE PROTECTION!
752 $this->loadedTemplates[] = $template;
753 } catch (FileNotFoundException $e) {
754 // This template was never found. We silently ignore it
755 unset($this->rawTemplates[$key]);
756 } catch (FilePointerNotOpenedException $e) {
757 // This template was never found. We silently ignore it
758 unset($this->rawTemplates[$key]);
765 * Assign all found template variables
767 * @param $varMatches An array full of variable/value pairs.
769 * @todo Unfinished work or don't die here.
771 private function assignAllVariables (array $varMatches) {
772 // Search for all variables
773 foreach ($varMatches[1] as $key => $var) {
775 // Detect leading equals
776 if (substr($varMatches[2][$key], 0, 1) == "=") {
777 // Remove and cast it
778 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
781 // Do we have some quotes left and right side? Then it is free text
782 if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
783 // Free string detected! Which we can assign directly
784 $this->assignVariable($var, $varMatches[3][$key]);
785 } elseif (!empty($varMatches[2][$key])) {
786 // Non-string found so we need some deeper analysis...
787 die("Deeper analysis not yet implemented!");
790 } // for ($varMatches ...
793 * Compiles all loaded raw templates
795 * @param $templateMatches See method analyzeTemplate() for details
798 private function compileRawTemplateData (array $templateMatches) {
799 // Are some code-templates found which we need to compile?
800 if (count($this->loadedRawData) > 0) {
803 foreach ($this->loadedRawData as $template => $code) {
805 // Is this template already compiled?
806 if (in_array($template, $this->compiledTemplates)) {
811 // Search for the template
812 $foundIndex = array_search($template, $templateMatches[1]);
814 // Lookup the matching variable data
815 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
817 // Split it up with another reg. exp. into variable=value pairs
818 preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
820 // Assign all variables
821 $this->assignAllVariables($varMatches);
823 } // END - if (isset($templateMatches ...
825 // Compile the loaded template
826 $this->compileCode($code, $template);
828 } // END - foreach ($this->loadedRawData ...
830 // Insert all templates
831 $this->insertAllTemplates($templateMatches);
833 } // END - if (count($this->loadedRawData) ...
837 * Inserts all raw templates into their respective variables
841 private function insertRawTemplates () {
842 // Load all templates
843 foreach ($this->rawTemplates as $template => $content) {
844 // Set the template as a variable with the content
845 $this->assignVariable($template, $content);
850 * Finalizes the compilation of all template variables
854 private function finalizeVariableCompilation () {
856 $content = $this->getRawTemplateData();
857 //* DEBUG: */ echo __METHOD__.": content before=".strlen($content)." (".md5($content).")<br />\n";
859 // Walk through all variables
860 foreach ($this->varStack['general'] as $currEntry) {
861 //* DEBUG: */ echo __METHOD__.": name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
862 // Replace all [$var] or {?$var?} with the content
863 // Old behaviour, will become obsolete!
864 $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
866 // Yet another old way
867 $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
870 $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
873 //* DEBUG: */ echo __METHOD__.": content after=".strlen($content)." (".md5($content).")<br />\n";
875 // Set the content back
876 $this->setRawTemplateData($content);
880 * Load a specified web template into the engine
882 * @param $template The web template we shall load which is located in
886 public function loadWebTemplate ($template) {
888 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
890 // Load the special template
891 $this->loadTemplate($template);
895 * Assign a given congfiguration variable with a value
897 * @param $var The configuration variable we want to assign
900 public function assignConfigVariable ($var) {
901 // Sweet and simple...
902 //* DEBUG: */ echo __METHOD__.":var={$var}<br />\n";
903 $this->varStack['config'][$var] = $this->getConfigInstance()->readConfig($var);
907 * Load a specified email template into the engine
909 * @param $template The email template we shall load which is located in
910 * "emails" by default
913 public function loadEmailTemplate ($template) {
915 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
917 // Load the special template
918 $this->loadTemplate($template);
922 * Load a specified code template into the engine
924 * @param $template The code template we shall load which is
925 * located in "code" by default
928 public function loadCodeTemplate ($template) {
930 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
932 // Load the special template
933 $this->loadTemplate($template);
937 * Compile all variables by inserting their respective values
940 * @todo Make this code some nicer...
942 public final function compileVariables () {
943 // Initialize the $content array
944 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
947 // Iterate through all general variables
948 foreach ($this->varStack['general'] as $currVariable) {
949 // Transfer it's name/value combination to the $content array
950 //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
951 $dummy[$currVariable['name']] = $currVariable['value'];
954 // Set the new variable (don't remove the second dollar!)
957 // Prepare all configuration variables
959 if (isset($this->varStack['config'])) {
960 $config = $this->varStack['config'];
963 // Remove some variables
965 unset($currVariable);
967 // Run the compilation twice to get content from helper classes in
970 // Finalize the compilation of template variables
971 $this->finalizeVariableCompilation();
973 // Prepare the eval() command for comiling the template
974 $eval = sprintf("\$result = \"%s\";",
975 addslashes($this->getRawTemplateData())
978 // This loop does remove the backslashes (\) in PHP parameters
979 while (strpos($eval, "<?php") !== false) {
980 // Get left part before "<?"
981 $evalLeft = substr($eval, 0, strpos($eval, "<?php"));
983 // Get all from right of "<?"
984 $evalRight = substr($eval, (strpos($eval, "<?php") + 5));
986 // Cut middle part out and remove escapes
987 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
988 $evalMiddle = stripslashes($evalMiddle);
990 // Remove the middle part from right one
991 $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
993 // And put all together
994 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
997 // Prepare PHP code for eval() command
1001 "%>", "\n\$result .= \"", $eval
1005 // Run the constructed command. This will "compile" all variables in
1008 // Goes something wrong?
1009 if (!isset($result)) {
1010 // Output eval command
1011 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1013 // Output backtrace here
1014 $this->debugBackTrace();
1017 // Set raw template data
1018 $this->setRawTemplateData($result);
1022 // Final variable assignment
1023 $this->finalizeVariableCompilation();
1025 // Set the new content
1026 $this->setCompiledData($this->getRawTemplateData());
1030 * Compile all required templates into the current loaded one
1033 * @throws UnexpectedTemplateTypeException If the template type is
1035 * @throws InvalidArrayCountException If an unexpected array
1036 * count has been found
1038 public function compileTemplate () {
1039 // We will only work with template type "code" from configuration
1040 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1042 throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1045 // Get the raw data.
1046 $rawData = $this->getRawTemplateData();
1048 // Remove double spaces and trim leading/trailing spaces
1049 $rawData = trim(str_replace(" ", " ", $rawData));
1051 // Search for raw variables
1052 $this->extractVariablesFromRawData($rawData);
1054 // Search for code-tags which are {? ?}
1055 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1057 // Analyze the matches array
1058 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1059 // Entries are found:
1061 // The main analysis
1062 $this->analyzeTemplate($templateMatches);
1064 // Compile raw template data
1065 $this->compileRawTemplateData($templateMatches);
1067 // Are there some raw templates left for loading?
1068 $this->loadExtraRawTemplates();
1070 // Are some raw templates found and loaded?
1071 if (count($this->rawTemplates) > 0) {
1073 // Insert all raw templates
1074 $this->insertRawTemplates();
1076 // Remove the raw template content as well
1077 $this->setRawTemplateData("");
1081 } // END - if($templateMatches ...
1085 * A old deprecated method
1089 * @see BaseTemplateEngine::transferToResponse
1091 public function output () {
1092 // Check which type of template we have
1093 switch ($this->getTemplateType()) {
1094 case "html": // Raw HTML templates can be send to the output buffer
1096 $this->getWebOutputInstance()->output($this->getCompiledData());
1099 default: // Unknown type found
1100 // Construct message
1101 $msg = sprintf("[%s->%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1102 $this->__toString(),
1104 $this->getTemplateType()
1107 // Write the problem to the world...
1108 $this->debugOutput($msg);
1114 * Loads a given view helper (by name)
1116 * @param $helperName The helper's name
1118 * @throws ViewHelperNotFoundException If the given view helper was not found
1120 protected function loadViewHelper ($helperName) {
1121 // Make first character upper case, rest low
1122 $helperName = ucfirst($helperName);
1124 // Is this view helper loaded?
1125 if (!isset($this->helpers[$helperName])) {
1126 // Create a class name
1127 $className = "{$helperName}ViewHelper";
1129 // Does this class exists?
1130 if (!class_exists($className)) {
1132 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1135 // Generate new instance
1136 $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1146 // Return the requested instance
1147 return $this->helpers[$helperName];
1151 * Assigns the last loaded raw template content with a given variable
1153 * @param $templateName Name of the template we want to assign
1154 * @param $variableName Name of the variable we want to assign
1157 public function assignTemplateWithVariable ($templateName, $variableName) {
1158 // Get the content from last loaded raw template
1159 $content = $this->getRawTemplateData();
1161 // Assign the variable
1162 $this->assignVariable($variableName, $content);
1164 // Purge raw content
1165 $this->setRawTemplateData("");
1169 * Transfers the content of this template engine to a given response instance
1171 * @param $responseInstance An instance of a response class
1174 public function transferToResponse (Responseable $responseInstance) {
1175 // Get the content and set it in the response class
1176 $responseInstance->writeToBody($this->getCompiledData());
1180 * Assigns all the application data with template variables
1182 * @param $appInstance A manageable application instance
1185 public function assignApplicationData (ManageableApplication $appInstance) {
1186 // Get long name and assign it
1187 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1189 // Get short name and assign it
1190 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1192 // Get version number and assign it
1193 $this->assignVariable('app_version' , $appInstance->getAppVersion());
1195 // Assign extra application-depending data
1196 $appInstance->assignExtraTemplateData($this);
1200 * "Compiles" a variable by replacing {?var?} with it's content
1202 * @param $rawCode Raw code to compile
1203 * @return $rawCode Compile code with inserted variable value
1205 public function compileRawCode ($rawCode) {
1206 // Find the variables
1207 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1208 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1210 // Compile all variables
1211 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1212 foreach ($varMatches[0] as $match) {
1213 // Add variable tags around it
1214 $varCode = "{?".$match."?}";
1216 // Is the variable found in code? (safes some calls)
1217 if (strpos($rawCode, $varCode) !== false) {
1218 // Replace the variable with it's value, if found
1219 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1220 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1224 // Return the compiled data
1229 * Getter for variable group array
1231 * @return $vargroups All variable groups
1233 public final function getVariableGroups () {
1234 return $this->varGroups;
1238 * Renames a variable in code and in stack
1240 * @param $oldName Old name of variable
1241 * @param $newName New name of variable
1244 public function renameVariable ($oldName, $newName) {
1245 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1246 // Get raw template code
1247 $rawData = $this->getRawTemplateData();
1250 $rawData = str_replace($oldName, $newName, $rawData);
1252 // Set the code back
1253 $this->setRawTemplateData($rawData);
1257 * Renders the given XML content
1259 * @param $content Valid XML content or if not set the current loaded raw content
1261 * @throws XmlParserException If an XML error was found
1263 public final function renderXmlContent ($content = null) {
1264 // Is the content set?
1265 if (is_null($content)) {
1266 // Get current content
1267 $content = $this->getRawTemplateData();
1270 // Convert all to UTF8
1271 $content = recode("html..utf8", $content);
1273 // Get an XML parser
1274 $xmlParser = xml_parser_create();
1276 // Force case-folding to on
1277 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
1280 xml_set_object($xmlParser, $this);
1282 // Set handler call-backs
1283 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
1284 xml_set_character_data_handler($xmlParser, 'characterHandler');
1286 // Now parse the XML tree
1287 if (!xml_parse($xmlParser, $content)) {
1288 // Error found in XML!
1289 //die("<pre>".htmlentities($content)."</pre>");
1290 throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
1294 xml_parser_free($xmlParser);