217f8e73a0b901fea4a1756624d3d95d66f38ae4
[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 // Init XML system
44 function initXml () {
45         // All conditions
46         $GLOBALS['__XML_CONDITIONS'] = array(
47                 // Equals not
48                 'NOT-EQUALS' => ' != ',
49                 // Is not
50                 'IS-NOT'     => ' IS NOT ',
51                 // Is
52                 'IS'         => ' IS ',
53                 // Equals
54                 'EQUALS'     => ' = ',
55         );
56 }
57
58 // Calls back a function based on given XML template data
59 function doGenericXmlTemplateCallback ($template, $content = array(), $compileCode = TRUE) {
60         // Init XML system as sch calls will be only used once per run
61         initXml();
62
63         // Generate FQFN for with special path
64         $FQFN = sprintf("%stemplates/xml/%s%s.xml",
65                 getPath(),
66                 detectExtraTemplatePath('xml', $template),
67                 $template
68         );
69
70         // Is the file readable?
71         if (!isFileReadable($FQFN)) {
72                 // No, use without extra path
73                 $FQFN = sprintf("%stemplates/xml/%s.xml",
74                         getPath(),
75                         $template
76                 );
77         } // END - if
78
79         // Is it again readable?
80         if (isFileReadable($FQFN)) {
81                 // Is there cache?
82                 if ((!isDebuggingTemplateCache()) && (isTemplateCached('xml', $template))) {
83                         // Evaluate the cache
84                         eval(readTemplateCache('xml', $template));
85                 } else {
86                         // Read it
87                         $templateContent = readFromFile($FQFN);
88
89                         // Prepare it for finaly eval() command
90                         $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), FALSE, TRUE, TRUE, $compileCode) . '");';
91
92                         // Eval the code, this does insert any array elements from $content
93                         eval($GLOBALS['template_eval']['xml'][$template]);
94                 }
95
96                 // Init main arrays
97                 $GLOBALS['__XML_CALLBACKS'] = array(
98                         'callbacks' => array(),
99                         'functions' => array()
100                 );
101                 $GLOBALS['__XML_ARGUMENTS'] = array();
102                 $GLOBALS['__COLUMN_INDEX']  = array();
103
104                 // Handle it over to the parser
105                 parseXmlData($templateContent);
106
107                 // Add special elements, e.g. column index
108                 addXmlSpecialElements($template);
109
110                 // Call the call-back function
111                 doCallXmlCallbackFunction();
112         } else {
113                 // Template not found
114                 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
115         }
116 }
117
118 // Adds special elements by calling back another template-depending function
119 function addXmlSpecialElements ($template) {
120         // Generate the FQCN (Full-Qualified Callback Name)
121         $FQCN = 'addXmlSpecial' . capitalizeUnderscoreString($template);
122
123         // Is it there?
124         if (function_exists($FQCN)) {
125                 // Call it
126                 call_user_func($FQCN);
127         } elseif (isDebugModeEnabled()) {
128                 // This callback function is only optional
129                 logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $FQCN . ' for template ' . $template . ' does not exist.');
130         }
131 }
132
133 // Parses the XML content
134 function parseXmlData ($content) {
135         // Is there recode?
136         if (!function_exists('recode')) {
137                 // No fallback ATM
138                 reportBug('PHP extension recode is missing. Please install it.');
139         } // END - if
140
141         // Convert HTML entities to UTF-8
142         $content = recode('html..utf8', $content);
143
144         // Create a new XML parser
145         $xmlParser = xml_parser_create();
146
147         // Force case-folding to on
148         xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
149
150         // Set UTF-8
151         xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
152
153         // Set handler call-backs
154         xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
155         xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
156
157         // Now parse the XML tree
158         if (!xml_parse($xmlParser, $content)) {
159                 // Error found in XML!
160                 //* DEBUG: */ die('<pre>'.htmlentities($content).'</pre>');
161                 reportBug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
162         } // END - if
163
164         // Free the parser
165         xml_parser_free($xmlParser);
166 }
167
168 // Calls the found call-back function
169 function doCallXmlCallbackFunction () {
170         // Loop through all added entries
171         foreach ($GLOBALS['__XML_CALLBACKS']['callbacks'] as $callback) {
172                 // Is there the entry?
173                 if ((isset($GLOBALS['__XML_CALLBACKS']['functions'][$callback])) && (isset($GLOBALS['__XML_ARGUMENTS'][$callback]))) {
174                         // Run all function callbacks
175                         foreach ($GLOBALS['__XML_CALLBACKS']['functions'][$callback] as $function) {
176                                 // Trim all function names
177                                 $function = trim($function);
178
179                                 // If the function is empty, simply skip to the (maybe) next one
180                                 if (empty($function)) {
181                                         // Skip this
182                                         continue;
183                                 } // END - if
184
185                                 // Now construct the call-back function's name with 'Execute' at the end
186                                 $callbackName = $callback . 'Execute';
187
188                                 // Is it there?
189                                 if (!function_exists($callbackName)) {
190                                         // No, then please add it
191                                         reportBug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . 'arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ' - execute call-back does not exist.');
192                                 } // END - if
193
194                                 // Call it
195                                 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback]));
196                         } // END - foreach
197                 } else {
198                         // Not found
199                         reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
200                 }
201         } // END - foreach
202 }
203
204 //-----------------------------------------------------------------------------
205 //                     Call-back functions for XML parser
206 //-----------------------------------------------------------------------------
207
208 // Starts an element
209 function startXmlElement ($resource, $element, $attributes) {
210         // Call-back function for given element
211         $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
212
213         // Is the call-back function there?
214         if (!function_exists($elementCallback)) {
215                 // Not there
216                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
217         } // END - if
218
219         // Call the call-back function
220         call_user_func_array($elementCallback, array($resource, $attributes));
221 }
222
223 // Ends an element
224 function endXmlElement ($resource, $element) {
225         // Out-of-function for now
226 }
227
228 // Handle characters
229 function xmlCharacterHandler ($resource, $characters) {
230         // Trim spaces away
231         $characters = trim($characters);
232
233         // Are there some to handle?
234         if (strlen($characters) == 0) {
235                 // Nothing to handle
236                 return;
237         } // END - if
238
239         // @TODO Handle characters
240         die(__FUNCTION__ . ':characters[]='.strlen($characters));
241 }
242
243 // Checks if given type is valid, makes all lower-case
244 function isInvalidXmlType ($type) {
245         // All lower-case
246         $type = strtolower(trim($type));
247
248         // Is it found?
249         return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
250 }
251
252 // Checks if given condition is valid
253 function isXmlConditionValid ($condition) {
254         // Trim and make lower-case
255         $condition = trim(strtolower($condition));
256
257         // Is it valid?
258         return (in_array($condition, array('equals')));
259 }
260
261 // Checks if given value is valid/verifyable
262 function isXmlValueValid ($type, $value) {
263         // Depends on type, so build a call-back
264         $callbackName = 'isXmlType' . trim(capitalizeUnderscoreString($type));
265
266         // Is the call-back function there?
267         if (!function_exists($callbackName)) {
268                 // Not there
269                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
270         } // END - if
271
272         // Call and return it
273         return call_user_func_array($callbackName, array($value));
274 }
275
276 // Converts given condition into a symbol
277 function convertXmlContion ($condition) {
278         // Detect the condition again
279         if (!isset($GLOBALS['__XML_CONDITIONS'][$condition])) {
280                 reportBug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
281         } // END - if
282
283         // Return it
284         return $GLOBALS['__XML_CONDITIONS'][$condition];
285 }
286
287 // "Getter" for sql part back from given array
288 function getSqlPartFromXmlArray ($columns) {
289         // Init SQL
290         $SQL = '';
291
292         // Walk through all entries
293         foreach ($columns as $columnArray) {
294                 // Init SQL part
295                 $sqlPart = '';
296
297                 // Is there a table/alias
298                 if (!empty($columnArray['table'])) {
299                         // Pre-add it
300                         $sqlPart .= $columnArray['table'] . '.';
301                 } // END - if
302
303                 // Add column
304                 $sqlPart .= '`' . $columnArray['column'] . '`';
305
306                 // Is a function and alias set?
307                 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
308                         // Add both
309                         $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
310                 } // END - if
311
312                 // Add finished SQL part to the query
313                 $SQL .= $sqlPart . ',';
314         } // END - foreach
315
316         // Return it without last commata
317         return substr($SQL, 0, -1);
318 }
319
320 // Searches in given XML array for value and returns the parent index
321 function searchXmlArray ($value, $columns, $childKey) {
322         // Default is not found
323         $return = FALSE;
324
325         // Walk through whole array
326         foreach ($columns as $key => $columnArray) {
327                 // Make sure the element is there
328                 assert(isset($columnArray[$childKey]));
329
330                 // Now is it what we are looking for?
331                 if ($columnArray[$childKey] === $value) {
332                         // Remember this match
333                         $return = $key;
334
335                         // And abort any further searches
336                         break;
337                 } // END - if
338         } // END - foreach
339
340         // Return key/false
341         return $return;
342 }
343
344 // [EOF]
345 ?>