renamed deprecated exception name to a more common one
[core.git] / framework / main / classes / template / mail / class_MailTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Template\Engine;
4
5 // Import framework stuff
6 use CoreFramework\Mailer\DeliverableMail;
7 use CoreFramework\Parser\Xml\XmlParser;
8 use CoreFramework\Registry\Registry;
9 use CoreFramework\Response\Responseable;
10 use CoreFramework\Template\CompileableTemplate;
11
12 // Import SPL stuff
13 use \UnexpectedValueException;
14
15 /**
16  * The own template engine for loading caching and sending out images
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  * @todo                This template engine does not make use of setTemplateType()
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program. If not, see <http://www.gnu.org/licenses/>.
37  */
38 class MailTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
39         /**
40          * Main nodes in the XML tree
41          */
42         private $mainNodes = array(
43                 'mail-data'
44         );
45
46         /**
47          * Sub nodes in the XML tree
48          */
49         private $subNodes = array(
50                 'subject-line',
51                 'sender-address',
52                 'recipient-address',
53                 'message'
54         );
55
56         /**
57          * Mailer instance
58          */
59         private $mailerInstance = NULL;
60
61         /**
62          * Current main node
63          */
64         private $currMainNode = '';
65
66         /**
67          * Protected constructor
68          *
69          * @return      void
70          */
71         protected function __construct () {
72                 // Call parent constructor
73                 parent::__construct(__CLASS__);
74         }
75
76         /**
77          * Creates an instance of the class TemplateEngine and prepares it for usage
78          *
79          * @return      $templateInstance               An instance of TemplateEngine
80          * @throws      UnexpectedValueException                If the provided $templateBasePath is empty or no string
81          * @throws      InvalidDirectoryException       If $templateBasePath is no
82          *                                                                                      directory or not found
83          * @throws      BasePathReadProtectedException  If $templateBasePath is
84          *                                                                                      read-protected
85          */
86         public static final function createMailTemplateEngine () {
87                 // Get a new instance
88                 $templateInstance = new MailTemplateEngine();
89
90                 // Get the application instance from registry
91                 $applicationInstance = Registry::getRegistry()->getInstance('app');
92
93                 // Determine base path
94                 $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getRequestInstance()->getRequestElement('app') . '/';
95
96                 // Is the base path valid?
97                 if (empty($templateBasePath)) {
98                         // Base path is empty
99                         throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
100                 } elseif (!is_string($templateBasePath)) {
101                         // Is not a string
102                         throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
103                 } elseif (!is_dir($templateBasePath)) {
104                         // Is not a path
105                         throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
106                 } elseif (!is_readable($templateBasePath)) {
107                         // Is not readable
108                         throw new BasePathReadProtectedException(array($templateInstance, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
109                 }
110
111                 // Set the base path
112                 $templateInstance->setTemplateBasePath($templateBasePath);
113
114                 // Set template extensions
115                 $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
116                 $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
117
118                 // Absolute output path for compiled templates
119                 $templateInstance->setCompileOutputPath($templateInstance->getConfigInstance()->getConfigEntry('base_path') . $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path'));
120
121                 // Return the prepared instance
122                 return $templateInstance;
123         }
124
125         /**
126          * Getter for current main node
127          *
128          * @return      $currMainNode   Current main node
129          */
130         public final function getCurrMainNode () {
131                 return $this->currMainNode;
132         }
133
134         /**
135          * Getter for main node array
136          *
137          * @return      $mainNodes      Array with valid main node names
138          */
139         public final function getMainNodes () {
140                 return $this->mainNodes;
141         }
142
143         /**
144          * Getter for sub node array
145          *
146          * @return      $subNodes       Array with valid sub node names
147          */
148         public final function getSubNodes () {
149                 return $this->subNodes;
150         }
151
152         /**
153          * Handles the start element of an XML resource
154          *
155          * @param       $resource               XML parser resource (currently ignored)
156          * @param       $element                The element we shall handle
157          * @param       $attributes             All attributes
158          * @return      void
159          * @throws      InvalidXmlNodeException         If an unknown/invalid XML node name was found
160          */
161         public function startElement ($resource, $element, array $attributes) {
162                 // Initial method name which will never be called...
163                 $methodName = 'initEmail';
164
165                 // Make the element name lower-case
166                 $element = strtolower($element);
167
168                 // Is the element a main node?
169                 //* DEBUG: */ echo "START: &gt;".$element."&lt;<br />\n";
170                 if (in_array($element, $this->getMainNodes())) {
171                         // Okay, main node found!
172                         $methodName = 'setEmail' . self::convertToClassName($element);
173                 } elseif (in_array($element, $this->getSubNodes())) {
174                         // Sub node found
175                         $methodName = 'setEmailProperty' . self::convertToClassName($element);
176                 } elseif ($element != 'text-mail') {
177                         // Invalid node name found
178                         throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
179                 }
180
181                 // Call method
182                 //* DEBUG: */ echo "call: ".$methodName."<br />\n";
183                 call_user_func_array(array($this, $methodName), $attributes);
184         }
185
186         /**
187          * Ends the main or sub node by sending out the gathered data
188          *
189          * @param       $resource       An XML resource pointer (currently ignored)
190          * @param       $nodeName       Name of the node we want to finish
191          * @return      void
192          * @throws      XmlNodeMismatchException        If current main node mismatches the closing one
193          */
194         public function finishElement ($resource, $nodeName) {
195                 // Make all lower-case
196                 $nodeName = strtolower($nodeName);
197
198                 // Does this match with current main node?
199                 //* DEBUG: */ echo "END: &gt;".$nodeName."&lt;<br />\n";
200                 if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
201                         // Did not match!
202                         throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
203                 } elseif (in_array($nodeName, $this->getSubNodes())) {
204                         // Silently ignore sub nodes
205                         return;
206                 }
207
208                 // Construct method name
209                 $methodName = 'finish' . self::convertToClassName($nodeName);
210
211                 // Call the corresponding method
212                 call_user_func_array(array($this, $methodName), array());
213         }
214
215         /**
216          * Adds the message text to the template engine
217          *
218          * @param       $resource               XML parser resource (currently ignored)
219          * @param       $characters             Characters to handle
220          * @return      void
221          */
222         public function characterHandler ($resource, $characters) {
223                 // Trim all spaces away
224                 $characters = trim($characters);
225
226                 // Is this string empty?
227                 if (empty($characters)) {
228                         // Then skip it silently
229                         return;
230                 } // END - if
231
232                 // Add the message now
233                 $this->assignVariable('message', $characters);
234         }
235
236         /**
237          * Intializes the mail
238          *
239          * @return      void
240          * @todo        Add cache creation here
241          */
242         private function initEmail () {
243                 // Unfinished work!
244         }
245
246         /**
247          * Setter for mail data node
248          *
249          * @return      void
250          * @todo        Should we call back the mailer class here?
251          */
252         private function setEmailMailData () {
253                 // Set current main node
254                 $this->currMainNode = 'mail-data';
255         }
256
257         /**
258          * Setter for sender address property
259          *
260          * @param       $senderAddress  Sender address to set in email
261          * @return      void
262          */
263         private function setEmailPropertySenderAddress ($senderAddress) {
264                 // Set the template variable
265                 $this->assignVariable('sender', $senderAddress);
266         }
267
268         /**
269          * Setter for recipient address property
270          *
271          * @param       $recipientAddress       Recipient address to set in email
272          * @return      void
273          */
274         private function setEmailPropertyRecipientAddress ($recipientAddress) {
275                 // Set the template variable
276                 $this->assignVariable('recipient', $recipientAddress);
277         }
278
279         /**
280          * Setter for subject line property
281          *
282          * @return      void
283          */
284         private function setEmailPropertySubjectLine () {
285                 // Empty for now
286         }
287
288         /**
289          * Method stub to avoid output
290          *
291          * @return      void
292          */
293         private function setEmailPropertyMessage () {
294                 // Empty for now
295         }
296
297         /**
298          * Gets the template variable "message", stores it back as raw template data
299          * and compiles all variables so the mail message got prepared for output
300          *
301          * @return      void
302          */
303         private function finishMailData () {
304                 // Get the message and set it as new raw template data back
305                 $message = $this->readVariable('message');
306                 $this->setRawTemplateData($message);
307
308                 // Get some variables to compile
309                 //$sender = $this->compileRawCode($this->readVariable('sender'));
310                 //$this->assignVariable('sender', $sender);
311
312                 // Then compile all variables
313                 $this->compileVariables();
314         }
315
316         /**
317          * Invokes the final mail process
318          *
319          * @return      void
320          */
321         private function finishTextMail () {
322                 $this->getMailerInstance()->invokeMailDelivery();
323         }
324
325         /**
326          * Getter for image cache file (FQFN)
327          *
328          * @return      $fqfn   Full-qualified file name of the image cache
329          * @todo        0% done
330          */
331         public function getMailCacheFqfn () {
332                 // Initialize FQFN
333                 $fqfn = '';
334                 $this->debugBackTrace('Unfinished area!');
335
336                 // Return it
337                 return $fqfn;
338         }
339
340         /**
341          * Setter for mailer instance
342          *
343          * @param       $mailerInstance         A mailer instance
344          * @return      void
345          */
346         public final function setMailerInstance (DeliverableMail $mailerInstance) {
347                 $this->mailerInstance = $mailerInstance;
348         }
349
350         /**
351          * Getter for mailer instance
352          *
353          * @return      $mailerInstance         A mailer instance
354          */
355         protected final function getMailerInstance () {
356                 return $this->mailerInstance;
357         }
358
359         /**
360          * Outputs the mail to the world. This should only the mailer debug class do!
361          *
362          * @param       $responseInstance       An instance of a Responseable class
363          * @return      void
364          */
365         public function transferToResponse (Responseable $responseInstance) {
366                 $responseInstance->writeToBody($this->getCompiledData());
367         }
368
369 }