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