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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
46 $GLOBALS['__XML_CONDITIONS'] = array(
48 'NOT-EQUALS' => ' != ',
50 'IS-NOT' => ' IS NOT ',
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
63 // Generate FQFN for with special path
64 $FQFN = sprintf('%stemplates/xml/%s%s.xml',
66 detectExtraTemplatePath('xml', $template),
70 // Is the file readable?
71 if (!isFileReadable($FQFN)) {
72 // No, use without extra path
73 $FQFN = sprintf('%stemplates/xml/%s.xml',
79 // Is it again readable?
80 if (isFileReadable($FQFN)) {
82 if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('xml', $template))) {
84 $templateContent = readTemplateCache('xml', $template, $content);
87 $templateContent = readFromFile($FQFN);
89 // Prepare it for finaly eval() command
90 $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), TRUE, $compileCode) . '");';
92 // Eval the code, this does insert any array elements from $content
93 eval($GLOBALS['template_eval']['xml'][$template]);
97 $GLOBALS['__XML_CALLBACKS'] = array(
98 'callbacks' => array(),
99 'functions' => array()
101 $GLOBALS['__XML_ARGUMENTS'] = array();
102 $GLOBALS['__COLUMN_INDEX'] = array();
103 $GLOBALS['__XML_CONTENT'] = $content;
105 // Handle it over to the parser
106 parseXmlData($templateContent);
108 // Add special elements, e.g. column index
109 addXmlSpecialElements($template);
111 // Call the call-back function
112 doCallXmlCallbackFunction();
114 // Template not found
115 displayMessage('{%message,XML_TEMPLATE_404=' . $template . '%}');
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);
125 if (function_exists($FQCN)) {
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.');
134 // Parses the XML content
135 function parseXmlData ($content) {
137 if (!extension_loaded('recode')) {
139 reportBug(__FUNCTION__, __LINE__, 'PHP extension recode is missing. Please install it.');
142 // Convert HTML entities to UTF-8
143 $content = recode('html..utf8', $content);
145 // Create a new XML parser
146 $xmlParser = xml_parser_create();
148 // Force case-folding to on
149 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
152 xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
154 // Set handler call-backs
155 xml_set_element_handler($xmlParser, 'startXmlElement', 'endXmlElement');
156 xml_set_character_data_handler($xmlParser, 'xmlCharacterHandler');
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));
166 xml_parser_free($xmlParser);
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);
180 // If the function is empty, simply skip to the (maybe) next one
181 if (empty($function)) {
186 // Now construct the call-back function's name with 'Execute' at the end
187 $callbackName = $callback . 'Execute';
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.');
196 call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
200 reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
205 //-----------------------------------------------------------------------------
206 // Call-back functions for XML parser
207 //-----------------------------------------------------------------------------
210 function startXmlElement ($resource, $element, $attributes) {
211 // Call-back function for given element
212 $elementCallback = 'doXml' . capitalizeUnderscoreString($element);
214 // Is the call-back function there?
215 if (!function_exists($elementCallback)) {
217 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
220 // Call the call-back function
221 call_user_func_array($elementCallback, array($resource, $attributes));
225 function endXmlElement ($resource, $element) {
226 // Out-of-function for now
230 function xmlCharacterHandler ($resource, $characters) {
232 $characters = trim($characters);
234 // Are there some to handle?
235 if (empty($characters)) {
240 // @TODO Handle characters
241 die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
244 // Checks if given type is valid, makes all lower-case
245 function isInvalidXmlType ($type) {
247 $type = strtolower(trim($type));
250 return (in_array($type, array('string', 'array', 'bool', 'int', 'callback')));
253 // Checks if given condition is valid
254 function isXmlConditionValid ($condition) {
255 // Trim and make lower-case
256 $condition = trim(strtolower($condition));
259 return (in_array($condition, array('equals', 'and')));
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));
267 // Is the call-back function there?
268 if (!function_exists($callbackName)) {
270 reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
273 // Call and return it
274 return call_user_func_array($callbackName, array($value));
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.');
285 return $GLOBALS['__XML_CONDITIONS'][$condition];
288 // "Getter" for FROM statement from given columns
289 function getSqlXmlFromTable ($tableName) {
291 $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
294 if (!empty($tableName[0]['alias'])) {
296 $sql .= ' AS `' . $tableName[0]['alias'] . '`';
303 // "Getter" for sql part back from given array
304 function getSqlPartFromXmlArray ($columns) {
308 // Walk through all entries
309 foreach ($columns as $columnArray) {
311 assert(is_array($columnArray));
316 // Is there a table/alias
317 if (!empty($columnArray['table'])) {
319 $sqlPart .= '`' . $columnArray['table'] . '`.';
323 $sqlPart .= '`' . $columnArray['column'] . '`';
325 // Is a function and alias set?
326 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
328 $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
331 // Add finished SQL part to the query
332 $sql .= $sqlPart . ',';
335 // Return it without last commata
336 return substr($sql, 0, -1);
339 // "Getter" for JOIN statement
340 function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
342 assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
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'] . '`';
353 if (!empty($tableJoinName[$key]['alias'])) {
355 $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
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'] . '`';
362 $sql .= $joinOnCondition[$key];
364 $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
371 // "Getter" for WHERE statement from given columns and conditions arrays
372 function getSqlXmlWhereConditions ($whereColumns, $conditions) {
376 // Are there some conditions?
377 if (isFilledArray($whereColumns)) {
378 // Then add these as well
379 if (count($whereColumns) == 1) {
383 // Table/alias included?
384 if (!empty($whereColumns[0]['table'])) {
386 $sql .= $whereColumns[0]['table'] . '.';
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) {
395 $condition = ' WHERE ';
397 // Is the condition element there?
398 if (isset($conditions[$columnArray['column']])) {
399 // Assume the condition
400 $condition = ' ' . $conditions[$columnArray['column']] . ' ';
406 // Table/alias included?
407 if (!empty($whereColumns[$idx]['table'])) {
409 $sql .= $whereColumns[$idx]['table'] . '.';
413 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
416 // Did not set $conditions
417 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
425 // "Getter" for ORDER BY statement from given columns
426 function getSqlXmlOrderBy ($orderByColumns) {
430 // Are there entries from orderByColumns to add?
431 if (isFilledArray($orderByColumns)) {
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)));
439 // table/alias can be omitted
440 if (!empty($table)) {
441 // table/alias is given
442 $sql .= '`' . $table . '`.';
445 // Add order-by column
446 $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
449 // Remove last column
450 $sql = substr($sql, 0, -1);
457 // Searches in given XML array for value and returns the parent index
458 function searchXmlArray ($value, $columns, $childKey) {
459 // Default is not found
462 // Walk through whole array
463 foreach ($columns as $key => $columnArray) {
464 // Make sure the element is there
465 assert(isset($columnArray[$childKey]));
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
473 // And abort any further searches