From: Roland Häder Date: Sun, 22 Jun 2008 22:22:39 +0000 (+0000) Subject: TemplateEngine is known as WebTemplateEngine (most parts are in BasTemplateEngine... X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=835d890d25d67c76e40ffdf3ba525b8b18c5d007;p=shipsimu.git TemplateEngine is known as WebTemplateEngine (most parts are in BasTemplateEngine), image creation supported added with a lot (!) stubs --- diff --git a/.gitattributes b/.gitattributes index 96837fa..513b4ff 100644 --- a/.gitattributes +++ b/.gitattributes @@ -149,6 +149,9 @@ application/ship-simu/templates/de/code/shipsimu_main.ctp -text application/ship-simu/templates/de/html/.htaccess -text application/ship-simu/templates/de/html/nav_advert.tpl -text application/ship-simu/templates/de/html/selector_ship-simu.tpl -text +application/ship-simu/templates/images/.htaccess -text +application/ship-simu/templates/images/de/.htaccess -text +application/ship-simu/templates/images/de/image/.htaccess -text db/.htaccess -text db/news/.htaccess -text db/user/.htaccess -text @@ -202,7 +205,7 @@ inc/classes/exceptions/helper/class_InvalidFormNameException.php -text inc/classes/exceptions/helper/class_UserInstanceMissingException.php -text inc/classes/exceptions/io/.htaccess -text inc/classes/exceptions/io/class_DirPointerNotOpenedException.php -text -inc/classes/exceptions/io/class_FileIsMissingException.php -text +inc/classes/exceptions/io/class_FileNotFoundException.php -text inc/classes/exceptions/io/class_FilePointerNotOpenedException.php -text inc/classes/exceptions/io/class_FileReadProtectedException.php -text inc/classes/exceptions/io/class_InvalidDataLengthException.php -text @@ -259,6 +262,9 @@ inc/classes/exceptions/user/class_AccountPasswordMismatchException.php -text inc/classes/exceptions/user/class_UserEmailMissingException.php -text inc/classes/exceptions/user/class_UserPasswordMismatchException.php -text inc/classes/exceptions/user/class_UsernameMissingException.php -text +inc/classes/exceptions/xml/.htaccess -text +inc/classes/exceptions/xml/class_InvalidXmlNodeException.php -text +inc/classes/exceptions/xml/class_XmlParserException.php -text inc/classes/interfaces/.htaccess -text inc/classes/interfaces/actions/.htaccess -text inc/classes/interfaces/actions/class_PerformableAction.php -text @@ -298,6 +304,7 @@ inc/classes/interfaces/filter/.htaccess -text inc/classes/interfaces/filter/class_Filterable.php -text inc/classes/interfaces/helper/.htaccess -text inc/classes/interfaces/helper/class_HelpableLogin.php -text +inc/classes/interfaces/helper/class_HelpableTemplate.php -text inc/classes/interfaces/io/.htaccess -text inc/classes/interfaces/io/class_Streamable.php -text inc/classes/interfaces/io/file/.htaccess -text @@ -462,10 +469,17 @@ inc/classes/main/helper/captcha/web/.htaccess -text inc/classes/main/helper/captcha/web/class_GraphicalCodeCaptcha.php -text inc/classes/main/helper/class_ -text inc/classes/main/helper/class_BaseHelper.php -text +inc/classes/main/helper/images/.htaccess -text +inc/classes/main/helper/images/class_ImageHelper.php -text inc/classes/main/helper/login/.htaccess -text inc/classes/main/helper/login/class_BaseLoginHelper.php -text inc/classes/main/helper/web/.htaccess -text inc/classes/main/helper/web/class_WebFormHelper.php -text +inc/classes/main/images/.htaccess -text +inc/classes/main/images/class_ -text +inc/classes/main/images/class_BaseImage.php -text +inc/classes/main/images/extended/.htaccess -text +inc/classes/main/images/extended/class_PngImage.php -text inc/classes/main/io/.htaccess -text inc/classes/main/io/class_FileIoStream.php -text inc/classes/main/io/class_FrameworkDirectoryPointer.php -text @@ -505,12 +519,17 @@ inc/classes/main/resolver/controller/web/.htaccess -text inc/classes/main/resolver/controller/web/class_WebControllerResolver.php -text inc/classes/main/response/.htaccess -text inc/classes/main/response/class_HttpResponse.php -text +inc/classes/main/response/class_ImageResponse.php -text inc/classes/main/result/.htaccess -text inc/classes/main/result/class_DatabaseResult.php -text inc/classes/main/rng/.htaccess -text inc/classes/main/rng/class_RandomNumberGenerator.php -text inc/classes/main/template/.htaccess -text -inc/classes/main/template/class_TemplateEngine.php -text +inc/classes/main/template/class_BaseTemplateEngine.php -text +inc/classes/main/template/image/.htaccess -text +inc/classes/main/template/image/class_ImageTemplateEngine.php -text +inc/classes/main/template/web/.htaccess -text +inc/classes/main/template/web/class_WebTemplateEngine.php -text inc/classes/main/user/.htaccess -text inc/classes/main/user/class_Guest.php -text inc/classes/main/user/class_User.php -text @@ -618,6 +637,11 @@ templates/de/code/emergency_exit.ctp -text templates/de/code/footer_msg.ctp -text templates/de/code/header.ctp -text templates/de/html/.htaccess -text +templates/images/.htaccess -text +templates/images/de/.htaccess -text +templates/images/de/image/.htaccess -text +templates/images/de/image/base_image.img -text +templates/images/de/image/emergency_exit.img -text tests/ConfigTest.php -text tests/RegistryTest.php -text tests/RequestTest.php -text diff --git a/application/ship-simu/class_ApplicationHelper.php b/application/ship-simu/class_ApplicationHelper.php index 32bd764..370bd02 100644 --- a/application/ship-simu/class_ApplicationHelper.php +++ b/application/ship-simu/class_ApplicationHelper.php @@ -185,8 +185,19 @@ class ApplicationHelper extends BaseFrameworkSystem implements ManageableApplica // Create a new request object $requestInstance = ObjectFactory::createObjectByName('HttpRequest'); + // Default response is HTTP (HTML page) and type is "Web" + $response = "http"; + $responseType = "web"; + + // Do we have another response? + if ($requestInstance->isRequestElementSet('response')) { + // Then use it + $response = strtolower($requestInstance->getRequestElement('response')); + $responseType = $response; + } // END - if + // ... and a new response object - $responseInstance = ObjectFactory::createObjectByName('HttpResponse', array($this)); + $responseInstance = ObjectFactory::createObjectByName(ucfirst($response)."Response", array($this)); // Remember both in this application $this->setRequestInstance($requestInstance); @@ -201,7 +212,7 @@ class ApplicationHelper extends BaseFrameworkSystem implements ManageableApplica } // END - if // Get a resolver - $resolverInstance = WebControllerResolver::createWebControllerResolver($commandName, $this); + $resolverInstance = ObjectFactory::createObjectByName(ucfirst($responseType)."ControllerResolver", array($commandName, $this)); // Get a controller instance as well $this->controllerInstance = $resolverInstance->resolveController(); diff --git a/application/ship-simu/templates/images/.htaccess b/application/ship-simu/templates/images/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/application/ship-simu/templates/images/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/application/ship-simu/templates/images/de/.htaccess b/application/ship-simu/templates/images/de/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/application/ship-simu/templates/images/de/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/application/ship-simu/templates/images/de/image/.htaccess b/application/ship-simu/templates/images/de/image/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/application/ship-simu/templates/images/de/image/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/exceptions/io/class_FileIsMissingException.php b/inc/classes/exceptions/io/class_FileIsMissingException.php deleted file mode 100644 index 61fa308..0000000 --- a/inc/classes/exceptions/io/class_FileIsMissingException.php +++ /dev/null @@ -1,42 +0,0 @@ - - * @version 0.0.0 - * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software - * @license GNU GPL 3.0 or any newer version - * @link http://www.ship-simu.org - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -class FileIsMissingException extends FrameworkException { - /** - * The constructor - * - * @param $fqfn Full-qualified file name of (maybe) missing file - * @param $code Code number for the exception - * @return void - */ - public function __construct ($fqfn, $code) { - // Add a message around the missing class - $message = sprintf("The requested file %s is missing.", $fqfn); - - // Call parent constructor - parent::__construct($message, $code); - } -} - -// [EOF] -?> diff --git a/inc/classes/exceptions/io/class_FileNotFoundException.php b/inc/classes/exceptions/io/class_FileNotFoundException.php new file mode 100644 index 0000000..a8ff449 --- /dev/null +++ b/inc/classes/exceptions/io/class_FileNotFoundException.php @@ -0,0 +1,42 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class FileNotFoundException extends FrameworkException { + /** + * The constructor + * + * @param $fqfn Full-qualified file name of (maybe) missing file + * @param $code Code number for the exception + * @return void + */ + public function __construct ($fqfn, $code) { + // Add a message around the missing class + $message = sprintf("The requested file %s was not found.", $fqfn); + + // Call parent constructor + parent::__construct($message, $code); + } +} + +// [EOF] +?> diff --git a/inc/classes/exceptions/xml/.htaccess b/inc/classes/exceptions/xml/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/exceptions/xml/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/exceptions/xml/class_InvalidXmlNodeException.php b/inc/classes/exceptions/xml/class_InvalidXmlNodeException.php new file mode 100644 index 0000000..75a2353 --- /dev/null +++ b/inc/classes/exceptions/xml/class_InvalidXmlNodeException.php @@ -0,0 +1,54 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class InvalidXmlNodeException extends FrameworkException { + /** + * The super constructor for all exceptions + * + * @param $classArray Array holding the exception data + * @param $code Error code + * @return void + */ + public function __construct (array $classArray, $code) { + // Extract attributes + $attributes = "None"; + if ((is_array($classArray[2])) && (count($classArray[2]) > 0)) { + $attributes = implode(", ", $classArray[2]); + } // END - if + + // Construct our message + $message = sprintf("[%s:%d] Invalid XML node found: %s, attributes: %s.", + $classArray[0]->__toString(), + $this->getLine(), + $classArray[1], + $attributes + ); + die($message); + + // Call parent exception constructor + parent::__construct($message, $code); + } +} + +// [EOF] +?> diff --git a/inc/classes/exceptions/xml/class_XmlParserException.php b/inc/classes/exceptions/xml/class_XmlParserException.php new file mode 100644 index 0000000..1f14281 --- /dev/null +++ b/inc/classes/exceptions/xml/class_XmlParserException.php @@ -0,0 +1,47 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class XmlParserException extends FrameworkException { + /** + * The super constructor for all exceptions + * + * @param $classArray Array holding the exception data + * @param $code Error code + * @return void + */ + public function __construct (array $classArray, $code) { + // Construct our message + $message = sprintf("[%s:%d] XML Error: %s at line %d.", + $classArray[0]->__toString(), + $this->getLine(), + xml_error_string(xml_get_error_code($classArray[1])), + xml_get_current_line_number($classArray[1]) + ); + + // Call parent exception constructor + parent::__construct($message, $code); + } +} + +// [EOF] +?> diff --git a/inc/classes/interfaces/helper/class_HelpableTemplate.php b/inc/classes/interfaces/helper/class_HelpableTemplate.php new file mode 100644 index 0000000..c9d61cd --- /dev/null +++ b/inc/classes/interfaces/helper/class_HelpableTemplate.php @@ -0,0 +1,34 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +interface HelpableTemplate extends FrameworkInterface { + /** + * Flush the content out,e g. to a template variable + * + * @return void + */ + function flushContent (); +} + +// +?> diff --git a/inc/classes/interfaces/template/class_CompileableTemplate.php b/inc/classes/interfaces/template/class_CompileableTemplate.php index 2b3499e..3aef610 100644 --- a/inc/classes/interfaces/template/class_CompileableTemplate.php +++ b/inc/classes/interfaces/template/class_CompileableTemplate.php @@ -25,8 +25,8 @@ interface CompileableTemplate extends FrameworkInterface { /** * Assign variables for templates * - * @param $var The "variable" we want to assign - * @param $value The value we want to store in the variable + * @param $var The "variable" we want to assign + * @param $value The value we want to store in the variable * @return void */ function assignVariable ($var, $value); @@ -44,7 +44,7 @@ interface CompileableTemplate extends FrameworkInterface { * Load a specified code template into the engine for later compilation * with other code/web/email templates. * - * @param $template The code template we shall load which is + * @param $template The code template we shall load which is * located in "html" by default * @return void */ @@ -53,7 +53,7 @@ interface CompileableTemplate extends FrameworkInterface { /** * Load a specified email template into the engine * - * @param $template The email template we shall load which is + * @param $template The email template we shall load which is * located in "emails" by default * @return void */ diff --git a/inc/classes/main/class_BaseFrameworkSystem.php b/inc/classes/main/class_BaseFrameworkSystem.php index 3b0a939..132d5be 100644 --- a/inc/classes/main/class_BaseFrameworkSystem.php +++ b/inc/classes/main/class_BaseFrameworkSystem.php @@ -256,9 +256,12 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface { } elseif (is_null($arg)) { // Null $argsString .= "(null)"; + } elseif (is_resource($arg)) { + // Resource + $argsString .= "(resource)"; } else { // Unknown type (please report!) - $argsString .= $arg."(unknown!)"; + $argsString .= $arg."(unknown!)"; } // Add comma @@ -266,7 +269,9 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface { } // Remove last comma - if (substr($argsString, -2, 1) === ",") $argsString = substr($argsString, 0, -2); + if (substr($argsString, -2, 1) === ",") { + $argsString = substr($argsString, 0, -2); + } // END - if } else { // Invalid arguments! $argsString = sprintf("!INVALID:%s!", $args); @@ -880,7 +885,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface { } /** - * Prepare the template engine (TemplateEngine by default) for a given + * Prepare the template engine (WebTemplateEngine by default) for a given * application helper instance (ApplicationHelper by default). * * @param $appInstance An application helper instance or diff --git a/inc/classes/main/helper/captcha/web/class_GraphicalCodeCaptcha.php b/inc/classes/main/helper/captcha/web/class_GraphicalCodeCaptcha.php index 6dcf0aa..d40a1ba 100644 --- a/inc/classes/main/helper/captcha/web/class_GraphicalCodeCaptcha.php +++ b/inc/classes/main/helper/captcha/web/class_GraphicalCodeCaptcha.php @@ -133,7 +133,17 @@ class GraphicalCodeCaptcha extends BaseCaptcha implements SolveableCaptcha { * @return void */ public function renderCode () { - $this->partialStub("Please implement this method."); + // Load a template for this CAPTCHA + $this->getTemplateInstance()->loadCodeTemplate("captch_graphic_code"); + + // Assign variable + $this->getTemplateInstance()->assignVariable('encrypted_code', urlencode(base64_encode($this->encryptedString))); + + // Compile the template + $this->getTemplateInstance()->compileTemplate(); + + // Get the content back + $this->addContent($this->getTemplateInstance()->getRawTemplateData()); } } diff --git a/inc/classes/main/helper/class_BaseHelper.php b/inc/classes/main/helper/class_BaseHelper.php index 1a48194..d266d5b 100644 --- a/inc/classes/main/helper/class_BaseHelper.php +++ b/inc/classes/main/helper/class_BaseHelper.php @@ -22,6 +22,10 @@ * along with this program. If not, see . */ class BaseHelper extends BaseFrameworkSystem { + // Exception constants + const EXCEPTION_XML_PARSER_ERROR = 0x0d0; + const EXCEPTION_XML_NODE_UNKNOWN = 0x0d1; + /** * Template engine instance */ diff --git a/inc/classes/main/helper/images/.htaccess b/inc/classes/main/helper/images/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/main/helper/images/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/main/helper/images/class_ImageHelper.php b/inc/classes/main/helper/images/class_ImageHelper.php new file mode 100644 index 0000000..5490a40 --- /dev/null +++ b/inc/classes/main/helper/images/class_ImageHelper.php @@ -0,0 +1,253 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class ImageHelper extends BaseHelper implements HelpableTemplate { + /** + * The image type + */ + private $imageType = "png"; + + /** + * Width of the image in pixel + */ + private $width = 0; + + /** + * Height of the image in pixel + */ + private $height = 0; + + /** + * Array for background color values + */ + private $backgroundColor = array( + 'red' => 0, + 'green' => 0, + 'blue' => 0 + ); + + /** + * Array for foreground color values + */ + private $foregroundColor = array( + 'red' => 0, + 'green' => 0, + 'blue' => 0 + ); + + /** + * Image message string + */ + private $imageString = "No message set!"; + + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription("A image helper class"); + } + + /** + * Creates the helper class + * + * @param $templateInstance An instance of a template engine + * @param $imageType Type of the image + * @return $helperInstance A preparedf instance of this class + */ + public final static function createImageHelper (CompileableTemplate $templateInstance, $imageType) { + // Get new instance + $helperInstance = new ImageHelper(); + + // Set template instance + $helperInstance->setTemplateInstance($templateInstance); + + // Set image type (blindly) + $helperInstance->setImageType($imageType); + + // Return the prepared instance + return $helperInstance; + } + + /** + * Setter for image type + * + * @param $imageType Type of the image + * @return void + */ + protected final function setImageType ($imageType) { + $this->imageType = (string) $imageType; + } + + /** + * Getter for image type + * + * @return $imageType Type of the image + */ + public final function getImageType () { + return $this->imageType; + } + + /** + * Setter for image width + * + * @param $width Width of the image + * @return void + */ + public final function setWidth ($width) { + $this->width = (int) $width; + } + + /** + * Getter for image width + * + * @return $width Width of the image + */ + public final function getWidth () { + return $this->width; + } + + /** + * Setter for image height + * + * @param $height Height of the image + * @return void + */ + public final function setHeight ($height) { + $this->height = (int) $height; + } + + /** + * Getter for image height + * + * @return $height Height of the image + */ + public final function getHeight () { + return $this->height; + } + + /** + * Setter for RGB of background color + * + * @param $red Color value for red + * @param $green Color value for green + * @param $blue Color value for blue + * @return void + */ + public final function setBackgroundColorRedGreenBlue ($red, $green, $blue) { + $this->backgroundColor['red'] = (int) $red; + $this->backgroundColor['green'] = (int) $green; + $this->backgroundColor['blue'] = (int) $blue; + } + + /** + * Setter for RGB of foreground color + * + * @param $red Color value for red + * @param $green Color value for green + * @param $blue Color value for blue + * @return void + */ + public final function setForegroundColorRedGreenBlue ($red, $green, $blue) { + $this->foregroundColor['red'] = (int) $red; + $this->foregroundColor['green'] = (int) $green; + $this->foregroundColor['blue'] = (int) $blue; + } + + /** + * Setter for image message string + * + * @param $imageString A message to display in the image + * @return void + */ + public final function setImageString ($imageString) { + $this->imageString = (string) $imageString; + } + + /** + * Getter for image message string + * + * @return $imageString A message to display in the image + */ + public final function getImageString () { + return $this->imageString; + } + + /** + * Setter for base image + * + * @param $baseImage A base image template + * @return void + */ + public final function setBaseImage ($baseImage) { + $this->baseImage = (string) $baseImage; + } + + /** + * Getter for base image + * + * @return $baseImage A base image template + */ + public final function getBaseImage () { + return $this->baseImage; + } + + /** + * Flushs the content out + * + * @return void + */ + public function flushContent () { + // Get a template instance + $templateInstance = $this->getTemplateInstance(); + + // Get the base image + $templateInstance->loadCodeTemplate($this->getBaseImage()); + + // Assign all the image values with the template + $templateInstance->assignVariable("image_type" , $this->getImageType()); + $templateInstance->assignVariable("image_width" , $this->getWidth()); + $templateInstance->assignVariable("image_height" , $this->getHeight()); + $templateInstance->assignVariable("image_bg_red" , $this->backgroundColor['red']); + $templateInstance->assignVariable("image_bg_green", $this->backgroundColor['green']); + $templateInstance->assignVariable("image_bg_blue" , $this->backgroundColor['blue']); + $templateInstance->assignVariable("image_fg_red" , $this->foregroundColor['red']); + $templateInstance->assignVariable("image_fg_green", $this->foregroundColor['green']); + $templateInstance->assignVariable("image_fg_blue" , $this->foregroundColor['blue']); + $templateInstance->assignVariable("image_string" , $this->getImageString()); + + // Get the raw content + $imageContent = $templateInstance->getRawTemplateData(); + + // Transfer all to the template engine + $templateInstance->renderImageContent($imageContent); + } +} + +// [EOF] +?> diff --git a/inc/classes/main/helper/web/class_WebFormHelper.php b/inc/classes/main/helper/web/class_WebFormHelper.php index ddb10a8..8d20001 100644 --- a/inc/classes/main/helper/web/class_WebFormHelper.php +++ b/inc/classes/main/helper/web/class_WebFormHelper.php @@ -21,7 +21,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -class WebFormHelper extends BaseHelper { +class WebFormHelper extends BaseHelper implements HelpableTemplate { /** * Instance to the class which provides field values */ @@ -53,6 +53,11 @@ class WebFormHelper extends BaseHelper { */ private $subGroupName = ""; + /** + * Wether form tag is enabled (default: true) + */ + private $formEnabled = true; + // Class Constants const EXCEPTION_FORM_NAME_INVALID = 0x030; const EXCEPTION_CLOSED_FORM = 0x031; @@ -81,9 +86,10 @@ class WebFormHelper extends BaseHelper { * @param $templateInstance An instance of a valid template engine * @param $formName Name of the form * @param $formId Value for "id" attribute (default: $formName) + * @param $withForm Wether include the form tag * @return $helperInstance A preparedf instance of this class */ - public final static function createWebFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false) { + public final static function createWebFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false, $withForm = true) { // Get new instance $helperInstance = new WebFormHelper(); @@ -94,10 +100,18 @@ class WebFormHelper extends BaseHelper { if ($formId === false) { // Use form id from form name $formId = $formName; - } + } // END - if - // Create the form - $helperInstance->addFormTag($formName, $formId); + // Set form name + $helperInstance->setFormName($formName); + // A form-less field may say "false" here... + if ($withForm === true) { + // Create the form + $helperInstance->addFormTag($formName, $formId); + } else { + // Disable form + $helperInstance->enableForm(false); + } // Return the prepared instance return $helperInstance; @@ -141,7 +155,7 @@ class WebFormHelper extends BaseHelper { $formContent = ""; // Check wether we shall open or close the form - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Add HTML code $formContent = sprintf("
getConfigInstance()->readConfig('form_target') ); - // Is the form id set? - if ($formId !== false) { - // Then add it as well - $formContent .= sprintf(" id=\"%s_form\"", - $formId - ); - } + // Add form id as well + $formContent .= sprintf(" id=\"%s_form\"", + $formId + ); // Add close bracket $formContent .= ">"; // Open the form and remeber the form name $this->formOpened = true; - $this->formName = $formName; } else { // Add the hidden field required to identify safely this form - $this->addInputHiddenField('form', $this->formName); + $this->addInputHiddenField('form', $this->getFormName()); // Is a group open? if ($this->groupOpened === true) { @@ -194,7 +204,7 @@ class WebFormHelper extends BaseHelper { */ public function addInputTextField ($fieldName, $fieldValue = "") { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -236,7 +246,7 @@ class WebFormHelper extends BaseHelper { */ public function addInputPasswordField ($fieldName, $fieldValue = "") { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -263,7 +273,7 @@ class WebFormHelper extends BaseHelper { */ public function addInputHiddenField ($fieldName, $fieldValue = "") { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -320,7 +330,7 @@ class WebFormHelper extends BaseHelper { */ public function addInputCheckboxField ($fieldName, $fieldChecked = true) { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -350,14 +360,14 @@ class WebFormHelper extends BaseHelper { */ public function addInputResetButton ($buttonText) { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, "reset"), self::EXCEPTION_CLOSED_FORM); } // END - if // Generate the content $inputContent = sprintf("", - $this->formName, + $this->getFormName(), $buttonText ); @@ -375,15 +385,15 @@ class WebFormHelper extends BaseHelper { */ public function addInputSubmitButton ($buttonText) { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, "submit"), self::EXCEPTION_CLOSED_FORM); } // END - if // Generate the content $inputContent = sprintf("", - $this->formName, - $this->formName, + $this->getFormName(), + $this->getFormName(), $buttonText ); @@ -402,7 +412,7 @@ class WebFormHelper extends BaseHelper { */ public function addFormGroup ($groupName, $groupText) { // Is a form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw exception here throw new FormClosedException(array($this, $groupName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -531,7 +541,7 @@ class WebFormHelper extends BaseHelper { */ public function addFieldText ($fieldName, $fieldText) { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -564,7 +574,7 @@ class WebFormHelper extends BaseHelper { */ public function addFormNote ($formNotes) { // Is the form opened? - if ($this->formOpened === false) { + if (($this->formOpened === false) && ($this->formEnabled === true)) { // Throw an exception throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM); } // END - if @@ -742,7 +752,7 @@ class WebFormHelper extends BaseHelper { * @return $isSecured Wether this form is secured by a CAPTCHA */ public function ifFormSecuredWithCaptcha () { - $isSecured = ($this->getConfigInstance()->readConfig($this->formName."_captcha_secured") == "Y"); + $isSecured = ($this->getConfigInstance()->readConfig($this->getFormName()."_captcha_secured") == "Y"); return $isSecured; } @@ -755,13 +765,13 @@ class WebFormHelper extends BaseHelper { */ public function flushContent () { // Is the form still open? - if ($this->formOpened === true) { + if (($this->formOpened === true) && ($this->formEnabled === true)) { // Close the form automatically $this->addFormTag(); } // END - if // Send content to template engine - $this->getTemplateInstance()->assignVariable($this->formName, $this->getContent()); + $this->getTemplateInstance()->assignVariable($this->getFormName(), $this->getContent()); } /** @@ -788,7 +798,7 @@ class WebFormHelper extends BaseHelper { $extraInstance = Registry::getRegistry()->getInstance('extra'); // Get a configured instance - $captchaInstance = ObjectFactory::createObjectByConfiguredName("{$this->formName}_captcha", array($this->getTemplateInstance(), $extraInstance)); + $captchaInstance = ObjectFactory::createObjectByConfiguredName($this->getFormName()."_captcha", array($this->getTemplateInstance(), $extraInstance)); // Initiate the CAPTCHA $captchaInstance->initiateCaptcha(); @@ -799,6 +809,35 @@ class WebFormHelper extends BaseHelper { // Get the content and add it to the helper $this->addContent($captchaInstance->getContent()); } + + /** + * Enables/disables the form tag usage + * + * @param $formEnabled Wether form is enabled or disabled + * @return void + */ + public final function enableForm ($formEnabled = true) { + $this->formEnabled = (bool) $formEnabled; + } + + /** + * Setter for form name + * + * @param $formName Name of this form + * @return void + */ + public final function setFormName ($formName) { + $this->formName = (string) $formName; + } + + /** + * Getter for form name + * + * @return $formName Name of this form + */ + public final function getFormName () { + return $this->formName; + } } // [EOF] diff --git a/inc/classes/main/images/.htaccess b/inc/classes/main/images/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/main/images/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/main/images/class_ b/inc/classes/main/images/class_ new file mode 100644 index 0000000..9a90092 --- /dev/null +++ b/inc/classes/main/images/class_ @@ -0,0 +1,56 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class ???Image extends BaseImage { + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription(""); + + // Create unique ID number + $this->generateUniqueId(); + } + + /** + * Creates an instance of this image class + * + * @return $imageInstance An instance of this image class + */ + public final static function create???Image() { + // Get a new instance + $imageInstance = new ???Image(); + + // Return the instance + return $imageInstance; + } +} + +// [EOF] +?> diff --git a/inc/classes/main/images/class_BaseImage.php b/inc/classes/main/images/class_BaseImage.php new file mode 100644 index 0000000..2273945 --- /dev/null +++ b/inc/classes/main/images/class_BaseImage.php @@ -0,0 +1,42 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class BaseImage extends BaseFrameworkSystem { + /** + * Protected constructor + * + * @param $className Name of the class + * @return void + */ + protected function __construct ($className) { + // Call parent constructor + parent::__construct($className); + + // Clean up a little + $this->removeNumberFormaters(); + $this->removeSystemArray(); + } +} + +// [EOF] +?> diff --git a/inc/classes/main/images/extended/.htaccess b/inc/classes/main/images/extended/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/main/images/extended/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/main/images/extended/class_PngImage.php b/inc/classes/main/images/extended/class_PngImage.php new file mode 100644 index 0000000..4693a3d --- /dev/null +++ b/inc/classes/main/images/extended/class_PngImage.php @@ -0,0 +1,56 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class PngImage extends BaseImage { + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription(""); + + // Create unique ID number + $this->generateUniqueId(); + } + + /** + * Creates an instance of this image class + * + * @return $imageInstance An instance of this image class + */ + public final static function createPngImage() { + // Get a new instance + $imageInstance = new PngImage(); + + // Return the instance + return $imageInstance; + } +} + +// [EOF] +?> diff --git a/inc/classes/main/io/class_FrameworkFileInputPointer.php b/inc/classes/main/io/class_FrameworkFileInputPointer.php index fe6b058..c81db57 100644 --- a/inc/classes/main/io/class_FrameworkFileInputPointer.php +++ b/inc/classes/main/io/class_FrameworkFileInputPointer.php @@ -81,7 +81,7 @@ class FrameworkFileInputPointer extends BaseFrameworkSystem { throw new FileIsEmptyException(null, self::EXCEPTION_UNEXPECTED_EMPTY_STRING); } elseif (!file_exists($fileName)) { // File does not exist! - throw new FileIsMissingException($fileName, self::EXCEPTION_FILE_NOT_FOUND); + throw new FileNotFoundException($fileName, self::EXCEPTION_FILE_NOT_FOUND); } elseif (!is_readable($fileName)) { // File does not exist! throw new FileReadProtectedException($fileName, self::EXCEPTION_FILE_CANNOT_BE_READ); diff --git a/inc/classes/main/response/class_ImageResponse.php b/inc/classes/main/response/class_ImageResponse.php new file mode 100644 index 0000000..2e2fd09 --- /dev/null +++ b/inc/classes/main/response/class_ImageResponse.php @@ -0,0 +1,376 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * The extended headers are taken from phpMyAdmin setup tool, written by + * Michal Cihar , licensed under GNU GPL 2.0. + */ +class ImageResponse extends BaseFrameworkSystem implements Responseable { + /** + * Response status + */ + private $responseStatus = "200 OK"; + + /** + * Array with all headers + */ + private $responseHeaders = array(); + + /** + * Cookies we shall sent out + */ + private $cookies = array(); + + /** + * Body of the response + */ + private $responseBody = ""; + + /** + * Instance of the template engine + */ + private $templateEngine = null; + + /** + * Fatal resolved messages from filters and so on + */ + private $fatalMessages = array(); + + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription("HTTP response"); + + // Create unique ID number + $this->generateUniqueId(); + + // Clean up a little + $this->removeNumberFormaters(); + $this->removeSystemArray(); + } + + /** + * Creates an object of this class + * + * @param $appInstance An instance of a manageable application + * @return $responseInstance A prepared instance of this class + */ + public final static function createImageResponse (ManageableApplication $appInstance) { + // Get a new instance + $responseInstance = new ImageResponse(); + + // Set the application instance + $responseInstance->setApplicationInstance($appInstance); + + // Initialize the template engine here + $responseInstance->initTemplateEngine($appInstance); + + // Return the prepared instance + return $responseInstance; + } + + /** + * Setter for status + * + * @param $status New response status + * @return void + */ + public final function setResponseStatus ($status) { + $this->responseStatus = (string) $status; + } + + /** + * Add header element + * + * @param $name Name of header element + * @param $value Value of header element + * @return void + */ + public final function addHeader ($name, $value) { + $this->responseHeaders[$name] = $value; + } + + /** + * Reset the header array + * + * @return void + */ + public final function resetResponseHeaders () { + $this->responseHeaders = array(); + } + + /** + * "Writes" data to the response body + * + * @param $output Output we shall sent in the HTTP response + * @return void + */ + public function writeToBody ($output) { + $this->responseBody .= $output; + } + + /** + * Sets the response body to something new + * + * @param $output Output we shall sent in the HTTP response + * @return void + */ + public function setResponseBody ($output) { + $this->responseBody = $output; + } + + /** + * Flushs the cached HTTP response to the outer world + * + * @param $force Wether we shall force the output or abort if headers are + * already sent with an exception + * @return void + * @throws ResponseHeadersAlreadySentException Thrown if headers are + * already sent + */ + public function flushBuffer ($force=false) { + if ((headers_sent()) && (!$force)) { + // Headers are already sent! + throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT); + } elseif (!headers_sent()) { + // Send headers out + header("HTTP/1.1 {$this->responseStatus}"); + + // Used later + $now = gmdate('D, d M Y H:i:s') . ' GMT'; + + // General header for no caching + $this->addHeader('Expired', $now); // rfc2616 - Section 14.21 + $this->addHeader('Last-Modified', $now); + $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1 + $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0 + + // Define the charset to be used + //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset'))); + + foreach ($this->responseHeaders as $name=>$value) { + header("{$name}: {$value}"); + } // END - foreach + + // Send cookies out? + if (count($this->cookies) > 0) { + // Send all cookies + $cookieString = implode(" ", $this->cookies); + header("Set-Cookie: {$cookieString}"); + + // Remove them all + $this->cookies = array(); + } // END - if + } + + // Are there some error messages? + if (count($this->fatalMessages) == 0) { + // Flush the output to the world + $this->getWebOutputInstance()->output($this->responseBody); + } else { + // Display all error messages + $this->getApplicationInstance()->handleFatalMessages($this->fatalMessages); + + // Send the error messages out to the world + $this->getWebOutputInstance()->output($this->responseBody); + } + + // Clear response header and body + $this->setResponseBody(""); + $this->resetResponseHeaders(); + } + + /** + * Initializes the template engine instance + * + * @param $appInstance An instance of a manageable application + * @return void + */ + public final function initTemplateEngine (ManageableApplication $appInstance) { + // Get config instance + $cfg = $this->getConfigInstance(); + + // Set new template engine + $cfg->setConfigEntry('template_class', "ImageTemplateEngine"); + $cfg->setConfigEntry('raw_template_extension', ".img"); + $cfg->setConfigEntry('code_template_extension', ".img"); + $cfg->setConfigEntry('tpl_base_path', "templates/images/"); + $cfg->setConfigEntry('code_template_type', "image"); + + // Get a prepared instance + $this->templateEngine = $this->prepareTemplateEngine($appInstance); + } + + /** + * Getter for the template engine instance + * + * @return $templateEngine An instance of the used template engine + */ + public final function getTemplateEngine () { + return $this->templateEngine; + } + + /** + * Adds a fatal message id to the response. The added messages can then be + * processed and outputed to the world + * + * @param $messageId The message id we shall add + * @return void + */ + public final function addFatalMessage ($messageId) { + // Adds the resolved message id to the fatal message list + $this->fatalMessages[] = $this->getApplicationInstance()->getLanguageInstance()->getMessage($messageId); + } + + /** + * Adds a cookie to the response + * + * @param $cookieName Cookie's name + * @param $cookieValue Value to store in the cookie + * @param $encrypted Do some extra encryption on the value + * @param $expires Timestamp of expiration (default: configured) + * @return void + * @throws ResponseHeadersAlreadySentException If headers are already sent + * @todo Encryption of cookie data not yet supported. + * @todo Why are these parameters conflicting? + * @todo If the return statement is removed and setcookie() commented out, + * @todo this will send only one cookie out, the first one. + */ + public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) { + // Are headers already sent? + if (headers_sent()) { + // Throw an exception here + throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT); + } // END - if + + // Shall we encrypt the cookie? + if ($encrypted === true) { + } // END - if + + // For slow browsers set the cookie array element first + $_COOKIE[$cookieName] = $cookieValue; + + // Get all config entries + if (is_null($expires)) { + $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire')); + } // END - if + + $path = $this->getConfigInstance()->readConfig('cookie_path'); + $domain = $this->getConfigInstance()->readConfig('cookie_domain'); + + setcookie($cookieName, $cookieValue, $expires); + //, $path, $domain, (isset($_SERVER['HTTPS'])) + return; + + // Now construct the full header + $cookieString = $cookieName . "=" . $cookieValue . "; "; + $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT"; + // $cookieString .= "; path=".$path."; domain=".$domain; + + // Set the cookie as a header + $this->cookies[$cookieName] = $cookieString; + } + + /** + * Redirect to a configured URL. The URL can be absolute or relative. In + * case of relative URL it will be extended automatically. + * + * @param $configEntry The configuration entry which holds our URL + * @return void + * @throws ResponseHeadersAlreadySentException If headers are already sent + */ + public function redirectToConfiguredUrl ($configEntry) { + // Is the header not yet sent? + if (headers_sent()) { + // Throw an exception here + throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT); + } // END - if + + // Get the url from config + $url = $this->getConfigInstance()->readConfig($configEntry); + + // Do we have a "http" in front of the URL? + if (substr(strtolower($url), 0, 4) != "http") { + // Is there a / in front of the relative URL? + if (substr($url, 0, 1) == "/") $url = substr($url, 1); + + // No, then extend it with our base URL + $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url; + } // END - if + + // Add redirect header + $this->addHeader("Location", $url); + + // Set correct response status + $this->setResponseStatus("301 Moved Permanently"); + + // Clear the body + $this->setResponseBody(""); + + // Flush the result + $this->flushBuffer(); + + // All done here... + exit(); + } + + /** + * Expires the given cookie if it is set + * + * @param $cookieName Cookie to expire + * @return void + */ + public function expireCookie ($cookieName) { + // Is the cookie there? + if (isset($_COOKIE[$cookieName])) { + // Then expire it with 20 minutes past + $this->addCookie($cookieName, "", false, (time() - 1200)); + + // Remove it from array + unset($_COOKIE[$cookieName]); + } // END - if + } + + /** + * Refreshs a given cookie. This will make the cookie live longer + * + * @param $cookieName Cookie to refresh + * @return void + */ + public function refreshCookie ($cookieName) { + // Only update existing cookies + if (isset($_COOKIE[$cookieName])) { + // Update the cookie + $this->addCookie($cookieName, $_COOKIE[$cookieName], false); + } // END - if + } +} + +// [EOF] +?> diff --git a/inc/classes/main/rng/class_RandomNumberGenerator.php b/inc/classes/main/rng/class_RandomNumberGenerator.php index 1e702c9..15f4373 100644 --- a/inc/classes/main/rng/class_RandomNumberGenerator.php +++ b/inc/classes/main/rng/class_RandomNumberGenerator.php @@ -122,7 +122,7 @@ class RandomNumberGenerator extends BaseFrameworkSystem { } // One-way data we need for "extra-salting" the random number - $this->extraSalt = sha1($this->fixedSalt . ":" . getenv('SERVER_SOFTWARE') . ":" . $this->getConfigInstance()->readConfig('date_key')); + $this->extraSalt = sha1($this->fixedSalt . ":" . getenv('SERVER_SOFTWARE') . ":" . $this->getConfigInstance()->readConfig('date_key') . $this->getConfigInstance()->readConfig('base_url')); // Get config entry for max salt length $this->rndStrLen = $this->getConfigInstance()->readConfig('rnd_str_length'); diff --git a/inc/classes/main/template/class_BaseTemplateEngine.php b/inc/classes/main/template/class_BaseTemplateEngine.php new file mode 100644 index 0000000..7188fda --- /dev/null +++ b/inc/classes/main/template/class_BaseTemplateEngine.php @@ -0,0 +1,1184 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class BaseTemplateEngine extends BaseFrameworkSystem { + /** + * The local path name where all templates and sub folders for special + * templates are stored. We will internally determine the language plus + * "html" for web templates or "emails" for email templates + */ + private $basePath = ""; + + /** + * Template type + */ + private $templateType = "html"; + + /** + * The extension for web and email templates (not compiled templates) + */ + private $templateExtension = ".tpl"; + + /** + * The extension for code templates (not compiled templates) + */ + private $codeExtension = ".ctp"; + + /** + * Path relative to $basePath and language code for compiled code-templates + */ + private $compileOutputPath = "templates/_compiled"; + + /** + * The raw (maybe uncompiled) template + */ + private $rawTemplateData = ""; + + /** + * Template data with compiled-in variables + */ + private $compiledData = ""; + + /** + * The last loaded template's FQFN for debugging the engine + */ + private $lastTemplate = ""; + + /** + * The variable stack for the templates. This must be initialized and + * shall become an instance of FrameworkArrayObject. + */ + private $varStack = null; + + /** + * Configuration variables in a simple array + */ + private $configVariables = array(); + + /** + * Loaded templates for recursive protection and detection + */ + private $loadedTemplates = array(); + + /** + * Compiled templates for recursive protection and detection + */ + private $compiledTemplates = array(); + + /** + * Loaded raw template data + */ + private $loadedRawData = null; + + /** + * Raw templates which are linked in code templates + */ + private $rawTemplates = null; + + /** + * A regular expression for variable=value pairs + */ + private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/'; + + /** + * A regular expression for filtering out code tags + * + * E.g.: {?template:variable=value;var2=value2;[...]?} + */ + private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/'; + + /** + * Loaded helpers + */ + private $helpers = array(); + + // Exception codes for the template engine + const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x020; + const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021; + const EXCEPTION_INVALID_VIEW_HELPER = 0x022; + + /** + * Initialize the variable stack. This holds all variables for later + * compilation. + * + * @return void + */ + public final function initVariableStack () { + $this->varStack = new FrameworkArrayObject("FakedVariableStack"); + } + + /** + * Protected constructor + * + * @param $className Name of the class + * @return void + */ + protected function __construct ($className) { + // Call parent constructor + parent::__construct($className); + + // Clean up a little + $this->removeNumberFormaters(); + $this->removeSystemArray(); + } + + /** + * Search for a variable in the stack + * + * @param $var The variable we are looking for + * @return $idx FALSE means not found, >=0 means found on a specific index + */ + private function isVariableAlreadySet ($var) { + // First everything is not found + $found = false; + + // Now search for it + for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { + // Get current item + $currEntry = $idx->current(); + + // Is the entry found? + if ($currEntry['name'] == $var) { + // Found! + $found = $idx->key(); + break; + } + } + + // Return the current position + return $found; + } + + /** + * Return a content of a variable or null if not found + * + * @param $var The variable we are looking for + * @return $content Content of the variable or null if not found + */ + private function readVariable ($var) { + // First everything is not found + $content = null; + + // Now search for it + for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { + // Get current item + $currEntry = $idx->current(); + + // Is the entry found? + if ($currEntry['name'] == $var) { + // Found! + $content = $currEntry['value']; + break; + } + } + + // Return the current position + return $content; + } + + /** + * Add a variable to the stack + * + * @param $var The variable we are looking for + * @param $value The value we want to store in the variable + * @return void + */ + private function addVariable ($var, $value) { + // Add it to the stack + $this->varStack->append(array( + 'name' => trim($var), + 'value' => trim($value) + )); + } + + /** + * Modify an entry on the stack + * + * @param $var The variable we are looking for + * @param $value The value we want to store in the variable + * @return void + */ + private function modifyVariable ($var, $value) { + // It should be there so let's look again... + for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { + // Get current entry + $currEntry = $idx->current(); + + // Is this the requested variable? + if ($currEntry['name'] == $var) { + // Change it to the other value + $this->varStack->offsetSet($idx->key(), array( + 'name' => $var, + 'value' => $value + )); + } + } + } + + /** + * Setter for template type. Only "html", "emails" and "compiled" should + * be sent here + * + * @param $templateType The current template's type + * @return void + */ + private final function setTemplateType ($templateType) { + // Cast it + $templateType = (string) $templateType; + + // And set it (only 2 letters) + $this->templateType = $templateType; + } + + /** + * Setter for the last loaded template's FQFN + * + * @param $template The last loaded template + * @return void + */ + private final function setLastTemplate ($template) { + // Cast it to string + $template = (string) $template; + $this->lastTemplate = $template; + } + + /** + * Getter for the last loaded template's FQFN + * + * @return $template The last loaded template + */ + private final function getLastTemplate () { + return $this->lastTemplate; + } + + /** + * Setter for base path + * + * @param $basePath The local base path for all templates + * @return void + */ + public final function setBasePath ($basePath) { + // Cast it + $basePath = (string) $basePath; + + // And set it + $this->basePath = $basePath; + } + + /** + * Getter for base path + * + * @return $basePath The local base path for all templates + */ + public final function getBasePath () { + // And set it + return $this->basePath; + } + + /** + * Setter for template extension + * + * @param $templateExtension The file extension for all uncompiled + * templates + * @return void + */ + public final function setRawTemplateExtension ($templateExtension) { + // Cast it + $templateExtension = (string) $templateExtension; + + // And set it + $this->templateExtension = $templateExtension; + } + + /** + * Setter for code template extension + * + * @param $codeExtension The file extension for all uncompiled + * templates + * @return void + */ + public final function setCodeTemplateExtension ($codeExtension) { + // Cast it + $codeExtension = (string) $codeExtension; + + // And set it + $this->codeExtension = $codeExtension; + } + + /** + * Getter for template extension + * + * @return $templateExtension The file extension for all uncompiled + * templates + */ + public final function getRawTemplateExtension () { + // And set it + return $this->templateExtension; + } + + /** + * Getter for code-template extension + * + * @return $codeExtension The file extension for all code- + * templates + */ + public final function getCodeTemplateExtension () { + // And set it + return $this->codeExtension; + } + + /** + * Setter for path of compiled templates + * + * @param $compileOutputPath The local base path for all compiled + * templates + * @return void + */ + public final function setCompileOutputPath ($compileOutputPath) { + // Cast it + $compileOutputPath = (string) $compileOutputPath; + + // And set it + $this->compileOutputPath = $compileOutputPath; + } + + /** + * Getter for template type + * + * @return $templateType The current template's type + */ + public final function getTemplateType () { + return $this->templateType; + } + + /** + * Assign (add) a given variable with a value + * + * @param $var The variable we are looking for + * @param $value The value we want to store in the variable + * @return void + */ + public final function assignVariable ($var, $value) { + // First search for the variable if it was already added + $idx = $this->isVariableAlreadySet($var); + + // Was it found? + if ($idx === false) { + // Add it to the stack + $this->addVariable($var, $value); + } elseif (!empty($value)) { + // Modify the stack entry + $this->modifyVariable($var, $value); + } + } + + /** + * Removes a given variable + * + * @param $var The variable we are looking for + * @return void + */ + public final function removeVariable ($var) { + // First search for the variable if it was already added + $idx = $this->isVariableAlreadySet($var); + + // Was it found? + if ($idx !== false) { + // Remove this variable + $this->varStack->offsetUnset($idx); + } + } + + /** + * Private setter for raw template data + * + * @param $rawTemplateData The raw data from the template + * @return void + */ + private final function setRawTemplateData ($rawTemplateData) { + // Cast it to string + $rawTemplateData = (string) $rawTemplateData; + + // And store it in this class + $this->rawTemplateData = $rawTemplateData; + } + + /** + * Private setter for compiled templates + * + * @return void + */ + private final function setCompiledData ($compiledData) { + // Cast it to string + $compiledData = (string) $compiledData; + + // And store it in this class + $this->compiledData = $compiledData; + } + + /** + * Private loader for all template types + * + * @param $template The template we shall load + * @return void + */ + private function loadTemplate ($template) { + // Cast it to string + $template = (string) $template; + + // Get extension for the template + $ext = $this->getRawTemplateExtension(); + + // If we shall load a code-template we need to switch the file extension + if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) { + // Switch over to the code-template extension + $ext = $this->getCodeTemplateExtension(); + } // END - if + + // Construct the FQFN for the template by honoring the current language + $fqfn = sprintf("%s%s/%s/%s%s", + $this->getBasePath(), + $this->getLanguageInstance()->getLanguageCode(), + $this->getTemplateType(), + $template, + $ext + ); + + // Load the raw template data + $this->loadRawTemplateData($fqfn); + } + + /** + * A private loader for raw template names + * + * @param $fqfn The full-qualified file name for a template + * @return void + * @throws NullPointerException If $inputInstance is null + * @throws NoObjectException If $inputInstance is not an object + * @throws MissingMethodException If $inputInstance is missing a + * required method + */ + private function loadRawTemplateData ($fqfn) { + // Get a input/output instance from the middleware + $ioInstance = $this->getFileIoInstance(); + + // Validate the instance + if (is_null($ioInstance)) { + // Throw exception + throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER); + } elseif (!is_object($ioInstance)) { + // Throw another exception + throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT); + } elseif (!method_exists($ioInstance, 'loadFileContents')) { + // Throw yet another exception + throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD); + } + + /* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."
\n"; + + // Load the raw template + $rawTemplateData = $ioInstance->loadFileContents($fqfn); + + // Store the template's contents into this class + $this->setRawTemplateData($rawTemplateData); + + // Remember the template's FQFN + $this->setLastTemplate($fqfn); + } + + /** + * Try to assign an extracted template variable as a "content" or "config" + * variable. + * + * @param $varName The variable's name (shall be content orconfig) by + * default + * @param $var The variable we want to assign + */ + private function assignTemplateVariable ($varName, $var) { + // Is it not a config variable? + if ($varName != "config") { + // Regular template variables + $this->assignVariable($var, ""); + } else { + // Configuration variables + $this->assignConfigVariable($var); + } + } + + /** + * Extract variables from a given raw data stream + * + * @param $rawData The raw template data we shall analyze + * @return void + */ + private function extractVariablesFromRawData ($rawData) { + // Cast to string + $rawData = (string) $rawData; + + // Search for variables + @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches); + + // Did we find some variables? + if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) { + // Initialize all missing variables + foreach ($variableMatches[3] as $key=>$var) { + // Try to assign it, empty strings are being ignored + $this->assignTemplateVariable($variableMatches[1][$key], $var); + } // END - foreach + } // END - if + } + + /** + * Main analysis of the loaded template + * + * @param $templateMatches Found template place-holders, see below + * @return void + * + *--------------------------------- + * Structure of $templateMatches: + *--------------------------------- + * [0] => Array - An array with all full matches + * [1] => Array - An array with left part (before the ":") of a match + * [2] => Array - An array with right part of a match including ":" + * [3] => Array - An array with right part of a match excluding ":" + */ + private function analyzeTemplate (array $templateMatches) { + // Backup raw template data + $backup = $this->getRawTemplateData(); + + // Initialize some arrays + if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); } + + // Load all requested templates + foreach ($templateMatches[1] as $template) { + + // Load and compile only templates which we have not yet loaded + // RECURSIVE PROTECTION! BE CAREFUL HERE! + if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) { + + // Template not found, but maybe variable assigned? + if ($this->isVariableAlreadySet($template) !== false) { + // Use that content here + $this->loadedRawData[$template] = $this->readVariable($template); + + // Recursive protection: + $this->loadedTemplates[] = $template; + } else { + // Then try to search for code-templates + try { + // Load the code template and remember it's contents + $this->loadCodeTemplate($template); + $this->loadedRawData[$template] = $this->getRawTemplateData(); + + // Remember this template for recursion detection + // RECURSIVE PROTECTION! + $this->loadedTemplates[] = $template; + } catch (FileNotFoundException $e) { + // Even this is not done... :/ + $this->rawTemplates[] = $template; + } catch (FilePointerNotOpenedException $e) { + // Even this is not done... :/ + $this->rawTemplates[] = $template; + } + } + } // END - if + } // END - foreach + + // Restore the raw template data + $this->setRawTemplateData($backup); + } + + /** + * Compile a given raw template code and remember it for later usage + * + * @param $code The raw template code + * @param $template The template's name + * @return void + */ + private function compileCode ($code, $template) { + // Is this template already compiled? + if (in_array($template, $this->compiledTemplates)) { + // Abort here... + return; + } + + // Remember this template being compiled + $this->compiledTemplates[] = $template; + + // Compile the loaded code in five steps: + // + // 1. Backup current template data + $backup = $this->getRawTemplateData(); + + // 2. Set the current template's raw data as the new content + $this->setRawTemplateData($code); + + // 3. Compile the template data + $this->compileTemplate(); + + // 4. Remember it's contents + $this->loadedRawData[$template] = $this->getRawTemplateData(); + + // 5. Restore the previous raw content from backup variable + $this->setRawTemplateData($backup); + } + + /** + * Insert all given and loaded templates by running through all loaded + * codes and searching for their place-holder in the main template + * + * @param $templateMatches See method analyzeTemplate() + * @return void + */ + private function insertAllTemplates (array $templateMatches) { + // Run through all loaded codes + foreach ($this->loadedRawData as $template=>$code) { + + // Search for the template + $foundIndex = array_search($template, $templateMatches[1]); + + // Lookup the matching template replacement + if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) { + + // Get the current raw template + $rawData = $this->getRawTemplateData(); + + // Replace the space holder with the template code + $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData); + + // Set the new raw data + $this->setRawTemplateData($rawData); + + } // END - if + + } // END - foreach + } + + /** + * Load all extra raw templates + * + * @return void + */ + private function loadExtraRawTemplates () { + // Are there some raw templates we need to load? + if (count($this->rawTemplates) > 0) { + // Try to load all raw templates + foreach ($this->rawTemplates as $key => $template) { + try { + // Load the template + $this->loadWebTemplate($template); + + // Remember it's contents + $this->rawTemplates[$template] = $this->getRawTemplateData(); + + // Remove it from the loader list + unset($this->rawTemplates[$key]); + + // Remember this template for recursion detection + // RECURSIVE PROTECTION! + $this->loadedTemplates[] = $template; + } catch (FileNotFoundException $e) { + // This template was never found. We silently ignore it + unset($this->rawTemplates[$key]); + } catch (FilePointerNotOpenedException $e) { + // This template was never found. We silently ignore it + unset($this->rawTemplates[$key]); + } + } + } + } + + /** + * Assign all found template variables + * + * @param $varMatches An array full of variable/value pairs. + * @return void + * @todo Unfinished work or don't die here. + */ + private function assignAllVariables (array $varMatches) { + // Search for all variables + foreach ($varMatches[1] as $key=>$var) { + + // Detect leading equals + if (substr($varMatches[2][$key], 0, 1) == "=") { + // Remove and cast it + $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1); + } + + // Do we have some quotes left and right side? Then it is free text + if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) { + // Free string detected! Which we can assign directly + $this->assignVariable($var, $varMatches[3][$key]); + } elseif (!empty($varMatches[2][$key])) { + // Non-string found so we need some deeper analysis... + die("Deeper analysis not yet implemented!"); + } + + } // for ($varMatches ... + } + /** + * Compiles all loaded raw templates + * + * @param $templateMatches See method analyzeTemplate() for details + * @return void + */ + private function compileRawTemplateData (array $templateMatches) { + // Are some code-templates found which we need to compile? + if (count($this->loadedRawData) > 0) { + + // Then compile all! + foreach ($this->loadedRawData as $template=>$code) { + + // Is this template already compiled? + if (in_array($template, $this->compiledTemplates)) { + // Then skip it + continue; + } + + // Search for the template + $foundIndex = array_search($template, $templateMatches[1]); + + // Lookup the matching variable data + if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) { + + // Split it up with another reg. exp. into variable=value pairs + preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches); + + // Assign all variables + $this->assignAllVariables($varMatches); + + } // END - if (isset($templateMatches ... + + // Compile the loaded template + $this->compileCode($code, $template); + + } // END - foreach ($this->loadedRawData ... + + // Insert all templates + $this->insertAllTemplates($templateMatches); + + } // END - if (count($this->loadedRawData) ... + } + + /** + * Inserts all raw templates into their respective variables + * + * @return void + */ + private function insertRawTemplates () { + // Load all templates + foreach ($this->rawTemplates as $template=>$content) { + // Set the template as a variable with the content + $this->assignVariable($template, $content); + } + } + + /** + * Finalizes the compilation of all template variables + * + * @return void + */ + private function finalizeVariableCompilation () { + // Get the content + $content = $this->getRawTemplateData(); + + // Walk through all variables + for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { + // Get current entry + $currEntry = $idx->current(); + + // Replace all [$var] or {?$var?} with the content + //* DEBUG: */ echo "name=".$currEntry['name'].", value=
".htmlentities($currEntry['value'])."
\n"; + $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content); + $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content); + $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content); + } // END - for + + // Set the content back + $this->setRawTemplateData($content); + } + + /** + * Getter for raw template data + * + * @return $rawTemplateData The raw data from the template + */ + public final function getRawTemplateData () { + return $this->rawTemplateData; + } + + /** + * Getter for compiled templates + */ + public final function getCompiledData () { + return $this->compiledData; + } + + /** + * Load a specified web template into the engine + * + * @param $template The web template we shall load which is + * located in "html" by default + * @return void + */ + public function loadWebTemplate ($template) { + // Set template type + $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type')); + + // Load the special template + $this->loadTemplate($template); + } + + /** + * Assign a given congfiguration variable with a value + * + * @param $var The configuration variable we want to assign + * @return void + */ + public function assignConfigVariable ($var) { + // Sweet and simple... + $this->configVariables[$var] = $this->getConfigInstance()->readConfig($var); + } + + /** + * Load a specified email template into the engine + * + * @param $template The email template we shall load which is + * located in "emails" by default + * @return void + */ + public function loadEmailTemplate ($template) { + // Set template type + $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type')); + + // Load the special template + $this->loadTemplate($template); + } + + /** + * Load a specified code template into the engine + * + * @param $template The code template we shall load which is + * located in "code" by default + * @return void + */ + public function loadCodeTemplate ($template) { + // Set template type + $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type')); + + // Load the special template + $this->loadTemplate($template); + } + + /** + * Compile all variables by inserting their respective values + * + * @return void + * @todo Make this code some nicer... + */ + public final function compileVariables () { + // Initialize the $content array + $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var'); + $dummy = array(); + + // Iterate through all variables + for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { + + // Get current variable from the stack + $currVariable = $idx->current(); + + // Transfer it's name/value combination to the $content array + //* DEBUG: */ echo $currVariable['name']."=
".htmlentities($currVariable['value'])."
\n"; + $dummy[$currVariable['name']] = $currVariable['value']; + + }// END - if + + // Set the new variable (don't remove the second dollar !) + $$validVar = $dummy; + + // Prepare all configuration variables + $config = $this->configVariables; + + // Remove some variables + unset($idx); + unset($currVariable); + + // Run the compilation twice to get content from helper classes in + $cnt = 0; + while ($cnt < 3) { + // Finalize the compilation of template variables + $this->finalizeVariableCompilation(); + + // Prepare the eval() command for comiling the template + $eval = sprintf("\$result = \"%s\";", + addslashes($this->getRawTemplateData()) + ); + + // This loop does remove the backslashes (\) in PHP parameters + while (strpos($eval, ""))); + $evalMiddle = stripslashes($evalMiddle); + + // Remove the middle part from right one + $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2)); + + // And put all together + $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight); + } // END - while + + // Prepare PHP code for eval() command + $evalLength = strlen($eval); + $eval = str_replace( + "<%php", "\";", + str_replace( + "%>", "\n\$result .= \"", $eval + ) + ); + + // Did something change? + if (strlen($eval) != $eval) { + // Run the constructed command. This will "compile" all variables in + @eval($eval); + } // END - if + + // Goes something wrong? + if (!isset($result)) { + // Output eval command + $this->debugOutput(sprintf("Failed eval() code:
%s
", $this->markupCode($eval, true)), true); + + // Output backtrace here + $this->debugBacktrace(); + } // END - if + + // Set raw template data + $this->setRawTemplateData($result); + $cnt++; + } + + // Set the new content + $this->setCompiledData($result); + } + + /** + * Compile all required templates into the current loaded one + * + * @return void + * @throws UnexpectedTemplateTypeException If the template type is + * not "code" + * @throws InvalidArrayCountException If an unexpected array + * count has been found + */ + public final function compileTemplate () { + // We will only work with template type "code" from configuration + if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) { + // Abort here + throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED); + } // END - if + + // Get the raw data. + $rawData = $this->getRawTemplateData(); + + // Remove double spaces and trim leading/trailing spaces + $rawData = trim(str_replace(" ", " ", $rawData)); + + // Search for raw variables + $this->extractVariablesFromRawData($rawData); + + // Search for code-tags which are {? ?} + preg_match_all($this->regExpCodeTags, $rawData, $templateMatches); + + // Analyze the matches array + if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) { + // Entries are found: + // + // The main analysis + $this->analyzeTemplate($templateMatches); + + // Compile raw template data + $this->compileRawTemplateData($templateMatches); + + // Are there some raw templates left for loading? + $this->loadExtraRawTemplates(); + + // Are some raw templates found and loaded? + if (count($this->rawTemplates) > 0) { + + // Insert all raw templates + $this->insertRawTemplates(); + + // Remove the raw template content as well + $this->setRawTemplateData(""); + + } // END - if + + } // END - if($templateMatches ... + } + + /** + * Output the compiled page to the outside world. In case of web templates + * this would be vaild (X)HTML code. And in case of email templates this + * would store a prepared email body inside the template engine. + * + * @return void + */ + public final function output () { + // Check which type of template we have + switch ($this->getTemplateType()) { + case "html": // Raw HTML templates can be send to the output buffer + // Quick-N-Dirty: + $this->getWebOutputInstance()->output($this->getCompiledData()); + break; + + default: // Unknown type found + // Construct message + $msg = sprintf("[%s->%s] Unknown/unsupported template type %s detected.", + $this->__toString(), + __FUNCTION__, + $this->getTemplateType() + ); + + // Write the problem to the world... + $this->debugOutput($msg); + break; + } + } + + /** + * Loads a given view helper (by name) + * + * @param $helperName The helper's name + * @return void + * @throws ViewHelperNotFoundException If the given view helper was not found + */ + protected function loadViewHelper ($helperName) { + // Make first character upper case, rest low + $helperName = ucfirst($helperName); + + // Is this view helper loaded? + if (!isset($this->helpers[$helperName])) { + // Create a class name + $className = "{$helperName}ViewHelper"; + + // Does this class exists? + if (!class_exists($className)) { + // Abort here! + throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER); + } + + // Generate new instance + $eval = sprintf("\$this->helpers[%s] = %s::create%s();", + $helperName, + $className, + $className + ); + + // Run the code + eval($eval); + } + + // Return the requested instance + return $this->helpers[$helperName]; + } + + /** + * Assigns the last loaded raw template content with a given variable + * + * @param $templateName Name of the template we want to assign + * @param $variableName Name of the variable we want to assign + * @return void + */ + public function assignTemplateWithVariable ($templateName, $variableName) { + // Get the content from last loaded raw template + $content = $this->getRawTemplateData(); + + // Assign the variable + $this->assignVariable($variableName, $content); + + // Purge raw content + $this->setRawTemplateData(""); + } + + /** + * Transfers the content of this template engine to a given response instance + * + * @param $responseInstance An instance of a response class + * @return void + */ + public function transferToResponse (Responseable $responseInstance) { + // Get the content and set it in the response class + $responseInstance->writeToBody($this->getCompiledData()); + } + + /** + * Assigns all the application data with template variables + * + * @param $appInstance A manageable application instance + * @return void + */ + public function assignApplicationData (ManageableApplication $appInstance) { + // Get long name and assign it + $this->assignVariable("app_full_name" , $appInstance->getAppName()); + + // Get short name and assign it + $this->assignVariable("app_short_name", $appInstance->getAppShortName()); + + // Get version number and assign it + $this->assignVariable("app_version" , $appInstance->getAppVersion()); + } + + /** + * "Compiles" a variable by replacing {?var?} with it's content + * + * @param $rawCode Raw code to compile + * @return $rawCode Compile code with inserted variable value + */ + protected function compileRawCode ($rawCode) { + // Find the variables + preg_match_all($this->regExpVarValue, $rawCode, $varMatches); + + // Compile all variables + foreach ($varMatches[0] as $match) { + // Replace the variable with it's value, if found + $rawCode = str_replace("{?".$match."?}", $this->readVariable($match), $rawCode); + } // END - foreach + + // Return the compiled data + return $rawCode; + } +} + +// [EOF] +?> diff --git a/inc/classes/main/template/class_TemplateEngine.php b/inc/classes/main/template/class_TemplateEngine.php deleted file mode 100644 index 23ac8b4..0000000 --- a/inc/classes/main/template/class_TemplateEngine.php +++ /dev/null @@ -1,1221 +0,0 @@ - - * @version 0.0.0 - * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software - * @license GNU GPL 3.0 or any newer version - * @link http://www.ship-simu.org - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate { - /** - * The local path name where all templates and sub folders for special - * templates are stored. We will internally determine the language plus - * "html" for web templates or "emails" for email templates - */ - private $basePath = ""; - - /** - * The extension for web and email templates (not compiled templates) - */ - private $templateExtension = ".tpl"; - - /** - * The extension for code templates (not compiled templates) - */ - private $codeExtension = ".ctp"; - - /** - * Path relative to $basePath and language code for compiled code-templates - */ - private $compileOutputPath = "templates/_compiled"; - - /** - * The raw (maybe uncompiled) template - */ - private $rawTemplateData = ""; - - /** - * Template data with compiled-in variables - */ - private $compiledData = ""; - - /** - * The last loaded template's FQFN for debugging the engine - */ - private $lastTemplate = ""; - - /** - * The variable stack for the templates. This must be initialized and - * shall become an instance of FrameworkArrayObject. - */ - private $varStack = null; - - /** - * Configuration variables in a simple array - */ - private $configVariables = array(); - - /** - * Loaded templates for recursive protection and detection - */ - private $loadedTemplates = array(); - - /** - * Compiled templates for recursive protection and detection - */ - private $compiledTemplates = array(); - - /** - * Loaded raw template data - */ - private $loadedRawData = null; - - /** - * Raw templates which are linked in code templates - */ - private $rawTemplates = null; - - /** - * A regular expression for variable=value pairs - */ - private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/'; - - /** - * A regular expression for filtering out code tags - * - * E.g.: {?template:variable=value;var2=value2;[...]?} - */ - private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/'; - - /** - * Loaded helpers - */ - private $helpers = array(); - - // Exception codes for the template engine - const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x020; - const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021; - const EXCEPTION_INVALID_VIEW_HELPER = 0x022; - - /** - * Protected constructor - * - * @return void - */ - protected function __construct () { - // Call parent constructor - parent::__construct(__CLASS__); - - // Set part description - $this->setObjectDescription("Web template engine"); - - // Create unique ID number - $this->generateUniqueId(); - - // Clean up a little - $this->removeNumberFormaters(); - $this->removeSystemArray(); - } - - /** - * Creates an instance of the class TemplateEngine and prepares it for usage - * - * @param $basePath The local base path for all templates - * @param $langInstance An instance of LanguageSystem (default) - * @param $ioInstance An instance of FileIoHandler (default, middleware!) - * @return $tplInstance An instance of TemplateEngine - * @throws BasePathIsEmptyException If the provided $basePath is empty - * @throws InvalidBasePathStringException If $basePath is no string - * @throws BasePathIsNoDirectoryException If $basePath is no - * directory or not found - * @throws BasePathReadProtectedException If $basePath is - * read-protected - */ - public final static function createTemplateEngine ($basePath, ManageableLanguage $langInstance, FileIoHandler $ioInstance) { - // Get a new instance - $tplInstance = new TemplateEngine(); - - // Is the base path valid? - if (empty($basePath)) { - // Base path is empty - throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING); - } elseif (!is_string($basePath)) { - // Is not a string - throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING); - } elseif (!is_dir($basePath)) { - // Is not a path - throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME); - } elseif (!is_readable($basePath)) { - // Is not readable - throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH); - } - - // Get configuration instance - $cfgInstance = FrameworkConfiguration::getInstance(); - - // Set the base path - $tplInstance->setBasePath($basePath); - - // Initialize the variable stack - $tplInstance->initVariableStack(); - - // Set the language and IO instances - $tplInstance->setLanguageInstance($langInstance); - $tplInstance->setFileIoInstance($ioInstance); - - // Set template extensions - $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension')); - $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension')); - - // Absolute output path for compiled templates - $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path')); - - // Return the prepared instance - return $tplInstance; - } - - /** - * Search for a variable in the stack - * - * @param $var The variable we are looking for - * @return $idx FALSE means not found, >=0 means found on a specific index - */ - private function isVariableAlreadySet ($var) { - // First everything is not found - $found = false; - - // Now search for it - for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { - // Get current item - $currEntry = $idx->current(); - - // Is the entry found? - if ($currEntry['name'] == $var) { - // Found! - $found = $idx->key(); - break; - } - } - - // Return the current position - return $found; - } - - /** - * Return a content of a variable or null if not found - * - * @param $var The variable we are looking for - * @return $content Content of the variable or null if not found - */ - private function readVariable ($var) { - // First everything is not found - $content = null; - - // Now search for it - for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { - // Get current item - $currEntry = $idx->current(); - - // Is the entry found? - if ($currEntry['name'] == $var) { - // Found! - $content = $currEntry['value']; - break; - } - } - - // Return the current position - return $content; - } - - /** - * Add a variable to the stack - * - * @param $var The variable we are looking for - * @param $value The value we want to store in the variable - * @return void - */ - private function addVariable ($var, $value) { - // Add it to the stack - $this->varStack->append(array( - 'name' => trim($var), - 'value' => trim($value) - )); - } - - /** - * Modify an entry on the stack - * - * @param $var The variable we are looking for - * @param $value The value we want to store in the variable - * @return void - */ - private function modifyVariable ($var, $value) { - // It should be there so let's look again... - for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { - // Get current entry - $currEntry = $idx->current(); - - // Is this the requested variable? - if ($currEntry['name'] == $var) { - // Change it to the other value - $this->varStack->offsetSet($idx->key(), array( - 'name' => $var, - 'value' => $value - )); - } - } - } - - /** - * Setter for template type. Only "html", "emails" and "compiled" should - * be sent here - * - * @param $templateType The current template's type - * @return void - */ - private final function setTemplateType ($templateType) { - // Cast it - $templateType = (string) $templateType; - - // And set it (only 2 letters) - $this->templateType = $templateType; - } - - /** - * Setter for the last loaded template's FQFN - * - * @param $template The last loaded template - * @return void - */ - private final function setLastTemplate ($template) { - // Cast it to string - $template = (string) $template; - $this->lastTemplate = $template; - } - - /** - * Getter for the last loaded template's FQFN - * - * @return $template The last loaded template - */ - private final function getLastTemplate () { - return $this->lastTemplate; - } - - /** - * Initialize the variable stack. This holds all variables for later - * compilation. - * - * @return void - */ - public final function initVariableStack () { - $this->varStack = new FrameworkArrayObject("FakedVariableStack"); - } - - /** - * Setter for base path - * - * @param $basePath The local base path for all templates - * @return void - */ - public final function setBasePath ($basePath) { - // Cast it - $basePath = (string) $basePath; - - // And set it - $this->basePath = $basePath; - } - - /** - * Getter for base path - * - * @return $basePath The local base path for all templates - */ - public final function getBasePath () { - // And set it - return $this->basePath; - } - - /** - * Setter for template extension - * - * @param $templateExtension The file extension for all uncompiled - * templates - * @return void - */ - public final function setRawTemplateExtension ($templateExtension) { - // Cast it - $templateExtension = (string) $templateExtension; - - // And set it - $this->templateExtension = $templateExtension; - } - - /** - * Setter for code template extension - * - * @param $codeExtension The file extension for all uncompiled - * templates - * @return void - */ - public final function setCodeTemplateExtension ($codeExtension) { - // Cast it - $codeExtension = (string) $codeExtension; - - // And set it - $this->codeExtension = $codeExtension; - } - - /** - * Getter for template extension - * - * @return $templateExtension The file extension for all uncompiled - * templates - */ - public final function getRawTemplateExtension () { - // And set it - return $this->templateExtension; - } - - /** - * Getter for code-template extension - * - * @return $codeExtension The file extension for all code- - * templates - */ - public final function getCodeTemplateExtension () { - // And set it - return $this->codeExtension; - } - - /** - * Setter for path of compiled templates - * - * @param $compileOutputPath The local base path for all compiled - * templates - * @return void - */ - public final function setCompileOutputPath ($compileOutputPath) { - // Cast it - $compileOutputPath = (string) $compileOutputPath; - - // And set it - $this->compileOutputPath = $compileOutputPath; - } - - /** - * Getter for template type - * - * @return $templateType The current template's type - */ - public final function getTemplateType () { - return $this->templateType; - } - - /** - * Assign (add) a given variable with a value - * - * @param $var The variable we are looking for - * @param $value The value we want to store in the variable - * @return void - */ - public final function assignVariable ($var, $value) { - // First search for the variable if it was already added - $idx = $this->isVariableAlreadySet($var); - - // Was it found? - if ($idx === false) { - // Add it to the stack - $this->addVariable($var, $value); - } elseif (!empty($value)) { - // Modify the stack entry - $this->modifyVariable($var, $value); - } - } - - /** - * Removes a given variable - * - * @param $var The variable we are looking for - * @return void - */ - public final function removeVariable ($var) { - // First search for the variable if it was already added - $idx = $this->isVariableAlreadySet($var); - - // Was it found? - if ($idx !== false) { - // Remove this variable - $this->varStack->offsetUnset($idx); - } - } - - /** - * Private setter for raw template data - * - * @param $rawTemplateData The raw data from the template - * @return void - */ - private final function setRawTemplateData ($rawTemplateData) { - // Cast it to string - $rawTemplateData = (string) $rawTemplateData; - - // And store it in this class - $this->rawTemplateData = $rawTemplateData; - } - - /** - * Private setter for compiled templates - * - * @return void - */ - private final function setCompiledData ($compiledData) { - // Cast it to string - $compiledData = (string) $compiledData; - - // And store it in this class - $this->compiledData = $compiledData; - } - - /** - * Private loader for all template types - * - * @param $template The template we shall load - * @return void - */ - private function loadTemplate ($template) { - // Cast it to string - $template = (string) $template; - - // Get extension for the template - $ext = $this->getRawTemplateExtension(); - - // If we shall load a code-template we need to switch the file extension - if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) { - // Switch over to the code-template extension - $ext = $this->getCodeTemplateExtension(); - } - - // Construct the FQFN for the template by honoring the current language - $fqfn = sprintf("%s%s/%s/%s%s", - $this->getBasePath(), - $this->getLanguageInstance()->getLanguageCode(), - $this->getTemplateType(), - $template, - $ext - ); - - // Load the raw template data - $this->loadRawTemplateData($fqfn); - } - - /** - * A private loader for raw template names - * - * @param $fqfn The full-qualified file name for a template - * @return void - * @throws NullPointerException If $inputInstance is null - * @throws NoObjectException If $inputInstance is not an object - * @throws MissingMethodException If $inputInstance is missing a - * required method - */ - private function loadRawTemplateData ($fqfn) { - // Get a input/output instance from the middleware - $ioInstance = $this->getFileIoInstance(); - - // Validate the instance - if (is_null($ioInstance)) { - // Throw exception - throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER); - } elseif (!is_object($ioInstance)) { - // Throw another exception - throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT); - } elseif (!method_exists($ioInstance, 'loadFileContents')) { - // Throw yet another exception - throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD); - } - - // Load the raw template - $rawTemplateData = $ioInstance->loadFileContents($fqfn); - - // Store the template's contents into this class - $this->setRawTemplateData($rawTemplateData); - - // Remember the template's FQFN - $this->setLastTemplate($fqfn); - } - - /** - * Try to assign an extracted template variable as a "content" or "config" - * variable. - * - * @param $varName The variable's name (shall be content orconfig) by - * default - * @param $var The variable we want to assign - */ - private function assignTemplateVariable ($varName, $var) { - // Is it not a config variable? - if ($varName != "config") { - // Regular template variables - $this->assignVariable($var, ""); - } else { - // Configuration variables - $this->assignConfigVariable($var); - } - } - - /** - * Extract variables from a given raw data stream - * - * @param $rawData The raw template data we shall analyze - * @return void - */ - private function extractVariablesFromRawData ($rawData) { - // Cast to string - $rawData = (string) $rawData; - - // Search for variables - @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches); - - // Did we find some variables? - if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) { - // Initialize all missing variables - foreach ($variableMatches[3] as $key=>$var) { - // Try to assign it, empty strings are being ignored - $this->assignTemplateVariable($variableMatches[1][$key], $var); - } // END - foreach - } // END - if - } - - /** - * Main analysis of the loaded template - * - * @param $templateMatches Found template place-holders, see below - * @return void - * - *--------------------------------- - * Structure of $templateMatches: - *--------------------------------- - * [0] => Array - An array with all full matches - * [1] => Array - An array with left part (before the ":") of a match - * [2] => Array - An array with right part of a match including ":" - * [3] => Array - An array with right part of a match excluding ":" - */ - private function analyzeTemplate (array $templateMatches) { - // Backup raw template data - $backup = $this->getRawTemplateData(); - - // Initialize some arrays - if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); } - - // Load all requested templates - foreach ($templateMatches[1] as $template) { - - // Load and compile only templates which we have not yet loaded - // RECURSIVE PROTECTION! BE CAREFUL HERE! - if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) { - - // Template not found, but maybe variable assigned? - if ($this->isVariableAlreadySet($template) !== false) { - // Use that content here - $this->loadedRawData[$template] = $this->readVariable($template); - - // Recursive protection: - $this->loadedTemplates[] = $template; - } else { - // Then try to search for code-templates - try { - // Load the code template and remember it's contents - $this->loadCodeTemplate($template); - $this->loadedRawData[$template] = $this->getRawTemplateData(); - - // Remember this template for recursion detection - // RECURSIVE PROTECTION! - $this->loadedTemplates[] = $template; - } catch (FileIsMissingException $e) { - // Even this is not done... :/ - $this->rawTemplates[] = $template; - } catch (FilePointerNotOpenedException $e) { - // Even this is not done... :/ - $this->rawTemplates[] = $template; - } - } - - } // if ((!isset( ... - - } // for ($templateMatches ... - - // Restore the raw template data - $this->setRawTemplateData($backup); - } - - /** - * Compile a given raw template code and remember it for later usage - * - * @param $code The raw template code - * @param $template The template's name - * @return void - */ - private function compileCode ($code, $template) { - // Is this template already compiled? - if (in_array($template, $this->compiledTemplates)) { - // Abort here... - return; - } - - // Remember this template being compiled - $this->compiledTemplates[] = $template; - - // Compile the loaded code in five steps: - // - // 1. Backup current template data - $backup = $this->getRawTemplateData(); - - // 2. Set the current template's raw data as the new content - $this->setRawTemplateData($code); - - // 3. Compile the template data - $this->compileTemplate(); - - // 4. Remember it's contents - $this->loadedRawData[$template] = $this->getRawTemplateData(); - - // 5. Restore the previous raw content from backup variable - $this->setRawTemplateData($backup); - } - - /** - * Insert all given and loaded templates by running through all loaded - * codes and searching for their place-holder in the main template - * - * @param $templateMatches See method analyzeTemplate() - * @return void - */ - private function insertAllTemplates (array $templateMatches) { - // Run through all loaded codes - foreach ($this->loadedRawData as $template=>$code) { - - // Search for the template - $foundIndex = array_search($template, $templateMatches[1]); - - // Lookup the matching template replacement - if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) { - - // Get the current raw template - $rawData = $this->getRawTemplateData(); - - // Replace the space holder with the template code - $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData); - - // Set the new raw data - $this->setRawTemplateData($rawData); - - } // END - if - - } // END - foreach - } - - /** - * Load all extra raw templates - * - * @return void - */ - private function loadExtraRawTemplates () { - // Are there some raw templates we need to load? - if (count($this->rawTemplates) > 0) { - // Try to load all raw templates - foreach ($this->rawTemplates as $key => $template) { - try { - // Load the template - $this->loadWebTemplate($template); - - // Remember it's contents - $this->rawTemplates[$template] = $this->getRawTemplateData(); - - // Remove it from the loader list - unset($this->rawTemplates[$key]); - - // Remember this template for recursion detection - // RECURSIVE PROTECTION! - $this->loadedTemplates[] = $template; - } catch (FileIsMissingException $e) { - // This template was never found. We silently ignore it - unset($this->rawTemplates[$key]); - } catch (FilePointerNotOpenedException $e) { - // This template was never found. We silently ignore it - unset($this->rawTemplates[$key]); - } - } - } - } - - /** - * Assign all found template variables - * - * @param $varMatches An array full of variable/value pairs. - * @return void - * @todo Unfinished work or don't die here. - */ - private function assignAllVariables (array $varMatches) { - // Search for all variables - foreach ($varMatches[1] as $key=>$var) { - - // Detect leading equals - if (substr($varMatches[2][$key], 0, 1) == "=") { - // Remove and cast it - $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1); - } - - // Do we have some quotes left and right side? Then it is free text - if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) { - // Free string detected! Which we can assign directly - $this->assignVariable($var, $varMatches[3][$key]); - } elseif (!empty($varMatches[2][$key])) { - // Non-string found so we need some deeper analysis... - die("Deeper analysis not yet implemented!"); - } - - } // for ($varMatches ... - } - /** - * Compiles all loaded raw templates - * - * @param $templateMatches See method analyzeTemplate() for details - * @return void - */ - private function compileRawTemplateData (array $templateMatches) { - // Are some code-templates found which we need to compile? - if (count($this->loadedRawData) > 0) { - - // Then compile all! - foreach ($this->loadedRawData as $template=>$code) { - - // Is this template already compiled? - if (in_array($template, $this->compiledTemplates)) { - // Then skip it - continue; - } - - // Search for the template - $foundIndex = array_search($template, $templateMatches[1]); - - // Lookup the matching variable data - if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) { - - // Split it up with another reg. exp. into variable=value pairs - preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches); - - // Assign all variables - $this->assignAllVariables($varMatches); - - } // END - if (isset($templateMatches ... - - // Compile the loaded template - $this->compileCode($code, $template); - - } // END - foreach ($this->loadedRawData ... - - // Insert all templates - $this->insertAllTemplates($templateMatches); - - } // END - if (count($this->loadedRawData) ... - } - - /** - * Inserts all raw templates into their respective variables - * - * @return void - */ - private function insertRawTemplates () { - // Load all templates - foreach ($this->rawTemplates as $template=>$content) { - // Set the template as a variable with the content - $this->assignVariable($template, $content); - } - } - - /** - * Finalizes the compilation of all template variables - * - * @return void - */ - private function finalizeVariableCompilation () { - // Get the content - $content = $this->getRawTemplateData(); - - // Walk through all variables - for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { - // Get current entry - $currEntry = $idx->current(); - - // Replace all [$var] or {?$var?} with the content - //* DEBUG: */ echo "name=".$currEntry['name'].", value=
".htmlentities($currEntry['value'])."
\n"; - $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content); - $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content); - $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content); - } // END - for - - // Set the content back - $this->setRawTemplateData($content); - } - - /** - * Getter for raw template data - * - * @return $rawTemplateData The raw data from the template - */ - public final function getRawTemplateData () { - return $this->rawTemplateData; - } - - /** - * Getter for compiled templates - */ - public final function getCompiledData () { - return $this->compiledData; - } - - /** - * Load a specified web template into the engine - * - * @param $template The web template we shall load which is - * located in "html" by default - * @return void - */ - public function loadWebTemplate ($template) { - // Set template type - $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type')); - - // Load the special template - $this->loadTemplate($template); - } - - /** - * Assign a given congfiguration variable with a value - * - * @param $var The configuration variable we want to assign - * @return void - */ - public function assignConfigVariable ($var) { - // Sweet and simple... - $this->configVariables[$var] = $this->getConfigInstance()->readConfig($var); - } - - /** - * Load a specified email template into the engine - * - * @param $template The email template we shall load which is - * located in "emails" by default - * @return void - */ - public function loadEmailTemplate ($template) { - // Set template type - $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type')); - - // Load the special template - $this->loadTemplate($template); - } - - /** - * Load a specified code template into the engine - * - * @param $template The code template we shall load which is - * located in "code" by default - * @return void - */ - public function loadCodeTemplate ($template) { - // Set template type - $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type')); - - // Load the special template - $this->loadTemplate($template); - } - - /** - * Compile all variables by inserting their respective values - * - * @return void - * @todo Make this code some nicer... - */ - public final function compileVariables () { - // Initialize the $content array - $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var'); - $dummy = array(); - - // Iterate through all variables - for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) { - - // Get current variable from the stack - $currVariable = $idx->current(); - - // Transfer it's name/value combination to the $content array - //* DEBUG: */ echo $currVariable['name']."=
".htmlentities($currVariable['value'])."
\n"; - $dummy[$currVariable['name']] = $currVariable['value']; - - }// END - if - - // Set the new variable (don't remove the second dollar !) - $$validVar = $dummy; - - // Prepare all configuration variables - $config = $this->configVariables; - - // Remove some variables - unset($idx); - unset($currVariable); - - // Run the compilation twice to get content from helper classes in - $cnt = 0; - while ($cnt < 3) { - // Finalize the compilation of template variables - $this->finalizeVariableCompilation(); - - // Prepare the eval() command for comiling the template - $eval = sprintf("\$result = \"%s\";", - addslashes($this->getRawTemplateData()) - ); - - // This loop does remove the backslashes (\) in PHP parameters - while (strpos($eval, ""))); - $evalMiddle = stripslashes($evalMiddle); - - // Remove the middle part from right one - $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2)); - - // And put all together - $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight); - } // END - while - - // Prepare PHP code for eval() command - $evalLength = strlen($eval); - $eval = str_replace( - "<%php", "\";", - str_replace( - "%>", "\n\$result .= \"", $eval - ) - ); - - // Did something change? - if (strlen($eval) != $eval) { - // Run the constructed command. This will "compile" all variables in - @eval($eval); - } // END - if - - // Goes something wrong? - if (!isset($result)) { - // Output eval command - $this->debugOutput(sprintf("Failed eval() code:
%s
", $this->markupCode($eval, true)), true); - - // Output backtrace here - $this->debugBacktrace(); - } // END - if - - // Set raw template data - $this->setRawTemplateData($result); - $cnt++; - } - - // Set the new content - $this->setCompiledData($result); - } - - /** - * Compile all required templates into the current loaded one - * - * @return void - * @throws UnexpectedTemplateTypeException If the template type is - * not "code" - * @throws InvalidArrayCountException If an unexpected array - * count has been found - */ - public final function compileTemplate () { - // We will only work with template type "code" from configuration - if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) { - // Abort here - throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED); - } // END - if - - // Get the raw data. - $rawData = $this->getRawTemplateData(); - - // Remove double spaces and trim leading/trailing spaces - $rawData = trim(str_replace(" ", " ", $rawData)); - - // Search for raw variables - $this->extractVariablesFromRawData($rawData); - - // Search for code-tags which are {? ?} - preg_match_all($this->regExpCodeTags, $rawData, $templateMatches); - - // Analyze the matches array - if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) { - // Entries are found: - // - // The main analysis - $this->analyzeTemplate($templateMatches); - - // Compile raw template data - $this->compileRawTemplateData($templateMatches); - - // Are there some raw templates left for loading? - $this->loadExtraRawTemplates(); - - // Are some raw templates found and loaded? - if (count($this->rawTemplates) > 0) { - - // Insert all raw templates - $this->insertRawTemplates(); - - // Remove the raw template content as well - $this->setRawTemplateData(""); - - } // END - if - - } // END - if($templateMatches ... - } - - /** - * Output the compiled page to the outside world. In case of web templates - * this would be vaild (X)HTML code. And in case of email templates this - * would store a prepared email body inside the template engine. - * - * @return void - */ - public final function output () { - // Check which type of template we have - switch ($this->getTemplateType()) { - case "html": // Raw HTML templates can be send to the output buffer - // Quick-N-Dirty: - $this->getWebOutputInstance()->output($this->getCompiledData()); - break; - - default: // Unknown type found - // Construct message - $msg = sprintf("[%s:] Unknown/unsupported template type %s detected.", - $this->__toString(), - $this->getTemplateType() - ); - - // Write the problem to the world... - $this->debugOutput($msg); - break; - } - } - - /** - * Loads a given view helper (by name) - * - * @param $helperName The helper's name - * @return void - * @throws ViewHelperNotFoundException If the given view helper was not found - */ - protected function loadViewHelper ($helperName) { - // Make first character upper case, rest low - $helperName = ucfirst($helperName); - - // Is this view helper loaded? - if (!isset($this->helpers[$helperName])) { - // Create a class name - $className = "{$helperName}ViewHelper"; - - // Does this class exists? - if (!class_exists($className)) { - // Abort here! - throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER); - } - - // Generate new instance - $eval = sprintf("\$this->helpers[%s] = %s::create%s();", - $helperName, - $className, - $className - ); - - // Run the code - eval($eval); - } - - // Return the requested instance - return $this->helpers[$helperName]; - } - - /** - * Assigns the last loaded raw template content with a given variable - * - * @param $templateName Name of the template we want to assign - * @param $variableName Name of the variable we want to assign - * @return void - */ - public function assignTemplateWithVariable ($templateName, $variableName) { - // Get the content from last loaded raw template - $content = $this->getRawTemplateData(); - - // Assign the variable - $this->assignVariable($variableName, $content); - - // Purge raw content - $this->setRawTemplateData(""); - } - - /** - * Transfers the content of this template engine to a given response instance - * - * @param $responseInstance An instance of a response class - * @return void - */ - public function transferToResponse (Responseable $responseInstance) { - // Get the content and set it in the response class - $responseInstance->writeToBody($this->getCompiledData()); - } - - /** - * Assigns all the application data with template variables - * - * @param $appInstance A manageable application instance - * @return void - */ - public function assignApplicationData (ManageableApplication $appInstance) { - // Get long name and assign it - $this->assignVariable("app_full_name" , $appInstance->getAppName()); - - // Get short name and assign it - $this->assignVariable("app_short_name", $appInstance->getAppShortName()); - - // Get version number and assign it - $this->assignVariable("app_version" , $appInstance->getAppVersion()); - } -} - -// [EOF] -?> diff --git a/inc/classes/main/template/image/.htaccess b/inc/classes/main/template/image/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/main/template/image/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/main/template/image/class_ImageTemplateEngine.php b/inc/classes/main/template/image/class_ImageTemplateEngine.php new file mode 100644 index 0000000..6e80fd1 --- /dev/null +++ b/inc/classes/main/template/image/class_ImageTemplateEngine.php @@ -0,0 +1,210 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class ImageTemplateEngine extends BaseTemplateEngine implements CompileableTemplate { + /** + * Main nodes in the XML tree ("image" is ignored) + */ + private $mainNodes = array("type", "resolution", "background-color", "foreground-color", "image-string"); + + /** + * Sub nodes in the XML tree + */ + private $subNodes = array("width", "height", "red", "green", "blue", "text"); + + /** + * Image instance + */ + private $imageInstance = null; + + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription("Image template engine"); + + // Create unique ID number + $this->generateUniqueId(); + + // Clean up a little + $this->removeNumberFormaters(); + $this->removeSystemArray(); + } + + /** + * Creates an instance of the class TemplateEngine and prepares it for usage + * + * @param $basePath The local base path for all templates + * @param $langInstance An instance of LanguageSystem (default) + * @param $ioInstance An instance of FileIoHandler (default, middleware!) + * @return $tplInstance An instance of TemplateEngine + * @throws BasePathIsEmptyException If the provided $basePath is empty + * @throws InvalidBasePathStringException If $basePath is no string + * @throws BasePathIsNoDirectoryException If $basePath is no + * directory or not found + * @throws BasePathReadProtectedException If $basePath is + * read-protected + */ + public final static function createImageTemplateEngine ($basePath, ManageableLanguage $langInstance, FileIoHandler $ioInstance) { + // Get a new instance + $tplInstance = new ImageTemplateEngine(); + + // Is the base path valid? + if (empty($basePath)) { + // Base path is empty + throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING); + } elseif (!is_string($basePath)) { + // Is not a string + throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING); + } elseif (!is_dir($basePath)) { + // Is not a path + throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME); + } elseif (!is_readable($basePath)) { + // Is not readable + throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH); + } + + // Get configuration instance + $cfgInstance = FrameworkConfiguration::getInstance(); + + // Set the base path + $tplInstance->setBasePath($basePath); + + // Initialize the variable stack + $tplInstance->initVariableStack(); + + // Set the language and IO instances + $tplInstance->setLanguageInstance($langInstance); + $tplInstance->setFileIoInstance($ioInstance); + + // Set template extensions + $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension')); + $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension')); + + // Absolute output path for compiled templates + $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path')); + + // Return the prepared instance + return $tplInstance; + } + + /** + * Renders the given image content + * + * @param $imageContent A valid XML image content + * @return void + * @throws XmlParserException If an XML error was found + */ + public function renderImageContent ($imageContent) { + // Get an XML parser + $xmlParser = xml_parser_create(); + + // Force case-folding to on + xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true); + + // Set object + xml_set_object($xmlParser, $this); + + // Set handler call-backs + xml_set_element_handler($xmlParser, "startElement", "endElement"); + xml_set_character_data_handler($xmlParser, "characterHandler"); + + // Now parse the XML tree + if (!xml_parse($xmlParser, $imageContent)) { + // Error found in XML! + throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR); + } // END - if + + // Free the parser + xml_parser_free($xmlParser); + } + + /** + * Handles the start element of an XML resource + * + * @param $resource XML parser resource + * @param $element The element we shall handle + * @param $attributes All attributes + * @return void + * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found + */ + public function startElement ($resource, $element, array $attributes) { + // Initial method name which will never be called... + $methodName = "initImage"; + + // Make the element name lower-case + $element = strtolower($element); + + // Is the element a main node? + if (in_array($element, $this->mainNodes)) { + // Okay, main node found! + $methodName = "setImage" . $this->convertToClassName($element); + } elseif (in_array($element, $this->subNodes)) { + // Sub node found + $methodName = "setImageProperty" . $this->convertToClassName($element); + } elseif ($element != "image") { + // Invalid node name found + throw new InvalidXmlNodeException(array($this, $element, $attributes), self::EXCEPTION_XML_NODE_UNKNOWN); + } + + // Call method + //* DEBUG: */ echo "call: ".$methodName."
\n"; + call_user_func_array(array($this, $methodName), $attributes); + } + + /** + * Intializes the image + * + * @return void + * @todo Add cache creation here + */ + private function initImage () { + // Unfinished work! + } + + /** + * Set the image type + * + * @param $imageType Code fragment or direct value holding the image type + * @return void + */ + private function setImageType ($imageType) { + // Try to compile it first to get the value from variable stack + $imageType = $this->compileRawCode($imageType); + + // Now make a class name of it + $className = $this->convertToClassName($imageType."_image"); + + // And try to initiate it + $this->imageInstance = ObjectFactory::createObjectByName($className); + } +} + +// [EOF] +?> diff --git a/inc/classes/main/template/web/.htaccess b/inc/classes/main/template/web/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/inc/classes/main/template/web/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/inc/classes/main/template/web/class_WebTemplateEngine.php b/inc/classes/main/template/web/class_WebTemplateEngine.php new file mode 100644 index 0000000..8c9c408 --- /dev/null +++ b/inc/classes/main/template/web/class_WebTemplateEngine.php @@ -0,0 +1,104 @@ + + * @version 0.0.0 + * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software + * @license GNU GPL 3.0 or any newer version + * @link http://www.ship-simu.org + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +class WebTemplateEngine extends BaseTemplateEngine implements CompileableTemplate { + /** + * Protected constructor + * + * @return void + */ + protected function __construct () { + // Call parent constructor + parent::__construct(__CLASS__); + + // Set part description + $this->setObjectDescription("Web template engine"); + + // Create unique ID number + $this->generateUniqueId(); + + // Clean up a little + $this->removeNumberFormaters(); + $this->removeSystemArray(); + } + + /** + * Creates an instance of the class TemplateEngine and prepares it for usage + * + * @param $basePath The local base path for all templates + * @param $langInstance An instance of LanguageSystem (default) + * @param $ioInstance An instance of FileIoHandler (default, middleware!) + * @return $tplInstance An instance of TemplateEngine + * @throws BasePathIsEmptyException If the provided $basePath is empty + * @throws InvalidBasePathStringException If $basePath is no string + * @throws BasePathIsNoDirectoryException If $basePath is no + * directory or not found + * @throws BasePathReadProtectedException If $basePath is + * read-protected + */ + public final static function createWebTemplateEngine ($basePath, ManageableLanguage $langInstance, FileIoHandler $ioInstance) { + // Get a new instance + $tplInstance = new WebTemplateEngine(); + + // Is the base path valid? + if (empty($basePath)) { + // Base path is empty + throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING); + } elseif (!is_string($basePath)) { + // Is not a string + throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING); + } elseif (!is_dir($basePath)) { + // Is not a path + throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME); + } elseif (!is_readable($basePath)) { + // Is not readable + throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH); + } + + // Get configuration instance + $cfgInstance = FrameworkConfiguration::getInstance(); + + // Set the base path + $tplInstance->setBasePath($basePath); + + // Initialize the variable stack + $tplInstance->initVariableStack(); + + // Set the language and IO instances + $tplInstance->setLanguageInstance($langInstance); + $tplInstance->setFileIoInstance($ioInstance); + + // Set template extensions + $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension')); + $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension')); + + // Absolute output path for compiled templates + $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path')); + + // Return the prepared instance + return $tplInstance; + } + +// [EOF] +?> diff --git a/inc/config.php b/inc/config.php index 145761f..a9e567f 100644 --- a/inc/config.php +++ b/inc/config.php @@ -90,7 +90,7 @@ $cfg->setConfigEntry('application_path', "application"); $cfg->setConfigEntry('compile_output_path', "templates/_compiled/"); // DON'T MISS THE TRAILING SLASH! // CFG: TEMPLATE-ENGINE -$cfg->setConfigEntry('template_class', "TemplateEngine"); +$cfg->setConfigEntry('template_class', "WebTemplateEngine"); // CFG: DEBUG-ENGINE $cfg->setConfigEntry('debug_class', "DebugWebOutput"); diff --git a/templates/images/.htaccess b/templates/images/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/templates/images/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/templates/images/de/.htaccess b/templates/images/de/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/templates/images/de/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/templates/images/de/image/.htaccess b/templates/images/de/image/.htaccess new file mode 100644 index 0000000..3a42882 --- /dev/null +++ b/templates/images/de/image/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/templates/images/de/image/base_image.img b/templates/images/de/image/base_image.img new file mode 100644 index 0000000..39781ef --- /dev/null +++ b/templates/images/de/image/base_image.img @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/templates/images/de/image/emergency_exit.img b/templates/images/de/image/emergency_exit.img new file mode 100644 index 0000000..b46b738 --- /dev/null +++ b/templates/images/de/image/emergency_exit.img @@ -0,0 +1,22 @@ +setBaseImage("base_image"); + +// Set image dimensions +$helper->setWidth(400); +$helper->setHeight(200); + +// Background and foreground color +$helper->setBackgroundColorRedGreenBlue(0xFF, 0xAA, 0xAA); +$helper->setForegroundColorRedGreenBlue(0x00, 0x00, 0x00); + +// Add error message +$helper->setImageString("Genereller Fehler!"); + +// Flush content to the template engine +$helper->flushContent(); + +// Comment this out if image is done +//$this->debugInstance(); +?>