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