]> git.mxchange.org Git - mailer.git/blobdiff - inc/xml-functions.php
Must be updated here as well :(
[mailer.git] / inc / xml-functions.php
index d59207e916ae0357fae647a85af646bc91a5673c..87f2d4e1b62f1174b350ff18bb8a643dc2962075 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -40,19 +40,37 @@ if (!defined('__SECURITY')) {
        die();
 } // END - if
 
+// Init XML system
+function initXml () {
+       // All conditions
+       $GLOBALS['__XML_CONDITIONS'] = array(
+               // Equals not
+               'NOT-EQUALS' => ' != ',
+               // Is not
+               'IS-NOT'     => ' IS NOT ',
+               // Is
+               'IS'         => ' IS ',
+               // Equals
+               'EQUALS'     => ' = ',
+       );
+}
+
 // Calls back a function based on given XML template data
-function showEntriesByXmlCallback ($template) {
+function doGenericXmlTemplateCallback ($template, $content = array(), $compileCode = TRUE) {
+       // Init XML system as sch calls will be only used once per run
+       initXml();
+
        // Generate FQFN for with special path
-       $FQFN = sprintf("%stemplates/xml/%s%s.xml",
+       $FQFN = sprintf('%stemplates/xml/%s%s.xml',
                getPath(),
-               detectExtraTemplatePath($template),
+               detectExtraTemplatePath('xml', $template),
                $template
        );
 
        // Is the file readable?
        if (!isFileReadable($FQFN)) {
                // No, use without extra path
-               $FQFN = sprintf("%stemplates/xml/%s.xml",
+               $FQFN = sprintf('%stemplates/xml/%s.xml',
                        getPath(),
                        $template
                );
@@ -60,8 +78,20 @@ function showEntriesByXmlCallback ($template) {
 
        // Is it again readable?
        if (isFileReadable($FQFN)) {
-               // Read it
-               $templateContent = readFromFile($FQFN);
+               // Is there cache?
+               if ((!isDebugTemplateCacheEnabled()) && (isTemplateCached('xml', $template))) {
+                       // Evaluate the cache
+                       $templateContent = readTemplateCache('xml', $template, $content);
+               } else {
+                       // Read it
+                       $templateContent = readFromFile($FQFN);
+
+                       // Prepare it for finaly eval() command
+                       $GLOBALS['template_eval']['xml'][$template] = '$templateContent = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($templateContent), TRUE, $compileCode) . '");';
+
+                       // Eval the code, this does insert any array elements from $content
+                       eval($GLOBALS['template_eval']['xml'][$template]);
+               }
 
                // Init main arrays
                $GLOBALS['__XML_CALLBACKS'] = array(
@@ -69,10 +99,15 @@ function showEntriesByXmlCallback ($template) {
                        'functions' => array()
                );
                $GLOBALS['__XML_ARGUMENTS'] = array();
+               $GLOBALS['__COLUMN_INDEX']  = array();
+               $GLOBALS['__XML_CONTENT']   = $content;
 
                // Handle it over to the parser
                parseXmlData($templateContent);
 
+               // Add special elements, e.g. column index
+               addXmlSpecialElements($template);
+
                // Call the call-back function
                doCallXmlCallbackFunction();
        } else {
@@ -81,22 +116,37 @@ function showEntriesByXmlCallback ($template) {
        }
 }
 
+// Adds special elements by calling back another template-depending function
+function addXmlSpecialElements ($template) {
+       // Generate the FQCN (Full-Qualified Callback Name)
+       $FQCN = 'addXmlSpecial' . capitalizeUnderscoreString($template);
+
+       // Is it there?
+       if (function_exists($FQCN)) {
+               // Call it
+               call_user_func($FQCN);
+       } elseif (isDebugModeEnabled()) {
+               // This callback function is only optional
+               logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $FQCN . ' for template ' . $template . ' does not exist.');
+       }
+}
+
 // Parses the XML content
 function parseXmlData ($content) {
-       // Do we have recode?
-       if (function_exists('recode')) {
-               // Convert 'HTML' to UTF-8
-               $content = recode('html..utf8', $content);
-       } else {
+       // Is there recode?
+       if (!extension_loaded('recode')) {
                // No fallback ATM
-               debug_report_bug('PHP extension recode is missing. Please install it.');
-       }
+               reportBug(__FUNCTION__, __LINE__, 'PHP extension recode is missing. Please install it.');
+       } // END - if
+
+       // Convert HTML entities to UTF-8
+       $content = recode('html..utf8', $content);
 
        // Create a new XML parser
        $xmlParser = xml_parser_create();
 
        // Force case-folding to on
-       xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
+       xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
 
        // Set UTF-8
        xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
@@ -109,7 +159,7 @@ function parseXmlData ($content) {
        if (!xml_parse($xmlParser, $content)) {
                // Error found in XML!
                //* DEBUG: */ die('<pre>'.htmlentities($content).'</pre>');
-               debug_report_bug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
+               reportBug(__FUNCTION__, __LINE__, 'Error found in XML. errorMessage=' . xml_error_string(xml_get_error_code($xmlParser)) . ', line=' . xml_get_current_line_number($xmlParser));
        } // END - if
 
        // Free the parser
@@ -120,7 +170,7 @@ function parseXmlData ($content) {
 function doCallXmlCallbackFunction () {
        // Loop through all added entries
        foreach ($GLOBALS['__XML_CALLBACKS']['callbacks'] as $callback) {
-               // Do we have the entry?
+               // Is there the entry?
                if ((isset($GLOBALS['__XML_CALLBACKS']['functions'][$callback])) && (isset($GLOBALS['__XML_ARGUMENTS'][$callback]))) {
                        // Run all function callbacks
                        foreach ($GLOBALS['__XML_CALLBACKS']['functions'][$callback] as $function) {
@@ -138,15 +188,16 @@ function doCallXmlCallbackFunction () {
 
                                // Is it there?
                                if (!function_exists($callbackName)) {
-                                       debug_report_bug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . 'arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ' - execute call-back not found.');
+                                       // No, then please add it
+                                       reportBug(__FUNCTION__, __LINE__, 'callback=' . $callback . ',function=' . $function . ',arguments()=' . count($GLOBALS['__XML_ARGUMENTS'][$callback]) . ',content()=' . count($GLOBALS['__XML_CONTENT']) . ' - execute call-back does not exist.');
                                } // END - if
 
                                // Call it
-                               call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback]));
+                               call_user_func_array($callbackName, array($function, $GLOBALS['__XML_ARGUMENTS'][$callback], $GLOBALS['__COLUMN_INDEX'][$callback], $GLOBALS['__XML_CONTENT']));
                        } // END - foreach
                } else {
                        // Not found
-                       debug_report_bug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
+                       reportBug(__FUNCTION__, __LINE__, 'Entry in callbacks does exist, but not in functions, callback= ' . $callback);
                }
        } // END - foreach
 }
@@ -163,7 +214,7 @@ function startXmlElement ($resource, $element, $attributes) {
        // Is the call-back function there?
        if (!function_exists($elementCallback)) {
                // Not there
-               debug_report_bug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
+               reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $elementCallback . ', please add it.');
        } // END - if
 
        // Call the call-back function
@@ -180,14 +231,14 @@ function xmlCharacterHandler ($resource, $characters) {
        // Trim spaces away
        $characters = trim($characters);
 
-       // Do we have some to handle?
-       if (strlen($characters) == 0) {
+       // Are there some to handle?
+       if (empty($characters)) {
                // Nothing to handle
                return;
        } // END - if
 
        // @TODO Handle characters
-       die(__FUNCTION__ . ':characters[]='.strlen($characters));
+       die(__FUNCTION__ . ':characters[' . gettype($characters) . ']=' . strlen($characters));
 }
 
 // Checks if given type is valid, makes all lower-case
@@ -205,41 +256,226 @@ function isXmlConditionValid ($condition) {
        $condition = trim(strtolower($condition));
 
        // Is it valid?
-       return (in_array($condition, array('equals')));
+       return (in_array($condition, array('equals', 'and')));
 }
 
 // Checks if given value is valid/verifyable
 function isXmlValueValid ($type, $value) {
        // Depends on type, so build a call-back
-       $callbackFunction = 'isXmlType' . trim(capitalizeUnderscoreString($type));
+       $callbackName = 'isXmlType' . trim(capitalizeUnderscoreString($type));
 
        // Is the call-back function there?
-       if (!function_exists($callbackFunction)) {
+       if (!function_exists($callbackName)) {
                // Not there
-               debug_report_bug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackFunction . ', please add it.');
+               reportBug(__FUNCTION__, __LINE__, 'Missing call-back function ' . $callbackName . ', please add it.');
        } // END - if
 
        // Call and return it
-       return call_user_func_array($callbackFunction, array($value));
+       return call_user_func_array($callbackName, array($value));
 }
 
 // Converts given condition into a symbol
 function convertXmlContion ($condition) {
-       // Default is an invalid one
-       $return = '???';
-
        // Detect the condition again
-       switch ($condition) {
-               case 'EQUALS': // Equals
-                       $return = '=';
-                       break;
+       if (!isset($GLOBALS['__XML_CONDITIONS'][$condition])) {
+               reportBug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
+       } // END - if
+
+       // Return it
+       return $GLOBALS['__XML_CONDITIONS'][$condition];
+}
+
+// "Getter" for FROM statement from given columns
+function getSqlXmlFromTable ($tableName) {
+       // Init SQL
+       $sql = ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0]['value'] . '`';
+
+       // Is alias set?
+       if (!empty($tableName[0]['alias'])) {
+               // Also add it
+               $sql .= ' AS `' . $tableName[0]['alias'] . '`';
+       } // END - if
+
+       // Return SQL
+       return $sql;
+}
+
+// "Getter" for sql part back from given array
+function getSqlPartFromXmlArray ($columns) {
+       // Init SQL
+       $sql = '';
+
+       // Walk through all entries
+       foreach ($columns as $columnArray) {
+               // Must be an array
+               assert(is_array($columnArray));
+
+               // Init SQL part
+               $sqlPart = '';
+
+               // Is there a table/alias
+               if (!empty($columnArray['table'])) {
+                       // Pre-add it
+                       $sqlPart .= '`' . $columnArray['table'] . '`.';
+               } // END - if
 
-               default: // Unknown condition
-                       debug_report_bug(__FUNCTION__, __LINE__, 'Condition ' . $condition . ' is unknown/unsupported.');
+               // Add column
+               $sqlPart .= '`' . $columnArray['column'] . '`';
+
+               // Is a function and alias set?
+               if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
+                       // Add both
+                       $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
+               } // END - if
+
+               // Add finished SQL part to the query
+               $sql .= $sqlPart . ',';
+       } // END - foreach
+
+       // Return it without last commata
+       return substr($sql, 0, -1);
+}
+
+// "Getter" for JOIN statement
+function getSqlXmlJoinedTable ($tableJoinType, $tableJoinName, $joinOnLeftTable, $joinOnCondition, $joinOnRightTable) {
+       // Are all set?
+       assert((isFilledArray($tableJoinType)) && (isFilledArray($tableJoinName)) && (isFilledArray($joinOnLeftTable)) && (isFilledArray($joinOnCondition)) && (isFilledArray($joinOnRightTable)));
+
+       // Init SQL
+       $sql = '';
+
+       // "Walk" through all JOINs
+       foreach ($tableJoinType as $key => $joinType) {
+               // 1) Add JOIN type and table name with alias
+               $sql .= ' ' . $joinType . ' `{?_MYSQL_PREFIX?}_' . $tableJoinName[$key]['name'] . '`';
+
+               // Alias set?
+               if (!empty($tableJoinName[$key]['alias'])) {
+                       // Add it
+                       $sql .= ' AS `' . $tableJoinName[$key]['alias'] . '`';
+               } // END - if
+
+               // 2) Add left part + condition + right part with aliases
+               // 2/1) ON + left part
+               $sql .= ' ON `' . $joinOnLeftTable[$key]['name'] . '`.`' . $joinOnLeftTable[$key]['column'] . '`';
+               // 2/2) Condition
+               $sql .= $joinOnCondition[$key];
+               // 2/3) right part
+               $sql .= '`' . $joinOnRightTable[$key]['name'] . '`.`' . $joinOnRightTable[$key]['column'] . '`';
+       } // END - foreach
+
+       // Return SQL
+       return $sql;
+}
+
+// "Getter" for WHERE statement from given columns and conditions arrays
+function getSqlXmlWhereConditions ($whereColumns, $conditions) {
+       // Init SQL
+       $sql = '';
+
+       // Are there some conditions?
+       if (isFilledArray($whereColumns)) {
+               // Then add these as well
+               if (count($whereColumns) == 1) {
+                       // One entry found
+                       $sql .= ' WHERE ';
+
+                       // Table/alias included?
+                       if (!empty($whereColumns[0]['table'])) {
+                               // Add it as well
+                               $sql .= $whereColumns[0]['table'] . '.';
+                       } // END - if
+
+                       // Add the rest
+                       $sql .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
+               } elseif ((count($whereColumns > 1)) && (isFilledArray($conditions))) {
+                       // More than one "WHERE" + condition found
+                       foreach ($whereColumns as $idx => $columnArray) {
+                               // Default is WHERE
+                               $condition = ' WHERE ';
+
+                               // Is the condition element there?
+                               if (isset($conditions[$columnArray['column']])) {
+                                       // Assume the condition
+                                       $condition = ' ' . $conditions[$columnArray['column']] . ' ';
+                               } // END - if
+
+                               // Add to SQL query
+                               $sql .= $condition;
+
+                               // Table/alias included?
+                               if (!empty($whereColumns[$idx]['table'])) {
+                                       // Add it as well
+                                       $sql .= $whereColumns[$idx]['table'] . '.';
+                               } // END - if
+
+                               // Add the rest
+                               $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
+                       } // END - foreach
+               } else {
+                       // Did not set $conditions
+                       reportBug(__FUNCTION__, __LINE__, 'Supplied more than &quot;whereColumns&quot; entries but no conditions! Please fix your XML template.');
+               }
+       } // END - if
+
+       // Return SQL
+       return $sql;
+}
+
+// "Getter" for ORDER BY statement from given columns
+function getSqlXmlOrderBy ($orderByColumns) {
+       // Init SQL
+       $sql = '';
+
+       // Are there entries from orderByColumns to add?
+       if (isFilledArray($orderByColumns)) {
+               // Add them as well
+               $sql .= ' ORDER BY ';
+               foreach ($orderByColumns as $orderByColumn => $array) {
+                       // Get keys (table/alias) and values (sorting itself)
+                       $table   = trim(implode('', array_keys($array)));
+                       $sorting = trim(implode('', array_values($array)));
+
+                       // table/alias can be omitted
+                       if (!empty($table)) {
+                               // table/alias is given
+                               $sql .= '`' . $table . '`.';
+                       } // END - if
+
+                       // Add order-by column
+                       $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
+               } // END - foreach
+
+               // Remove last column
+               $sql = substr($sql, 0, -1);
+       } // END - if
+
+       // Return SQL
+       return $sql;
+}
+
+// Searches in given XML array for value and returns the parent index
+function searchXmlArray ($value, $columns, $childKey) {
+       // Default is not found
+       $return = FALSE;
+
+       // Walk through whole array
+       foreach ($columns as $key => $columnArray) {
+               // Make sure the element is there
+               assert(isset($columnArray[$childKey]));
+
+               // Now is it what we are looking for?
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',key=' . $key . ',childKey=' . $childKey . ',columnArray=' . $columnArray[$childKey]);
+               if ($columnArray[$childKey] === $value) {
+                       // Remember this match
+                       $return = $key;
+
+                       // And abort any further searches
                        break;
-       } // END - switch
+               } // END - if
+       } // END - foreach
 
-       // Return it
+       // Return key/false
        return $return;
 }