update copyright as changes will happen this year
[core.git] / inc / main / classes / 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@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.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(
29                 'base',
30                 'type',
31                 'resolution',
32                 'background-color',
33                 'foreground-color',
34                 'image-string'
35         );
36
37         /**
38          * Sub nodes in the XML tree
39          */
40         private $subNodes = array(
41                 'name',
42                 'string-name',
43                 'x',
44                 'y',
45                 'font-size',
46                 'width',
47                 'height',
48                 'red',
49                 'green',
50                 'blue',
51                 'text'
52         );
53
54         /**
55          * Current main node
56          */
57         private $currMainNode = '';
58
59         /**
60          * Protected constructor
61          *
62          * @return      void
63          */
64         protected function __construct () {
65                 // Call parent constructor
66                 parent::__construct(__CLASS__);
67         }
68
69         /**
70          * Creates an instance of the class TemplateEngine and prepares it for usage
71          *
72          * @return      $templateInstance               An instance of TemplateEngine
73          * @throws      BasePathIsEmptyException                If the provided $templateBasePath is empty
74          * @throws      InvalidBasePathStringException  If $templateBasePath is no string
75          * @throws      BasePathIsNoDirectoryException  If $templateBasePath is no
76          *                                                                                      directory or not found
77          * @throws      BasePathReadProtectedException  If $templateBasePath is
78          *                                                                                      read-protected
79          */
80         public static final function createImageTemplateEngine () {
81                 // Get a new instance
82                 $templateInstance = new ImageTemplateEngine();
83
84                 // Get the application instance from registry
85                 $applicationInstance = Registry::getRegistry()->getInstance('app');
86
87                 // Determine base path
88                 $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getRequestInstance()->getRequestElement('app') . '/';
89
90                 // Is the base path valid?
91                 if (empty($templateBasePath)) {
92                         // Base path is empty
93                         throw new BasePathIsEmptyException($templateInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
94                 } elseif (!is_string($templateBasePath)) {
95                         // Is not a string
96                         throw new InvalidBasePathStringException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_STRING);
97                 } elseif (!is_dir($templateBasePath)) {
98                         // Is not a path
99                         throw new BasePathIsNoDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
100                 } elseif (!is_readable($templateBasePath)) {
101                         // Is not readable
102                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
103                 }
104
105                 // Set the base path
106                 $templateInstance->setTemplateBasePath($templateBasePath);
107
108                 // Set template extensions
109                 $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
110                 $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
111
112                 // Absolute output path for compiled templates
113                 $templateInstance->setCompileOutputPath($templateInstance->getConfigInstance()->getConfigEntry('base_path') . $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path'));
114
115                 // Return the prepared instance
116                 return $templateInstance;
117         }
118
119         /**
120          * Getter for current main node
121          *
122          * @return      $currMainNode   Current main node
123          */
124         public final function getCurrMainNode () {
125                 return $this->currMainNode;
126         }
127
128         /**
129          * Getter for main node array
130          *
131          * @return      $mainNodes      Array with valid main node names
132          */
133         public final function getMainNodes () {
134                 return $this->mainNodes;
135         }
136
137         /**
138          * Getter for sub node array
139          *
140          * @return      $subNodes       Array with valid sub node names
141          */
142         public final function getSubNodes () {
143                 return $this->subNodes;
144         }
145
146         /**
147          * Handles the start element of an XML resource
148          *
149          * @param       $resource               XML parser resource (currently ignored)
150          * @param       $element                The element we shall handle
151          * @param       $attributes             All attributes
152          * @return      void
153          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
154          */
155         public function startElement ($resource, $element, array $attributes) {
156                 // Initial method name which will never be called...
157                 $methodName = 'initImage';
158
159                 // Make the element name lower-case
160                 $element = strtolower($element);
161
162                 // Is the element a main node?
163                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
164                 if (in_array($element, $this->mainNodes)) {
165                         // Okay, main node found!
166                         $methodName = 'setImage' . self::convertToClassName($element);
167                 } elseif (in_array($element, $this->subNodes)) {
168                         // Sub node found
169                         $methodName = 'setImageProperty' . self::convertToClassName($element);
170                 } elseif ($element != 'image') {
171                         // Invalid node name found
172                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
173                 }
174
175                 // Call method
176                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
177                 call_user_func_array(array($this, $methodName), $attributes);
178         }
179
180         /**
181          * Ends the main or sub node by sending out the gathered data
182          *
183          * @param       $resource       An XML resource pointer (currently ignored)
184          * @param       $nodeName       Name of the node we want to finish
185          * @return      void
186          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
187          */
188         public function finishElement ($resource, $nodeName) {
189                 // Make all lower-case
190                 $nodeName = strtolower($nodeName);
191
192                 // Does this match with current main node?
193                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
194                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
195                         // Did not match!
196                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
197                 } elseif (in_array($nodeName, $this->getSubNodes())) {
198                         // Silently ignore sub nodes
199                         return;
200                 }
201
202                 // Construct method name
203                 $methodName = 'finish' . self::convertToClassName($nodeName);
204
205                 // Call the corresponding method
206                 call_user_func_array(array($this->getImageInstance(), $methodName), array());
207         }
208
209         /**
210          * Currently not used
211          *
212          * @param       $resource               XML parser resource (currently ignored)
213          * @param       $characters             Characters to handle
214          * @return      void
215          * @todo        Find something usefull with this!
216          */
217         public function characterHandler ($resource, $characters) {
218                 // Trim all spaces away
219                 $characters = trim($characters);
220
221                 // Is this string empty?
222                 if (empty($characters)) {
223                         // Then skip it silently
224                         return;
225                 } // END - if
226
227                 // Unfinished work!
228                 $this->partialStub('Handling extra characters is not yet supported!');
229         }
230
231         /**
232          * Intializes the image
233          *
234          * @return      void
235          * @todo        Add cache creation here
236          */
237         private function initImage () {
238                 // Unfinished work!
239         }
240
241         /**
242          * Set the image type
243          *
244          * @param       $imageType      Code fragment or direct value holding the image type
245          * @return      void
246          */
247         private function setImageType ($imageType) {
248                 // Set group to general
249                 $this->setVariableGroup('general');
250
251                 // Try to compile it first to get the value from variable stack
252                 $imageType = $this->compileRawCode($imageType);
253
254                 // Now make a class name of it
255                 $className = self::convertToClassName($imageType.'_image');
256
257                 // And try to initiate it
258                 $this->setImageInstance(ObjectFactory::createObjectByName($className, array($this)));
259
260                 // Set current main node to type
261                 $this->currMainNode = 'type';
262         }
263
264         /**
265          * "Setter" for resolution, we first need to collect the resolution from the
266          * sub-nodes. So first, this method will prepare an array for it
267          *
268          * @return      void
269          */
270         private function setImageResolution () {
271                 // Call the image class
272                 $this->getImageInstance()->initResolution();
273
274                 // Current main node is resolution
275                 $this->currMainNode = 'resolution';
276         }
277
278         /**
279          * "Setter" for base information. For more details see above method!
280          *
281          * @return      void
282          * @see         ImageTemplateEngine::setImageResolution
283          */
284         private function setImageBase () {
285                 // Call the image class
286                 $this->getImageInstance()->initBase();
287
288                 // Current main node is resolution
289                 $this->currMainNode = 'base';
290         }
291
292         /**
293          * "Setter" for background-color. For more details see above method!
294          *
295          * @return      void
296          * @see         ImageTemplateEngine::setImageResolution
297          */
298         private function setImageBackgroundColor () {
299                 // Call the image class
300                 $this->getImageInstance()->initBackgroundColor();
301
302                 // Current main node is background-color
303                 $this->currMainNode = 'background-color';
304         }
305
306         /**
307          * "Setter" for foreground-color. For more details see above method!
308          *
309          * @return      void
310          * @see         ImageTemplateEngine::setImageResolution
311          */
312         private function setImageForegroundColor () {
313                 // Call the image class
314                 $this->getImageInstance()->initForegroundColor();
315
316                 // Current main node is foreground-color
317                 $this->currMainNode = 'foreground-color';
318         }
319
320         /**
321          * "Setter" for image-string. For more details see above method!
322          *
323          * @param       $groupable      Whether this image string is groupable
324          * @return      void
325          * @see         ImageTemplateEngine::setImageResolution
326          */
327         private function setImageImageString ($groupable = 'single') {
328                 // Call the image class
329                 $this->getImageInstance()->initImageString($groupable);
330
331                 // Current main node is foreground-color
332                 $this->currMainNode = 'image-string';
333         }
334
335         /**
336          * Setter for image name
337          *
338          * @param       $imageName      Name of the image
339          * @return      void
340          */
341         private function setImagePropertyName ($imageName) {
342                 // Call the image class
343                 $this->getImageInstance()->setImageName($imageName);
344         }
345
346         /**
347          * Setter for image width
348          *
349          * @param       $width  Width of the image or variable
350          * @return      void
351          */
352         private function setImagePropertyWidth ($width) {
353                 // Call the image class
354                 $this->getImageInstance()->setWidth($width);
355         }
356
357         /**
358          * Setter for image height
359          *
360          * @param       $height Height of the image or variable
361          * @return      void
362          */
363         private function setImagePropertyHeight ($height) {
364                 // Call the image class
365                 $this->getImageInstance()->setHeight($height);
366         }
367
368         /**
369          * Setter for image red color
370          *
371          * @param       $red    Red color value
372          * @return      void
373          */
374         private function setImagePropertyRed ($red) {
375                 // Call the image class
376                 $this->getImageInstance()->setRed($red);
377         }
378
379         /**
380          * Setter for image green color
381          *
382          * @param       $green  Green color value
383          * @return      void
384          */
385         private function setImagePropertyGreen ($green) {
386                 // Call the image class
387                 $this->getImageInstance()->setGreen($green);
388         }
389
390         /**
391          * Setter for image blue color
392          *
393          * @param       $blue   Blue color value
394          * @return      void
395          */
396         private function setImagePropertyBlue ($blue) {
397                 // Call the image class
398                 $this->getImageInstance()->setBlue($blue);
399         }
400
401         /**
402          * Setter for string name (identifier)
403          *
404          * @param       $stringName             String name (identifier)
405          * @return      void
406          */
407         private function setImagePropertyStringName ($stringName) {
408                 // Call the image class
409                 $this->getImageInstance()->setStringName($stringName);
410         }
411
412         /**
413          * Setter for font size
414          *
415          * @param       $fontSize       Size of the font
416          * @return      void
417          */
418         private function setImagePropertyFontSize ($fontSize) {
419                 // Call the image class
420                 $this->getImageInstance()->setFontSize($fontSize);
421         }
422
423         /**
424          * Setter for image string
425          *
426          * @param       $imageString    Image string to set
427          * @return      void
428          */
429         private function setImagePropertyText ($imageString) {
430                 // Call the image class
431                 $this->getImageInstance()->setString($imageString);
432         }
433
434         /**
435          * Setter for X coordinate
436          *
437          * @param       $x      X coordinate
438          * @return      void
439          */
440         private function setImagePropertyX ($x) {
441                 // Call the image class
442                 $this->getImageInstance()->setX($x);
443         }
444
445         /**
446          * Setter for Y coordinate
447          *
448          * @param       $y      Y coordinate
449          * @return      void
450          */
451         private function setImagePropertyY ($y) {
452                 // Call the image class
453                 $this->getImageInstance()->setY($y);
454         }
455
456         /**
457          * Getter for image cache file (FQFN)
458          *
459          * @return      $fqfn   Full-qualified file name of the image cache
460          */
461         public function getImageCacheFqfn () {
462                 // Get the FQFN ready
463                 $fqfn = sprintf('%s%s%s/%s.%s',
464                         $this->getConfigInstance()->getConfigEntry('base_path'),
465                         $this->getGenericBasePath(),
466                         'images/_cache',
467                         md5(
468                                 $this->getImageInstance()->getImageName() . ':' . $this->__toString() . ':' . $this->getImageInstance()->__toString()
469                         ),
470                         $this->getImageInstance()->getImageType()
471                 );
472
473                 // Return it
474                 return $fqfn;
475         }
476
477         /**
478          * Outputs the image to the world
479          *
480          * @param       $responseInstance       An instance of a Responseable class
481          * @return      void
482          */
483         public function transferToResponse (Responseable $responseInstance) {
484                 // Set the image instance
485                 $responseInstance->setImageInstance($this->getImageInstance());
486         }
487
488         /**
489          * Load a specified image template into the engine
490          *
491          * @param       $template       The image template we shall load which is
492          *                                              located in 'image' by default
493          * @return      void
494          */
495         public function loadImageTemplate ($template) {
496                 // Set template type
497                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('image_template_type'));
498
499                 // Load the special template
500                 $this->loadTemplate($template);
501         }
502 }
503
504 // [EOF]
505 ?>