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