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