3e02dff95c2d6f3b06a1bf00a53e4b0493b0d40a
[mailer.git] / inc / libs / yoomedia_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/10/2008 *
4  * ===================                          Last change: 10/10/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : yoomedia_functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : Special functions for yoomedia extension         *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Spezielle Funktion fuer Yoo!Media-Erweiterung    *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Queries the given Yoo!Media API 2.0 script
44 function YOOMEDIA_QUERY_API ($script, $countQuery = true) {
45         // Init response array
46         $response = array();
47
48         // Enougth queries left?
49         if ((getConfig('yoomedia_requests_remain') > 0) || ($countQuery === false)) {
50                 // Prepare the low-level request
51                 $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",
52                         $script,
53                         getConfig('yoomedia_id'),
54                         getConfig('yoomedia_sid'),
55                         getConfig('yoomedia_passwd'),
56                         getConfig('yoomedia_tm_max_reload'),
57                         getConfig('yoomedia_tm_min_wait'),
58                         getConfig('yoomedia_tm_clicks_remain'),
59                         getConfig('yoomedia_tm_min_pay'),
60                         getConfig('yoomedia_erotic_allowed')
61                 );
62
63                 // Run the query
64                 $response = sendGetRequest($requestString);
65
66                 // Convert from ISO to UTF-8 only if count is > 3 because <= 3 means timeout
67                 if (count($response) > 3) {
68                         // Convert all lines to UTF-8
69                         foreach ($response as $k => $v) {
70                                 // Convert the line
71                                 $response[$k] = iconv('windows-1252', 'UTF-8//TRANSLIT', $v);
72                                 /*
73                                 // iconv()-less ISO-8859-1 -> UTF-8
74                                 $response[$k] = preg_replace(
75                                         "/([\x80-\xFF])/e",
76                                         "chr(0xC0|ord('\\1')>>6).chr(0x80|ord('\\1')&0x3F)",
77                                         $v
78                                 );
79                                 */
80                         } // END - foreach
81                 } // END - if
82
83                 // Shall we count the query as used?
84                 if ($countQuery === true) {
85                         // Then update the config!
86                         updateConfiguration('yoomedia_requests_remain', 1, '-');
87                 } // END - if
88         } // END - if
89
90         // Return the data
91         return $response;
92 }
93
94 // Test if the extension settings did work
95 function YOOMEDIA_TEST_CONFIG ($data) {
96         // Is this admin?
97         if (!isAdmin()) {
98                 // No admin!
99                 return false;
100         } // END - if
101
102         // Transfer config data
103         mergeConfig($data);
104
105         // Temporary allow maximum
106         setConfigEntry('yoomedia_tm_max_reload'   , 100000);
107         setConfigEntry('yoomedia_tm_min_wait'     , 0);
108         setConfigEntry('yoomedia_tm_clicks_remain', 10);
109         setConfigEntry('yoomedia_tm_min_pay'      , 0);
110         setConfigEntry('yoomedia_erotic_allowed'  , 1);
111
112         // Query the API with a test request without couting it
113         // If zero reply comes back the data is invalid!
114         $response = YOOMEDIA_QUERY_API('out_textmail.php', true); // @TODO Ask Yoo!Media for test script
115
116         // Default error code is 0 = all fine!
117         $errorCode = YOOMEDIA_GET_ERRORCODE_FROM_RESULT($response);
118
119         // Log the response if failed
120         if (count($response) == 0) {
121                 // Queries depleted (as we count here!)
122                 logDebugMessage(__FUNCTION__, __LINE__, 'Requested depleted. Maxmimum was: ' . getConfig('yoomedia_requests_total'));
123                 $errorCode = -1;
124         } elseif (!isset($response[8])) {
125                 // Invalid response
126                 logDebugMessage(__FUNCTION__, __LINE__, 'Missing response line [8]. Raw response=' . base64_encode(serialize($response)));
127                 $errorCode = -1;
128         } elseif ((($errorCode <= 4) && ($errorCode > 0)) || ($errorCode >= 8)) {
129                 // An error has returned from the account
130                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected error code ' . $errorCode . ' received.');
131         } elseif (count($response) < 9) {
132                 // Log serialized raw response
133                 logDebugMessage(__FUNCTION__, __LINE__, 'Raw response=' . base64_encode(serialize($response)));
134                 $errorCode = -1;
135         } else {
136                 // This is fine, because the result array is okay and the response code on element 8 is fine
137                 $errorCode = '0';
138         }
139
140         // Do we have some data there?
141         return ($errorCode == '0');
142 }
143
144 // "Getter" for a parsed result for all text mails. This means an array without
145 // the header lines will be returned
146 function YOOMEDIA_GET_PARSED_RESULT_TEXTMAILS () {
147         // Get the raw response
148         $response = YOOMEDIA_QUERY_API('out_textmail.php');
149
150         // Parse the response
151         $result = YOOMEDIA_PARSE_RESPONSE($response, 'textmail');
152
153         // Return result
154         return $result;
155 }
156
157 // Parser function for Yoo!Media API responses
158 function YOOMEDIA_PARSE_RESPONSE ($response, $type) {
159         // Init result
160         $result = array();
161
162         // Cut off the header
163         $dummy = $response;
164         foreach ($response as $line) {
165                 // Remove line
166                 array_shift($dummy);
167
168                 // Is this line empty?
169                 if (empty($line)) {
170                         // Then stop here
171                         break;
172                 } // END - if
173         } // END - foreach
174
175         // If we have no result, abort here
176         if (count($dummy) == 0) {
177                 // Empty response from API
178                 logDebugMessage(__FUNCTION__, __LINE__, 'Empy result from API received.');
179                 return array();
180         } // END - if
181
182         // The result is now still raw, so we must split it up and trim spaces away
183         $responseLine = trim(implode("\n", $dummy));
184
185         // Last line should never be a pipe!
186         if (substr($responseLine, -1, 1) == '|') $responseLine = substr($responseLine, 0, -1);
187
188         // Now, explode all in one array
189         $dataArray = explode('|', $responseLine);
190
191         // Now make the result array with two dimensions
192         $count = '0'; $entry = '0';
193         foreach ($dataArray as $line) {
194                 // Add the line
195                 $result[$entry][yoomediaTranslateIndex($type, $count)] = $line;
196
197                 // End of data of first entry reached?
198                 if ($count == 6) {
199                         // Then advance to next entry and reset counter
200                         $entry++;
201                         $count = '0';
202                 } else {
203                         // Count up
204                         $count++;
205                 }
206         } // END - foreach
207
208         // Return it
209         return $result;
210 }
211
212 // Prepares a bonus mail for delivery. Works only if extension 'bonus' is active
213 function YOOMEDIA_PREPARE_MAIL_DELIVERY ($data) {
214         // Is this an admin?
215         if (!isAdmin()) {
216                 // Abort here
217                 return false;
218         } elseif (!isExtensionActive('bonus')) {
219                 // Abort here
220                 return false;
221         }
222
223         // Is the waiting time below one second? Then fix it to one (zero seconds are not yet supported!)
224         if ($data['wait'] < 1) $data['wait'] = 1;
225
226         // Half of waiting time is a good reward!
227         $data['reward'] = round($data['wait'] / 2 + 0.4);
228
229         // Is the reward below one?
230         if ($data['reward'] < 1) $data['reward'] = 1;
231
232         // Load template
233         loadTemplate('admin_send_yoomedia', false, $data);
234 }
235
236 // Adds the mail to the bonus mail pool
237 function YOOMEDIA_SEND_BONUS_MAIL ($data, $mode) {
238         // Is this an admin?
239         if (!isAdmin()) {
240                 // Abort here
241                 return false;
242         } elseif (!isExtensionActive('bonus')) {
243                 // Abort here
244                 return false;
245         }
246
247         // Add dummy receiver to avoid notice
248         $data['receiver'] = '0';
249
250         // HTML or normal? (normal is default...)
251         $type = 't';
252         if (($mode == 'html') && (isExtensionActive('html_mail'))) $type = 'h';
253
254         // Auto-generate URL
255         $data['url'] = sprintf("http://www.yoomedia.de/code/%s-mail.php?id=%s&sid=%s",
256                 $type,
257                 $data['id'],
258                 $data['sid']
259         );
260
261         // Lock this mail for new delivery
262         YOOMEDIA_RELOAD_LOCK($data, $mode);
263
264         // Call the lower function
265         addNewBonusMail($data, $mode);
266 }
267
268 // Lockdown given id
269 function YOOMEDIA_EXCLUDE_MAIL ($data, $mode) {
270         // Search for the entry
271         if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
272                 // Convert mode for mails
273                 $mode = YOOMEDIA_CONVERT_MODE($mode);
274
275                 // Add the entry
276                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`,`inserted`) VALUES ('%s',%s,%s,'0000-00-00 00:00')",
277                         array(
278                                 $mode,
279                                 bigintval($data['id']),
280                                 bigintval($data['reload'])
281                         ), __FUNCTION__, __LINE__);
282         } // END - if
283 }
284
285 // Remove lock of given mail
286 function YOOMEDIA_UNLIST_MAIL ($data, $mode) {
287         // Convert mode for mails
288         $mode = YOOMEDIA_CONVERT_MODE($mode);
289
290         // Add the entry
291         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
292                 array($mode, bigintval($data['id'])), __FUNCTION__, __LINE__);
293 }
294
295 // "Translates" the index number into an assosiative value
296 function yoomediaTranslateIndex ($type, $index) {
297         // Default is the index
298         $return = $index;
299
300         // Is the element there?
301         if (isset($GLOBALS['translation_tables']['yoomedia'][$type][$index])) {
302                 // Use this element
303                 $return = $GLOBALS['translation_tables']['yoomedia'][$type][$index];
304         } else {
305                 // Not found!
306                 logDebugMessage(__FUNCTION__, __LINE__, "type={$type},index={$index} not found.");
307         }
308
309         // Return value
310         return $return;
311 }
312
313 // "Translate" error code
314 function translateYooMediaError ($errorCode) {
315         // Default is 'failed'
316         $return = 'failed (Code: ' . $errorCode . ')';
317
318         // Is the entry there?
319         if (isset($GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode])) {
320                 // Entry found!
321                 $return = $GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode];
322         } else {
323                 // Log missing entries
324                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown error code <strong>%s[%s]</strong> detected.", $errorCode, gettype($errorCode)));
325         }
326
327         // Return value
328         return $return;
329 }
330
331 // Checks if the mail id is in reload lock
332 function YOOMEDIA_CHECK_RELOAD ($id, $reload, $type) {
333         // Default is not in reload lock
334         $reloaded = false;
335
336         // Query database
337         $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",
338                 array($type, bigintval($id)), __FUNCTION__, __LINE__);
339
340         // Entry found?
341         if (SQL_NUMROWS($result) == 1) {
342                 // Load time
343                 list($id, $time) = SQL_FETCHROW($result);
344
345                 // Are we ready to sent again?
346                 if (((time() - $time) >= ($reload * 60*60)) && ($time > 0)) {
347                         // Remove entry
348                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `id`=%s LIMIT 1",
349                                 array($id), __FUNCTION__, __LINE__);
350                 } else {
351                         // Dont' sent again this mail
352                         $reloaded = $time;
353                 }
354         } // END - if
355
356         // Free result
357         SQL_FREERESULT($result);
358
359         // Return result
360         return $reloaded;
361 }
362
363 // Lock given mail down for reload lock
364 function YOOMEDIA_RELOAD_LOCK ($data, $mode) {
365         // Search for the entry
366         if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
367                 // Convert mode for mails
368                 $mode = YOOMEDIA_CONVERT_MODE($mode);
369
370                 // Add the entry
371                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`) VALUES ('%s',%s,%s)",
372                         array($mode, bigintval($data['id']), bigintval($data['reload'])), __FUNCTION__, __LINE__);
373         } // END - if
374 }
375
376 // Convert mode for mails
377 function YOOMEDIA_CONVERT_MODE ($mode) {
378         // Convert mode for normal/html
379         switch ($mode) {
380                 case 'normal':
381                         $mode = 'textmail';
382                         break;
383
384                 case 'html':
385                         $mode = 'htmlmail';
386                         break;
387         } // END - switch
388
389         // Return result
390         return $mode;
391 }
392
393 // Extract code from response
394 function YOOMEDIA_GET_ERRORCODE_FROM_RESULT ($response) {
395         // Bad code as default
396         $code = -999;
397
398         // Which response should we parse?
399         if ((isset($response[8])) && (count($response) == 9)) {
400                 // Use error code from element 8 (mostly API errors)
401                 $codeArray = explode('<br>', $response[8]);
402
403                 // Use only the first element
404                 $code = bigintval($codeArray[0]);
405         } elseif ((is_array($response[0])) && (isset($response[0]['id']))) {
406                 // Begin with extraction
407                 $codeArray = explode(' ', $response[0]['id']);
408                 $code = $codeArray[0];
409                 $codeArray = explode('<br />', $code);
410                 $code = $codeArray[0];
411                 $codeArray = explode('<br>', $code);
412                 $code = $codeArray[0];
413
414                 // Remove all new-line characters
415                 $codeArray = explode("\n", $code);
416                 $code = $codeArray[0];
417
418                 // Remove carrige-return
419                 $code = str_replace("\n", '', $code);
420
421         } elseif (count($response) < 9) {
422                 // Should not happen!
423                 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot parse response. Raw response:<pre>' . print_r($response, true) . '</pre>');
424         }
425
426         // Fix empty code to bad
427         if (empty($code)) {
428                 $code = -999;
429         } // END - if
430
431         // Return error code
432         return $code;
433 }
434
435 // [EOF]
436 ?>