Rewrote 'we' word a little, rewrote mail order to use SQL_INSERTID() instead of anoth...
[mailer.git] / inc / libs / yoomedia_functions.php
index 4ed0f57bbd2df9291e94156ebce33c2ba97c2452..bedb886982080d2d197b8df02e93aef986692bfb 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 10/10/2008 *
- * ===============                              Last change: 10/10/2008 *
+ * Mailer v0.2.1-FINAL                                Start: 10/10/2008 *
+ * ===================                          Last change: 10/10/2008 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : yoomedia_functions.php                           *
  * $Date::                                                            $ *
  * $Tag:: 0.2.1-FINAL                                                 $ *
  * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder                           *
- * For more information visit: http://www.mxchange.org                  *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
+ * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * it under the terms of the GNU General Public License as published by *
 
 // Some security stuff...
 if (!defined('__SECURITY')) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
-       require($INC);
+       die();
+} // END - if
+
+// Queries the given Yoo!Media API 2.0 script
+function YOOMEDIA_QUERY_API ($script, $countQuery = true) {
+       // Init response array
+       $response = array();
+
+       // Enougth queries left?
+       if ((getConfig('yoomedia_requests_remain') > 0) || ($countQuery === false)) {
+               // Prepare request array
+               $requestData = array(
+                       'id'         => getConfig('yoomedia_id'),
+                       'sid'        => getConfig('yoomedia_sid'),
+                       'pw'         => getConfig('yoomedia_passwd'),
+                       'reload'     => getConfig('yoomedia_tm_max_reload'),
+                       'ma'         => getConfig('yoomedia_tm_min_wait'),
+                       'uebrig'     => getConfig('yoomedia_tm_clicks_remain'),
+                       'verguetung' => getConfig('yoomedia_tm_min_pay'),
+                       'erotik'     => getConfig('yoomedia_erotic_allowed')
+               );
+
+               // Run the query
+               $response = sendGetRequest('http://www.yoomedia.de/interface_2.0/' . $script, $requestData, true);
+
+               // Convert from ISO to UTF-8 only if count is > 3 because <= 3 means timeout
+               if (count($response) > 3) {
+                       // Convert all lines to UTF-8
+                       foreach ($response as $k => $v) {
+                               // Convert the line
+                               $response[$k] = iconv('windows-1252', 'UTF-8//TRANSLIT', $v);
+                       } // END - foreach
+               } // END - if
+
+               // Shall we count the query as used?
+               if ($countQuery === true) {
+                       // Then update the config!
+                       updateConfiguration('yoomedia_requests_remain', 1, '-');
+               } // END - if
+       } // END - if
+
+       // Return the data
+       return $response;
 }
 
 // Test if the extension settings did work
 function YOOMEDIA_TEST_CONFIG ($data) {
        // Is this admin?
-       if (!IS_ADMIN()) {
+       if (!isAdmin()) {
                // No admin!
                return false;
        } // END - if
 
-       // Transfer config data
+       // Remove 'ok'
+       unset($data['ok']);
+
+       // Merge config
        mergeConfig($data);
 
        // Temporary allow maximum
-       setConfigEntry('yoomedia_tm_max_reload'   , 100000);
-       setConfigEntry('yoomedia_tm_min_wait'     , 0);
-       setConfigEntry('yoomedia_tm_clicks_remain', 10);
-       setConfigEntry('yoomedia_tm_min_pay'      , 0);
-       setConfigEntry('yoomedia_erotic_allowed'  , 1);
+       setConfigEntry('yoomedia_tm_max_reload'   , '100000');
+       setConfigEntry('yoomedia_tm_min_wait'     , '1000');
+       setConfigEntry('yoomedia_tm_clicks_remain', '10');
+       setConfigEntry('yoomedia_tm_min_pay'      , '0.00001');
+       setConfigEntry('yoomedia_erotic_allowed'  , '1');
 
        // Query the API with a test request without couting it
        // If zero reply comes back the data is invalid!
@@ -68,62 +111,24 @@ function YOOMEDIA_TEST_CONFIG ($data) {
        $errorCode = YOOMEDIA_GET_ERRORCODE_FROM_RESULT($response);
 
        // Log the response if failed
-       if (count($response) == 0) {
+       if ((count($response) == 0) && ($errorCode > 0)) {
                // Queries depleted (as we count here!)
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Requested depleted. Maxmimum was: " . getConfig('yoomedia_requests_total'));
-               $errorCode = -1;
-       } elseif (!isset($response[8])) {
-               // Invalid response
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Missing response line [8]. Raw response=" . base64_encode(serialize($response)));
+               logDebugMessage(__FUNCTION__, __LINE__, 'Requested depleted. Maxmimum was: ' . getConfig('yoomedia_requests_total') . ',errorCode=' . $errorCode);
                $errorCode = -1;
        } elseif ((($errorCode <= 4) && ($errorCode > 0)) || ($errorCode >= 8)) {
                // An error has returned from the account
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Unexpected error code " . $errorCode . " received.");
-       } elseif (count($response) < 9) {
+               logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected error code ' . $errorCode . ' received.');
+       } elseif ((count($response) > 0) && ($errorCode != 0)) {
                // Log serialized raw response
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Raw response=" . base64_encode(serialize($response)));
+               logDebugMessage(__FUNCTION__, __LINE__, 'errorCode=' . $errorCode . ',response=' . base64_encode(serialize($response)));
                $errorCode = -1;
        } else {
                // This is fine, because the result array is okay and the response code on element 8 is fine
-               $errorCode = 0;
+               $errorCode = '0';
        }
 
-       // Do we have some data there?
-       return ($errorCode == 0);
-}
-
-// Queries the given Yoo!Media API 2.0 script
-function YOOMEDIA_QUERY_API ($script, $countQuery = true) {
-       // Init response array
-       $response = array();
-
-       // Enougth queries left?
-       if ((getConfig('yoomedia_requests_remain') > 0) || (!$countQuery)) {
-               // Prepare the low-level request
-               $requestString = sprintf("http://www.yoomedia.de/interface_2.0/%s?id=%s&sid=%s&pw=%s&reload=%s&ma=%s&uebrig=%s&verguetung=%s&erotik=%s",
-                       $script,
-                       getConfig('yoomedia_id'),
-                       getConfig('yoomedia_sid'),
-                       getConfig('yoomedia_passwd'),
-                       getConfig('yoomedia_tm_max_reload'),
-                       getConfig('yoomedia_tm_min_wait'),
-                       getConfig('yoomedia_tm_clicks_remain'),
-                       getConfig('yoomedia_tm_min_pay'),
-                       getConfig('yoomedia_erotic_allowed')
-               );
-
-               // Run the query
-               $response = sendGetRequest($requestString);
-
-               // Shall we count the query as used?
-               if ($countQuery === true) {
-                       // Then update the config!
-                       updateConfiguration('yoomedia_requests_remain', 1, '-');
-               } // END - if
-       } // END - if
-
-       // Return the data
-       return $response;
+       // Is some data there?
+       return ($errorCode == '0');
 }
 
 // "Getter" for a parsed result for all text mails. This means an array without
@@ -132,8 +137,13 @@ function YOOMEDIA_GET_PARSED_RESULT_TEXTMAILS () {
        // Get the raw response
        $response = YOOMEDIA_QUERY_API('out_textmail.php');
 
+       // By default an empty result is returned
+       $result = array();
+
        // Parse the response
-       $result = YOOMEDIA_PARSE_RESPONSE($response, 'textmail');
+       if (count($response) > 0) {
+               $result = YOOMEDIA_PARSE_RESPONSE($response, 'textmail');
+       } // END - if
 
        // Return result
        return $result;
@@ -145,41 +155,40 @@ function YOOMEDIA_PARSE_RESPONSE ($response, $type) {
        $result = array();
 
        // Cut off the header
-       $dummy = $response;
-       foreach ($response as $line) {
-               // Remove line
-               array_shift($dummy);
-
-               // Is this line empty?
-               if (empty($line)) {
-                       // Then stop here
-                       break;
-               } // END - if
-       } // END - foreach
+       $dummy = removeHttpHeaderFromResponse($response);
+
+       // If we have no result, abort here
+       if (count($dummy) == 0) {
+               // Empty response from API
+               reportBug(__FUNCTION__, __LINE__, 'Empty result from API received. response()=' . count($response) . ',type=' . $type);
+               return array();
+       } // END - if
 
        // The result is now still raw, so we must split it up and trim spaces away
-       $responseLine = trim(implode("\n", $dummy));
+       $responseLine = trim(implode(chr(10), $dummy));
 
        // Last line should never be a pipe!
-       if (substr($responseLine, -1, 1) == '|') $responseLine = substr($responseLine, 0, -1);
+       if (substr($responseLine, -1, 1) == '|') {
+               $responseLine = substr($responseLine, 0, -1);
+       } // END - if
 
        // Now, explode all in one array
        $dataArray = explode('|', $responseLine);
 
        // Now make the result array with two dimensions
-       $cnt = 0; $entry = 0;
+       $count = '0'; $entry = '0';
        foreach ($dataArray as $line) {
                // Add the line
-               $result[$entry][yoomediaTranslateIndex($type, $cnt)] = $line;
+               $result[$entry][yoomediaTranslateIndex($type, $count)] = $line;
 
                // End of data of first entry reached?
-               if ($cnt == 6) {
+               if ($count == 6) {
                        // Then advance to next entry and reset counter
                        $entry++;
-                       $cnt = 0;
+                       $count = '0';
                } else {
                        // Count up
-                       $cnt++;
+                       $count++;
                }
        } // END - foreach
 
@@ -190,89 +199,88 @@ function YOOMEDIA_PARSE_RESPONSE ($response, $type) {
 // Prepares a bonus mail for delivery. Works only if extension 'bonus' is active
 function YOOMEDIA_PREPARE_MAIL_DELIVERY ($data) {
        // Is this an admin?
-       if (!IS_ADMIN()) {
+       if (!isAdmin()) {
                // Abort here
                return false;
-       } elseif (!EXT_IS_ACTIVE('bonus')) {
+       } elseif (!isExtensionActive('bonus')) {
                // Abort here
                return false;
        }
 
        // Is the waiting time below one second? Then fix it to one (zero seconds are not yet supported!)
-       if ($data['wait'] < 1) $data['wait'] = 1;
+       if ($data['wait'] < 1) {
+               $data['wait'] = 1;
+       } // END - if
 
        // Half of waiting time is a good reward!
        $data['reward'] = round($data['wait'] / 2 + 0.4);
 
        // Is the reward below one?
-       if ($data['reward'] < 1) $data['reward'] = 1;
-
-       // Add website id
-       $data['sid'] = getConfig('yoomedia_sid');
-
-       // Add total receivers
-       $data['all'] = translateComma(getTotalReceivers());
-
-       // Add categories
-       $data['categories'] = generateCategoryOptionsList('normal');
+       if ($data['reward'] < 1) {
+               $data['reward'] = 1;
+       } // END - if
 
        // Load template
-       LOAD_TEMPLATE("admin_send_yoomedia", false, $data);
+       loadTemplate('admin_send_yoomedia', false, $data);
 }
 
 // Adds the mail to the bonus mail pool
-function YOOMEDIA_SEND_BONUS_MAIL ($data, $mode) {
+function YOOMEDIA_SEND_BONUS_MAIL ($data, $mailMode) {
        // Is this an admin?
-       if (!IS_ADMIN()) {
+       if (!isAdmin()) {
                // Abort here
                return false;
-       } elseif (!EXT_IS_ACTIVE('bonus')) {
+       } elseif (!isExtensionActive('bonus')) {
                // Abort here
                return false;
        }
 
        // Add dummy receiver to avoid notice
-       $data['receiver'] = 0;
+       $data['receiver'] = '0';
 
        // HTML or normal? (normal is default...)
        $type = 't';
-       if (($mode == 'html') && (EXT_IS_ACTIVE('html_mail'))) $type = 'h';
+       if (($mailMode == 'html') && (isExtensionActive('html_mail'))) $type = 'h';
 
        // Auto-generate URL
        $data['url'] = sprintf("http://www.yoomedia.de/code/%s-mail.php?id=%s&sid=%s",
-       $type,
-       $data['id'],
-       $data['sid']
+               $type,
+               $data['id'],
+               $data['sid']
        );
 
        // Lock this mail for new delivery
-       YOOMEDIA_RELOAD_LOCK($data, $mode);
+       YOOMEDIA_RELOAD_LOCK($data, $mailMode);
 
        // Call the lower function
-       addNewBonusMail($data, $mode);
+       addNewBonusMail($data, $mailMode);
 }
 
 // Lockdown given id
-function YOOMEDIA_EXCLUDE_MAIL ($data, $mode) {
+function YOOMEDIA_EXCLUDE_MAIL ($data, $mailMode) {
        // Search for the entry
-       if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
+       if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mailMode) === false) {
                // Convert mode for mails
-               $mode = YOOMEDIA_CONVERT_MODE($mode);
+               $mailMode = YOOMEDIA_CONVERT_MODE($mailMode);
 
                // Add the entry
-               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_yoomedia_reload` (`type`,`y_id`,`y_reload`,`inserted`) VALUES ('%s',%s,%s,'0000-00-00 00:00')",
-               array($mode, bigintval($data['id']), bigintval($data['reload'])), __FUNCTION__, __LINE__);
+               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`,`inserted`) VALUES ('%s',%s,%s,'0000-00-00 00:00')",
+                       array(
+                               $mailMode,
+                               bigintval($data['id']),
+                               bigintval($data['reload'])
+                       ), __FUNCTION__, __LINE__);
        } // END - if
 }
 
 // Remove lock of given mail
-function YOOMEDIA_UNLIST_MAIL ($data, $mode) {
+function YOOMEDIA_UNLIST_MAIL ($data, $mailMode) {
        // Convert mode for mails
-       $mode = YOOMEDIA_CONVERT_MODE($mode);
+       $mailMode = YOOMEDIA_CONVERT_MODE($mailMode);
 
        // Add the entry
-       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
-       array($mode, bigintval($data['id'])), __FUNCTION__, __LINE__);
+       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
+               array($mailMode, bigintval($data['id'])), __FUNCTION__, __LINE__);
 }
 
 // "Translates" the index number into an assosiative value
@@ -285,8 +293,8 @@ function yoomediaTranslateIndex ($type, $index) {
                // Use this element
                $return = $GLOBALS['translation_tables']['yoomedia'][$type][$index];
        } else {
-               // Not found!
-               DEBUG_LOG(__FUNCTION__, __LINE__, "type={$type},index={$index} not found.");
+               // Not found
+               logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',index=' . $index . ' not found');
        }
 
        // Return value
@@ -294,20 +302,17 @@ function yoomediaTranslateIndex ($type, $index) {
 }
 
 // "Translate" error code
-function yoomediaTranslateError ($errorCode) {
+function translateYooMediaError ($errorCode) {
        // Default is 'failed'
-       $return = 'failed';
+       $return = 'failed (Code: ' . $errorCode . ')';
 
        // Is the entry there?
        if (isset($GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode])) {
-               // Entry found!
+               // Entry found
                $return = $GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode];
        } else {
                // Log missing entries
-               DEBUG_LOG(__FUNCTION__, __LINE__, "errorCode={$errorCode}");
-               print('<pre>');
-               debug_print_backtrace();
-               die('</pre>');
+               reportBug(__FUNCTION__, __LINE__, sprintf("Unknown error code <strong>%s[%s]</strong> detected.", $errorCode, gettype($errorCode)));
        }
 
        // Return value
@@ -320,7 +325,7 @@ function YOOMEDIA_CHECK_RELOAD ($id, $reload, $type) {
        $reloaded = false;
 
        // Query database
-       $result = SQL_QUERY_ESC("SELECT `id`, UNIX_TIMESTAMP(`inserted`) AS inserted FROM `{!_MYSQL_PREFIX!}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
+       $result = SQL_QUERY_ESC("SELECT `id`, UNIX_TIMESTAMP(`inserted`) AS inserted FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
                array($type, bigintval($id)), __FUNCTION__, __LINE__);
 
        // Entry found?
@@ -331,8 +336,8 @@ function YOOMEDIA_CHECK_RELOAD ($id, $reload, $type) {
                // Are we ready to sent again?
                if (((time() - $time) >= ($reload * 60*60)) && ($time > 0)) {
                        // Remove entry
-                       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_yoomedia_reload` WHERE `id`=%s LIMIT 1",
-                       array($id), __FUNCTION__, __LINE__);
+                       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `id`=%s LIMIT 1",
+                               array($id), __FUNCTION__, __LINE__);
                } else {
                        // Dont' sent again this mail
                        $reloaded = $time;
@@ -347,65 +352,86 @@ function YOOMEDIA_CHECK_RELOAD ($id, $reload, $type) {
 }
 
 // Lock given mail down for reload lock
-function YOOMEDIA_RELOAD_LOCK ($data, $mode) {
+function YOOMEDIA_RELOAD_LOCK ($data, $mailMode) {
        // Search for the entry
-       if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
+       if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mailMode) === false) {
                // Convert mode for mails
-               $mode = YOOMEDIA_CONVERT_MODE($mode);
+               $mailMode = YOOMEDIA_CONVERT_MODE($mailMode);
 
                // Add the entry
-               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_yoomedia_reload` (`type`,`y_id`,`y_reload`) VALUES ('%s',%s,%s)",
-                       array($mode, bigintval($data['id']), bigintval($data['reload'])), __FUNCTION__, __LINE__);
+               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`) VALUES ('%s',%s,%s)",
+                       array($mailMode, bigintval($data['id']), bigintval($data['reload'])), __FUNCTION__, __LINE__);
        } // END - if
 }
 
 // Convert mode for mails
-function YOOMEDIA_CONVERT_MODE ($mode) {
+function YOOMEDIA_CONVERT_MODE ($mailMode) {
        // Convert mode for normal/html
-       switch ($mode) {
+       switch ($mailMode) {
                case 'normal':
-                       $mode = "textmail";
+                       $mailMode = 'textmail';
                        break;
 
                case 'html':
-                       $mode = "htmlmail";
+                       $mailMode = 'htmlmail';
                        break;
        } // END - switch
 
        // Return result
-       return $mode;
+       return $mailMode;
 }
 
 // Extract code from response
-function YOOMEDIA_GET_ERRORCODE_FROM_RESULT (array $response) {
+function YOOMEDIA_GET_ERRORCODE_FROM_RESULT ($response) {
+       // The response must be an array
+       assert(is_array($response));
+
        // Bad code as default
        $code = -999;
 
        // Which response should we parse?
-       if (isset($response[8])) {
+       if ((isset($response[8])) && (count($response) == 9)) {
                // Use error code from element 8 (mostly API errors)
-               $codeArray = explode("<br>", $response[8]);
+               $codeArray = explode('<br>', $response[8]);
 
                // Use only the first element
                $code = bigintval($codeArray[0]);
-       } elseif (isset($response[0]['id'])) {
-               // Begin with extraction
-               $codeArray = explode(" ", $response[0]['id']);
-               $code = $codeArray[0];
-               $codeArray = explode("<br />", $code);
-               $code = $codeArray[0];
-               $codeArray = explode("<br>", $code);
-               $code = $codeArray[0];
-
-               // Remove all new-line characters
-               $codeArray = explode("\n", $code);
-               $code = $codeArray[0];
-
-               // Remove carrige-return
-               $code = str_replace("\n", '', $code);
+       } elseif (!empty($response[0])) {
+               // Merge response together
+               $parts = explode('|', implode('', $response));
+
+               // If we have only one part, we got an error
+               if (count($parts) > 1) {
+                       // All fine
+                       $code = '0';
+               } else {
+                       // Begin with extraction of error code
+                       $codeArray = explode(' ', $response[0]);
+                       $code = $codeArray[0];
+                       $codeArray = explode('<br />', $code);
+                       $code = $codeArray[0];
+                       $codeArray = explode('<br>', $code);
+                       $code = $codeArray[0];
+
+                       // Remove all new-line characters
+                       $codeArray = explode(chr(10), $code);
+                       $code = $codeArray[0];
+
+                       // Remove carrige-return
+                       $code = trim(str_replace(chr(10), '', $code));
+
+                       // Is it still empty?
+                       if (empty($code)) {
+                               // Then fix it
+                               $code = -999;
+                       } // END - if
+               }
+       } elseif (count($response) == 0) {
+               // All fine, but empty result
+               $code = '0';
        } else {
                // Should not happen!
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot parse response. Raw response=" . base64_encode(serialize($response)));
+               reportBug(__FUNCTION__, __LINE__, 'Cannot parse response. Raw response:<pre>' . print_r($response, true) . '</pre>');
        }
 
        // Return error code