Moved "fix" files (which only helps to fix stuff) in own inc/fixes/ folder.
[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  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
14  * Copyright (c) 2009 - 2016 by Mailer Developer Team                   *
15  * For more information visit: http://mxchange.org                      *
16  *                                                                      *
17  * This program is free software; you can redistribute it and/or modify *
18  * it under the terms of the GNU General Public License as published by *
19  * the Free Software Foundation; either version 2 of the License, or    *
20  * (at your option) any later version.                                  *
21  *                                                                      *
22  * This program is distributed in the hope that it will be useful,      *
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
25  * GNU General Public License for more details.                         *
26  *                                                                      *
27  * You should have received a copy of the GNU General Public License    *
28  * along with this program; if not, write to the Free Software          *
29  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
30  * MA  02110-1301  USA                                                  *
31  ************************************************************************/
32
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
35         die();
36 } // END - if
37
38 // Init XML system
39 function initXml () {
40         // All conditions
41         $GLOBALS['__XML_CONDITIONS'] = array(
42                 // Equals not
43                 'NOT-EQUALS' => ' != ',
44                 // Is not
45                 'IS-NOT'     => ' IS NOT ',
46                 // Is
47                 'IS'         => ' IS ',
48                 // Equals
49                 'EQUALS'     => ' = ',
50         );
51 }
52
53 // Calls back a function based on given XML template data
54 function doGenericXmlTemplateCallback ($template, $content = array(), $compileCode = TRUE) {
55         // Init XML system as sch calls will be only used once per run
56         initXml();
57
58         // Generate FQFN for with special path
59         $FQFN = sprintf('%stemplates/xml/%s%s.xml',
60                 getPath(),
61                 detectExtraTemplatePath('xml', $template),
62                 $template
63         );
64
65         // Is the file readable?
66         if (!isFileReadable($FQFN)) {
67                 // No, use without extra path
68                 $FQFN = sprintf('%stemplates/xml/%s.xml',
69                         getPath(),
70                         $template
71                 );
72         } // END - if
73
74         // Is it again readable?
75         if (isFileReadable($FQFN)) {
76                 // Is there cache?
77                 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('xml', $template))) {
78                         // Evaluate the cache
79                         $templateContent = readTemplateCache('xml', $template, $content);
80                 } else {
81                         // Read it
82                         $templateContent = readFromFile($FQFN);
83
84                         // Prepare it for finaly eval() command
85                         $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), TRUE, $compileCode) . '");';
86
87                         // Eval the code, this does insert any array elements from $content
88                         eval($GLOBALS['template_eval']['xml'][$template]);
89                 }
90
91                 // Init main arrays
92                 $GLOBALS['__XML_CALLBACKS'] = array(
93                         'callbacks' => array(),
94                         'functions' => array()
95                 );
96                 $GLOBALS['__XML_ARGUMENTS'] = array();
97                 $GLOBALS['__COLUMN_INDEX']  = array();
98                 $GLOBALS['__XML_CONTENT']   = $content;
99
100                 // Handle it over to the parser
101                 parseXmlData($templateContent);
102
103                 // Add special elements, e.g. column index
104                 addXmlSpecialElements($template);
105
106                 // Call the call-back function
107                 doCallXmlCallbackFunction();
108         } else {
109                 // Template not found
110                 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
111         }
112 }
113
114 // Adds special elements by calling back another template-depending function
115 function addXmlSpecialElements ($template) {
116         // Generate the FQCN (Full-Qualified Callback Name)
117         $FQCN = 'addXmlSpecial' . capitalizeUnderscoreString($template);
118
119         // Is it there?
120         if (function_exists($FQCN)) {
121                 // Call it
122                 call_user_func($FQCN);
123         } elseif (isDebugModeEnabled()) {
124                 // This callback function is only optional
125                 logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $FQCN . ' for template ' . $template . ' does not exist.');
126         }
127 }
128
129 // Parses the XML content
130 function parseXmlData ($content) {
131         // Is there recode?
132         if (!isPhpExtensionLoaded('recode')) {
133                 // No fallback ATM
134                 reportBug(__FUNCTION__, __LINE__, 'PHP extension recode is missing. Please install it.');
135         } // END - if
136
137         // Convert HTML entities to UTF-8
138         $content = recode('html..utf8', $content);
139
140         // Create a new XML parser
141         $xmlParser = xml_parser_create();
142
143         // Force case-folding to on
144         xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
145
146         // Set UTF-8
147         xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
148
149         // Set handler call-backs
150         xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
151         xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
152
153         // Now parse the XML tree
154         if (!xml_parse($xmlParser, $content)) {
155                 // Error found in XML!
156                 //* DEBUG: */ die('<pre>'.htmlentities($content).'</pre>');
157                 reportBug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
158         } // END - if
159
160         // Free the parser
161         xml_parser_free($xmlParser);
162 }
163
164 // Calls the found call-back function
165 function doCallXmlCallbackFunction () {
166         // Loop through all added entries
167         foreach ($GLOBALS['__XML_CALLBACKS']['callbacks'] as $callback) {
168                 // Is there the entry?
169                 if ((isset($GLOBALS['__XML_CALLBACKS']['functions'][$callback])) && (isset($GLOBALS['__XML_ARGUMENTS'][$callback]))) {
170                         // Run all function callbacks
171                         foreach ($GLOBALS['__XML_CALLBACKS']['functions'][$callback] as $function) {
172                                 // Trim all function names
173                                 $function = trim($function);
174
175                                 // If the function is empty, simply skip to the (maybe) next one
176                                 if (empty($function)) {
177                                         // Skip this
178                                         continue;
179                                 } // END - if
180
181                                 // Now construct the call-back function's name with 'Execute' at the end
182                                 $callbackName = $callback . 'Execute';
183
184                                 // Is it there?
185                                 if (!function_exists($callbackName)) {
186                                         // No, then please add it
187                                         reportBug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . ',arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ',content()=' . count($GLOBALS['__XML_CONTENT']) . ' - execute call-back does not exist.');
188                                 } // END - if
189
190                                 // Call it
191                                 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
192                         } // END - foreach
193                 } else {
194                         // Not found
195                         reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
196                 }
197         } // END - foreach
198 }
199
200 //-----------------------------------------------------------------------------
201 //                     Call-back functions for XML parser
202 //-----------------------------------------------------------------------------
203
204 // Starts an element
205 function startXmlElement ($resource, $element, $attributes) {
206         // Call-back function for given element
207         $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
208
209         // Is the call-back function there?
210         if (!function_exists($elementCallback)) {
211                 // Not there
212                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
213         } // END - if
214
215         // Call the call-back function
216         call_user_func_array($elementCallback, array($resource, $attributes));
217 }
218
219 // Ends an element
220 function endXmlElement ($resource, $element) {
221         // Out-of-function for now
222 }
223
224 // Handle characters
225 function xmlCharacterHandler ($resource, $characters) {
226         // Trim spaces away
227         $characters = trim($characters);
228
229         // Are there some to handle?
230         if (empty($characters)) {
231                 // Nothing to handle
232                 return;
233         } // END - if
234
235         // @TODO Handle characters
236         die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
237 }
238
239 // Checks if given type is valid, makes all lower-case
240 function isInvalidXmlType ($type) {
241         // All lower-case
242         $type = strtolower(trim($type));
243
244         // Is it found?
245         return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
246 }
247
248 // Checks if given condition is valid
249 function isXmlConditionValid ($condition) {
250         // Trim and make lower-case
251         $condition = trim(strtolower($condition));
252
253         // Is it valid?
254         return (in_array($condition, array('equals', 'and')));
255 }
256
257 // Checks if given value is valid/verifyable
258 function isXmlValueValid ($type, $value) {
259         // Depends on type, so build a call-back
260         $callbackName = 'isXmlType' . trim(capitalizeUnderscoreString($type));
261
262         // Is the call-back function there?
263         if (!function_exists($callbackName)) {
264                 // Not there
265                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
266         } // END - if
267
268         // Call and return it
269         return call_user_func_array($callbackName, array($value));
270 }
271
272 // Converts given condition into a symbol
273 function convertXmlContion ($condition) {
274         // Detect the condition again
275         if (!isset($GLOBALS['__XML_CONDITIONS'][$condition])) {
276                 reportBug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
277         } // END - if
278
279         // Return it
280         return $GLOBALS['__XML_CONDITIONS'][$condition];
281 }
282
283 // "Getter" for FROM statement from given columns
284 function getSqlXmlFromTable ($tableName) {
285         // Init SQL
286         $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
287
288         // Is alias set?
289         if (!empty($tableName[0]['alias'])) {
290                 // Also add it
291                 $sql .= ' AS `' . $tableName[0]['alias'] . '`';
292         } // END - if
293
294         // Return SQL
295         return $sql;
296 }
297
298 // "Getter" for sql part back from given array
299 function getSqlPartFromXmlArray ($columns) {
300         // Init SQL
301         $sql = '';
302
303         // Walk through all entries
304         foreach ($columns as $columnArray) {
305                 // Must be an array
306                 assert(is_array($columnArray));
307
308                 // Init SQL part
309                 $sqlPart = '';
310
311                 // Is there a table/alias
312                 if (!empty($columnArray['table'])) {
313                         // Pre-add it
314                         $sqlPart .= '`' . $columnArray['table'] . '`.';
315                 } // END - if
316
317                 // Add column
318                 $sqlPart .= '`' . $columnArray['column'] . '`';
319
320                 // Is a function and alias set?
321                 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
322                         // Add both
323                         $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
324                 } // END - if
325
326                 // Add finished SQL part to the query
327                 $sql .= $sqlPart . ',';
328         } // END - foreach
329
330         // Return it without last commata
331         return substr($sql, 0, -1);
332 }
333
334 // "Getter" for JOIN statement
335 function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
336         // Are all set?
337         assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
338
339         // Init SQL
340         $sql = '';
341
342         // "Walk" through all JOINs
343         foreach ($tableJoinType as $key => $joinType) {
344                 // 1) Add JOIN type and table name with alias
345                 $sql .= ' ' . $joinType . ' `{?_MYSQL_PREFIX?}_' . $tableJoinName[$key]['name'] . '`';
346
347                 // Alias set?
348                 if (!empty($tableJoinName[$key]['alias'])) {
349                         // Add it
350                         $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
351                 } // END - if
352
353                 // 2) Add left part + condition + right part with aliases
354                 // 2/1) ON + left part
355                 $sql .= ' ON `' . $joinOnLeftTable[$key]['name'] . '`.`' . $joinOnLeftTable[$key]['column'] . '`';
356                 // 2/2) Condition
357                 $sql .= $joinOnCondition[$key];
358                 // 2/3) right part
359                 $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
360         } // END - foreach
361
362         // Return SQL
363         return $sql;
364 }
365
366 // "Getter" for WHERE statement from given columns and conditions arrays
367 function getSqlXmlWhereConditions ($whereColumns, $conditions) {
368         // Init SQL
369         $sql = '';
370
371         // Are there some conditions?
372         if (isFilledArray($whereColumns)) {
373                 // Then add these as well
374                 if (count($whereColumns) == 1) {
375                         // One entry found
376                         $sql .= ' WHERE ';
377
378                         // Table/alias included?
379                         if (!empty($whereColumns[0]['table'])) {
380                                 // Add it as well
381                                 $sql .= $whereColumns[0]['table'] . '.';
382                         } // END - if
383
384                         // Add the rest
385                         $sql .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
386                 } elseif ((count($whereColumns > 1)) && (isFilledArray($conditions))) {
387                         // More than one "WHERE" + condition found
388                         foreach ($whereColumns as $idx => $columnArray) {
389                                 // Default is WHERE
390                                 $condition = ' WHERE ';
391
392                                 // Is the condition element there?
393                                 if (isset($conditions[$columnArray['column']])) {
394                                         // Assume the condition
395                                         $condition = ' ' . $conditions[$columnArray['column']] . ' ';
396                                 } // END - if
397
398                                 // Add to SQL query
399                                 $sql .= $condition;
400
401                                 // Table/alias included?
402                                 if (!empty($whereColumns[$idx]['table'])) {
403                                         // Add it as well
404                                         $sql .= $whereColumns[$idx]['table'] . '.';
405                                 } // END - if
406
407                                 // Add the rest
408                                 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
409                         } // END - foreach
410                 } else {
411                         // Did not set $conditions
412                         reportBug(__FUNCTION__, __LINE__, 'Supplied more than &quot;whereColumns&quot; entries but no conditions! Please fix your XML template.');
413                 }
414         } // END - if
415
416         // Return SQL
417         return $sql;
418 }
419
420 // "Getter" for ORDER BY statement from given columns
421 function getSqlXmlOrderBy ($orderByColumns) {
422         // Init SQL
423         $sql = '';
424
425         // Are there entries from orderByColumns to add?
426         if (isFilledArray($orderByColumns)) {
427                 // Add them as well
428                 $sql .= ' ORDER BY ';
429                 foreach ($orderByColumns as $orderByColumn => $array) {
430                         // Get keys (table/alias) and values (sorting itself)
431                         $table   = trim(implode('', array_keys($array)));
432                         $sorting = trim(implode('', array_values($array)));
433
434                         // table/alias can be omitted
435                         if (!empty($table)) {
436                                 // table/alias is given
437                                 $sql .= '`' . $table . '`.';
438                         } // END - if
439
440                         // Add order-by column
441                         $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
442                 } // END - foreach
443
444                 // Remove last column
445                 $sql = substr($sql, 0, -1);
446         } // END - if
447
448         // Return SQL
449         return $sql;
450 }
451
452 // Searches in given XML array for value and returns the parent index
453 function searchXmlArray ($value, $columns, $childKey) {
454         // Default is not found
455         $return = FALSE;
456
457         // Walk through whole array
458         foreach ($columns as $key => $columnArray) {
459                 // Make sure the element is there
460                 assert(isset($columnArray[$childKey]));
461
462                 // Now is it what we are looking for?
463                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',key=' . $key . ',childKey=' . $childKey . ',columnArray=' . $columnArray[$childKey]);
464                 if ($columnArray[$childKey] === $value) {
465                         // Remember this match
466                         $return = $key;
467
468                         // And abort any further searches
469                         break;
470                 } // END - if
471         } // END - foreach
472
473         // Return key/false
474         return $return;
475 }
476
477 // [EOF]
478 ?>