Caching of XML/email templates finished:
[mailer.git] / inc / xml-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 01/27/2011 *
4  * ===================                          Last change: 01/27/2011 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : xml-functions.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for handling XML templates             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen zum Umgang mit XML-Templates          *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Calls back a function based on given XML template data
44 function showEntriesByXmlCallback ($template, $content = array(), $compileCode = true) {
45         // Generate FQFN for with special path
46         $FQFN = sprintf("%stemplates/xml/%s%s.xml",
47                 getPath(),
48                 detectExtraTemplatePath('xml', $template),
49                 $template
50         );
51
52         // Is the file readable?
53         if (!isFileReadable($FQFN)) {
54                 // No, use without extra path
55                 $FQFN = sprintf("%stemplates/xml/%s.xml",
56                         getPath(),
57                         $template
58                 );
59         } // END - if
60
61         // Is it again readable?
62         if (isFileReadable($FQFN)) {
63                 // Is there cache?
64                 if ((!isDebuggingTemplateCache()) && (isTemplateCached('xml', $template))) {
65                         // Evaluate the cache
66                         eval(readTemplateCache('xml', $template));
67                 } else {
68                         // Read it
69                         $templateContent = readFromFile($FQFN);
70
71                         // Prepare it for finaly eval() command
72                         $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), false, true, true, $compileCode) . '");';
73
74                         // Eval the code, this does insert any array elements from $content
75                         eval($GLOBALS['template_eval']['xml'][$template]);
76                 }
77
78                 // Init main arrays
79                 $GLOBALS['__XML_CALLBACKS'] = array(
80                         'callbacks' => array(),
81                         'functions' => array()
82                 );
83                 $GLOBALS['__XML_ARGUMENTS'] = array();
84                 $GLOBALS['__COLUMN_INDEX']  = array();
85
86                 // Handle it over to the parser
87                 parseXmlData($templateContent);
88
89                 // Add special elements, e.g. column index
90                 addXmlSpecialElements($template);
91
92                 // Call the call-back function
93                 doCallXmlCallbackFunction();
94         } else {
95                 // Template not found
96                 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
97         }
98 }
99
100 // Adds special elements by calling back another template-depending function
101 function addXmlSpecialElements ($template) {
102         // Generate the FQCN (Full-Qualified Callback Name)
103         $FQCN = 'addXmlSpecial' . capitalizeUnderscoreString($template);
104
105         // Is it there?
106         if (function_exists($FQCN)) {
107                 // Call it
108                 call_user_func($FQCN);
109         } elseif (isDebugModeEnabled()) {
110                 // This callback function is only optional
111                 logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $FQCN . ' for template ' . $template . ' does not exist.');
112         }
113 }
114
115 // Parses the XML content
116 function parseXmlData ($content) {
117         // Is there recode?
118         if (!function_exists('recode')) {
119                 // No fallback ATM
120                 reportBug('PHP extension recode is missing. Please install it.');
121         } // END - if
122
123         // Convert HTML entities to UTF-8
124         $content = recode('html..utf8', $content);
125
126         // Create a new XML parser
127         $xmlParser = xml_parser_create();
128
129         // Force case-folding to on
130         xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
131
132         // Set UTF-8
133         xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
134
135         // Set handler call-backs
136         xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
137         xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
138
139         // Now parse the XML tree
140         if (!xml_parse($xmlParser, $content)) {
141                 // Error found in XML!
142                 //* DEBUG: */ die('<pre>'.htmlentities($content).'</pre>');
143                 reportBug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
144         } // END - if
145
146         // Free the parser
147         xml_parser_free($xmlParser);
148 }
149
150 // Calls the found call-back function
151 function doCallXmlCallbackFunction () {
152         // Loop through all added entries
153         foreach ($GLOBALS['__XML_CALLBACKS']['callbacks'] as $callback) {
154                 // Is there the entry?
155                 if ((isset($GLOBALS['__XML_CALLBACKS']['functions'][$callback])) && (isset($GLOBALS['__XML_ARGUMENTS'][$callback]))) {
156                         // Run all function callbacks
157                         foreach ($GLOBALS['__XML_CALLBACKS']['functions'][$callback] as $function) {
158                                 // Trim all function names
159                                 $function = trim($function);
160
161                                 // If the function is empty, simply skip to the (maybe) next one
162                                 if (empty($function)) {
163                                         // Skip this
164                                         continue;
165                                 } // END - if
166
167                                 // Now construct the call-back function's name with 'Execute' at the end
168                                 $callbackName = $callback . 'Execute';
169
170                                 // Is it there?
171                                 if (!function_exists($callbackName)) {
172                                         // No, then please add it
173                                         reportBug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . 'arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ' - execute call-back does not exist.');
174                                 } // END - if
175
176                                 // Call it
177                                 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback]));
178                         } // END - foreach
179                 } else {
180                         // Not found
181                         reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
182                 }
183         } // END - foreach
184 }
185
186 //-----------------------------------------------------------------------------
187 //                     Call-back functions for XML parser
188 //-----------------------------------------------------------------------------
189
190 // Starts an element
191 function startXmlElement ($resource, $element, $attributes) {
192         // Call-back function for given element
193         $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
194
195         // Is the call-back function there?
196         if (!function_exists($elementCallback)) {
197                 // Not there
198                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
199         } // END - if
200
201         // Call the call-back function
202         call_user_func_array($elementCallback, array($resource, $attributes));
203 }
204
205 // Ends an element
206 function endXmlElement ($resource, $element) {
207         // Out-of-function for now
208 }
209
210 // Handle characters
211 function xmlCharacterHandler ($resource, $characters) {
212         // Trim spaces away
213         $characters = trim($characters);
214
215         // Are there some to handle?
216         if (strlen($characters) == 0) {
217                 // Nothing to handle
218                 return;
219         } // END - if
220
221         // @TODO Handle characters
222         die(__FUNCTION__ . ':characters[]='.strlen($characters));
223 }
224
225 // Checks if given type is valid, makes all lower-case
226 function isInvalidXmlType ($type) {
227         // All lower-case
228         $type = strtolower(trim($type));
229
230         // Is it found?
231         return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
232 }
233
234 // Checks if given condition is valid
235 function isXmlConditionValid ($condition) {
236         // Trim and make lower-case
237         $condition = trim(strtolower($condition));
238
239         // Is it valid?
240         return (in_array($condition, array('equals')));
241 }
242
243 // Checks if given value is valid/verifyable
244 function isXmlValueValid ($type, $value) {
245         // Depends on type, so build a call-back
246         $callbackName = 'isXmlType' . trim(capitalizeUnderscoreString($type));
247
248         // Is the call-back function there?
249         if (!function_exists($callbackName)) {
250                 // Not there
251                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
252         } // END - if
253
254         // Call and return it
255         return call_user_func_array($callbackName, array($value));
256 }
257
258 // Converts given condition into a symbol
259 function convertXmlContion ($condition) {
260         // Default is an invalid one
261         $return = '???';
262
263         // Detect the condition again
264         switch ($condition) {
265                 case 'EQUALS': // Equals
266                         $return = '=';
267                         break;
268
269                 default: // Unknown condition
270                         reportBug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
271                         break;
272         } // END - switch
273
274         // Return it
275         return $return;
276 }
277
278 // "Getter" for sql part back from given array
279 function getSqlPartFromXmlArray ($columns) {
280         // Init SQL
281         $SQL = '';
282
283         // Walk through all entries
284         foreach ($columns as $columnArray) {
285                 // Init SQL part
286                 $sqlPart = '';
287
288                 // Is there a table/alias
289                 if (!empty($columnArray['table'])) {
290                         // Pre-add it
291                         $sqlPart .= $columnArray['table'] . '.';
292                 } // END - if
293
294                 // Add column
295                 $sqlPart .= '`' . $columnArray['column'] . '`';
296
297                 // Is a function and alias set?
298                 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
299                         // Add both
300                         $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
301                 } // END - if
302
303                 // Add finished SQL part to the query
304                 $SQL .= $sqlPart . ',';
305         } // END - foreach
306
307         // Return it without last commata
308         return substr($SQL, 0, -1);
309 }
310
311 // Searches in given XML array for value and returns the parent index
312 function searchXmlArray ($value, $columns, $childKey) {
313         // Default is not found
314         $return = false;
315
316         // Walk through whole array
317         foreach ($columns as $key => $columnArray) {
318                 // Make sure the element is there
319                 assert(isset($columnArray[$childKey]));
320
321                 // Now is it what we are looking for?
322                 if ($columnArray[$childKey] == $value) {
323                         // Remember this match
324                         $return = $key;
325
326                         // And abort any further searches
327                         break;
328                 } // END - if
329         } // END - foreach
330
331         // Return key/false
332         return $return;
333 }
334
335 // [EOF]
336 ?>