Removed 2nd parameter for assert() as this is only available in PHP 5.4.8+ but Mailer...
[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 - 2013 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 ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('xml', $template))) {
83                         // Evaluate the cache
84                         $templateContent = readTemplateCache('xml', $template, $content);
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), 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                 $GLOBALS['__XML_CONTENT']   = $content;
104
105                 // Handle it over to the parser
106                 parseXmlData($templateContent);
107
108                 // Add special elements, e.g. column index
109                 addXmlSpecialElements($template);
110
111                 // Call the call-back function
112                 doCallXmlCallbackFunction();
113         } else {
114                 // Template not found
115                 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
116         }
117 }
118
119 // Adds special elements by calling back another template-depending function
120 function addXmlSpecialElements ($template) {
121         // Generate the FQCN (Full-Qualified Callback Name)
122         $FQCN = 'addXmlSpecial' . capitalizeUnderscoreString($template);
123
124         // Is it there?
125         if (function_exists($FQCN)) {
126                 // Call it
127                 call_user_func($FQCN);
128         } elseif (isDebugModeEnabled()) {
129                 // This callback function is only optional
130                 logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $FQCN . ' for template ' . $template . ' does not exist.');
131         }
132 }
133
134 // Parses the XML content
135 function parseXmlData ($content) {
136         // Is there recode?
137         if (!function_exists('recode')) {
138                 // No fallback ATM
139                 reportBug(__FUNCTION__, __LINE__, 'PHP extension recode is missing. Please install it.');
140         } // END - if
141
142         // Convert HTML entities to UTF-8
143         $content = recode('html..utf8', $content);
144
145         // Create a new XML parser
146         $xmlParser = xml_parser_create();
147
148         // Force case-folding to on
149         xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
150
151         // Set UTF-8
152         xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
153
154         // Set handler call-backs
155         xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
156         xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
157
158         // Now parse the XML tree
159         if (!xml_parse($xmlParser, $content)) {
160                 // Error found in XML!
161                 //* DEBUG: */ die('<pre>'.htmlentities($content).'</pre>');
162                 reportBug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
163         } // END - if
164
165         // Free the parser
166         xml_parser_free($xmlParser);
167 }
168
169 // Calls the found call-back function
170 function doCallXmlCallbackFunction () {
171         // Loop through all added entries
172         foreach ($GLOBALS['__XML_CALLBACKS']['callbacks'] as $callback) {
173                 // Is there the entry?
174                 if ((isset($GLOBALS['__XML_CALLBACKS']['functions'][$callback])) && (isset($GLOBALS['__XML_ARGUMENTS'][$callback]))) {
175                         // Run all function callbacks
176                         foreach ($GLOBALS['__XML_CALLBACKS']['functions'][$callback] as $function) {
177                                 // Trim all function names
178                                 $function = trim($function);
179
180                                 // If the function is empty, simply skip to the (maybe) next one
181                                 if (empty($function)) {
182                                         // Skip this
183                                         continue;
184                                 } // END - if
185
186                                 // Now construct the call-back function's name with 'Execute' at the end
187                                 $callbackName = $callback . 'Execute';
188
189                                 // Is it there?
190                                 if (!function_exists($callbackName)) {
191                                         // No, then please add it
192                                         reportBug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . ',arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ',content()=' . count($GLOBALS['__XML_CONTENT']) . ' - execute call-back does not exist.');
193                                 } // END - if
194
195                                 // Call it
196                                 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
197                         } // END - foreach
198                 } else {
199                         // Not found
200                         reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
201                 }
202         } // END - foreach
203 }
204
205 //-----------------------------------------------------------------------------
206 //                     Call-back functions for XML parser
207 //-----------------------------------------------------------------------------
208
209 // Starts an element
210 function startXmlElement ($resource, $element, $attributes) {
211         // Call-back function for given element
212         $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
213
214         // Is the call-back function there?
215         if (!function_exists($elementCallback)) {
216                 // Not there
217                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
218         } // END - if
219
220         // Call the call-back function
221         call_user_func_array($elementCallback, array($resource, $attributes));
222 }
223
224 // Ends an element
225 function endXmlElement ($resource, $element) {
226         // Out-of-function for now
227 }
228
229 // Handle characters
230 function xmlCharacterHandler ($resource, $characters) {
231         // Trim spaces away
232         $characters = trim($characters);
233
234         // Are there some to handle?
235         if (empty($characters)) {
236                 // Nothing to handle
237                 return;
238         } // END - if
239
240         // @TODO Handle characters
241         die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
242 }
243
244 // Checks if given type is valid, makes all lower-case
245 function isInvalidXmlType ($type) {
246         // All lower-case
247         $type = strtolower(trim($type));
248
249         // Is it found?
250         return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
251 }
252
253 // Checks if given condition is valid
254 function isXmlConditionValid ($condition) {
255         // Trim and make lower-case
256         $condition = trim(strtolower($condition));
257
258         // Is it valid?
259         return (in_array($condition, array('equals', 'and')));
260 }
261
262 // Checks if given value is valid/verifyable
263 function isXmlValueValid ($type, $value) {
264         // Depends on type, so build a call-back
265         $callbackName = 'isXmlType' . trim(capitalizeUnderscoreString($type));
266
267         // Is the call-back function there?
268         if (!function_exists($callbackName)) {
269                 // Not there
270                 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
271         } // END - if
272
273         // Call and return it
274         return call_user_func_array($callbackName, array($value));
275 }
276
277 // Converts given condition into a symbol
278 function convertXmlContion ($condition) {
279         // Detect the condition again
280         if (!isset($GLOBALS['__XML_CONDITIONS'][$condition])) {
281                 reportBug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
282         } // END - if
283
284         // Return it
285         return $GLOBALS['__XML_CONDITIONS'][$condition];
286 }
287
288 // "Getter" for FROM statement from given columns
289 function getSqlXmlFromTable ($tableName) {
290         // Init SQL
291         $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
292
293         // Is alias set?
294         if (!empty($tableName[0]['alias'])) {
295                 // Also add it
296                 $sql .= ' AS `' . $tableName[0]['alias'] . '`';
297         } // END - if
298
299         // Return SQL
300         return $sql;
301 }
302
303 // "Getter" for sql part back from given array
304 function getSqlPartFromXmlArray ($columns) {
305         // Init SQL
306         $sql = '';
307
308         // Walk through all entries
309         foreach ($columns as $columnArray) {
310                 // Must be an array
311                 assert(is_array($columnArray));
312
313                 // Init SQL part
314                 $sqlPart = '';
315
316                 // Is there a table/alias
317                 if (!empty($columnArray['table'])) {
318                         // Pre-add it
319                         $sqlPart .= '`' . $columnArray['table'] . '`.';
320                 } // END - if
321
322                 // Add column
323                 $sqlPart .= '`' . $columnArray['column'] . '`';
324
325                 // Is a function and alias set?
326                 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
327                         // Add both
328                         $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
329                 } // END - if
330
331                 // Add finished SQL part to the query
332                 $sql .= $sqlPart . ',';
333         } // END - foreach
334
335         // Return it without last commata
336         return substr($sql, 0, -1);
337 }
338
339 // "Getter" for JOIN statement
340 function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
341         // Are all set?
342         assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
343
344         // Init SQL
345         $sql = '';
346
347         // "Walk" through all JOINs
348         foreach ($tableJoinType as $key => $joinType) {
349                 // 1) Add JOIN type and table name with alias
350                 $sql .= ' ' . $joinType . ' `{?_MYSQL_PREFIX?}_' . $tableJoinName[$key]['name'] . '`';
351
352                 // Alias set?
353                 if (!empty($tableJoinName[$key]['alias'])) {
354                         // Add it
355                         $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
356                 } // END - if
357
358                 // 2) Add left part + condition + right part with aliases
359                 // 2/1) ON + left part
360                 $sql .= ' ON `' . $joinOnLeftTable[$key]['name'] . '`.`' . $joinOnLeftTable[$key]['column'] . '`';
361                 // 2/2) Condition
362                 $sql .= $joinOnCondition[$key];
363                 // 2/3) right part
364                 $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
365         } // END - foreach
366
367         // Return SQL
368         return $sql;
369 }
370
371 // "Getter" for WHERE statement from given columns and conditions arrays
372 function getSqlXmlWhereConditions ($whereColumns, $conditions) {
373         // Init SQL
374         $sql = '';
375
376         // Are there some conditions?
377         if (isFilledArray($whereColumns)) {
378                 // Then add these as well
379                 if (count($whereColumns) == 1) {
380                         // One entry found
381                         $sql .= ' WHERE ';
382
383                         // Table/alias included?
384                         if (!empty($whereColumns[0]['table'])) {
385                                 // Add it as well
386                                 $sql .= $whereColumns[0]['table'] . '.';
387                         } // END - if
388
389                         // Add the rest
390                         $sql .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
391                 } elseif ((count($whereColumns > 1)) && (isFilledArray($conditions))) {
392                         // More than one "WHERE" + condition found
393                         foreach ($whereColumns as $idx => $columnArray) {
394                                 // Default is WHERE
395                                 $condition = ' WHERE ';
396
397                                 // Is the condition element there?
398                                 if (isset($conditions[$columnArray['column']])) {
399                                         // Assume the condition
400                                         $condition = ' ' . $conditions[$columnArray['column']] . ' ';
401                                 } // END - if
402
403                                 // Add to SQL query
404                                 $sql .= $condition;
405
406                                 // Table/alias included?
407                                 if (!empty($whereColumns[$idx]['table'])) {
408                                         // Add it as well
409                                         $sql .= $whereColumns[$idx]['table'] . '.';
410                                 } // END - if
411
412                                 // Add the rest
413                                 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
414                         } // END - foreach
415                 } else {
416                         // Did not set $conditions
417                         reportBug(__FUNCTION__, __LINE__, 'Supplied more than &quot;whereColumns&quot; entries but no conditions! Please fix your XML template.');
418                 }
419         } // END - if
420
421         // Return SQL
422         return $sql;
423 }
424
425 // "Getter" for ORDER BY statement from given columns
426 function getSqlXmlOrderBy ($orderByColumns) {
427         // Init SQL
428         $sql = '';
429
430         // Are there entries from orderByColumns to add?
431         if (isFilledArray($orderByColumns)) {
432                 // Add them as well
433                 $sql .= ' ORDER BY ';
434                 foreach ($orderByColumns as $orderByColumn => $array) {
435                         // Get keys (table/alias) and values (sorting itself)
436                         $table   = trim(implode('', array_keys($array)));
437                         $sorting = trim(implode('', array_values($array)));
438
439                         // table/alias can be omitted
440                         if (!empty($table)) {
441                                 // table/alias is given
442                                 $sql .= '`' . $table . '`.';
443                         } // END - if
444
445                         // Add order-by column
446                         $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
447                 } // END - foreach
448
449                 // Remove last column
450                 $sql = substr($sql, 0, -1);
451         } // END - if
452
453         // Return SQL
454         return $sql;
455 }
456
457 // Searches in given XML array for value and returns the parent index
458 function searchXmlArray ($value, $columns, $childKey) {
459         // Default is not found
460         $return = FALSE;
461
462         // Walk through whole array
463         foreach ($columns as $key => $columnArray) {
464                 // Make sure the element is there
465                 assert(isset($columnArray[$childKey]));
466
467                 // Now is it what we are looking for?
468                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',key=' . $key . ',childKey=' . $childKey . ',columnArray=' . $columnArray[$childKey]);
469                 if ($columnArray[$childKey] === $value) {
470                         // Remember this match
471                         $return = $key;
472
473                         // And abort any further searches
474                         break;
475                 } // END - if
476         } // END - foreach
477
478         // Return key/false
479         return $return;
480 }
481
482 // [EOF]
483 ?>