Filters for configurable userid exclusion added:
[mailer.git] / inc / libs / network_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 11/04/2009 *
4  * ===================                          Last change: 11/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : network_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for ext-network                        *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer ext-network                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Private setter for current network id
44 function setCurrentNetworkId ($networkId) {
45         $GLOBALS['current_network_id'] = bigintval($networkId);
46 }
47
48 // Private getter for current network id
49 function getCurrentNetworkId () {
50         return $GLOBALS['current_network_id'];
51 }
52
53 // Checks whether the current network id is set
54 function isCurrentNetworkIdSet () {
55         // So is it there?
56         return isset($GLOBALS['current_network_id']);
57 }
58
59 // Getter for network_form_name
60 function getNetworkFormName () {
61         return $GLOBALS['network_form_name'];
62 }
63
64 // Setter for network_form_name
65 function setNetworkFormName ($networkFormName) {
66         $GLOBALS['network_form_name'] = (string) $networkFormName;
67 }
68
69 // Detects if a supported form has been sent
70 function detectNetworkProcessForm () {
71         // 'do' must be provided in URL
72         if (!isGetRequestElementSet('do')) {
73                 // Not provided!
74                 reportBug(__FUNCTION__, __LINE__, 'No "do" has been provided. Please fix your templates.');
75         } // END - if
76
77         // Default is invalid
78         setNetworkFormName('invalid');
79
80         // Now search all valid
81         foreach (array('save_config', 'add', 'edit', 'delete', 'do_edit', 'do_delete') as $formName) {
82                 // Is it detected
83                 if (isFormSent($formName)) {
84                         // Use this form name
85                         setNetworkFormName($formName);
86
87                         // Remove it generically here
88                         unsetPostRequestElement($formName);
89
90                         // Abort loop
91                         break;
92                 } // END - if
93         } // END - foreach
94
95         // Has the form being detected?
96         if (getNetworkFormName() == 'invalid') {
97                 // Not supported
98                 reportBug(__FUNCTION__, __LINE__, 'POST form could not be detected, postData=<pre>' . print_r(postRequestArray(), TRUE));
99         } // END - if
100 }
101
102 // Handle a (maybe) sent form here
103 function doNetworkHandleForm () {
104         // Is there a form sent?
105         if (countRequestPost() > 0) {
106                 // Detect sent POST form
107                 detectNetworkProcessForm();
108         } elseif (!isGetRequestElementSet('do')) {
109                 // Skip any further requests
110                 return;
111         }
112
113         // Process the request
114         doAdminNetworkProcessForm();
115 }
116
117 // Processes an admin form
118 function doAdminNetworkProcessForm () {
119         // Create function name
120         $functionName = sprintf("doAdminNetworkProcess%s", capitalizeUnderscoreString(getRequestElement('do')));
121
122         // Is the function valid?
123         if (!function_exists($functionName)) {
124                 // Invalid function name
125                 reportBug(__FUNCTION__, __LINE__, 'Invalid do ' . getRequestElement('do') . ', function ' . $functionName .' does not exist.', FALSE);
126         } // END - if
127
128         // Init global arrays
129         $GLOBALS['network_types_disabled'] = array();
130
131         // Call-back the method handling our request
132         call_user_func($functionName);
133 }
134
135 // Checks whether the (short) network name is already used (valid)
136 function isNetworkNameValid ($name) {
137         // Is there cache?
138         if (!isset($GLOBALS[__FUNCTION__][$name])) {
139                 // Does it exist?
140                 $GLOBALS[__FUNCTION__][$name] = (countSumTotalData($name, 'network_data', 'network_id', 'network_short_name', TRUE) == 1);
141         } // END - if
142
143         // Return result
144         return $GLOBALS[__FUNCTION__][$name];
145 }
146
147 // Checks whether the (short) named network is activated
148 function isNetworkActiveByShortName ($name) {
149         // Is there cache?
150         if (!isset($GLOBALS[__FUNCTION__][$name])) {
151                 // Does it exist?
152                 $GLOBALS[__FUNCTION__][$name] = ((isNetworkNameValid($name)) && (countSumTotalData($name, 'network_data', 'network_id', 'network_short_name', TRUE, " AND `network_active`='Y'") == 1));
153         } // END - if
154
155         // Return result
156         return $GLOBALS[__FUNCTION__][$name];
157 }
158
159 // Checks whether the network by given id is activated
160 function isNetworkActiveById ($networkId) {
161         // Is there cache?
162         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
163                 // Does it exist?
164                 $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(bigintval($networkId), 'network_data', 'network_id', 'network_id', TRUE, " AND `network_active`='Y'") == 1);
165         } // END - if
166
167         // Return result
168         return $GLOBALS[__FUNCTION__][$networkId];
169 }
170
171 // "Getter" for 'network_activated' column depending on current administrator's expert setting
172 function getNetworkActivatedColumn ($whereAnd = 'WHERE', $table = '') {
173         // Is there cache?
174         if (!isset($GLOBALS[__FUNCTION__][$whereAnd][$table])) {
175                 // Default is exclude deactivated networks
176                 $GLOBALS[__FUNCTION__][$whereAnd][$table] = ' ' . $whereAnd . ' ' . $table . "`network_active`='Y'";
177
178                 // Is the export setting on and debug mode enabled?
179                 if ((isAdminsExpertSettingEnabled()) && (isDebugModeEnabled())) {
180                         // Then allow all networks
181                         $GLOBALS[__FUNCTION__][$whereAnd][$table] = '';
182                 } // END - if
183         } // END - if
184
185         // Return cache
186         return $GLOBALS[__FUNCTION__][$whereAnd][$table];
187 }
188
189 // Checks whether the given network type is already used (valid)
190 function isNetworkTypeHandleValid ($type, $networkId) {
191         // Query for it
192         $result = SQL_QUERY_ESC("SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s AND `network_type_handler`='%s' LIMIT 1",
193                 array(
194                         $networkId,
195                         $type
196                 ), __FUNCTION__, __LINE__);
197
198         // Does it exist?
199         $isValid = (SQL_NUMROWS($result) == 1);
200
201         // Free result
202         SQL_FREERESULT($result);
203
204         // Return result
205         return $isValid;
206 }
207
208 // Checks whether the given network request parameter is already used (valid)
209 function isNetworkRequestElementValid ($key, $type, $networkId) {
210         // Query for it
211         $result = SQL_QUERY_ESC("SELECT `network_request_param_id` FROM `{?_MYSQL_PREFIX?}_network_request_params` WHERE `network_id`=%s AND `network_type_id`=%s AND `network_request_param_key`='%s' LIMIT 1",
212                 array(
213                         $networkId,
214                         $type,
215                         $key
216                 ), __FUNCTION__, __LINE__);
217
218         // Does it exist?
219         $isValid = (SQL_NUMROWS($result) == 1);
220
221         // Free result
222         SQL_FREERESULT($result);
223
224         // Return result
225         return $isValid;
226 }
227
228 // Checks whether the given vcheck request parameter is already used (valid)
229 function isNetworkVcheckElementValid ($key, $networkId) {
230         // Query for it
231         $result = SQL_QUERY_ESC("SELECT `network_vcheck_param_id` FROM `{?_MYSQL_PREFIX?}_network_vcheck_params` WHERE `network_id`=%s AND `network_vcheck_param_key`='%s' LIMIT 1",
232                 array(
233                         $networkId,
234                         $key
235                 ), __FUNCTION__, __LINE__);
236
237         // Does it exist?
238         $isValid = (SQL_NUMROWS($result) == 1);
239
240         // Free result
241         SQL_FREERESULT($result);
242
243         // Return result
244         return $isValid;
245 }
246
247 // Checks whether the given network API array translation
248 function isNetworkArrayTranslationValid ($key, $type, $networkId) {
249         // Query for it
250         $result = SQL_QUERY_ESC("SELECT `network_array_id` FROM `{?_MYSQL_PREFIX?}_network_array_translation` WHERE `network_id`=%s AND `network_type_id`=%s AND `network_array_index`='%s' LIMIT 1",
251                 array(
252                         $networkId,
253                         $type,
254                         $key
255                 ), __FUNCTION__, __LINE__);
256
257         // Does it exist?
258         $isValid = (SQL_NUMROWS($result) == 1);
259
260         // Free result
261         SQL_FREERESULT($result);
262
263         // Return result
264         return $isValid;
265 }
266
267 // "Getter" for a network's data by provided id number
268 function getNetworkDataById ($networkId, $column = '') {
269         // Ids lower one are not accepted
270         if (!isValidId($networkId)) {
271                 // Not good, should be fixed
272                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is smaller than 1.');
273         } elseif ((!isNetworkActiveById($networkId)) && (!isAdminsExpertSettingEnabled())) {
274                 // Do not load inactive network data
275                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is not active.');
276         }
277
278         // Set current network id
279         setCurrentNetworkId($networkId);
280
281         // Is it cached?
282         if (!isset($GLOBALS['network_data'][$networkId])) {
283                 // By default there is no data
284                 $GLOBALS['network_data'][$networkId] = array();
285
286                 // Query for the network data
287                 $result = SQL_QUERY_ESC('SELECT
288         `network_id`,
289         `network_short_name`,
290         `network_title`,
291         `network_reflink`,
292         `network_data_separator`,
293         `network_row_separator`,
294         `network_request_type`,
295         `network_charset`,
296         `network_require_id_card`,
297         `network_query_amount`
298 FROM
299         `{?_MYSQL_PREFIX?}_network_data`
300 WHERE
301         `network_id`=%s
302 LIMIT 1',
303                         array(bigintval($networkId)), __FUNCTION__, __LINE__);
304
305                 // Is there an entry?
306                 if (SQL_NUMROWS($result) == 1) {
307                         // Then get it
308                         $GLOBALS['network_data'][$networkId] = SQL_FETCHARRAY($result);
309                 } // END - if
310
311                 // Free result
312                 SQL_FREERESULT($result);
313         } // END - if
314
315         // Return result
316         if ((empty($column)) && (isset($GLOBALS['network_data'][$networkId]))) {
317                 // Return array
318                 return $GLOBALS['network_data'][$networkId];
319         } elseif (isset($GLOBALS['network_data'][$networkId][$column])) {
320                 // Return column
321                 return $GLOBALS['network_data'][$networkId][$column];
322         }
323
324         // Return NULL
325         return NULL;
326 }
327
328 // "Getter" for a network's data by provided type id number
329 function getNetworkDataByTypeId ($networkTypeId, $column = '') {
330         // Ids lower one are not accepted
331         if (!isValidId($networkTypeId)) {
332                 // Not good, should be fixed
333                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkTypeId . ' is smaller than 1.');
334         } // END - if
335
336         // Is it cached?
337         if (!isset($GLOBALS['network_type_data'][$networkTypeId])) {
338                 // By default there is no data
339                 $GLOBALS['network_type_data'][$networkTypeId] = array();
340
341                 // Query for the network data
342                 $result = SQL_QUERY_ESC('SELECT
343         `d`.`network_id`,
344         `d`.`network_short_name`,
345         `d`.`network_title`,
346         `d`.`network_reflink`,
347         `d`.`network_data_separator`,
348         `d`.`network_row_separator`,
349         `d`.`network_request_type`,
350         `d`.`network_charset`,
351         `d`.`network_require_id_card`,
352         `d`.`network_query_amount`,
353         `d`.`network_active`,
354         `t`.`network_type_id`,
355         `t`.`network_type_handler`,
356         `t`.`network_type_api_url`,
357         `t`.`network_type_click_url`,
358         `t`.`network_type_banner_url`,
359         `t`.`network_text_encoding`
360 FROM
361         `{?_MYSQL_PREFIX?}_network_data` AS `d`
362 LEFT JOIN
363         `{?_MYSQL_PREFIX?}_network_types` AS `t`
364 ON
365         `d`.`network_id`=`t`.`network_id`
366 WHERE
367         `t`.`network_type_id`=%s
368 LIMIT 1',
369                         array(bigintval($networkTypeId)), __FUNCTION__, __LINE__);
370
371                 // Is there an entry?
372                 if (SQL_NUMROWS($result) == 1) {
373                         // Then get it
374                         $GLOBALS['network_type_data'][$networkTypeId] = SQL_FETCHARRAY($result);
375                 } // END - if
376
377                 // Free result
378                 SQL_FREERESULT($result);
379         } // END - if
380
381         // Return result
382         if (!isset($GLOBALS['network_type_data'][$networkTypeId])) {
383                 // Not found
384                 return NULL;
385         } elseif (empty($column)) {
386                 // Return array
387                 return $GLOBALS['network_type_data'][$networkTypeId];
388         } else {
389                 // Return column
390                 return $GLOBALS['network_type_data'][$networkTypeId][$column];
391         }
392 }
393
394 // "Getter" for a network type data by provided id number
395 function getNetworkTypeDataByTypeId ($networkTypeId) {
396         // Ids lower one are not accepted
397         if (!isValidId($networkTypeId)) {
398                 // Not good, should be fixed
399                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkTypeId . ' is smaller than 1.');
400         } // END - if
401
402         // Is it set?
403         if (!isset($GLOBALS['network_type_data'][$networkTypeId])) {
404                 // By default there is no data
405                 $GLOBALS['network_type_data'][$networkTypeId] = array();
406
407                 // Query for the network data
408                 $result = SQL_QUERY_ESC('SELECT
409         `network_type_id`,
410         `network_id`,
411         `network_type_handler`,
412         `network_type_api_url`,
413         `network_type_click_url`,
414         `network_type_banner_url`
415 FROM
416         `{?_MYSQL_PREFIX?}_network_types`
417 WHERE
418         `network_type_id`=%s
419 LIMIT 1',
420                         array(bigintval($networkTypeId)), __FUNCTION__, __LINE__);
421
422                 // Is there an entry?
423                 if (SQL_NUMROWS($result) == 1) {
424                         // Then get it
425                         $GLOBALS['network_type_data'][$networkTypeId] = SQL_FETCHARRAY($result);
426                 } // END - if
427
428                 // Free result
429                 SQL_FREERESULT($result);
430         } // END - if
431
432         // Return result
433         return $GLOBALS['network_type_data'][$networkTypeId];
434 }
435
436 // "Getter" for all network type data by provided id number
437 function getNetworkTypeDataById ($networkId) {
438         // Ids lower one are not accepted
439         if (!isValidId($networkId)) {
440                 // Not good, should be fixed
441                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkId . ' is smaller than 1.');
442         } // END - if
443
444         // Is it set?
445         if (!isset($GLOBALS['network_types'][$networkId])) {
446                 // By default there is no data
447                 $GLOBALS['network_types'][$networkId] = array();
448
449                 // Query for the network data
450                 $result = SQL_QUERY_ESC('SELECT
451         `network_type_id`,
452         `network_id`,
453         `network_type_handler`,
454         `network_type_api_url`,
455         `network_type_click_url`,
456         `network_type_banner_url`
457 FROM
458         `{?_MYSQL_PREFIX?}_network_types`
459 WHERE
460         `network_id`=%s
461 ORDER BY
462         `network_type_id` ASC',
463                         array(bigintval($networkId)), __FUNCTION__, __LINE__);
464
465                 // Is there an entry?
466                 if (!SQL_HASZERONUMS($result)) {
467                         // Then add all
468                         while ($row = SQL_FETCHARRAY($result)) {
469                                 // Add it with new index as it is no longer required
470                                 $GLOBALS['network_types'][$networkId][] = $row;
471                         } // END - if
472                 } // END - if
473
474                 // Free result
475                 SQL_FREERESULT($result);
476         } // END - if
477
478         // Return result
479         return $GLOBALS['network_types'][$networkId];
480 }
481
482 // "Getter" for a network request parameter data by provided id number
483 function getNetworkRequestParamsDataById ($networkRequestId) {
484         // Ids lower one are not accepted
485         if (!isValidId($networkRequestId)) {
486                 // Not good, should be fixed
487                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkRequestId . ' is smaller than 1.');
488         } // END - if
489
490         // By default there is no data
491         $networkRequestData = array();
492
493         // Query for the network data
494         $result = SQL_QUERY_ESC('SELECT
495         `network_request_param_id`,
496         `network_id`,
497         `network_type_id`,
498         `network_request_param_key`,
499         `network_request_param_value`,
500         `network_request_param_default`
501 FROM
502         `{?_MYSQL_PREFIX?}_network_request_params`
503 WHERE
504         `network_request_param_id`=%s
505 LIMIT 1',
506                 array(bigintval($networkRequestId)), __FUNCTION__, __LINE__);
507
508         // Is there an entry?
509         if (SQL_NUMROWS($result) == 1) {
510                 // Then get it
511                 $networkRequestData = SQL_FETCHARRAY($result);
512         } // END - if
513
514         // Free result
515         SQL_FREERESULT($result);
516
517         // Return result
518         return $networkRequestData;
519 }
520
521 // "Getter" for a network array translation data by provided id number
522 function getNetworkArrayTranslationsDataById ($networkTranslationId) {
523         // Ids lower one are not accepted
524         if (!isValidId($networkTranslationId)) {
525                 // Not good, should be fixed
526                 reportBug(__FUNCTION__, __LINE__, 'Network array translation id ' . $networkTranslationId . ' is smaller than 1.');
527         } // END - if
528
529         // By default there is no data
530         $networkTranslationData = array();
531
532         // Query for the network data
533         $result = SQL_QUERY_ESC('SELECT
534         `network_array_id`,
535         `network_id`,
536         `network_type_id`,
537         `network_array_index`,
538         `network_array_sort`
539 FROM
540         `{?_MYSQL_PREFIX?}_network_array_translation`
541 WHERE
542         `network_array_id`=%s
543 LIMIT 1',
544                 array(bigintval($networkTranslationId)), __FUNCTION__, __LINE__);
545
546         // Is there an entry?
547         if (SQL_NUMROWS($result) == 1) {
548                 // Then get it
549                 $networkTranslationData = SQL_FETCHARRAY($result);
550         } // END - if
551
552         // Free result
553         SQL_FREERESULT($result);
554
555         // Return result
556         return $networkTranslationData;
557 }
558
559 // "Getter" for network query request parameters
560 function getNetworkRequestParametersByTypeId ($networkTypeId) {
561         // Ids lower one are not accepted
562         if (!isValidId($networkTypeId)) {
563                 // Not good, should be fixed
564                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkTypeId . ' is smaller than 1.');
565         } // END - if
566
567         // Is it cached?
568         if (!isset($GLOBALS['network_request_parameters'][$networkTypeId])) {
569                 // By default there is no data
570                 $GLOBALS['network_request_parameters'][$networkTypeId] = array();
571
572                 // Search for all
573                 $result = SQL_QUERY_ESC('SELECT
574         `network_id`,
575         `network_type_id`,
576         `network_request_param_key`,
577         `network_request_param_value`,
578         `network_request_param_default`
579 FROM
580         `{?_MYSQL_PREFIX?}_network_request_params`
581 WHERE
582         `network_type_id`=%s
583 ORDER BY
584         `network_request_param_id` ASC',
585                 array(
586                         bigintval($networkTypeId)
587                 ), __FUNCTION__, __LINE__);
588
589                 // Are there records?
590                 if (!SQL_HASZERONUMS($result)) {
591                         // Load all but make new indexes as the old are not required
592                         while ($row = SQL_FETCHARRAY($result)) {
593                                 // Add it
594                                 $GLOBALS['network_request_parameters'][$networkTypeId][] = $row;
595                         } // END - while
596                 } // END - if
597
598                 // Free result
599                 SQL_FREERESULT($result);
600         } // END - if
601
602         // Return "cached" values
603         return $GLOBALS['network_request_parameters'][$networkTypeId];
604 }
605
606 // "Getter" for network configuration + handler config for given network type handler id
607 function getFullNetworkConfigurationByTypeId ($networkTypeId) {
608         // Ids lower one are not accepted
609         if (!isValidId($networkTypeId)) {
610                 // Not good, should be fixed
611                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkTypeId . ' is smaller than 1.');
612         } // END - if
613
614         // Is it cached?
615         if (!isset($GLOBALS['network_full_config'][$networkTypeId])) {
616                 // By default there is no data
617                 $GLOBALS['network_full_config'][$networkTypeId] = array();
618
619                 // Search for all
620                 $result = SQL_QUERY_ESC('SELECT
621         `nac`.`network_id`,
622         `ntc`.`network_type_id`,
623         `nac`.`network_api_affiliate_id`,
624         `nac`.`network_api_password`,
625         `nac`.`network_api_site_id`,
626         `nac`.`network_api_active`,
627         `nac`.`network_api_referral_link`,
628         `nac`.`network_api_referral_button`,
629         `nac`.`network_api_remaining_requests`,
630         `nts`.`network_type_reload_time_unit`,
631         `ntc`.`network_max_reload_time`,
632         `ntc`.`network_min_waiting_time`,
633         `ntc`.`network_max_waiting_time`,
634         `ntc`.`network_min_remain_clicks`,
635         `ntc`.`network_min_remain_budget`,
636         `ntc`.`network_min_payment`,
637         `ntc`.`network_allow_erotic`,
638         `ntc`.`network_media_size`,
639         `ntc`.`network_media_output`
640 FROM
641         `{?_MYSQL_PREFIX?}_network_api_config` AS `nac`
642 INNER JOIN
643         `{?_MYSQL_PREFIX?}_network_handler_config` AS `ntc`
644 ON
645         `nac`.`network_id`=`ntc`.`network_id`
646 INNER JOIN
647         `{?_MYSQL_PREFIX?}_network_types` AS `nts`
648 ON
649         `ntc`.`network_type_id`=`nts`.`network_type_id`
650 WHERE
651         `ntc`.`network_type_id`=%s
652 LIMIT 1',
653                 array(
654                         bigintval($networkTypeId)
655                 ), __FUNCTION__, __LINE__);
656
657                 // Is there one entry?
658                 if (SQL_NUMROWS($result) == 1) {
659                         // Load it
660                         $GLOBALS['network_full_config'][$networkTypeId] = SQL_FETCHARRAY($result);
661                 } // END - if
662
663                 // Free result
664                 SQL_FREERESULT($result);
665         } // END - if
666
667         // Return "cached" values
668         return $GLOBALS['network_full_config'][$networkTypeId];
669 }
670
671 // Removes given network entry
672 function doAdminRemoveNetworkEntry ($table, $column, $id, $limit = 1) {
673         // Remove the entry
674         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_network_%s` WHERE `%s`=%s LIMIT %s",
675                 array(
676                         $table,
677                         $column,
678                         $id,
679                         $limit
680                 ), __FUNCTION__, __LINE__);
681
682         // Return affected rows
683         return SQL_AFFECTEDROWS();
684 }
685
686 // Generates a list of networks for given script and returns it
687 function generateAdminNetworkList ($separated = FALSE, $includeConfigured = TRUE, $includeUnconfigured = TRUE, $extraName = '') {
688         // Init output
689         $content = '';
690
691         // Query for all networks
692         $result = SQL_QUERY('SELECT
693         `network_id`,
694         `network_short_name`,
695         `network_title`,
696         `network_request_type`,
697         `network_charset`,
698         `network_require_id_card`,
699         `network_query_amount`,
700         `network_active`
701 FROM
702         `{?_MYSQL_PREFIX?}_network_data`
703 ' . getNetworkActivatedColumn() . '
704 ORDER BY
705         `network_short_name` ASC', __FUNCTION__, __LINE__);
706
707         // Are there entries?
708         if (!SQL_HASZERONUMS($result)) {
709                 // List all entries
710                 $rows = array();
711                 while ($row = SQL_FETCHARRAY($result)) {
712                         // Is this valid, then add it
713                         if ((is_array($row)) && (isset($row['network_id']))) {
714                                 // Exclude configured and is it configured or same for unconfired but only if not separated lists?
715                                 if (((($includeConfigured === FALSE) && (isNetworkApiConfigured($row['network_id']))) || (($includeUnconfigured === FALSE) && (!isNetworkApiConfigured($row['network_id'])))) && ($separated === FALSE)) {
716                                         // Skip this entry
717                                         continue;
718                                 } // END - if
719
720                                 // Add entry
721                                 $rows[$row['network_id']] = $row;
722                         } // END - if
723                 } // END - while
724
725                 // Nothing found?
726                 if (count($rows) == 0) {
727                         // Then return nothing ... ;-)
728                         return '';
729                 } // END - if
730
731                 // Do separated?
732                 if ($separated === FALSE) {
733                         // Exclude un-/configured?
734                         if ($includeConfigured === FALSE) {
735                                 // Exclude configured, so only unconfigured
736                                 $extraName = '_unconfigured';
737                         } elseif ($includeUnconfigured === FALSE) {
738                                 // Exclude unconfigured, so only configured
739                                 $extraName = '_configured';
740                         }
741
742                         // Generate the big selection box
743                         $content = generateSelectionBoxFromArray($rows, 'network_id', 'network_id', '', $extraName, 'network');
744                 } else {
745                         // Generate two small, first configured
746                         $content = generateAdminNetworkList(FALSE, TRUE, FALSE, '_configured');
747
748                         // Then add unconfigured
749                         $content .= generateAdminNetworkList(FALSE, FALSE, TRUE, '_unconfigured');
750                 }
751         } else {
752                 // Nothing selected
753                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
754         }
755
756         // Free the result
757         SQL_FREERESULT($result);
758
759         // Return the list
760         return $content;
761 }
762
763 // Generator (somewhat getter) for a list of network types for given network id
764 function generateAdminNetworkTypeList ($networkId) {
765         // Init content
766         $content = '';
767
768         // Query all types of this network
769         $result = SQL_QUERY_ESC('SELECT
770         `network_type_id`,
771         `network_type_handler`
772 FROM
773         `{?_MYSQL_PREFIX?}_network_types`
774 WHERE
775         `network_id`=%s
776         ' . getNetworkActivatedColumn('AND') . '
777 ORDER BY
778         `network_type_handler` ASC',
779                 array(
780                         bigintval($networkId)
781                 ), __FUNCTION__, __LINE__);
782
783         // Are there entries?
784         if (!SQL_HASZERONUMS($result)) {
785                 // List all entries
786                 $rows = array();
787                 while ($row = SQL_FETCHARRAY($result)) {
788                         // Is this valid, then add it
789                         if ((is_array($row)) && (isset($row['network_type_id']))) {
790                                 // Add entry
791                                 $rows[$row['network_type_id']] = $row;
792                         } // END - if
793                 } // END - while
794
795                 // Generate the selection box
796                 $content = generateSelectionBoxFromArray($rows, 'network_type', 'network_type_id');
797         } else {
798                 // Nothing selected
799                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
800         }
801
802         // Free the result
803         SQL_FREERESULT($result);
804
805         // Return content
806         return $content;
807 }
808
809 // Generator (somewhat getter) for a list of network types for all types
810 function generateAdminDistinctNetworkTypeList () {
811         // Init content
812         $content = '';
813
814         // Query all types of this network
815         $result = SQL_QUERY('SELECT
816         `t`.`network_type_id`,
817         `t`.`network_type_handler`,
818         `d`.`network_title`
819 FROM
820         `{?_MYSQL_PREFIX?}_network_types` AS `t`
821 LEFT JOIN
822         `{?_MYSQL_PREFIX?}_network_data` AS `d`
823 ON
824         `t`.`network_id`=`d`.`network_id`
825 ' . getNetworkActivatedColumn('WHERE', 'd') . '
826 ORDER BY
827         `d`.`network_short_name` ASC,
828         `t`.`network_type_handler` ASC', __FUNCTION__, __LINE__);
829
830         // Are there entries?
831         if (!SQL_HASZERONUMS($result)) {
832                 // List all entries
833                 $rows = array();
834                 while ($row = SQL_FETCHARRAY($result)) {
835                         // Is this valid, then add it
836                         if ((is_array($row)) && (isset($row['network_type_id']))) {
837                                 // Add entry
838                                 $rows[$row['network_type_id']] = $row;
839                         } // END - if
840                 } // END - while
841
842                 // Generate the selection box
843                 $content = generateSelectionBoxFromArray($rows, 'network_type', 'network_type_id', '', '_title');
844         } else {
845                 // Nothing selected
846                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
847         }
848
849         // Free the result
850         SQL_FREERESULT($result);
851         //* DEBUG: */ die('<pre>'.encodeEntities($content).'</pre>');
852
853         // Return content
854         return $content;
855 }
856
857 // Generator (somewhat getter) for network type options
858 function generateNetworkTypeOptions ($networkId) {
859         // Is this an array, then we just came back from edit/delete actions
860         if (is_array($networkId)) {
861                 // Set it as empty string
862                 $networkId = '';
863         } // END - if
864
865         // Is this cached?
866         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
867                 // Generate output and cache it
868                 $GLOBALS[__FUNCTION__][$networkId] = generateOptions(
869                         'network_types',
870                         'network_type_id',
871                         'network_type_handler',
872                         $networkId,
873                         '',
874                         sprintf(
875                                 "WHERE `network_id`=%s" . getNetworkActivatedColumn('AND'),
876                                 bigintval(getRequestElement('network_id'))
877                         ),
878                         '',
879                         'translateNetworkTypeHandler'
880                 );
881         } // END - if
882
883         // Return content
884         return $GLOBALS[__FUNCTION__][$networkId];
885 }
886
887 // Generates an options list of all available (hard-coded) handlers
888 function generateNetworkTypesAvailableOptions ($defaultType = NULL) {
889         // Is it cached?
890         if (!isset($GLOBALS[__FUNCTION__][$defaultType])) {
891                 // Generate list
892                 $GLOBALS[__FUNCTION__][$defaultType] = generateOptions(
893                         '/ARRAY/',
894                         array(
895                                 'banner',
896                                 'banner_click',
897                                 'banner_view',
898                                 'button',
899                                 'button_click',
900                                 'button_view',
901                                 'surfbar',
902                                 'surfbar_click',
903                                 'surfbar_view',
904                                 'forced_banner',
905                                 'forced_button',
906                                 'forced_half_banner',
907                                 'forced_skyscraper',
908                                 'forced_textlink',
909                                 'textlink',
910                                 'textlink_click',
911                                 'textlink_view',
912                                 'skyscraper',
913                                 'skyscraper_click',
914                                 'skyscraper_view',
915                                 'halfbanner',
916                                 'halfbanner_click',
917                                 'halfbanner_view',
918                                 'layer',
919                                 'layer_click',
920                                 'layer_view',
921                                 'popup',
922                                 'popdown',
923                                 'textmail',
924                                 'htmlmail',
925                                 'lead',
926                                 'sale',
927                                 'lead_sale',
928                                 'payperactive',
929                                 'pagepeel',
930                                 'pagepeel_click',
931                                 'pagepeel_view',
932                                 'traffic',
933                                 'signature',
934                                 'signature_click',
935                                 'signature_view',
936                         ),
937                         array(),
938                         $defaultType,
939                         '', '',
940                         $GLOBALS['network_types_disabled'],
941                         'translateNetworkTypeHandler'
942                 );
943         } // END - if
944
945         // Return content
946         return $GLOBALS[__FUNCTION__][$defaultType];
947 }
948
949 // Generates an options list of all available (hard-coded) text encoders
950 function generateNetworkTextEncodingAvailableOptions ($defaultEncoding = NULL) {
951         // Is it cached?
952         if (!isset($GLOBALS[__FUNCTION__][$defaultEncoding])) {
953                 // Generate list
954                 $GLOBALS[__FUNCTION__][$defaultEncoding] = generateOptions(
955                         '/ARRAY/',
956                         array(
957                                 'NONE',
958                                 'BASE64',
959                         ),
960                         array(),
961                         $defaultEncoding,
962                         '', '',
963                         array(),
964                         'translateNetworkTextEncoding'
965                 );
966         } // END - if
967
968         // Return content
969         return $GLOBALS[__FUNCTION__][$defaultEncoding];
970 }
971
972 // Generates an options list (somewhat getter) for request keys
973 function generateNetworkRequestKeyOptions () {
974         // Is it cached?
975         if (!isset($GLOBALS[__FUNCTION__])) {
976                 // Generate and cache it
977                 $GLOBALS[__FUNCTION__] = generateOptions(
978                         '/ARRAY/',
979                         array(
980                                 'affiliate_id',
981                                 'site_id',
982                                 'hash',
983                                 'password',
984                                 'reload',
985                                 'maximum_stay',
986                                 'minimum_stay',
987                                 'currency',
988                                 'type',
989                                 'remain_budget',
990                                 'remain_clicks',
991                                 'reward',
992                                 'size',
993                                 'erotic',
994                                 'extra',
995                                 'country'
996                         ),
997                         array(),
998                         '',
999                         '', '',
1000                         $GLOBALS['network_request_params_disabled'],
1001                         'translateNetworkRequestParameterKey'
1002                 );
1003         } // END - if
1004
1005         // Return content
1006         return $GLOBALS[__FUNCTION__];
1007 }
1008
1009 // Generates an options list for vcheck request keys
1010 function generateNetworkVcheckKeyOptions () {
1011         // Is it cached?
1012         if (!isset($GLOBALS[__FUNCTION__])) {
1013                 // Generate and cache it
1014                 $GLOBALS[__FUNCTION__] = generateOptions(
1015                         '/ARRAY/',
1016                         array(
1017                                 'network_key',
1018                                 'site_id',
1019                                 'payment',
1020                                 'remote_address',
1021                                 'campaign_id',
1022                                 'status',
1023                                 'reason',
1024                                 'type',
1025                                 'network_name',
1026                                 'extra_value1',
1027                                 'extra_value2',
1028                                 'extra_value3',
1029                                 'extra_value4',
1030                         ),
1031                         array(),
1032                         '',
1033                         '', '',
1034                         $GLOBALS['network_vcheck_params_disabled'],
1035                         'translateNetworkVcheckParameterKey'
1036                 );
1037         } // END - if
1038
1039         // Return content
1040         return $GLOBALS[__FUNCTION__];
1041 }
1042
1043 // Generator (somewhat getter) for (return) array translation
1044 function generateNetworkTranslationOptions ($default = '') {
1045         // Is it cached?
1046         if (!isset($GLOBALS[__FUNCTION__][$default])) {
1047                 // Generate and cache it
1048                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
1049                         'network_translations',
1050                         'network_translation_id',
1051                         'network_translation_name',
1052                         $default,
1053                         '',
1054                         '',
1055                         $GLOBALS['network_array_translation_disabled'],
1056                         'translateNetworkTranslationName'
1057                 );
1058         } // END - if
1059
1060         // Return content
1061         return $GLOBALS[__FUNCTION__][$default];
1062 }
1063
1064 // Generates an option list of request types
1065 function generateNetworkRequestTypeOptions ($default = '') {
1066         // Is there cache?
1067         if (!isset($GLOBALS[__FUNCTION__][$default])) {
1068                 // Generate the list
1069                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
1070                         '/ARRAY/',
1071                         array(
1072                                 'GET',
1073                                 'POST'
1074                         ),
1075                         array(
1076                                 '{--ADMIN_NETWORK_REQUEST_TYPE_GET--}',
1077                                 '{--ADMIN_NETWORK_REQUEST_TYPE_POST--}'
1078                         ),
1079                         $default
1080                 );
1081         } // END - if
1082
1083         // Return cache
1084         return $GLOBALS[__FUNCTION__][$default];
1085 }
1086
1087 // Generates an option list of network_api_active
1088 function generateNetworkApiActiveOptions ($default = '') {
1089         // Is there cache?
1090         if (!isset($GLOBALS[__FUNCTION__][$default])) {
1091                 // Generate the list
1092                 $GLOBALS[__FUNCTION__][$default] = generateYesNoOptions($default);
1093         } // END - if
1094
1095         // Return cache
1096         return $GLOBALS[__FUNCTION__][$default];
1097 }
1098
1099 // Generator (somewhat getter) for network type options
1100 function generateNetworkMediaOutputOptions ($mediaOutput) {
1101         // Is this an array, then we just came back from edit/delete actions
1102         if (is_array($mediaOutput)) {
1103                 // Set it as empty string
1104                 $mediaOutput = '';
1105         } // END - if
1106
1107         // Is this cached?
1108         if (!isset($GLOBALS[__FUNCTION__][$mediaOutput])) {
1109                 // Generate output and cache it
1110                 $GLOBALS[__FUNCTION__][$mediaOutput] = generateOptions(
1111                         '/ARRAY/',
1112                         array(
1113                                 '',
1114                                 'banner',
1115                                 'html_email',
1116                                 'layer',
1117                                 'pagepeel',
1118                                 'popup',
1119                                 'popdown',
1120                                 'text_email',
1121                                 'textlink'
1122                         ),
1123                         array(
1124                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_NONE--}',
1125                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_BANNER--}',
1126                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_HTML_EMAIL--}',
1127                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_LAYER--}',
1128                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_PAGEPEEL--}',
1129                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_POPUP--}',
1130                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_POPDOWN--}',
1131                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_TEXT_EMAIL--}',
1132                                 '{--ADMIN_NETWORK_MEDIA_OUTPUT_TEXTLINK--}'
1133                         ),
1134                         $mediaOutput,
1135                         'translateNetworkMediaOutputType'
1136                 );
1137         } // END - if
1138
1139         // Return content
1140         return $GLOBALS[__FUNCTION__][$mediaOutput];
1141 }
1142
1143 // Checks if the given network is configured by looking its API configuration entry up
1144 function isNetworkApiConfigured ($networkId) {
1145         // Is there cache?
1146         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1147                 // Check for an entry in network_api_config
1148                 $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(
1149                         bigintval($networkId),
1150                         'network_api_config',
1151                         'network_id',
1152                         'network_id',
1153                         true
1154                 ) == 1);
1155         } // END - if
1156
1157         // Return cache
1158         return $GLOBALS[__FUNCTION__][$networkId];
1159 }
1160
1161 // Checks whether the given network type handler is configured
1162 function isNetworkTypeHandlerConfigured ($networkId, $networkTypeId) {
1163         // Is there cache?
1164         if (!isset($GLOBALS[__FUNCTION__][$networkId][$networkTypeId])) {
1165                 // Determine it
1166                 $GLOBALS[__FUNCTION__][$networkId][$networkTypeId] = (countSumTotalData(
1167                         bigintval($networkTypeId),
1168                         'network_handler_config',
1169                         'network_data_id',
1170                         'network_type_id',
1171                         true,
1172                         sprintf(' AND `network_id`=%s', bigintval($networkId))
1173                 ) == 1);
1174         } // END - if
1175
1176         // Return cache
1177         return $GLOBALS[__FUNCTION__][$networkId][$networkTypeId];
1178 }
1179
1180 // Handles the network-payment-check request
1181 function handleNetworkPaymentCheckRequest () {
1182         // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
1183         reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
1184 }
1185
1186 // Handle a single request parameter key by given network type handler id and "internal" key
1187 function handleRequestParameterKey ($networkTypeId, $networkRequestKey) {
1188         // Construct call-back function name
1189         $callbackName = 'doHandleNetworkRequest' . capitalizeUnderscoreString($networkRequestKey) . 'Key';
1190
1191         // Is the function there?
1192         if (!function_exists($callbackName)) {
1193                 // Call-back function does not exist
1194                 reportBug(__FUNCTION__, __LINE__, 'Call-back function ' . $callbackName . ' does not exist. networkTypeId=' . $networkTypeId . ',networkRequestKey=' . $networkRequestKey);
1195         } // END - if
1196
1197         // Call it with network type id
1198         return call_user_func_array($callbackName, array($networkTypeId));
1199 }
1200
1201 // Handle all keys given request parameter array loaded by getNetworkRequestParametersByTypeId()
1202 function handleNetworkRequestParameterKeys (&$requestParams) {
1203         // Simple check for validity
1204         assert(isset($requestParams[0]['network_request_param_key']));
1205
1206         // "Walk" through all
1207         foreach ($requestParams as $key => $params) {
1208                 // Is the default value not set?
1209                 if (empty($params['network_request_param_default'])) {
1210                         // This key needs to be handled, so call it
1211                         $requestParams[$key]['network_request_param_default'] = handleRequestParameterKey($params['network_type_id'], $params['network_request_param_key']);
1212                 } // END - if
1213         } // END - foreach
1214 }
1215
1216 /**
1217  * Logs given HTTP headers to database for debugging purposes.
1218  *
1219  * @param       $networkId              Network's id number
1220  * @param       $networkTypeId  Network type handler's id number
1221  * @param       $headers                All HTTP headers
1222  * @param       $type                   Can be only one of 'MANUAL' or 'CRON'
1223  * @return      void
1224  */
1225 function logNetworkResponseHeaders ($networkId, $networkTypeId, $headers, $type) {
1226         // Make sure type is valid
1227         assert(in_array($type, array('MANUAL', 'CRON')));
1228
1229         // Is debug logging enabled or status code not 200 OK?
1230         if ((getConfig('network_logging_debug') == 'Y') || (!isHttpStatusOkay($response[0]))) {
1231                 // Add entry
1232                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_network_header_logging` (`network_id`, `network_type_id`, `network_http_status_code`, `network_http_headers`, `network_logging_type`) VALUES(%s, %s, '%s', '%s', '%s')",
1233                         array(
1234                                 bigintval($networkId),
1235                                 bigintval($networkTypeId),
1236                                 trim($headers[0]),
1237                                 serialize($headers),
1238                                 $type
1239                         ), __FUNCTION__, __LINE__);
1240         } // END - if
1241 }
1242
1243 /**
1244  * Caches given reponse body from API into cache, updates existing cache if
1245  * found. This function does the charset-convertion, so you don't have to do it
1246  * again if you use this cached data.
1247  *
1248  * @param       $networkId              Network's id number
1249  * @param       $networkTypeId  Network type handler's id number
1250  * @param       $responseBody   Response body (string)
1251  * @param       $networkData    Network + type handler data as array
1252  * @param       $type                   Can be only one of 'MANUAL' or 'CRON'
1253  * @return      void
1254  */
1255 function saveNetworkResponseBodyInCache ($networkId, $networkTypeId, $responseBody, $networkData, $type) {
1256         // Make sure the body is not larger than this value
1257         assert(strlen($responseBody) <= 16777215);
1258         assert(in_array($type, array('MANUAL', 'CRON')));
1259
1260         // So is there cache?
1261         if (countSumTotalData($networkId, 'network_cache', 'network_cache_id', 'network_id', TRUE, ' AND `network_type_id`=' . bigintval($networkTypeId)) == 1) {
1262                 // Entry found, so update it
1263                 SQL_QUERY_ESC("UPDATE
1264         `{?_MYSQL_PREFIX?}_network_cache`
1265 SET
1266         `network_cache_data`='%s',
1267         `network_cache_body`='%s',
1268         `network_cache_type`='%s',
1269         `network_cache_admin_id`=%s,
1270         `network_cache_updated`=NOW()
1271 WHERE
1272         `network_id`=%s AND
1273         `network_type_id`=%s
1274 LIMIT 1",
1275                         array(
1276                                 serialize($networkData),
1277                                 compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
1278                                 $type,
1279                                 convertZeroToNull(getCurrentAdminId()),
1280                                 bigintval($networkId),
1281                                 bigintval($networkTypeId)
1282                         ), __FUNCTION__, __LINE__);
1283         } else {
1284                 // Add entry
1285                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_network_cache` (`network_id`, `network_type_id`, `network_cache_data`, `network_cache_body`, `network_cache_type`, `network_cache_admin_id`) VALUES(%s, %s, '%s', '%s', '%s', %s)",
1286                         array(
1287                                 bigintval($networkId),
1288                                 bigintval($networkTypeId),
1289                                 serialize($networkData),
1290                                 compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
1291                                 $type,
1292                                 convertZeroToNull(getCurrentAdminId())
1293                         ), __FUNCTION__, __LINE__);
1294         }
1295 }
1296
1297 // Queries network API with given network data and request data
1298 function queryNetworkApi ($networkData, $requestData) {
1299         // Query it
1300         $response = sendHttpRequest($networkData['network_request_type'], $networkData['network_type_api_url'], $requestData, FALSE, FALSE);
1301
1302         // Did all went fine? (also a 403 is considered as "okay" here)
1303         if (count($response) > 3) {
1304                 // Save response body, remove last empty line if really empty
1305                 $responseBody = (string) trim($response[count($response) - 1]);
1306                 unset($response[count($response) - 1]);
1307                 assert(empty($response[count($response)]));
1308                 unset($response[count($response) - 1]);
1309
1310                 // Register all HTTP headers for debugging purposes
1311                 logNetworkResponseHeaders($networkData['network_id'], postRequestElement('network_type_id'), $response, 'MANUAL');
1312
1313                 // Is all fine?
1314                 if (isHttpStatusOkay($response[0])) {
1315                         // Count API request
1316                         countNetworkApiRequest($networkData);
1317
1318                         // Save response in cache
1319                         saveNetworkResponseBodyInCache($networkData['network_id'], postRequestElement('network_type_id'), $responseBody, $networkData, 'MANUAL');
1320                 } // END - if
1321         } // END - if
1322
1323         // Return the response
1324         return $response;
1325 }
1326
1327 /**
1328  * Counts API request from given network data generated by getNetworkDataByTypeId()
1329  *
1330  * @param       $networkData    Array with network data
1331  * @return      $affectedRows   Affected rows (always one or FALSE if unlimited/depleted)
1332  */
1333 function countNetworkApiRequest ($networkData) {
1334         // Get API config
1335         $apiConfig = getFullNetworkConfigurationByTypeId($networkData['network_type_id']);
1336
1337         // Is the daily or remaining free amount zero?
1338         if (($networkData['network_query_amount'] == 0) || ($apiConfig['network_api_remaining_requests'] == 0)) {
1339                 // Then abort here
1340                 return FALSE;
1341         } // END - if
1342
1343         // Okay, so update database
1344         $result = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_network_api_config` SET `network_api_remaining_requests`=`network_api_remaining_requests`-1 WHERE `network_id`=%s LIMIT 1",
1345                 array(
1346                         bigintval($networkData['network_id'])
1347                 ), __FUNCTION__, __LINE__);
1348
1349         // Return affected rows
1350         return SQL_AFFECTEDROWS();
1351 }
1352
1353 /**
1354  * Generates a referral link for given network id (including HTML)
1355  *
1356  * @param       $networkId      Network id to generate link for
1357  * @return      $output         "Rendered" output
1358  */
1359 function generateMetworkReferralLinkById ($networkId) {
1360         // Simple output (no need for template!)
1361         $output = '<a href="{%network,getNetworkDataById,network_reflink=' . $networkId . '%}" target="_blank" title="{%network,getNetworkDataById,network_title=' . $networkId . '%}">{%network,getNetworkDataById,network_title=' . $networkId . '%}</a>';
1362
1363         // Return it
1364         return $output;
1365 }
1366
1367 //------------------------------------------------------------------------------
1368 //               "Translation" functions (can be used in EL code)
1369 //------------------------------------------------------------------------------
1370
1371 // Translates 'translate_name' for e.g. templates
1372 function translateNetworkTranslationName ($name) {
1373         // Return message id
1374         return translateGeneric('ADMIN_NETWORK_TRANSLATE', $name, '_NAME');
1375 }
1376
1377 // Translates the network type id to a handler
1378 function translateNetworkTypeHandlerByTypeId ($typeId) {
1379         // Get the data
1380         $data = getNetworkDataByTypeId($typeId, 'network_type_handler');
1381
1382         // Is data found?
1383         if (is_null($data)) {
1384                 // Not found
1385                 return translateNetworkTypeHandler('UNKNOWN');
1386         } // END - if
1387
1388         // Return actual translation
1389         return translateNetworkTypeHandler($data);
1390 }
1391
1392 // "Translates" give network media output (type)
1393 function translateNetworkMediaOutputType ($mediaOutput) {
1394         // Return message id
1395         return translateGeneric('ADMIN_NETWORK_MEDIA_OUTPUT', $mediaOutput);
1396 }
1397
1398 // Translates the network type handler (e.g. banner, paidmail) for templates
1399 function translateNetworkTypeHandler ($type) {
1400         // Generate id
1401         $messageId = 'ADMIN_NETWORK_TYPE_HANDLER_' . strtoupper($type);
1402
1403         // Is the message id there?
1404         if (!isMessageIdValid($messageId)) {
1405                 // Not valid type
1406                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
1407         } // END - if
1408
1409         // Return message id
1410         return '{--' . $messageId . '--}';
1411 }
1412
1413 // Translates request type
1414 function translateNetworkRequestType ($type) {
1415         // Generate id
1416         $messageId = 'ADMIN_NETWORK_REQUEST_TYPE_' . strtoupper($type) . '';
1417
1418         // Is the message id there?
1419         if (!isMessageIdValid($messageId)) {
1420                 // Not valid type
1421                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
1422         } // END - if
1423
1424         // Return message id
1425         return '{--' . $messageId . '--}';
1426 }
1427
1428 // Translates request parameter
1429 function translateNetworkRequestParameterKey ($param) {
1430         // Generate id
1431         $messageId = 'ADMIN_NETWORK_REQUEST_PARAMETER_' . strtoupper($param) . '';
1432
1433         // Is the message id there?
1434         if (!isMessageIdValid($messageId)) {
1435                 // Not valid param
1436                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
1437         } // END - if
1438
1439         // Return message id
1440         return '{--' . $messageId . '--}';
1441 }
1442
1443 // Translates vheck request parameter
1444 function translateNetworkVcheckParameterKey ($param) {
1445         // Generate id
1446         $messageId = 'ADMIN_NETWORK_VCHECK_PARAMETER_' . strtoupper($param) . '';
1447
1448         // Is the message id there?
1449         if (!isMessageIdValid($messageId)) {
1450                 // Not valid param
1451                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
1452         } // END - if
1453
1454         // Return message id
1455         return '{--' . $messageId . '--}';
1456 }
1457
1458 // Translate text-encoding
1459 function translateNetworkTextEncoding ($encoding) {
1460         // Generate id
1461         $messageId = 'ADMIN_NETWORK_TYPE_TEXT_ENCODING_' . strtoupper($encoding) . '';
1462
1463         // Is the message id there?
1464         if (!isMessageIdValid($messageId)) {
1465                 // Not valid encoding
1466                 reportBug(__FUNCTION__, __LINE__, 'encoding=' . $encoding . ' is invalid.');
1467         } // END - if
1468
1469         // Return message id
1470         return '{--' . $messageId . '--}';
1471 }
1472
1473 // Translates API index
1474 function translateNetworkApiIndex ($index) {
1475         // Is there cache?
1476         if (!isset($GLOBALS['network_array_index'])) {
1477                 // Get an array of all API array indexes
1478                 $GLOBALS['network_array_index'] = array();
1479
1480                 // Get all entries
1481                 $result = SQL_QUERY('SELECT
1482         `network_array_id`,
1483         `network_array_index`,
1484         `network_translation_name`
1485 FROM
1486         `{?_MYSQL_PREFIX?}_network_array_translation`
1487 INNER JOIN
1488         `{?_MYSQL_PREFIX?}_network_translations`
1489 ON
1490         `network_array_index`=`network_translation_id`
1491 ORDER BY
1492         `network_array_sort` ASC', __FUNCTION__, __LINE__);
1493
1494                 // Are there entries?
1495                 if (!SQL_HASZERONUMS($result)) {
1496                         // Get all entries
1497                         while ($row = SQL_FETCHARRAY($result)) {
1498                                 // Add it to our global array
1499                                 $GLOBALS['network_array_index'][$row['network_array_index']] = $row;
1500                         } // END - while
1501                 } // END - if
1502
1503                 // Free result
1504                 SQL_FREERESULT($result);
1505         } // END - if
1506
1507         // Default name is unknown
1508         $name = 'unknown';
1509
1510         // Is the entry there?
1511         if (isset($GLOBALS['network_array_index'][$index])) {
1512                 // Then get the name
1513                 $name = $GLOBALS['network_array_index'][$index]['network_translation_name'];
1514         } // END - if
1515
1516         // Return translation
1517         return translateNetworkTranslationName($name);
1518 }
1519
1520 // Translates network API configuration status (see function isNetworkApiConfigured()) by given id
1521 function translateNetworkApiConfiguredStatusById ($networkId) {
1522         // Is there cache?
1523         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1524                 // By default it is not configured
1525                 $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_CONFIGURED--}';
1526
1527                 // So is it configured?
1528                 if (!isNetworkActiveById($networkId)) {
1529                         // Network is not active
1530                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_ACTIVE--}';
1531                 } elseif (isNetworkApiConfigured($networkId)) {
1532                         // Yes, it is
1533                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_CONFIGURED--}';
1534                 } // END - if
1535         } // END - if
1536
1537         // Return cache
1538         return $GLOBALS[__FUNCTION__][$networkId];
1539 }
1540
1541 /**
1542  * "Translates" given amount of queries; 0 = unlimited
1543  *
1544  * @param       $amount                 Amount of free queries
1545  * @return      $translated             "Translated" value; 0 = unlimited
1546  */
1547 function translateNetworkQueryAmount ($amount) {
1548         // Default is unlimited (good! ;-) )
1549         $translated = '{--UNLIMITED--}';
1550
1551         // Is the amount larger zero?
1552         if ($amount > 0) {
1553                 // Then translate it
1554                 $translated = translateComma($amount);
1555         } // END - if
1556
1557         // Return translated value
1558         return $translated;
1559 }
1560
1561 /**
1562  * "Translates given status (Y/N) to "de-/activated" but only if expert and
1563  * debug mode are enabled.
1564  *
1565  * @param       $status                 Can be one of Y/N
1566  * @return      $translated             "Translated" status
1567  */
1568 function translateNetworkActivationStatus ($status) {
1569         // Is there cache?
1570         if (!isset($GLOBALS[__FUNCTION__][$status])) {
1571                 // Default is not enabled
1572                 $GLOBALS[__FUNCTION__][$status] = '';
1573
1574                 // Is expert + debug mode enabled?
1575                 if ((isAdminsExpertSettingEnabled()) && (isDebugModeEnabled())) {
1576                         // Then "translate" it
1577                         $GLOBALS[__FUNCTION__][$status] = translateActivationStatus($status);
1578                 } // END - if
1579         } // END - if
1580
1581         // Return "translation"
1582         return $GLOBALS[__FUNCTION__][$status];
1583 }
1584
1585 //------------------------------------------------------------------------------
1586 //               Wrapper functions to save data to network tables
1587 //------------------------------------------------------------------------------
1588
1589 // Updates given network (id) with data from array
1590 function doNetworkUpdateDataByArray ($networkId, $networkData) {
1591         // Ids lower one are not accepted
1592         if (!isValidId($networkId)) {
1593                 // Not good, should be fixed
1594                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is smaller than 1.');
1595         } // END - if
1596
1597         // Just call our inner method
1598         return adminSaveSettings($networkData, '_network_data', sprintf("`network_id`=%s", bigintval($networkId)), array(), FALSE, FALSE);
1599 }
1600
1601 // Updates given network type handler (id) with data from array
1602 function doNetworkUpdateTypeByArray ($networkTypeId, $networkTypeData) {
1603         // Ids lower one are not accepted
1604         if (!isValidId($networkTypeId)) {
1605                 // Not good, should be fixed
1606                 reportBug(__FUNCTION__, __LINE__, 'Network type handler id ' . $networkTypeId . ' is smaller than 1.');
1607         } // END - if
1608
1609         // Just call our inner method
1610         return adminSaveSettings($networkTypeData, '_network_types', sprintf("`network_type_id`=%s", bigintval($networkTypeId)), array(), FALSE, FALSE);
1611 }
1612
1613 // Updates given network request parameters (id) with data from array
1614 function doNetworkUpdateParamsByArray ($networkParamsId, $networkParamsData) {
1615         // Ids lower one are not accepted
1616         if (!isValidId($networkParamsId)) {
1617                 // Not good, should be fixed
1618                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkParamsId . ' is smaller than 1.');
1619         } // END - if
1620
1621         // Just call our inner method
1622         return adminSaveSettings($networkParamsData, '_network_request_params', sprintf("`network_request_param_id`=%s", bigintval($networkParamsId)), array(), FALSE, FALSE);
1623 }
1624
1625 // Updates given network array translations (id) with data from array
1626 function doNetworkUpdateArrayTranslationsByArray ($networkTranslationsId, $networkTranslationsData) {
1627         // Ids lower one are not accepted
1628         if (!isValidId($networkTranslationsId)) {
1629                 // Not good, should be fixed
1630                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkTranslationsId . ' is smaller than 1.');
1631         } // END - if
1632
1633         // Just call our inner method
1634         return adminSaveSettings($networkTranslationsData, '_network_array_translation', sprintf("`network_array_id`=%s", bigintval($networkTranslationsId)), array(), FALSE, FALSE);
1635 }
1636
1637 //------------------------------------------------------------------------------
1638 //                 Call-back functions for request parameter keys
1639 //------------------------------------------------------------------------------
1640
1641 // ----------------------- Table: network_api_config -----------------------
1642
1643 // Handles affiliate id
1644 function doHandleNetworkRequestAffiliateIdKey ($networkTypeId) {
1645         // It is assumed that the network + type handler are both configured
1646         // Load full config data (this will be "cached"!)
1647         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1648
1649         // Is the network activated?
1650         if (!isset($configData['network_api_active'])) {
1651                 // Configuration could not be loaded
1652                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1653         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1654                 // Is not activated, so don't handle it in non-debug mode
1655                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1656         } elseif (empty($configData['network_api_affiliate_id'])) {
1657                 // Required element is not set
1658                 reportBug(__FUNCTION__, __LINE__, 'network_api_affiliate_id for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1659         }
1660
1661         // Return configured value
1662         return $configData['network_api_affiliate_id'];
1663 }
1664
1665 // Handles site id
1666 function doHandleNetworkRequestSiteIdKey ($networkTypeId) {
1667         // It is assumed that the network + type handler are both configured
1668         // Load full config data (this will be "cached"!)
1669         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1670
1671         // Is the network activated?
1672         if (!isset($configData['network_api_active'])) {
1673                 // Configuration could not be loaded
1674                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1675         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1676                 // Is not activated, so don't handle it in non-debug mode
1677                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1678         } elseif (empty($configData['network_api_site_id'])) {
1679                 // Required element is not set
1680                 reportBug(__FUNCTION__, __LINE__, 'network_api_site_id for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1681         }
1682
1683         // Return configured value
1684         return $configData['network_api_site_id'];
1685 }
1686
1687 // Handles interface password
1688 function doHandleNetworkRequestPasswordKey ($networkTypeId) {
1689         // It is assumed that the network + type handler are both configured
1690         // Load full config data (this will be "cached"!)
1691         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1692
1693         // Is the network activated?
1694         if (!isset($configData['network_api_active'])) {
1695                 // Configuration could not be loaded
1696                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1697         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1698                 // Is not activated, so don't handle it in non-debug mode
1699                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1700         } elseif (empty($configData['network_api_password'])) {
1701                 // Required element is not set
1702                 reportBug(__FUNCTION__, __LINE__, 'network_api_password for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1703         }
1704
1705         // Return configured value
1706         return $configData['network_api_password'];
1707 }
1708
1709 // ----------------------- Table: network_handler_config -----------------------
1710
1711 // Handles reload lock
1712 function doHandleNetworkRequestReloadKey ($networkTypeId) {
1713         // It is assumed that the network + type handler are both configured
1714         // Load full config data (this will be "cached"!)
1715         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1716
1717         // Is the network activated?
1718         if (!isset($configData['network_api_active'])) {
1719                 // Configuration could not be loaded
1720                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1721         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1722                 // Is not activated, so don't handle it in non-debug mode
1723                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1724         }
1725
1726         // Return configured value
1727         return caluculateTimeUnitValue($configData['network_max_reload_time'], $configData['network_type_reload_time_unit']);
1728 }
1729
1730 // Handles minimum stay
1731 function doHandleNetworkRequestMinimumStayKey ($networkTypeId) {
1732         // It is assumed that the network + type handler are both configured
1733         // Load full config data (this will be "cached"!)
1734         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1735
1736         // Is the network activated?
1737         if (!isset($configData['network_api_active'])) {
1738                 // Configuration could not be loaded
1739                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1740         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1741                 // Is not activated, so don't handle it in non-debug mode
1742                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1743         }
1744
1745         // Return configured value
1746         return $configData['network_min_waiting_time'];
1747 }
1748
1749 // Handles maximum stay
1750 function doHandleNetworkRequestMaximumStayKey ($networkTypeId) {
1751         // It is assumed that the network + type handler are both configured
1752         // Load full config data (this will be "cached"!)
1753         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1754
1755         // Is the network activated?
1756         if (!isset($configData['network_api_active'])) {
1757                 // Configuration could not be loaded
1758                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1759         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1760                 // Is not activated, so don't handle it in non-debug mode
1761                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1762         }
1763
1764         // Return configured value
1765         return $configData['network_max_waiting_time'];
1766 }
1767
1768 // Handles remaining clicks
1769 function doHandleNetworkRequestRemainClicksKey ($networkTypeId) {
1770         // It is assumed that the network + type handler are both configured
1771         // Load full config data (this will be "cached"!)
1772         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1773
1774         // Is the network activated?
1775         if (!isset($configData['network_api_active'])) {
1776                 // Configuration could not be loaded
1777                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1778         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1779                 // Is not activated, so don't handle it in non-debug mode
1780                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1781         }
1782
1783         // Return configured value
1784         return $configData['network_min_remain_clicks'];
1785 }
1786
1787 // Handles remaining budget
1788 function doHandleNetworkRequestRemainBudgetKey ($networkTypeId) {
1789         // It is assumed that the network + type handler are both configured
1790         // Load full config data (this will be "cached"!)
1791         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1792
1793         // Is the network activated?
1794         if (!isset($configData['network_api_active'])) {
1795                 // Configuration could not be loaded
1796                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1797         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1798                 // Is not activated, so don't handle it in non-debug mode
1799                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1800         }
1801
1802         // Return configured value
1803         return $configData['network_min_remain_budget'];
1804 }
1805
1806 // Handles reward (payment)
1807 function doHandleNetworkRequestRewardKey ($networkTypeId) {
1808         // It is assumed that the network + type handler are both configured
1809         // Load full config data (this will be "cached"!)
1810         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1811
1812         // Is the network activated?
1813         if (!isset($configData['network_api_active'])) {
1814                 // Configuration could not be loaded
1815                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1816         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1817                 // Is not activated, so don't handle it in non-debug mode
1818                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1819         } elseif (empty($configData['network_min_payment'])) {
1820                 // Required element is not set
1821                 reportBug(__FUNCTION__, __LINE__, 'network_min_payment for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1822         }
1823
1824         // Return configured value
1825         return $configData['network_min_payment'];
1826 }
1827
1828 // Handles media size
1829 function doHandleNetworkRequestSizeKey ($networkTypeId) {
1830         // It is assumed that the network + type handler are both configured
1831         // Load full config data (this will be "cached"!)
1832         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1833
1834         // Is the network activated?
1835         if (!isset($configData['network_api_active'])) {
1836                 // Configuration could not be loaded
1837                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1838         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1839                 // Is not activated, so don't handle it in non-debug mode
1840                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1841         } elseif (empty($configData['network_media_size'])) {
1842                 // Required element is not set
1843                 reportBug(__FUNCTION__, __LINE__, 'network_media_size for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1844         }
1845
1846         // Return configured value
1847         return $configData['network_media_size'];
1848 }
1849
1850 // Handles media output (type)
1851 function doHandleNetworkRequestTypeKey ($networkTypeId) {
1852         // It is assumed that the network + type handler are both configured
1853         // Load full config data (this will be "cached"!)
1854         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1855
1856         // Is the network activated?
1857         if (!isset($configData['network_api_active'])) {
1858                 // Configuration could not be loaded
1859                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1860         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1861                 // Is not activated, so don't handle it in non-debug mode
1862                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1863         }
1864
1865         // Return configured value
1866         return $configData['network_media_output'];
1867 }
1868
1869 // Handles erotic
1870 function doHandleNetworkRequestEroticKey ($networkTypeId) {
1871         // It is assumed that the network + type handler are both configured
1872         // Load full config data (this will be "cached"!)
1873         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1874
1875         // Is the network activated?
1876         if (!isset($configData['network_api_active'])) {
1877                 // Configuration could not be loaded
1878                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1879         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1880                 // Is not activated, so don't handle it in non-debug mode
1881                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1882         } elseif (empty($configData['network_allow_erotic'])) {
1883                 // Required element is not set
1884                 reportBug(__FUNCTION__, __LINE__, 'network_allow_erotic for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1885         }
1886
1887         // Return configured value
1888         return $configData['network_allow_erotic'];
1889 }
1890
1891 // ----------------------- Table: network_request_params -----------------------
1892
1893 //------------------------------------------------------------------------------
1894 //                       Call-back functions for admin area
1895 //------------------------------------------------------------------------------
1896
1897 // Callback function to add new network
1898 function doAdminNetworkProcessAddNetwork () {
1899         // We can say here, the form is sent, so check if the network is already added
1900         if (isNetworkNameValid(postRequestElement('network_short_name'))) {
1901                 // Already there
1902                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ALREADY_ADDED=' . postRequestElement('network_short_name') . '%}');
1903                 return FALSE;
1904         } // END - if
1905
1906         // Add the whole request to database
1907         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_data'), __FUNCTION__, __LINE__);
1908
1909         // Add the id for output only
1910         setPostRequestElement('network_id', SQL_INSERTID());
1911
1912         // Output message
1913         if (!SQL_HASZEROAFFECTED()) {
1914                 // Successfully added
1915                 loadTemplate('admin_network_added', FALSE, postRequestArray());
1916         } else {
1917                 // Not added
1918                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_DATA_NOT_ADDED=' . postRequestElement('network_short_name') . '%}');
1919         }
1920 }
1921
1922 // Displays selected networks for editing
1923 function doAdminNetworkProcessHandleNetworks () {
1924         // Is there selections?
1925         if (ifPostContainsSelections()) {
1926                 // Something has been selected, so start displaying one by one
1927                 $OUT = '';
1928                 foreach (postRequestElement('sel') as $networkId => $sel) {
1929                         // Is this selected?
1930                         if ($sel == 1) {
1931                                 // Load this network's data
1932                                 $networkData = getNetworkDataById($networkId);
1933
1934                                 // Is there found the network?
1935                                 if (count($networkData) > 0) {
1936                                         // Add row template with given form name
1937                                         $OUT .= loadTemplate('admin_' . getNetworkFormName() . '_networks_row', TRUE, $networkData);
1938                                 } // END - if
1939                         } // END - if
1940                 } // END - foreach
1941
1942                 // If we have no rows, we don't need to display the edit form
1943                 if (!empty($OUT)) {
1944                         // Init array with generic element
1945                         $content = array(
1946                                 'rows' => $OUT
1947                         );
1948
1949                         // Output main template
1950                         loadTemplate('admin_' . getNetworkFormName() . '_networks', FALSE, $content);
1951
1952                         // Don't display the list/add new form
1953                         $GLOBALS['network_display'] = FALSE;
1954                 } else {
1955                         // Nothing selected/found
1956                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_FOUND--}');
1957                 }
1958         } // END - if
1959 }
1960
1961 // Handle network type form
1962 function doAdminNetworkProcessHandleNetworkTypes () {
1963         // Is there selections?
1964         if (ifPostContainsSelections()) {
1965                 // Load network data
1966                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1967
1968                 // Something has been selected, so start displaying one by one
1969                 $OUT = '';
1970                 foreach (postRequestElement('sel') as $networkId => $sel) {
1971                         // Is this selected?
1972                         if ($sel == 1) {
1973                                 // Load this network's data
1974                                 $networkTypeData = getNetworkTypeDataByTypeId($networkId);
1975
1976                                 // Is there found the network?
1977                                 if (count($networkTypeData) > 0) {
1978                                         if (getNetworkFormName() == 'edit') {
1979                                                 // Add row template for deleting
1980                                                 $OUT .= loadTemplate('admin_edit_network_types_row', TRUE, $networkTypeData);
1981                                         } elseif (getNetworkFormName() == 'delete') {
1982                                                 // Add row template for deleting
1983                                                 $OUT .= loadTemplate('admin_delete_network_types_row', TRUE, $networkTypeData);
1984                                         } else {
1985                                                 // Problem!
1986                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
1987                                         }
1988                                 } // END - if
1989                         } // END - if
1990                 } // END - foreach
1991
1992                 // If we have no rows, we don't need to display the edit form
1993                 if (!empty($OUT)) {
1994                         // Prepare array with generic elements
1995                         $content = array(
1996                                 'rows'       => $OUT,
1997                                 'network_id' => bigintval(getRequestElement('network_id'))
1998                         );
1999
2000                         // Output main template
2001                         if (getNetworkFormName() == 'edit') {
2002                                 loadTemplate('admin_edit_network_types', FALSE, $content);
2003                         } elseif (getNetworkFormName() == 'delete') {
2004                                 loadTemplate('admin_delete_network_types', FALSE, $content);
2005                         } else {
2006                                 // Problem!
2007                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2008                         }
2009
2010                         // Don't display the list/add new form
2011                         $GLOBALS['network_display'] = FALSE;
2012                 } else {
2013                         // Nothing selected/found
2014                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_FOUND--}');
2015                 }
2016         } // END - if
2017 }
2018
2019 // Handle network request parameter form
2020 function doAdminNetworkProcessHandleRequestParams () {
2021         // Is there selections?
2022         if (ifPostContainsSelections()) {
2023                 // Init cache array
2024                 $GLOBALS['network_request_params_disabled'] = array();
2025
2026                 // Load network data
2027                 $networkData = getNetworkDataById(getRequestElement('network_id'));
2028
2029                 // Something has been selected, so start displaying one by one
2030                 $OUT = '';
2031                 foreach (postRequestElement('sel') as $networkId => $sel) {
2032                         // Is this selected?
2033                         if ($sel == 1) {
2034                                 // Load this network's data
2035                                 $networkRequestData = getNetworkRequestParamsDataById($networkId);
2036
2037                                 // Is there found the network?
2038                                 if (count($networkRequestData) > 0) {
2039                                         if (getNetworkFormName() == 'edit') {
2040                                                 // Add row template for deleting
2041                                                 $OUT .= loadTemplate('admin_edit_network_request_params_row', TRUE, $networkRequestData);
2042                                         } elseif (getNetworkFormName() == 'delete') {
2043                                                 // Get type data
2044                                                 $networkRequestData['network_type_data'] = getNetworkTypeDataByTypeId($networkRequestData['network_type_id']);
2045
2046                                                 // Add row template for deleting
2047                                                 $OUT .= loadTemplate('admin_delete_network_request_params_row', TRUE, $networkRequestData);
2048                                         } else {
2049                                                 // Problem!
2050                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2051                                         }
2052                                 } // END - if
2053                         } // END - if
2054                 } // END - foreach
2055
2056                 // If we have no rows, we don't need to display the edit form
2057                 if (!empty($OUT)) {
2058                         // Prepare array with generic elements
2059                         $content = array(
2060                                 'rows'       => $OUT,
2061                                 'network_id' => bigintval(getRequestElement('network_id'))
2062                         );
2063
2064                         // Output main template
2065                         if (getNetworkFormName() == 'edit') {
2066                                 loadTemplate('admin_edit_network_request_params', FALSE, $content);
2067                         } elseif (getNetworkFormName() == 'delete') {
2068                                 loadTemplate('admin_delete_network_request_params', FALSE, $content);
2069                         } else {
2070                                 // Problem!
2071                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2072                         }
2073
2074                         // Don't display the list/add new form
2075                         $GLOBALS['network_display'] = FALSE;
2076                 } else {
2077                         // Nothing selected/found
2078                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
2079                 }
2080         } // END - if
2081 }
2082
2083 // Changes given networks
2084 function doAdminNetworkProcessChangeNetworks () {
2085         // Is there selections?
2086         if (ifPostContainsSelections()) {
2087                 // By default nothing is updated
2088                 $updated = 0;
2089
2090                 // Something has been selected, so start updating them
2091                 foreach (postRequestElement('sel') as $networkId => $sel) {
2092                         // Update this entry?
2093                         if ($sel == 1) {
2094                                 // Init data array
2095                                 $networkData = array();
2096
2097                                 // Transfer whole array, except 'sel'
2098                                 foreach (postRequestArray() as $key => $entry) {
2099                                         // Skip 'sel' and submit button
2100                                         if (in_array($key, array('sel', 'do_edit'))) {
2101                                                 continue;
2102                                         } // END - if
2103
2104                                         // Is there this enty?
2105                                         if (!isset($entry[$networkId])) {
2106                                                 // Not found, needs fixing
2107                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2108                                         } // END - if
2109
2110                                         // Add this entry
2111                                         $networkData[$key] = $entry[$networkId];
2112                                 } // END - foreach
2113
2114                                 // Update the network data
2115                                 $updated += doNetworkUpdateDataByArray($networkId, $networkData);
2116                         } // END - if
2117                 } // END - foreach
2118
2119                 // Is there updates?
2120                 if ($updated > 0) {
2121                         // Updates done
2122                         displayMessage('{%message,ADMIN_NETWORK_UPDATED=' . $updated . '%}');
2123                 } else {
2124                         // Nothing changed
2125                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_CHANGED--}');
2126                 }
2127         } // END - if
2128 }
2129
2130 // Removes given networks
2131 function doAdminNetworkProcessRemoveNetworks () {
2132         // Is there selections?
2133         if (ifPostContainsSelections()) {
2134                 // By default nothing is removed
2135                 $removed = 0;
2136
2137                 // Something has been selected, so start updating them
2138                 foreach (postRequestElement('sel') as $networkId => $sel) {
2139                         // Update this entry?
2140                         if ($sel == 1) {
2141                                 // Remove this entry
2142                                 $removed += doAdminRemoveNetworkEntry('data', 'network_id', $networkId);
2143                         } // END - if
2144                 } // END - foreach
2145
2146                 // Is there removes?
2147                 if ($removed > 0) {
2148                         // Removals done
2149                         displayMessage('{%message,ADMIN_NETWORK_REMOVED=' . $removed . '%}');
2150                 } else {
2151                         // Nothing removed
2152                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_REMOVED--}');
2153                 }
2154         } // END - if
2155 }
2156
2157 // Add a network type handler if not yet found
2158 function doAdminNetworkProcessAddNetworkType () {
2159         // Is the network type handle already used with given network?
2160         if (isNetworkTypeHandleValid(postRequestElement('network_type_handler'), getRequestElement('network_id'))) {
2161                 // Already added
2162                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_ALREADY_ADDED=' . postRequestElement('network_type_handler') . '%}');
2163
2164                 // ... so abort here
2165                 return FALSE;
2166         } // END - if
2167
2168         // Add id
2169         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2170
2171         // Is network_type_click_url set?
2172         if (!isPostRequestElementSet('network_type_click_url')) {
2173                 // Remove empty value to get a NULL for an optional entry
2174                 unsetPostRequestElement('network_type_click_url');
2175         } // END - if
2176
2177         // Is network_type_banner_url set?
2178         if (!isPostRequestElementSet('network_type_banner_url')) {
2179                 // Remove empty value to get a NULL for an optional entry
2180                 unsetPostRequestElement('network_type_banner_url');
2181         } // END - if
2182
2183         // Add the whole request to database
2184         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_types'), __FUNCTION__, __LINE__);
2185
2186         // Output message
2187         if (!SQL_HASZEROAFFECTED()) {
2188                 // Successfully added
2189                 loadTemplate('admin_network_type_added', FALSE, postRequestArray());
2190         } else {
2191                 // Not added
2192                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_NOT_ADDED=' . postRequestElement('network_type_handler') . '%}');
2193         }
2194 }
2195
2196 // Changes given network type handlers
2197 function doAdminNetworkProcessChangeHandlerTypes () {
2198         // Is there selections?
2199         if (ifPostContainsSelections()) {
2200                 // By default nothing is updated
2201                 $updated = 0;
2202
2203                 // Something has been selected, so start updating them
2204                 foreach (postRequestElement('sel') as $networkId => $sel) {
2205                         // Update this entry?
2206                         if ($sel == 1) {
2207                                 // Init data array
2208                                 $networkTypeData = array();
2209
2210                                 // Transfer whole array, except 'sel'
2211                                 foreach (postRequestArray() as $key => $entry) {
2212                                         // Skip 'sel' and submit button
2213                                         if (in_array($key, array('sel', 'do_edit'))) {
2214                                                 continue;
2215                                         } // END - if
2216
2217                                         // Is there this enty?
2218                                         if (!isset($entry[$networkId])) {
2219                                                 // Not found, needs fixing
2220                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2221                                         } // END - if
2222
2223                                         // Fix empty network_type_click/banner_url to NULL
2224                                         if ((in_array($key, array('network_type_click_url', 'network_type_banner_url'))) && (trim($entry[$networkId]) == '')) {
2225                                                 // Set it to NULL
2226                                                 $entry[$networkId] = NULL;
2227                                         } // END - if
2228
2229                                         // Add this entry
2230                                         $networkTypeData[$key] = $entry[$networkId];
2231                                 } // END - foreach
2232
2233                                 // Update the network data
2234                                 $updated += doNetworkUpdateTypeByArray($networkId, $networkTypeData);
2235                         } // END - if
2236                 } // END - foreach
2237
2238                 // Is there updates?
2239                 if ($updated > 0) {
2240                         // Updates done
2241                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_UPDATED=' . $updated . '%}');
2242                 } else {
2243                         // Nothing changed
2244                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_CHANGED--}');
2245                 }
2246         } // END - if
2247 }
2248
2249 // Changes given network request parameters
2250 function doAdminNetworkProcessChangeRequestParams () {
2251         // Is there selections?
2252         if (ifPostContainsSelections()) {
2253                 // By default nothing is updated
2254                 $updated = 0;
2255
2256                 // Something has been selected, so start updating them
2257                 foreach (postRequestElement('sel') as $networkId => $sel) {
2258                         // Update this entry?
2259                         if ($sel == 1) {
2260                                 // Init data array
2261                                 $networkParamsData = array();
2262
2263                                 // Transfer whole array, except 'sel'
2264                                 foreach (postRequestArray() as $key => $entry) {
2265                                         // Skip 'sel' and submit button
2266                                         if (in_array($key, array('sel', 'do_edit'))) {
2267                                                 continue;
2268                                         } // END - if
2269
2270                                         // Is there this enty?
2271                                         if (!isset($entry[$networkId])) {
2272                                                 // Not found, needs fixing
2273                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2274                                         } // END - if
2275
2276                                         // Fix empty network_request_param_default to NULL
2277                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
2278                                                 // Set it to NULL
2279                                                 $entry[$networkId] = NULL;
2280                                         } // END - if
2281
2282                                         // Add this entry
2283                                         $networkParamsData[$key] = $entry[$networkId];
2284                                 } // END - foreach
2285
2286                                 // Update the network data
2287                                 $updated += doNetworkUpdateParamsByArray($networkId, $networkParamsData);
2288                         } // END - if
2289                 } // END - foreach
2290
2291                 // Is there updates?
2292                 if ($updated > 0) {
2293                         // Updates done
2294                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_UPDATED=' . $updated . '%}');
2295                 } else {
2296                         // Nothing changed
2297                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_CHANGED--}');
2298                 }
2299         } // END - if
2300 }
2301
2302 // Changes given network array translations
2303 function doAdminNetworkProcessChangeArrayTranslation () {
2304         // Is there selections?
2305         if (ifPostContainsSelections()) {
2306                 // By default nothing is updated
2307                 $updated = 0;
2308
2309                 // Something has been selected, so start updating them
2310                 foreach (postRequestElement('sel') as $networkId => $sel) {
2311                         // Update this entry?
2312                         if ($sel == 1) {
2313                                 // Init data array
2314                                 $networkTranslationsData = array();
2315
2316                                 // Transfer whole array, except 'sel'
2317                                 foreach (postRequestArray() as $key => $entry) {
2318                                         // Skip 'sel' and submit button
2319                                         if (in_array($key, array('sel', 'do_edit'))) {
2320                                                 continue;
2321                                         } // END - if
2322
2323                                         // Is there this enty?
2324                                         if (!isset($entry[$networkId])) {
2325                                                 // Not found, needs fixing
2326                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2327                                         } // END - if
2328
2329                                         // Fix empty network_request_param_default to NULL
2330                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
2331                                                 // Set it to NULL
2332                                                 $entry[$networkId] = NULL;
2333                                         } // END - if
2334
2335                                         // Add this entry
2336                                         $networkTranslationsData[$key] = $entry[$networkId];
2337                                 } // END - foreach
2338
2339                                 // Update the network data
2340                                 $updated += doNetworkUpdateArrayTranslationsByArray($networkId, $networkTranslationsData);
2341                         } // END - if
2342                 } // END - foreach
2343
2344                 // Is there updates?
2345                 if ($updated > 0) {
2346                         // Updates done
2347                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_UPDATED=' . $updated . '%}');
2348                 } else {
2349                         // Nothing changed
2350                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_CHANGED--}');
2351                 }
2352         } // END - if
2353 }
2354
2355 // Removes given network type handlers
2356 function doAdminNetworkProcessRemoveNetworkTypes () {
2357         // Is there selections?
2358         if (ifPostContainsSelections()) {
2359                 // By default nothing is removed
2360                 $removed = 0;
2361
2362                 // Something has been selected, so start updating them
2363                 foreach (postRequestElement('sel') as $networkId => $sel) {
2364                         // Update this entry?
2365                         if ($sel == 1) {
2366                                 // Remove this entry
2367                                 $removed += doAdminRemoveNetworkEntry('types', 'network_type_id', $networkId);
2368                         } // END - if
2369                 } // END - foreach
2370
2371                 // Is there removes?
2372                 if ($removed > 0) {
2373                         // Removals done
2374                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_REMOVED=' . $removed . '%}');
2375                 } else {
2376                         // Nothing removed
2377                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_REMOVED--}');
2378                 }
2379         } // END - if
2380 }
2381
2382 // Removes given network request parameters
2383 function doAdminNetworkProcessRemoveNetworkRequestParams () {
2384         // Is there selections?
2385         if (ifPostContainsSelections()) {
2386                 // By default nothing is removed
2387                 $removed = 0;
2388
2389                 // Something has been selected, so start updating them
2390                 foreach (postRequestElement('sel') as $networkId => $sel) {
2391                         // Update this entry?
2392                         if ($sel == 1) {
2393                                 // Remove this entry
2394                                 $removed += doAdminRemoveNetworkEntry('request_params', 'network_request_param_id', $networkId);
2395                         } // END - if
2396                 } // END - foreach
2397
2398                 // Is there removes?
2399                 if ($removed > 0) {
2400                         // Removals done
2401                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_REMOVED=' . $removed . '%}');
2402                 } else {
2403                         // Nothing removed
2404                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_REMOVED--}');
2405                 }
2406         } // END - if
2407 }
2408
2409 // Removes given network array translations
2410 function doAdminNetworkProcessRemoveNetworkArrayTranslation () {
2411         // Is there selections?
2412         if (ifPostContainsSelections()) {
2413                 // By default nothing is removed
2414                 $removed = 0;
2415
2416                 // Something has been selected, so start updating them
2417                 foreach (postRequestElement('sel') as $networkId => $sel) {
2418                         // Update this entry?
2419                         if ($sel == 1) {
2420                                 // Remove this entry
2421                                 $removed += doAdminRemoveNetworkEntry('array_translation', 'network_array_id', $networkId);
2422                         } // END - if
2423                 } // END - foreach
2424
2425                 // Is there removes?
2426                 if ($removed > 0) {
2427                         // Removals done
2428                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_REMOVED=' . $removed . '%}');
2429                 } else {
2430                         // Nothing removed
2431                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_REMOVED--}');
2432                 }
2433         } // END - if
2434 }
2435
2436 // Adds a request parameter to given network and type
2437 function doAdminNetworkProcessAddRequestParam () {
2438         // Is the request parameter already used with given network?
2439         if (isNetworkRequestElementValid(postRequestElement('network_request_param_key'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
2440                 // Already added
2441                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_request_param_key') . '%}');
2442
2443                 // ... so abort here
2444                 return FALSE;
2445         } // END - if
2446
2447         // Add id
2448         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2449
2450         // Is network_request_param_default set?
2451         if (!isPostRequestElementSet('network_request_param_default')) {
2452                 // Remove empty value to get a NULL for an optional entry
2453                 unsetPostRequestElement('network_request_param_default');
2454         } // END - if
2455
2456         // Add the whole request to database
2457         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_request_params'), __FUNCTION__, __LINE__);
2458
2459         // Output message
2460         if (!SQL_HASZEROAFFECTED()) {
2461                 // Successfully added
2462                 loadTemplate('admin_network_request_param_added', FALSE, postRequestArray());
2463         } else {
2464                 // Not added
2465                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_NOT_ADDED=' . postRequestElement('network_request_param_key') . '%}');
2466         }
2467 }
2468
2469 // Adds a vheck request parameter to given network
2470 function doAdminNetworkProcessAddVcheckParam () {
2471         // Is the request parameter already used with given network?
2472         if (isNetworkVcheckElementValid(postRequestElement('network_vcheck_param_key'), getRequestElement('network_id'))) {
2473                 // Already added
2474                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
2475
2476                 // ... so abort here
2477                 return FALSE;
2478         } // END - if
2479
2480         // Add id
2481         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2482
2483         // Is network_vcheck_param_default set?
2484         if (!isPostRequestElementSet('network_vcheck_param_default')) {
2485                 // Remove empty value to get a NULL for an optional entry
2486                 unsetPostRequestElement('network_vcheck_param_default');
2487         } // END - if
2488
2489         // Add the whole vcheck to database
2490         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_vcheck_params'), __FUNCTION__, __LINE__);
2491
2492         // Output message
2493         if (!SQL_HASZEROAFFECTED()) {
2494                 // Successfully added
2495                 loadTemplate('admin_network_vcheck_param_added', FALSE, postRequestArray());
2496         } else {
2497                 // Not added
2498                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_NOT_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
2499         }
2500 }
2501
2502 // Adds a API response array entry
2503 function doAdminNetworkProcessAddNetworkArrayTranslation () {
2504         // Is the request parameter already used with given network?
2505         if (isNetworkArrayTranslationValid(postRequestElement('network_array_index'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
2506                 // Already added
2507                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_ALREADY_ADDED=' . postRequestElement('network_array_index') . '%}');
2508
2509                 // ... so abort here
2510                 return FALSE;
2511         } // END - if
2512
2513         // Add id
2514         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2515
2516         // Add sorting
2517         setPostRequestElement('network_array_sort', (countSumTotalData(
2518                 bigintval(postRequestElement('network_id')),
2519                 'network_array_translation',
2520                 'network_array_id',
2521                 'network_id',
2522                 true,
2523                 sprintf(" AND `network_type_id`=%s", bigintval(postRequestElement('network_type_id')))
2524         ) + 1));
2525
2526         // Add the whole request to database
2527         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_array_translation'), __FUNCTION__, __LINE__);
2528
2529         // Output message
2530         if (!SQL_HASZEROAFFECTED()) {
2531                 // Successfully added
2532                 loadTemplate('admin_network_array_translation_added', FALSE, postRequestArray());
2533         } else {
2534                 // Not added
2535                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_NOT_ADDED=' . postRequestElement('network_array_index') . '%}');
2536         }
2537 }
2538
2539 // Handle network array translation form
2540 function doAdminNetworkProcessHandleArrayTranslations () {
2541         // Is there selections?
2542         if (ifPostContainsSelections()) {
2543                 // Init cache array
2544                 $GLOBALS['network_array_translation_disabled'] = array();
2545
2546                 // Load network data
2547                 $networkData = getNetworkDataById(getRequestElement('network_id'));
2548
2549                 // Something has been selected, so start displaying one by one
2550                 $OUT = '';
2551                 foreach (postRequestElement('sel') as $networkId => $sel) {
2552                         // Is this selected?
2553                         if ($sel == 1) {
2554                                 // Load this network's data
2555                                 $networkTranslationsData = getNetworkArrayTranslationsDataById($networkId);
2556
2557                                 // Is there found the network?
2558                                 if (count($networkTranslationsData) > 0) {
2559                                         if (getNetworkFormName() == 'edit') {
2560                                                 // Add row template for deleting
2561                                                 $OUT .= loadTemplate('admin_edit_network_array_translation_row', TRUE, $networkTranslationsData);
2562                                         } elseif (getNetworkFormName() == 'delete') {
2563                                                 // Get type data
2564                                                 $networkTranslationsData['network_type_data'] = getNetworkTypeDataByTypeId($networkTranslationsData['network_type_id']);
2565
2566                                                 // Add row template for deleting
2567                                                 $OUT .= loadTemplate('admin_delete_network_array_translation_row', TRUE, $networkTranslationsData);
2568                                         } else {
2569                                                 // Problem!
2570                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2571                                         }
2572                                 } // END - if
2573                         } // END - if
2574                 } // END - foreach
2575
2576                 // If we have no rows, we don't need to display the edit form
2577                 if (!empty($OUT)) {
2578                         // Prepare array with generic elements
2579                         $content = array(
2580                                 'rows'       => $OUT,
2581                                 'network_id' => bigintval(getRequestElement('network_id'))
2582                         );
2583
2584                         // Output main template
2585                         if (getNetworkFormName() == 'edit') {
2586                                 loadTemplate('admin_edit_network_array_translation', FALSE, $content);
2587                         } elseif (getNetworkFormName() == 'delete') {
2588                                 loadTemplate('admin_delete_network_array_translation', FALSE, $content);
2589                         } else {
2590                                 // Problem!
2591                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2592                         }
2593
2594                         // Don't display the list/add new form
2595                         $GLOBALS['network_display'] = FALSE;
2596                 } else {
2597                         // Nothing selected/found
2598                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
2599                 }
2600         } // END - if
2601 }
2602
2603 // Adds/update network API configuration
2604 function doAdminNetworkProcessNetworkApiConfig () {
2605         // Add id
2606         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2607
2608         // Is network_api_referral_button set?
2609         if (!isPostRequestElementSet('network_api_referral_button')) {
2610                 // Remove empty value to get a NULL for an optional entry
2611                 unsetPostRequestElement('network_api_referral_button');
2612         } // END - if
2613
2614         // Is there already an entry?
2615         if (isNetworkApiConfigured(getRequestElement('network_id'))) {
2616                 // Generate SQL query
2617                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_api_config', 'network_id', postRequestElement('network_id'), array('network_id'));
2618         } else {
2619                 // Insert new entry
2620                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_api_config');
2621         }
2622
2623         // Run the query
2624         SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2625
2626         // Output message
2627         if (!SQL_HASZEROAFFECTED()) {
2628                 // Successfully added
2629                 displayMessage('{--ADMIN_CONFIG_NETWORK_API_SAVED--}');
2630         } else {
2631                 // Not added
2632                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_API_NOT_SAVED--}');
2633         }
2634 }
2635
2636 // Only adds network type configuration if not yet present
2637 function doAdminNetworkProcessAddHandlerTypesConfig ($displayMessage = TRUE, $convertComma = TRUE) {
2638         // Add both ids
2639         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2640         setPostRequestElement('network_type_id', bigintval(getRequestElement('network_type_id')));
2641
2642         // Convert comma to dot?
2643         if ($convertComma === TRUE) {
2644                 // Translate German comma to dot
2645                 convertCommaToDotInPostData('network_min_payment');
2646                 convertCommaToDotInPostData('network_min_remain_budget');
2647                 convertCommaToDotInPostData('network_min_remain_clicks');
2648         } // END - if
2649
2650         /*
2651          * Some parameters are optional, at least one must be given so check a bunch
2652          * of parameters.
2653          */
2654         foreach (array('network_min_waiting_time', 'network_max_waiting_time', 'network_min_remain_budget', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic', 'network_media_size', 'network_media_output') as $element) {
2655                 // Is this element empty?
2656                 if (!isPostRequestElementSet($element)) {
2657                         // Then unset it to get a NULL for optional parameter
2658                         unsetPostRequestElement($element);
2659                 } // END - if
2660         } // END - foreach
2661
2662         // Convert data in POST array
2663         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
2664
2665         // Is there already an entry?
2666         if (isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
2667                 // This network type handler is already configured
2668                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_ALREADY_CONFIGURED--}');
2669                 return;
2670         } // END - if
2671
2672         // Copy 'set all' and remove it from POST data
2673         $setAll = (postRequestElement('set_all') === 'Y');
2674         unsetPostRequestElement('set_all');
2675
2676         // Shall we set for all?
2677         if ($setAll === TRUE) {
2678                 // Get all handlers
2679                 $result = SQL_QUERY_ESC('SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
2680                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
2681
2682                 // Are there entries?
2683                 if (SQL_HASZERONUMS($result)) {
2684                         // No, then abort here
2685                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
2686                         return;
2687                 } // END - if
2688
2689                 // Init number of rows
2690                 $numRows = 0;
2691
2692                 // Fetch all ids
2693                 while (list($typeId) = SQL_FETCHROW($result)) {
2694                         // Set it in GET data
2695                         setGetRequestElement('network_type_id', $typeId);
2696
2697                         // Call this function again
2698                         $numRows += doAdminNetworkProcessAddHandlerTypesConfig(FALSE, FALSE);
2699                 } // END - while
2700
2701                 // Free result
2702                 SQL_FREERESULT($result);
2703
2704                 // Output message
2705                 if ($numRows > 0) {
2706                         // Something has been updated
2707                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2708                 } else {
2709                         // Nothing has been saved
2710                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2711                 }
2712         } else {
2713                 // Get SQL query for new entry
2714                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_handler_config');
2715
2716                 // Run the query
2717                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2718
2719                 // Shall we display the message?
2720                 if ($displayMessage === TRUE) {
2721                         // Output message
2722                         if (!SQL_HASZEROAFFECTED()) {
2723                                 // Successfully added
2724                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2725                         } else {
2726                                 // Not added
2727                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_SAVED--}');
2728                         }
2729                 } else {
2730                         // Return amount of affected rows (1 or 2)
2731                         return SQL_AFFECTEDROWS();
2732                 }
2733         }
2734 }
2735
2736 // Only changes network type configuration if not yet present
2737 function doAdminNetworkProcessEditHandlerTypesConfig ($displayMessage = TRUE, $convertComma = TRUE) {
2738         // Convert comma to dot?
2739         if ($convertComma === TRUE) {
2740                 // Translate German comma to dot
2741                 convertCommaToDotInPostData('network_min_payment');
2742                 convertCommaToDotInPostData('network_min_remain_budget');
2743                 convertCommaToDotInPostData('network_min_remain_clicks');
2744         } // END - if
2745
2746         /*
2747          * Some parameters are optional, at least one must be given so check a bunch
2748          * of parameters.
2749          */
2750         foreach (array('network_min_waiting_time', 'network_max_waiting_time', 'network_min_remain_budget', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic', 'network_media_size', 'network_media_output') as $element) {
2751                 // Is this element empty?
2752                 if (!isPostRequestElementSet($element)) {
2753                         // Then unset it to get a NULL for optional parameter
2754                         unsetPostRequestElement($element);
2755                 } // END - if
2756         } // END - foreach
2757
2758         // Convert time selections in POST data
2759         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
2760
2761         // Is there already an entry?
2762         if (!isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
2763                 // This network type handler is not configured
2764                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_NOT_CONFIGURED--}');
2765                 return;
2766         } // END - if
2767
2768         // Copy 'set all' and remove it from POST data
2769         $setAll = (postRequestElement('set_all') === 'Y');
2770         unsetPostRequestElement('set_all');
2771
2772         // Shall we set for all?
2773         if ($setAll === TRUE) {
2774                 // Get all data entries
2775                 $result = SQL_QUERY_ESC('SELECT `network_data_id` FROM `{?_MYSQL_PREFIX?}_network_handler_config` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
2776                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
2777
2778                 // Are there entries?
2779                 if (SQL_HASZERONUMS($result)) {
2780                         // No, then abort here
2781                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
2782                         return;
2783                 } // END - if
2784
2785                 // Init number of rows
2786                 $numRows = 0;
2787
2788                 // Fetch all ids
2789                 while (list($dataId) = SQL_FETCHROW($result)) {
2790                         // Set it in GET data
2791                         setPostRequestElement('network_data_id', $dataId);
2792
2793                         // Call this function again
2794                         $numRows += doAdminNetworkProcessEditHandlerTypesConfig(FALSE, FALSE);
2795                 } // END - while
2796
2797                 // Free result
2798                 SQL_FREERESULT($result);
2799
2800                 // Output message
2801                 if ($numRows > 0) {
2802                         // Something has been updated
2803                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2804                 } else {
2805                         // Nothing has been saved
2806                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2807                 }
2808         } else {
2809                 // Get SQL query for new entry
2810                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_handler_config', 'network_data_id', postRequestElement('network_data_id'), array('network_data_id'));
2811
2812                 // Run the query
2813                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2814
2815                 // Shall we display the message?
2816                 if ($displayMessage === TRUE) {
2817                         // Output message
2818                         if (!SQL_HASZEROAFFECTED()) {
2819                                 // Successfully added
2820                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2821                         } else {
2822                                 // Not added
2823                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2824                         }
2825                 } else {
2826                         // Return amount of affected rows (1 or 2)
2827                         return SQL_AFFECTEDROWS();
2828                 }
2829         }
2830 }
2831
2832 // Do expression code for this extension
2833 function doExpressionNetwork ($data) {
2834         // Construct replacer
2835         $replacer = sprintf(
2836                 "{DQUOTE} . %s(%s, '%s') . {DQUOTE}",
2837                 $data['callback'],
2838                 $data['matches'][4][$data['key']],
2839                 $data['extra_func']
2840         );
2841
2842         // Check matches[2] as it might contain more clues to look for
2843         $moreData = explode(',', $data['matches'][2][$data['key']]);
2844
2845         // First must be 'network' so unshift it
2846         shift_array($moreData, 'network');
2847
2848         // The second element must be a callable function
2849         if (!is_callable($moreData[0])) {
2850                 // Is not callable!
2851                 reportBug(__FUNCTION__, __LINE__, 'Call-back function ' . $moreData[0] . ' cannot be called.');
2852         } // END - if
2853
2854         // Is the current network id set?
2855         if (isCurrentNetworkIdSet()) {
2856                 // Replace %network_id% with the current network id
2857                 $replacer = str_replace('%network_id%', getCurrentNetworkId(), $replacer);
2858         } // END - if
2859
2860         // Replace the code
2861         $code = replaceExpressionCode($data, $replacer);
2862
2863         // Return it
2864         return $code;
2865 }
2866
2867 // ----------------------------------------------------------------------------
2868 //                     Call-back functions for exporting data
2869 // ----------------------------------------------------------------------------
2870
2871 // Callback function to export network tables
2872 function doAdminNetworkProcessExport () {
2873         // Init table with all valid what->table entries
2874         $validExports = array(
2875                 // General network data
2876                 'list_network_data'              => 'data',
2877                 // Network type handler
2878                 'list_network_types'             => 'types',
2879                 // Network request parameter
2880                 'list_network_request_params'    => 'request_params',
2881                 // Vcheck request parameter
2882                 'list_network_vcheck_params'     => 'vcheck_params',
2883                 // Network API response array index translation
2884                 'list_network_array_translation' => 'array_translation',
2885         );
2886
2887         // Is the 'what' key valid?
2888         if (!isset($validExports[getWhat()])) {
2889                 // Not valid
2890                 reportBug(__FUNCTION__, __LINE__, 'what=' . getWhat() . ' - not supported');
2891         } // END - if
2892
2893         // Generate call-back, some tables require to export not all columns
2894         $callbackName = 'doAdminNetworkExport' . capitalizeUnderscoreString($validExports[getWhat()]);
2895
2896         // Is the call-back function there?
2897         if (!function_exists($callbackName)) {
2898                 // No, this is really bad
2899                 reportBug(__FUNCTION__, __LINE__, 'Invalid call-back function ' . $callbackName . ' detected.');
2900         } elseif (isset($GLOBALS[__FUNCTION__][$callbackName])) {
2901                 // Already called!
2902                 reportBug(__FUNCTION__, __LINE__, 'Double-call of export function ' . $callbackName . ' detected.');
2903         }
2904
2905         // Call the function
2906         call_user_func($callbackName);
2907
2908         // Mark it as called
2909         $GLOBALS[__FUNCTION__][$callbackName] = TRUE;
2910
2911         // Don't display the list/add new form
2912         $GLOBALS['network_display'] = FALSE;
2913 }
2914
2915 // Exports (and displays) the table 'network_data'
2916 function doAdminNetworkExportData () {
2917         // Query for all networks
2918         $result = SQL_QUERY('SELECT
2919         `network_short_name`,
2920         `network_title`,
2921         `network_reflink`,
2922         `network_data_separator`,
2923         `network_row_separator`,
2924         `network_request_type`,
2925         `network_charset`,
2926         `network_require_id_card`,
2927         `network_query_amount`,
2928         `network_active`
2929 FROM
2930         `{?_MYSQL_PREFIX?}_network_data`
2931 ORDER BY
2932         `network_id` ASC',
2933                 __FUNCTION__, __LINE__);
2934
2935         // Start an empty SQL query
2936         $SQL = 'INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_data` (`network_short_name`, `network_title`, `network_reflink`, `network_data_separator`, `network_row_separator`, `network_request_type`, `network_charset`, `network_require_id_card`, `network_query_amount`, `network_active`) VALUES' . PHP_EOL;
2937
2938         // Load all entries
2939         while ($content = SQL_FETCHARRAY($result)) {
2940                 // Add row
2941                 $SQL .= "('" .
2942                         $content['network_short_name'] . "', '" .
2943                         $content['network_title'] . "', '" .
2944                         $content['network_reflink'] . "', '" .
2945                         $content['network_data_separator'] . "', '" .
2946                         $content['network_row_separator'] . "', '" .
2947                         $content['network_request_type'] . "', '" .
2948                         $content['network_charset'] . "', '" .
2949                         $content['network_require_id_card'] . "', " .
2950                         $content['network_query_amount'] . ", '" .
2951                         $content['network_active'] . "'),\n";
2952         } // END - while
2953
2954         // Remove last commata and close braces
2955         $SQL = substr($SQL, 0, -2);
2956
2957         // Free result
2958         SQL_FREERESULT($result);
2959
2960         // Output the SQL query
2961         loadTemplate('admin_export_network_data', FALSE, $SQL);
2962 }
2963
2964 // Exports (and displays) the table 'network_types'
2965 function doAdminNetworkExportTypes () {
2966         // 'network_id' must be set
2967         if (!isGetRequestElementSet('network_id')) {
2968                 // Only network handlers of one network will be exported per time
2969                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2970         } // END - if
2971
2972         // Get all network types of given network
2973         $result = SQL_QUERY_ESC('SELECT
2974         `network_type_id`,
2975         `network_id`,
2976         `network_type_handler`,
2977         `network_type_api_url`,
2978         `network_type_click_url`,
2979         `network_type_banner_url`,
2980         `network_type_reload_time_unit`,
2981         `network_text_encoding`
2982 FROM
2983         `{?_MYSQL_PREFIX?}_network_types`
2984 WHERE
2985         `network_id`=%s
2986 ORDER BY
2987         `network_type_id` ASC',
2988                 array(
2989                         bigintval(getRequestElement('network_id'))
2990                 ), __FUNCTION__, __LINE__);
2991
2992         // Start an empty SQL query
2993         $SQL = 'INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_types` (`network_type_id`, `network_id`, `network_type_handler`, `network_type_api_url`, `network_type_click_url`, `network_type_banner_url`, `network_type_reload_time_unit`, `network_text_encoding`) VALUES' . PHP_EOL;
2994
2995         // Load all entries
2996         while ($content = SQL_FETCHARRAY($result)) {
2997                 // Add row
2998                 $SQL .= '(' .
2999                         $content['network_type_id'] . ', ' .
3000                         $content['network_id'] . ", '" .
3001                         $content['network_type_handler'] . "', '" .
3002                         $content['network_type_api_url'] . "', ";
3003
3004                 // Is the column NULL?
3005                 if ((is_null($content['network_type_click_url'])) || (empty($content['network_type_click_url']))) {
3006                         // Column is NULL
3007                         $SQL .= 'NULL, ';
3008                 } else {
3009                         // Column is set
3010                         $SQL .= chr(39) . $content['network_type_click_url'] . chr(39) . ', ';
3011                 }
3012
3013                 // Is the column NULL?
3014                 if ((is_null($content['network_type_banner_url'])) || (empty($content['network_type_banner_url']))) {
3015                         // Column is NULL
3016                         $SQL .= 'NULL, ';
3017                 } else {
3018                         // Column is set
3019                         $SQL .= chr(39) . $content['network_type_banner_url'] . chr(39) . ', ';
3020                 }
3021
3022                 // Add more
3023                 $SQL .= chr(39) . $content['network_type_reload_time_unit'] . "','" . $content['network_text_encoding'] . "'),\n";
3024         } // END - while
3025
3026         // Remove last commata and close braces
3027         $SQL = substr($SQL, 0, -2);
3028
3029         // Free result
3030         SQL_FREERESULT($result);
3031
3032         // Output the SQL query
3033         loadTemplate('admin_export_network_types', FALSE, $SQL);
3034 }
3035
3036 // Exports (and displays) the table 'network_request_params'
3037 function doAdminNetworkExportRequestParams () {
3038         // 'network_id' must be set
3039         if (!isGetRequestElementSet('network_id')) {
3040                 // Only network request parameters of one network will be exported per time
3041                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3042         } // END - if
3043
3044         // Get all network types of given network
3045         $result = SQL_QUERY_ESC('SELECT
3046         `network_id`,
3047         `network_type_id`,
3048         `network_request_param_key`,
3049         `network_request_param_value`,
3050         `network_request_param_default`
3051 FROM
3052         `{?_MYSQL_PREFIX?}_network_request_params`
3053 WHERE
3054         `network_id`=%s
3055 ORDER BY
3056         `network_type_id` ASC ,
3057         `network_request_param_id` ASC',
3058                 array(
3059                         bigintval(getRequestElement('network_id'))
3060                 ), __FUNCTION__, __LINE__);
3061
3062         // Start an empty SQL query
3063         $SQL = 'INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_request_params` (`network_id`, `network_type_id`, `network_request_param_key`, `network_request_param_value`, `network_request_param_default`) VALUES' . PHP_EOL;
3064
3065         // Load all entries
3066         while ($content = SQL_FETCHARRAY($result)) {
3067                 // Add row
3068                 $SQL .= '(' .
3069                         $content['network_id'] . ', ' .
3070                         $content['network_type_id'] . ", '" .
3071                         $content['network_request_param_key'] . "', '" .
3072                         $content['network_request_param_value'] . "', ";
3073                 
3074                 // Is the column NULL?
3075                 if (is_null($content['network_request_param_default'])) {
3076                         // Column is NULL
3077                         $SQL .= "NULL),\n";
3078                 } else {
3079                         // Column is set
3080                         $SQL .= chr(39) . $content['network_request_param_default'] . "'),\n";
3081                 }
3082         } // END - while
3083
3084         // Remove last commata and close braces
3085         $SQL = substr($SQL, 0, -2);
3086
3087         // Free result
3088         SQL_FREERESULT($result);
3089
3090         // Output the SQL query
3091         loadTemplate('admin_export_network_request_params', FALSE, $SQL);
3092 }
3093
3094 // Exports (and displays) the table 'network_vcheck_params'
3095 function doAdminNetworkExportVcheckParams () {
3096         // 'network_id' must be set
3097         if (!isGetRequestElementSet('network_id')) {
3098                 // Only network vcheck parameters of one network will be exported per time
3099                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3100         } // END - if
3101
3102         // Get all network types of given network
3103         $result = SQL_QUERY_ESC('SELECT
3104         `network_id`,
3105         `network_vcheck_param_key`,
3106         `network_vcheck_param_value`,
3107         `network_vcheck_param_default`
3108 FROM
3109         `{?_MYSQL_PREFIX?}_network_vcheck_params`
3110 WHERE
3111         `network_id`=%s
3112 ORDER BY
3113         `network_vcheck_param_id` ASC',
3114                 array(
3115                         bigintval(getRequestElement('network_id'))
3116                 ), __FUNCTION__, __LINE__);
3117
3118         // Start an empty SQL query
3119         $SQL = 'INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_vcheck_params` (`network_id`, `network_vcheck_param_key`, `network_vcheck_param_value`, `network_vcheck_param_default`) VALUES' . PHP_EOL;
3120
3121         // Load all entries
3122         while ($content = SQL_FETCHARRAY($result)) {
3123                 // Add row
3124                 $SQL .= '(' .
3125                         $content['network_id'] . ", '" .
3126                         $content['network_vcheck_param_key'] . "', '" .
3127                         $content['network_vcheck_param_value'] . "', ";
3128                 
3129                 // Is the column NULL?
3130                 if (is_null($content['network_vcheck_param_default'])) {
3131                         // Column is NULL
3132                         $SQL .= "NULL),\n";
3133                 } else {
3134                         // Column is set
3135                         $SQL .= chr(39) . $content['network_vcheck_param_default'] . "'),\n";
3136                 }
3137         } // END - while
3138
3139         // Remove last commata and close braces
3140         $SQL = substr($SQL, 0, -2);
3141
3142         // Free result
3143         SQL_FREERESULT($result);
3144
3145         // Output the SQL query
3146         loadTemplate('admin_export_network_vcheck_params', FALSE, $SQL);
3147 }
3148
3149 // Exports (and displays) the table 'network_array_translation'
3150 function doAdminNetworkExportArrayTranslation () {
3151         // 'network_id' must be set
3152         if (!isGetRequestElementSet('network_id')) {
3153                 // Only network API array index translations of one network will be exported per time
3154                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3155         } // END - if
3156
3157         // Get all network types of given network
3158         $result = SQL_QUERY_ESC('SELECT
3159         `network_id`,
3160         `network_type_id`,
3161         `network_array_index`,
3162         `network_array_sort`
3163 FROM
3164         `{?_MYSQL_PREFIX?}_network_array_translation`
3165 WHERE
3166         `network_id`=%s
3167 ORDER BY
3168         `network_type_id` ASC,
3169         `network_array_sort` ASC',
3170                 array(
3171                         bigintval(getRequestElement('network_id'))
3172                 ), __FUNCTION__, __LINE__);
3173
3174         // Start an empty SQL query
3175         $SQL = 'INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_array_translation` (`network_id`, `network_type_id`, `network_array_index`, `network_array_sort`) VALUES' . PHP_EOL;
3176
3177         // Load all entries
3178         while ($content = SQL_FETCHARRAY($result)) {
3179                 // Add row
3180                 $SQL .= '(' .
3181                         $content['network_id'] . ', ' .
3182                         $content['network_type_id'] . ', ' .
3183                         $content['network_array_index'] . ', ' .
3184                         $content['network_array_sort'] . "),\n";
3185         } // END - while
3186
3187         // Remove last commata and close braces
3188         $SQL = substr($SQL, 0, -2);
3189
3190         // Free result
3191         SQL_FREERESULT($result);
3192
3193         // Output the SQL query
3194         loadTemplate('admin_export_network_array_translation', FALSE, $SQL);
3195 }
3196
3197 // ----------------------------------------------------------------------------
3198 //                     Call-back functions for AJAX requests
3199 // ----------------------------------------------------------------------------
3200
3201 // AJAX call-back function for quering a single API
3202 function doAjaxAdminNetworkQuerySingleApi () {
3203         // This must be be done only by admins
3204         if (!isAdmin()) {
3205                 // Only allowed for admins
3206                 reportBug(__FUNCTION__, __LINE__, 'Only allowed for admins.');
3207         } elseif (!isPostRequestElementSet('network_type_id')) {
3208                 // Required POST field 'network_type_id' is not there
3209                 reportBug(__FUNCTION__, __LINE__, 'Required POST field &quot;network_type_id&quot; is missing.');
3210         }
3211
3212         // Get network + type handler data
3213         $networkData = getNetworkDataByTypeId(postRequestElement('network_type_id'));
3214
3215         // Is it set?
3216         if (is_null($networkData)) {
3217                 // Provided type id is not found
3218                 reportBug(__FUNCTION__, __LINE__, 'Requested network type id ' . postRequestElement('network_type_id') . ' does not exist.');
3219         } elseif ((!isDebugModeEnabled()) && ($networkData['network_active'] == 'N')) {
3220                 // Network not active
3221                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' is not active. network_id=' . $networkData['network_id'] . ',network_type_id=' . postRequestElement('network_type_id'));
3222         } elseif (!isNetworkApiConfigured($networkData['network_id'])) {
3223                 // Network not configured
3224                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' is not configured yet. network_id=' . $networkData['network_id'] . ',network_type_id=' . postRequestElement('network_type_id'));
3225         } elseif (!isNetworkTypeHandlerConfigured($networkData['network_id'], postRequestElement('network_type_id'))) {
3226                 // Network type handler not configured
3227                 reportBug(__FUNCTION__, __LINE__, 'Network type handler ' . $networkData['network_type_handler'] . ' for network ' . $networkData['network_title'] . ' is not configured yet. network_id=' . $networkData['network_id'] . ',network_type_id=' . postRequestElement('network_type_id'));
3228         }
3229
3230         // Now load request parameters
3231         $requestParams = getNetworkRequestParametersByTypeId(postRequestElement('network_type_id'));
3232
3233         // Is there at least one entry?
3234         if (count($requestParams) == 0) {
3235                 // No entry found, please setup some first
3236                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' with id ' . $networkData['network_id'] . ' has no request parameters.');
3237         } // END - if
3238
3239         // Handle all keys
3240         handleNetworkRequestParameterKeys($requestParams);
3241
3242         /*
3243          * Array element network_request_param_value contains the request parameter
3244          * keys, network_request_param_default contains values. Now the request can
3245          * be build.
3246          */
3247         $requestData = array();
3248         foreach ($requestParams as $key => $params) {
3249                 // Add id
3250                 $requestData[$params['network_request_param_value']] = $params['network_request_param_default'];
3251         } // END - foreach
3252
3253         // Everything is setup and ready to send out to the affiliate network's API
3254         $response = queryNetworkApi($networkData, $requestData);
3255
3256         // Is the returned HTTP status '200 OK'?
3257         if (!isHttpStatusOkay($response[0])) {
3258                 // Not HTTP/1.x 200 OK
3259                 reportBug(__FUNCTION__, __LINE__, 'HTTP response code is not 200 OK, have: ' . $response[0]);
3260         } // END - if
3261
3262         // Load "success" message
3263         setAjaxReplyContent('{%message,ADMIN_NETWORK_QUERY_TYPE_OKAY=' . $networkData['network_title'] . '%}');
3264
3265         // All fine
3266         setHttpStatus('200 OK');
3267 }
3268
3269 // AJAX call-back function to return a JSON with all network type handler ids
3270 function doAjaxAdminNetworkListById () {
3271         // This must be be done only by admins
3272         if (!isAdmin()) {
3273                 // Only allowed for admins
3274                 reportBug(__FUNCTION__, __LINE__, 'Only allowed for admins.');
3275         } elseif (!isPostRequestElementSet('network_id')) {
3276                 // Required POST field 'network_id' is not there
3277                 reportBug(__FUNCTION__, __LINE__, 'Required POST field &quot;network_id&quot; is missing.');
3278         }
3279
3280         // Load all network type handlers by given network id and extract only network_type_id
3281         $networkTypes = getArrayFromArrayIndex(getNetworkTypeDataById(postRequestElement('network_id')), 'network_type_id');
3282
3283         // Set generated array
3284         setAjaxReplyContent(encodeJson($networkTypes));
3285
3286         // All fine
3287         setHttpStatus('200 OK');
3288 }
3289
3290 // [EOF]
3291 ?>