2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 01/27/2011 *
4 * =================== Last change: 01/27/2011 *
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 *
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. *
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. *
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, *
31 ************************************************************************/
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
41 $GLOBALS['__XML_CONDITIONS'] = array(
43 'NOT-EQUALS' => ' != ',
45 'IS-NOT' => ' IS NOT ',
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
58 // Generate FQFN for with special path
59 $FQFN = sprintf('%stemplates/xml/%s%s.xml',
61 detectExtraTemplatePath('xml', $template),
65 // Is the file readable?
66 if (!isFileReadable($FQFN)) {
67 // No, use without extra path
68 $FQFN = sprintf('%stemplates/xml/%s.xml',
74 // Is it again readable?
75 if (isFileReadable($FQFN)) {
77 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('xml', $template))) {
79 $templateContent = readTemplateCache('xml', $template, $content);
82 $templateContent = readFromFile($FQFN);
84 // Prepare it for finaly eval() command
85 $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), TRUE, $compileCode) . '");';
87 // Eval the code, this does insert any array elements from $content
88 eval($GLOBALS['template_eval']['xml'][$template]);
92 $GLOBALS['__XML_CALLBACKS'] = array(
93 'callbacks' => array(),
94 'functions' => array()
96 $GLOBALS['__XML_ARGUMENTS'] = array();
97 $GLOBALS['__COLUMN_INDEX'] = array();
98 $GLOBALS['__XML_CONTENT'] = $content;
100 // Handle it over to the parser
101 parseXmlData($templateContent);
103 // Add special elements, e.g. column index
104 addXmlSpecialElements($template);
106 // Call the call-back function
107 doCallXmlCallbackFunction();
109 // Template not found
110 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
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);
120 if (function_exists($FQCN)) {
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.');
129 // Parses the XML content
130 function parseXmlData ($content) {
131 // Convert HTML entities to UTF-8
132 $decoded = decodeEntities($content);
134 // Create a new XML parser
135 $xmlParser = xml_parser_create();
137 // Force case-folding to on
138 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
141 xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
143 // Set handler call-backs
144 xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
145 xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
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));
155 xml_parser_free($xmlParser);
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);
169 // If the function is empty, simply skip to the (maybe) next one
170 if (empty($function)) {
175 // Now construct the call-back function's name with 'Execute' at the end
176 $callbackName = $callback . 'Execute';
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.');
185 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
189 reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
194 //-----------------------------------------------------------------------------
195 // Call-back functions for XML parser
196 //-----------------------------------------------------------------------------
199 function startXmlElement ($resource, $element, $attributes) {
200 // Call-back function for given element
201 $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
203 // Is the call-back function there?
204 if (!function_exists($elementCallback)) {
206 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
209 // Call the call-back function
210 call_user_func_array($elementCallback, array($resource, $attributes));
214 function endXmlElement ($resource, $element) {
215 // Out-of-function for now
219 function xmlCharacterHandler ($resource, $characters) {
221 $characters = trim($characters);
223 // Are there some to handle?
224 if (empty($characters)) {
229 // @TODO Handle characters
230 die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
233 // Checks if given type is valid, makes all lower-case
234 function isInvalidXmlType ($type) {
236 $type = strtolower(trim($type));
239 return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
242 // Checks if given condition is valid
243 function isXmlConditionValid ($condition) {
244 // Trim and make lower-case
245 $condition = trim(strtolower($condition));
248 return (in_array($condition, array('equals', 'and')));
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));
256 // Is the call-back function there?
257 if (!function_exists($callbackName)) {
259 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
262 // Call and return it
263 return call_user_func_array($callbackName, array($value));
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.');
274 return $GLOBALS['__XML_CONDITIONS'][$condition];
277 // "Getter" for FROM statement from given columns
278 function getSqlXmlFromTable ($tableName) {
280 $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
283 if (!empty($tableName[0]['alias'])) {
285 $sql .= ' AS `' . $tableName[0]['alias'] . '`';
292 // "Getter" for sql part back from given array
293 function getSqlPartFromXmlArray ($columns) {
297 // Walk through all entries
298 foreach ($columns as $columnArray) {
300 assert(is_array($columnArray));
305 // Is there a table/alias
306 if (!empty($columnArray['table'])) {
308 $sqlPart .= '`' . $columnArray['table'] . '`.';
312 $sqlPart .= '`' . $columnArray['column'] . '`';
314 // Is a function and alias set?
315 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
317 $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
320 // Add finished SQL part to the query
321 $sql .= $sqlPart . ',';
324 // Return it without last commata
325 return substr($sql, 0, -1);
328 // "Getter" for JOIN statement
329 function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
331 assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
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'] . '`';
342 if (!empty($tableJoinName[$key]['alias'])) {
344 $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
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'] . '`';
351 $sql .= $joinOnCondition[$key];
353 $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
360 // "Getter" for WHERE statement from given columns and conditions arrays
361 function getSqlXmlWhereConditions ($whereColumns, $conditions) {
365 // Are there some conditions?
366 if (isFilledArray($whereColumns)) {
367 // Then add these as well
368 if (count($whereColumns) == 1) {
372 // Table/alias included?
373 if (!empty($whereColumns[0]['table'])) {
375 $sql .= $whereColumns[0]['table'] . '.';
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) {
384 $condition = ' WHERE ';
386 // Is the condition element there?
387 if (isset($conditions[$columnArray['column']])) {
388 // Assume the condition
389 $condition = ' ' . $conditions[$columnArray['column']] . ' ';
395 // Table/alias included?
396 if (!empty($whereColumns[$idx]['table'])) {
398 $sql .= $whereColumns[$idx]['table'] . '.';
402 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
405 // Did not set $conditions
406 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
414 // "Getter" for ORDER BY statement from given columns
415 function getSqlXmlOrderBy ($orderByColumns) {
419 // Are there entries from orderByColumns to add?
420 if (isFilledArray($orderByColumns)) {
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)));
428 // table/alias can be omitted
429 if (!empty($table)) {
430 // table/alias is given
431 $sql .= '`' . $table . '`.';
434 // Add order-by column
435 $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
438 // Remove last column
439 $sql = substr($sql, 0, -1);
446 // Searches in given XML array for value and returns the parent index
447 function searchXmlArray ($value, $columns, $childKey) {
448 // Default is not found
451 // Walk through whole array
452 foreach ($columns as $key => $columnArray) {
453 // Make sure the element is there
454 assert(isset($columnArray[$childKey]));
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
462 // And abort any further searches