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