Image generator added, first CAPTCHA added with missing controller (partly work)
[shipsimu.git] / inc / classes / main / template / image / class_ImageTemplateEngine.php
1 <?php
2 /**
3  * The own template engine for loading caching and sending out images
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright(c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class ImageTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
25         /**
26          * Main nodes in the XML tree ("image" is ignored)
27          */
28         private $mainNodes = array("base", "type", "resolution", "background-color", "foreground-color", "image-string");
29
30         /**
31          * Sub nodes in the XML tree
32          */
33         private $subNodes = array("name", "string-name", "x", "y", "font-size", "width", "height", "red", "green", "blue", "text");
34
35         /**
36          * Image instance
37          */
38         private $imageInstance = null;
39
40         /**
41          * Current main node
42          */
43         private $currMainNode = "";
44
45         /**
46          * Protected constructor
47          *
48          * @return      void
49          */
50         protected function __construct () {
51                 // Call parent constructor
52                 parent::__construct(__CLASS__);
53
54                 // Set part description
55                 $this->setObjectDescription("Image template engine");
56
57                 // Create unique ID number
58                 $this->generateUniqueId();
59
60                 // Clean up a little
61                 $this->removeNumberFormaters();
62                 $this->removeSystemArray();
63         }
64
65         /**
66          * Creates an instance of the class TemplateEngine and prepares it for usage
67          *
68          * @param       $basePath               The local base path for all templates
69          * @param       $langInstance   An instance of LanguageSystem (default)
70          * @param       $ioInstance             An instance of FileIoHandler (default, middleware!)
71          * @return      $tplInstance    An instance of TemplateEngine
72          * @throws      BasePathIsEmptyException                If the provided $basePath is empty
73          * @throws      InvalidBasePathStringException  If $basePath is no string
74          * @throws      BasePathIsNoDirectoryException  If $basePath is no
75          *                                                                                      directory or not found
76          * @throws      BasePathReadProtectedException  If $basePath is
77          *                                                                                      read-protected
78          */
79         public final static function createImageTemplateEngine ($basePath, ManageableLanguage  $langInstance, FileIoHandler $ioInstance) {
80                 // Get a new instance
81                 $tplInstance = new ImageTemplateEngine();
82
83                 // Is the base path valid?
84                 if (empty($basePath)) {
85                         // Base path is empty
86                         throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
87                 } elseif (!is_string($basePath)) {
88                         // Is not a string
89                         throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING);
90                 } elseif (!is_dir($basePath)) {
91                         // Is not a path
92                         throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME);
93                 } elseif (!is_readable($basePath)) {
94                         // Is not readable
95                         throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH);
96                 }
97
98                 // Get configuration instance
99                 $cfgInstance = FrameworkConfiguration::getInstance();
100
101                 // Set the base path
102                 $tplInstance->setBasePath($basePath);
103
104                 // Set the language and IO instances
105                 $tplInstance->setLanguageInstance($langInstance);
106                 $tplInstance->setFileIoInstance($ioInstance);
107
108                 // Set template extensions
109                 $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension'));
110                 $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension'));
111
112                 // Absolute output path for compiled templates
113                 $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path'));
114
115                 // Return the prepared instance
116                 return $tplInstance;
117         }
118
119         /**
120          * Renders the given image content
121          *
122          * @param       $imageContent           A valid XML image content
123          * @return      void
124          * @throws      XmlParserException      If an XML error was found
125          */
126         public function renderImageContent ($imageContent) {
127                 // Get an XML parser
128                 $xmlParser = xml_parser_create();
129
130                 // Force case-folding to on
131                 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
132
133                 // Set object
134                 xml_set_object($xmlParser, $this);
135
136                 // Set handler call-backs
137                 xml_set_element_handler($xmlParser, "startElement", "endElement");
138                 xml_set_character_data_handler($xmlParser, "characterHandler");
139
140                 // Now parse the XML tree
141                 if (!xml_parse($xmlParser, $imageContent)) {
142                         // Error found in XML!
143                         throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
144                 } // END - if
145
146                 // Free the parser
147                 xml_parser_free($xmlParser);
148         }
149
150         /**
151          * Handles the start element of an XML resource
152          *
153          * @param       $resource               XML parser resource (currently ignored)
154          * @param       $element                The element we shall handle
155          * @param       $attributes             All attributes
156          * @return      void
157          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
158          */
159         public function startElement ($resource, $element, array $attributes) {
160                 // Initial method name which will never be called...
161                 $methodName = "initImage";
162
163                 // Make the element name lower-case
164                 $element = strtolower($element);
165
166                 // Is the element a main node?
167                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
168                 if (in_array($element, $this->mainNodes)) {
169                         // Okay, main node found!
170                         $methodName = "setImage" . $this->convertToClassName($element);
171                 } elseif (in_array($element, $this->subNodes)) {
172                         // Sub node found
173                         $methodName = "setImageProperty" . $this->convertToClassName($element);
174                 } elseif ($element != "image") {
175                         // Invalid node name found
176                         throw new InvalidXmlNodeException(array($this, $element, $attributes), BaseHelper::EXCEPTION_XML_NODE_UNKNOWN);
177                 }
178
179                 // Call method
180                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
181                 call_user_func_array(array($this, $methodName), $attributes);
182         }
183
184         /**
185          * Ends the main or sub node by sending out the gathered data
186          *
187          * @param       $resource       An XML resource pointer (currently ignored)
188          * @param       $nodeName       Name of the node we want to finish
189          * @return      void
190          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
191          */
192         public function endElement ($resource, $nodeName) {
193                 // Make all lower-case
194                 $nodeName = strtolower($nodeName);
195
196                 // Does this match with current main node?
197                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
198                 if (($nodeName != $this->currMainNode) && (in_array($nodeName, $this->mainNodes))) {
199                         // Did not match!
200                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->currMainNode), BaseHelper::EXCEPTION_XML_NODE_MISMATCH);
201                 } elseif (in_array($nodeName, $this->subNodes)) {
202                         // Silently ignore sub nodes
203                         return;
204                 }
205
206                 // Construct method name
207                 $methodName = "finish" . $this->convertToClassName($nodeName);
208
209                 // Call the corresponding method
210                 call_user_func_array(array($this->imageInstance, $methodName), array());
211         }
212
213         /**
214          * Currently not used
215          *
216          * @param       $resource               XML parser resource (currently ignored)
217          * @param       $characters             Characters to handle
218          * @return      void
219          * @todo        Find something usefull with this!
220          */
221         public function characterHandler ($resource, $characters) {
222                 // Trim all spaces away
223                 $characters = trim($characters);
224
225                 // Is this string empty?
226                 if (empty($characters)) {
227                         // Then skip it silently
228                         return false;
229                 } // END - if
230
231                 // Unfinished work!
232                 $this->partialStub("Handling extra characters is not yet supported!");
233         }
234
235         /**
236          * Intializes the image
237          *
238          * @return      void
239          * @todo        Add cache creation here
240          */
241         private function initImage () {
242                 // Unfinished work!
243         }
244
245         /**
246          * Set the image type
247          *
248          * @param       $imageType      Code fragment or direct value holding the image type
249          * @return      void
250          */
251         private function setImageType ($imageType) {
252                 // Set group to general
253                 $this->setVariableGroup("general");
254
255                 // Try to compile it first to get the value from variable stack
256                 $imageType = $this->compileRawCode($imageType);
257
258                 // Now make a class name of it
259                 $className = $this->convertToClassName($imageType."_image");
260
261                 // And try to initiate it
262                 $this->imageInstance = ObjectFactory::createObjectByName($className, array($this));
263
264                 // Set current main node to type
265                 $this->currMainNode = "type";
266         }
267
268         /**
269          * "Setter" for resolution, we first need to collect the resolution from the
270          * sub-nodes. So first, this method will prepare an array for it
271          *
272          * @return      void
273          */
274         private function setImageResolution () {
275                 // Call the image class
276                 $this->imageInstance->initResolution();
277
278                 // Current main node is resolution
279                 $this->currMainNode = "resolution";
280         }
281
282         /**
283          * "Setter" for base information. For more details see above method!
284          *
285          * @return      void
286          * @see         ImageTemplateEngine::setImageResolution
287          */
288         private function setImageBase () {
289                 // Call the image class
290                 $this->imageInstance->initBase();
291
292                 // Current main node is resolution
293                 $this->currMainNode = "base";
294         }
295
296         /**
297          * "Setter" for background-color. For more details see above method!
298          *
299          * @return      void
300          * @see         ImageTemplateEngine::setImageResolution
301          */
302         private function setImageBackgroundColor () {
303                 // Call the image class
304                 $this->imageInstance->initBackgroundColor();
305
306                 // Current main node is background-color
307                 $this->currMainNode = "background-color";
308         }
309
310         /**
311          * "Setter" for foreground-color. For more details see above method!
312          *
313          * @return      void
314          * @see         ImageTemplateEngine::setImageResolution
315          */
316         private function setImageForegroundColor () {
317                 // Call the image class
318                 $this->imageInstance->initForegroundColor();
319
320                 // Current main node is foreground-color
321                 $this->currMainNode = "foreground-color";
322         }
323
324         /**
325          * "Setter" for image-string. For more details see above method!
326          *
327          * @param       $groupable      Wether this image string is groupable
328          * @return      void
329          * @see         ImageTemplateEngine::setImageResolution
330          */
331         private function setImageImageString ($groupable = "single") {
332                 // Call the image class
333                 $this->imageInstance->initImageString($groupable);
334
335                 // Current main node is foreground-color
336                 $this->currMainNode = "image-string";
337         }
338
339         /**
340          * Setter for image name
341          *
342          * @param       $imageName      Name of the image
343          * @return      void
344          */
345         private function setImagePropertyName ($imageName) {
346                 // Call the image class
347                 $this->imageInstance->setImageName($imageName);
348         }
349
350         /**
351          * Setter for image width
352          *
353          * @param       $width  Width of the image or variable
354          * @return      void
355          */
356         private function setImagePropertyWidth ($width) {
357                 // Call the image class
358                 $this->imageInstance->setWidth($width);
359         }
360
361         /**
362          * Setter for image height
363          *
364          * @param       $height Height of the image or variable
365          * @return      void
366          */
367         private function setImagePropertyHeight ($height) {
368                 // Call the image class
369                 $this->imageInstance->setHeight($height);
370         }
371
372         /**
373          * Setter for image red color
374          *
375          * @param       $red    Red color value
376          * @return      void
377          */
378         private function setImagePropertyRed ($red) {
379                 // Call the image class
380                 $this->imageInstance->setRed($red);
381         }
382
383         /**
384          * Setter for image green color
385          *
386          * @param       $green  Green color value
387          * @return      void
388          */
389         private function setImagePropertyGreen ($green) {
390                 // Call the image class
391                 $this->imageInstance->setGreen($green);
392         }
393
394         /**
395          * Setter for image blue color
396          *
397          * @param       $blue   Blue color value
398          * @return      void
399          */
400         private function setImagePropertyBlue ($blue) {
401                 // Call the image class
402                 $this->imageInstance->setBlue($blue);
403         }
404
405         /**
406          * Setter for string name (identifier)
407          *
408          * @param       $stringName             String name (identifier)
409          * @return      void
410          */
411         private function setImagePropertyStringName ($stringName) {
412                 // Call the image class
413                 $this->imageInstance->setStringName($stringName);
414         }
415
416         /**
417          * Setter for font size
418          *
419          * @param       $fontSize       Size of the font
420          * @return      void
421          */
422         private function setImagePropertyFontSize ($fontSize) {
423                 // Call the image class
424                 $this->imageInstance->setFontSize($fontSize);
425         }
426
427         /**
428          * Setter for image string
429          *
430          * @param       $imageString    Image string to set
431          * @return      void
432          */
433         private function setImagePropertyText ($imageString) {
434                 // Call the image class
435                 $this->imageInstance->setString($imageString);
436         }
437
438         /**
439          * Setter for X coordinate
440          *
441          * @param       $x      X coordinate
442          * @return      void
443          */
444         private function setImagePropertyX ($x) {
445                 // Call the image class
446                 $this->imageInstance->setX($x);
447         }
448
449         /**
450          * Setter for Y coordinate
451          *
452          * @param       $y      Y coordinate
453          * @return      void
454          */
455         private function setImagePropertyY ($y) {
456                 // Call the image class
457                 $this->imageInstance->setY($y);
458         }
459
460         /**
461          * Getter for image cache file (FQFN)
462          *
463          * @return      $fqfn   Full-qualified file name of the image cache
464          */
465         public function getImageCacheFqfn () {
466                 // Get the FQFN ready
467                 $fqfn = $this->getBasePath()."_cache/" . md5($this->imageInstance->getImageName()) . "." . $this->imageInstance->getImageType();
468
469                 // Return it
470                 return $fqfn;
471         }
472
473         /**
474          * Outputs the image to the world
475          *
476          * @param       $responseInstance       An instance of a Responseable class
477          * @return      void
478          */
479         public function transferToResponse (Responseable $responseInstance) {
480                 // Set the image instance
481                 $responseInstance->setImageInstance($this->imageInstance);
482         }
483 }
484
485 // [EOF]
486 ?>