]> git.mxchange.org Git - mailer.git/blob - inc/libs/yoomedia_functions.php
New functions introduced, several rewrites:
[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 }
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('windows-1252', 'UTF-8//TRANSLIT', $v);
120                         /*
121                         // iconv()-less ISO-8859-1 -> UTF-8
122                         $response[$k] = preg_replace(
123                                 "/([\x80-\xFF])/e",
124                                 "chr(0xC0|ord('\\1')>>6).chr(0x80|ord('\\1')&0x3F)",
125                                 $v
126                         );
127                         */
128                 } // END - if
129
130                 // Shall we count the query as used?
131                 if ($countQuery === true) {
132                         // Then update the config!
133                         updateConfiguration('yoomedia_requests_remain', 1, '-');
134                 } // END - if
135         } // END - if
136
137         // Return the data
138         return $response;
139 }
140
141 // "Getter" for a parsed result for all text mails. This means an array without
142 // the header lines will be returned
143 function YOOMEDIA_GET_PARSED_RESULT_TEXTMAILS () {
144         // Get the raw response
145         $response = YOOMEDIA_QUERY_API('out_textmail.php');
146
147         // Parse the response
148         $result = YOOMEDIA_PARSE_RESPONSE($response, 'textmail');
149
150         // Return result
151         return $result;
152 }
153
154 // Parser function for Yoo!Media API responses
155 function YOOMEDIA_PARSE_RESPONSE ($response, $type) {
156         // Init result
157         $result = array();
158
159         // Cut off the header
160         $dummy = $response;
161         foreach ($response as $line) {
162                 // Remove line
163                 array_shift($dummy);
164
165                 // Is this line empty?
166                 if (empty($line)) {
167                         // Then stop here
168                         break;
169                 } // END - if
170         } // END - foreach
171
172         // If we have no result, abort here
173         if (count($dummy) == 0) {
174                 // Empty response from API
175                 logDebugMessage(__FUNCTION__, __LINE__, 'Empy result from API received.');
176                 return array();
177         } // END - if
178
179         // The result is now still raw, so we must split it up and trim spaces away
180         $responseLine = trim(implode("\n", $dummy));
181
182         // Last line should never be a pipe!
183         if (substr($responseLine, -1, 1) == '|') $responseLine = substr($responseLine, 0, -1);
184
185         // Now, explode all in one array
186         $dataArray = explode('|', $responseLine);
187
188         // Now make the result array with two dimensions
189         $cnt = '0'; $entry = '0';
190         foreach ($dataArray as $line) {
191                 // Add the line
192                 $result[$entry][yoomediaTranslateIndex($type, $cnt)] = $line;
193
194                 // End of data of first entry reached?
195                 if ($cnt == 6) {
196                         // Then advance to next entry and reset counter
197                         $entry++;
198                         $cnt = '0';
199                 } else {
200                         // Count up
201                         $cnt++;
202                 }
203         } // END - foreach
204
205         // Return it
206         return $result;
207 }
208
209 // Prepares a bonus mail for delivery. Works only if extension 'bonus' is active
210 function YOOMEDIA_PREPARE_MAIL_DELIVERY ($data) {
211         // Is this an admin?
212         if (!isAdmin()) {
213                 // Abort here
214                 return false;
215         } elseif (!isExtensionActive('bonus')) {
216                 // Abort here
217                 return false;
218         }
219
220         // Is the waiting time below one second? Then fix it to one (zero seconds are not yet supported!)
221         if ($data['wait'] < 1) $data['wait'] = 1;
222
223         // Half of waiting time is a good reward!
224         $data['reward'] = round($data['wait'] / 2 + 0.4);
225
226         // Is the reward below one?
227         if ($data['reward'] < 1) $data['reward'] = 1;
228
229         // Add website id
230         $data['sid'] = getConfig('yoomedia_sid');
231
232         // Add total receivers
233         $data['all'] = translateComma(getTotalReceivers());
234
235         // Add categories
236         $data['categories'] = generateCategoryOptionsList('normal');
237
238         // Decode entities
239         $data['text'] = decodeEntities($data['text']);
240
241         // Load template
242         loadTemplate('admin_send_yoomedia', false, $data);
243 }
244
245 // Adds the mail to the bonus mail pool
246 function YOOMEDIA_SEND_BONUS_MAIL ($data, $mode) {
247         // Is this an admin?
248         if (!isAdmin()) {
249                 // Abort here
250                 return false;
251         } elseif (!isExtensionActive('bonus')) {
252                 // Abort here
253                 return false;
254         }
255
256         // Add dummy receiver to avoid notice
257         $data['receiver'] = '0';
258
259         // HTML or normal? (normal is default...)
260         $type = 't';
261         if (($mode == 'html') && (isExtensionActive('html_mail'))) $type = 'h';
262
263         // Auto-generate URL
264         $data['url'] = sprintf("http://www.yoomedia.de/code/%s-mail.php?id=%s&sid=%s",
265                 $type,
266                 $data['id'],
267                 $data['sid']
268         );
269
270         // Lock this mail for new delivery
271         YOOMEDIA_RELOAD_LOCK($data, $mode);
272
273         // Call the lower function
274         addNewBonusMail($data, $mode);
275 }
276
277 // Lockdown given id
278 function YOOMEDIA_EXCLUDE_MAIL ($data, $mode) {
279         // Search for the entry
280         if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
281                 // Convert mode for mails
282                 $mode = YOOMEDIA_CONVERT_MODE($mode);
283
284                 // Add the entry
285                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`,`inserted`) VALUES ('%s',%s,%s,'0000-00-00 00:00')",
286                         array(
287                                 $mode,
288                                 bigintval($data['id']),
289                                 bigintval($data['reload'])
290                         ), __FUNCTION__, __LINE__);
291         } // END - if
292 }
293
294 // Remove lock of given mail
295 function YOOMEDIA_UNLIST_MAIL ($data, $mode) {
296         // Convert mode for mails
297         $mode = YOOMEDIA_CONVERT_MODE($mode);
298
299         // Add the entry
300         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `type`='%s' AND `y_id`=%s LIMIT 1",
301                 array($mode, bigintval($data['id'])), __FUNCTION__, __LINE__);
302 }
303
304 // "Translates" the index number into an assosiative value
305 function yoomediaTranslateIndex ($type, $index) {
306         // Default is the index
307         $return = $index;
308
309         // Is the element there?
310         if (isset($GLOBALS['translation_tables']['yoomedia'][$type][$index])) {
311                 // Use this element
312                 $return = $GLOBALS['translation_tables']['yoomedia'][$type][$index];
313         } else {
314                 // Not found!
315                 logDebugMessage(__FUNCTION__, __LINE__, "type={$type},index={$index} not found.");
316         }
317
318         // Return value
319         return $return;
320 }
321
322 // "Translate" error code
323 function translateYooMediaError ($errorCode) {
324         // Default is 'failed'
325         $return = 'failed (Code: ' . $errorCode . ')';
326
327         // Is the entry there?
328         if (isset($GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode])) {
329                 // Entry found!
330                 $return = $GLOBALS['translation_tables']['yoomedia']['error_codes'][$errorCode];
331         } else {
332                 // Log missing entries
333                 debug_report_bug(sprintf("Unknown error code <strong>%s</strong> detected.", $errorCode));
334         }
335
336         // Return value
337         return $return;
338 }
339
340 // Checks if the mail id is in reload lock
341 function YOOMEDIA_CHECK_RELOAD ($id, $reload, $type) {
342         // Default is not in reload lock
343         $reloaded = false;
344
345         // Query database
346         $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",
347                 array($type, bigintval($id)), __FUNCTION__, __LINE__);
348
349         // Entry found?
350         if (SQL_NUMROWS($result) == 1) {
351                 // Load time
352                 list($id, $time) = SQL_FETCHROW($result);
353
354                 // Are we ready to sent again?
355                 if (((time() - $time) >= ($reload * 60*60)) && ($time > 0)) {
356                         // Remove entry
357                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_yoomedia_reload` WHERE `id`=%s LIMIT 1",
358                         array($id), __FUNCTION__, __LINE__);
359                 } else {
360                         // Dont' sent again this mail
361                         $reloaded = $time;
362                 }
363         } // END - if
364
365         // Free result
366         SQL_FREERESULT($result);
367
368         // Return result
369         return $reloaded;
370 }
371
372 // Lock given mail down for reload lock
373 function YOOMEDIA_RELOAD_LOCK ($data, $mode) {
374         // Search for the entry
375         if (YOOMEDIA_CHECK_RELOAD($data['id'], $data['reload'], $mode) === false) {
376                 // Convert mode for mails
377                 $mode = YOOMEDIA_CONVERT_MODE($mode);
378
379                 // Add the entry
380                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_yoomedia_reload` (`type`,`y_id`,`y_reload`) VALUES ('%s',%s,%s)",
381                         array($mode, bigintval($data['id']), bigintval($data['reload'])), __FUNCTION__, __LINE__);
382         } // END - if
383 }
384
385 // Convert mode for mails
386 function YOOMEDIA_CONVERT_MODE ($mode) {
387         // Convert mode for normal/html
388         switch ($mode) {
389                 case 'normal':
390                         $mode = 'textmail';
391                         break;
392
393                 case 'html':
394                         $mode = 'htmlmail';
395                         break;
396         } // END - switch
397
398         // Return result
399         return $mode;
400 }
401
402 // Extract code from response
403 function YOOMEDIA_GET_ERRORCODE_FROM_RESULT ($response) {
404         // Bad code as default
405         $code = -999;
406
407         // Which response should we parse?
408         if ((isset($response[8])) && (count($response) == 9)) {
409                 // Use error code from element 8 (mostly API errors)
410                 $codeArray = explode('<br>', $response[8]);
411
412                 // Use only the first element
413                 $code = bigintval($codeArray[0]);
414         } elseif ((is_array($response[0])) && (isset($response[0]['id']))) {
415                 // Begin with extraction
416                 $codeArray = explode(' ', $response[0]['id']);
417                 $code = $codeArray[0];
418                 $codeArray = explode('<br />', $code);
419                 $code = $codeArray[0];
420                 $codeArray = explode('<br>', $code);
421                 $code = $codeArray[0];
422
423                 // Remove all new-line characters
424                 $codeArray = explode("\n", $code);
425                 $code = $codeArray[0];
426
427                 // Remove carrige-return
428                 $code = str_replace("\n", '', $code);
429         } else {
430                 // Should not happen!
431                 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot parse response. Raw response=' . base64_encode(serialize($response)));
432         }
433
434         // Return error code
435         return $code;
436 }
437
438 // [EOF]
439 ?>