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