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