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 - 2013 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) {
132 if (!isPhpExtensionLoaded('recode')) {
134 reportBug(__FUNCTION__, __LINE__, 'PHP extension recode is missing. Please install it.');
137 // Convert HTML entities to UTF-8
138 $content = recode('html..utf8', $content);
140 // Create a new XML parser
141 $xmlParser = xml_parser_create();
143 // Force case-folding to on
144 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
147 xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
149 // Set handler call-backs
150 xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
151 xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
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));
161 xml_parser_free($xmlParser);
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);
175 // If the function is empty, simply skip to the (maybe) next one
176 if (empty($function)) {
181 // Now construct the call-back function's name with 'Execute' at the end
182 $callbackName = $callback . 'Execute';
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.');
191 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
195 reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
200 //-----------------------------------------------------------------------------
201 // Call-back functions for XML parser
202 //-----------------------------------------------------------------------------
205 function startXmlElement ($resource, $element, $attributes) {
206 // Call-back function for given element
207 $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
209 // Is the call-back function there?
210 if (!function_exists($elementCallback)) {
212 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
215 // Call the call-back function
216 call_user_func_array($elementCallback, array($resource, $attributes));
220 function endXmlElement ($resource, $element) {
221 // Out-of-function for now
225 function xmlCharacterHandler ($resource, $characters) {
227 $characters = trim($characters);
229 // Are there some to handle?
230 if (empty($characters)) {
235 // @TODO Handle characters
236 die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
239 // Checks if given type is valid, makes all lower-case
240 function isInvalidXmlType ($type) {
242 $type = strtolower(trim($type));
245 return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
248 // Checks if given condition is valid
249 function isXmlConditionValid ($condition) {
250 // Trim and make lower-case
251 $condition = trim(strtolower($condition));
254 return (in_array($condition, array('equals', 'and')));
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));
262 // Is the call-back function there?
263 if (!function_exists($callbackName)) {
265 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
268 // Call and return it
269 return call_user_func_array($callbackName, array($value));
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.');
280 return $GLOBALS['__XML_CONDITIONS'][$condition];
283 // "Getter" for FROM statement from given columns
284 function getSqlXmlFromTable ($tableName) {
286 $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
289 if (!empty($tableName[0]['alias'])) {
291 $sql .= ' AS `' . $tableName[0]['alias'] . '`';
298 // "Getter" for sql part back from given array
299 function getSqlPartFromXmlArray ($columns) {
303 // Walk through all entries
304 foreach ($columns as $columnArray) {
306 assert(is_array($columnArray));
311 // Is there a table/alias
312 if (!empty($columnArray['table'])) {
314 $sqlPart .= '`' . $columnArray['table'] . '`.';
318 $sqlPart .= '`' . $columnArray['column'] . '`';
320 // Is a function and alias set?
321 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
323 $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
326 // Add finished SQL part to the query
327 $sql .= $sqlPart . ',';
330 // Return it without last commata
331 return substr($sql, 0, -1);
334 // "Getter" for JOIN statement
335 function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
337 assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
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'] . '`';
348 if (!empty($tableJoinName[$key]['alias'])) {
350 $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
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'] . '`';
357 $sql .= $joinOnCondition[$key];
359 $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
366 // "Getter" for WHERE statement from given columns and conditions arrays
367 function getSqlXmlWhereConditions ($whereColumns, $conditions) {
371 // Are there some conditions?
372 if (isFilledArray($whereColumns)) {
373 // Then add these as well
374 if (count($whereColumns) == 1) {
378 // Table/alias included?
379 if (!empty($whereColumns[0]['table'])) {
381 $sql .= $whereColumns[0]['table'] . '.';
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) {
390 $condition = ' WHERE ';
392 // Is the condition element there?
393 if (isset($conditions[$columnArray['column']])) {
394 // Assume the condition
395 $condition = ' ' . $conditions[$columnArray['column']] . ' ';
401 // Table/alias included?
402 if (!empty($whereColumns[$idx]['table'])) {
404 $sql .= $whereColumns[$idx]['table'] . '.';
408 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
411 // Did not set $conditions
412 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
420 // "Getter" for ORDER BY statement from given columns
421 function getSqlXmlOrderBy ($orderByColumns) {
425 // Are there entries from orderByColumns to add?
426 if (isFilledArray($orderByColumns)) {
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)));
434 // table/alias can be omitted
435 if (!empty($table)) {
436 // table/alias is given
437 $sql .= '`' . $table . '`.';
440 // Add order-by column
441 $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
444 // Remove last column
445 $sql = substr($sql, 0, -1);
452 // Searches in given XML array for value and returns the parent index
453 function searchXmlArray ($value, $columns, $childKey) {
454 // Default is not found
457 // Walk through whole array
458 foreach ($columns as $key => $columnArray) {
459 // Make sure the element is there
460 assert(isset($columnArray[$childKey]));
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
468 // And abort any further searches