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