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