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