Extension ext-network continued:
[mailer.git] / inc / libs / network_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 11/04/2009 *
4  * ===================                          Last change: 11/04/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : network_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for ext-network                        *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer ext-network                      *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Private setter for current network id
44 function setCurrentNetworkId ($networkId) {
45         $GLOBALS['current_network_id'] = bigintval($networkId);
46 }
47
48 // Private getter for current network id
49 function getCurrentNetworkId () {
50         return $GLOBALS['current_network_id'];
51 }
52
53 // Checks whether the current network id is set
54 function isCurrentNetworkIdSet () {
55         // So is it there?
56         return isset($GLOBALS['current_network_id']);
57 }
58
59 // Getter for network_form_name
60 function getNetworkFormName () {
61         return $GLOBALS['network_form_name'];
62 }
63
64 // Setter for network_form_name
65 function setNetworkFormName ($networkFormName) {
66         $GLOBALS['network_form_name'] = (string) $networkFormName;
67 }
68
69 // Detects if a supported form has been sent
70 function detectNetworkProcessForm () {
71         // 'do' must be provided in URL
72         if (!isGetRequestElementSet('do')) {
73                 // Not provided!
74                 reportBug(__FUNCTION__, __LINE__, 'No "do" has been provided. Please fix your templates.');
75         } // END - if
76
77         // Default is invalid
78         setNetworkFormName('invalid');
79
80         // Now search all valid
81         foreach (array('save_config', 'add', 'edit', 'delete', 'do_edit', 'do_delete') as $formName) {
82                 // Is it detected
83                 if (isFormSent($formName)) {
84                         // Use this form name
85                         setNetworkFormName($formName);
86
87                         // Remove it generically here
88                         unsetPostRequestElement($formName);
89
90                         // Abort loop
91                         break;
92                 } // END - if
93         } // END - foreach
94
95         // Has the form being detected?
96         if (getNetworkFormName() == 'invalid') {
97                 // Not supported
98                 reportBug(__FUNCTION__, __LINE__, 'POST form could not be detected, postData=<pre>' . print_r(postRequestArray(), TRUE));
99         } // END - if
100 }
101
102 // Handle a (maybe) sent form here
103 function doNetworkHandleForm () {
104         // Is there a form sent?
105         if (countRequestPost() > 0) {
106                 // Detect sent POST form
107                 detectNetworkProcessForm();
108         } elseif (!isGetRequestElementSet('do')) {
109                 // Skip any further requests
110                 return;
111         } 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 = '', $addSql = '') {
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'" .  $addSql;
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 = '', $addSql = '') {
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('WHERE', '', $addSql) . '
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', $addSql);
751
752                         // Then add unconfigured
753                         $content .= generateAdminNetworkList(FALSE, FALSE, TRUE, '_unconfigured', $addSql);
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 // Handles the network-delete-url request
1191 function handleNetworkDeleteUrlRequest () {
1192         // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
1193         reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
1194 }
1195
1196 // Handle a single request parameter key by given network type handler id and "internal" key
1197 function handleRequestParameterKey ($networkTypeId, $networkRequestKey) {
1198         // Construct call-back function name
1199         $callbackName = 'doHandleNetworkRequest' . capitalizeUnderscoreString($networkRequestKey) . 'Key';
1200
1201         // Is the function there?
1202         if (!function_exists($callbackName)) {
1203                 // Call-back function does not exist
1204                 reportBug(__FUNCTION__, __LINE__, 'Call-back function ' . $callbackName . ' does not exist. networkTypeId=' . $networkTypeId . ',networkRequestKey=' . $networkRequestKey);
1205         } // END - if
1206
1207         // Call it with network type id
1208         return call_user_func_array($callbackName, array($networkTypeId));
1209 }
1210
1211 // Handle all keys given request parameter array loaded by getNetworkRequestParametersByTypeId()
1212 function handleNetworkRequestParameterKeys (&$requestParams) {
1213         // Simple check for validity
1214         assert(isset($requestParams[0]['network_request_param_key']));
1215
1216         // "Walk" through all
1217         foreach ($requestParams as $key => $params) {
1218                 // Is the default value not set?
1219                 if (empty($params['network_request_param_default'])) {
1220                         // This key needs to be handled, so call it
1221                         $requestParams[$key]['network_request_param_default'] = handleRequestParameterKey($params['network_type_id'], $params['network_request_param_key']);
1222                 } // END - if
1223         } // END - foreach
1224 }
1225
1226 /**
1227  * Logs given HTTP headers to database for debugging purposes.
1228  *
1229  * @param       $networkId              Network's id number
1230  * @param       $networkTypeId  Network type handler's id number
1231  * @param       $headers                All HTTP headers
1232  * @param       $type                   Can be only one of 'MANUAL' or 'CRON'
1233  * @return      void
1234  */
1235 function logNetworkResponseHeaders ($networkId, $networkTypeId, $headers, $type) {
1236         // Make sure type is valid
1237         assert(in_array($type, array('MANUAL', 'CRON')));
1238
1239         // Is debug logging enabled or status code not 200 OK?
1240         if ((getConfig('network_logging_debug') == 'Y') || (!isHttpStatusOkay($headers[0]))) {
1241                 // Add entry
1242                 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')",
1243                         array(
1244                                 bigintval($networkId),
1245                                 bigintval($networkTypeId),
1246                                 trim($headers[0]),
1247                                 serialize($headers),
1248                                 $type
1249                         ), __FUNCTION__, __LINE__);
1250         } // END - if
1251 }
1252
1253 /**
1254  * Caches given reponse body from API into cache, updates existing cache if
1255  * found. This function does the charset-convertion, so you don't have to do it
1256  * again if you use this cached data.
1257  *
1258  * @param       $networkId              Network's id number
1259  * @param       $networkTypeId  Network type handler's id number
1260  * @param       $responseBody   Response body (string)
1261  * @param       $networkData    Network + type handler data as array
1262  * @param       $type                   Can be only one of 'MANUAL' or 'CRON'
1263  * @return      void
1264  */
1265 function saveNetworkResponseBodyInCache ($networkId, $networkTypeId, $responseBody, $networkData, $type) {
1266         // Make sure the body is not larger than this value
1267         assert(strlen($responseBody) <= 16777215);
1268         assert(in_array($type, array('MANUAL', 'CRON')));
1269
1270         // So is there cache?
1271         if (countSumTotalData($networkId, 'network_cache', 'network_cache_id', 'network_id', TRUE, ' AND `network_type_id`=' . bigintval($networkTypeId)) == 1) {
1272                 // Entry found, so update it
1273                 SQL_QUERY_ESC("UPDATE
1274         `{?_MYSQL_PREFIX?}_network_cache`
1275 SET
1276         `network_cache_data`='%s',
1277         `network_cache_body`='%s',
1278         `network_cache_type`='%s',
1279         `network_cache_admin_id`=%s,
1280         `network_cache_updated`=NOW()
1281 WHERE
1282         `network_id`=%s AND
1283         `network_type_id`=%s
1284 LIMIT 1",
1285                         array(
1286                                 serialize($networkData),
1287                                 compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
1288                                 $type,
1289                                 convertZeroToNull(getCurrentAdminId()),
1290                                 bigintval($networkId),
1291                                 bigintval($networkTypeId)
1292                         ), __FUNCTION__, __LINE__);
1293         } else {
1294                 // Add entry
1295                 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)",
1296                         array(
1297                                 bigintval($networkId),
1298                                 bigintval($networkTypeId),
1299                                 serialize($networkData),
1300                                 compress(convertCharsetToUtf8($responseBody, $networkData['network_charset'])),
1301                                 $type,
1302                                 convertZeroToNull(getCurrentAdminId())
1303                         ), __FUNCTION__, __LINE__);
1304         }
1305 }
1306
1307 // Queries network API with given network data and request data
1308 function queryNetworkApi ($networkData, $requestData) {
1309         // Query it
1310         $response = sendHttpRequest($networkData['network_request_type'], $networkData['network_type_api_url'], $requestData, FALSE, FALSE);
1311
1312         // Did all went fine? (also a 403 is considered as "okay" here)
1313         if (count($response) > 3) {
1314                 // Save response body, remove last empty line if really empty
1315                 $responseBody = (string) trim($response[count($response) - 1]);
1316                 unset($response[count($response) - 1]);
1317                 assert(empty($response[count($response)]));
1318                 unset($response[count($response) - 1]);
1319
1320                 // Register all HTTP headers for debugging purposes
1321                 logNetworkResponseHeaders($networkData['network_id'], postRequestElement('network_type_id'), $response, 'MANUAL');
1322
1323                 // Is all fine?
1324                 if (isHttpStatusOkay($response[0])) {
1325                         // Count API request
1326                         countNetworkApiRequest($networkData);
1327
1328                         // Save response in cache
1329                         saveNetworkResponseBodyInCache($networkData['network_id'], postRequestElement('network_type_id'), $responseBody, $networkData, 'MANUAL');
1330                 } // END - if
1331         } // END - if
1332
1333         // Return the response
1334         return $response;
1335 }
1336
1337 /**
1338  * Counts API request from given network data generated by getNetworkDataByTypeId()
1339  *
1340  * @param       $networkData    Array with network data
1341  * @return      $affectedRows   Affected rows (always one or FALSE if unlimited/depleted)
1342  */
1343 function countNetworkApiRequest ($networkData) {
1344         // Get API config
1345         $apiConfig = getFullNetworkConfigurationByTypeId($networkData['network_type_id']);
1346
1347         // Is the daily or remaining free amount zero?
1348         if (($networkData['network_query_amount'] == 0) || ($apiConfig['network_api_remaining_requests'] == 0)) {
1349                 // Then abort here
1350                 return FALSE;
1351         } // END - if
1352
1353         // Okay, so update database
1354         $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",
1355                 array(
1356                         bigintval($networkData['network_id'])
1357                 ), __FUNCTION__, __LINE__);
1358
1359         // Return affected rows
1360         return SQL_AFFECTEDROWS();
1361 }
1362
1363 /**
1364  * Generates a referral link for given network id (including HTML)
1365  *
1366  * @param       $networkId      Network id to generate link for
1367  * @return      $output         "Rendered" output
1368  */
1369 function generateMetworkReferralLinkById ($networkId) {
1370         // Simple output (no need for template!)
1371         $output = '<a href="{%network,getNetworkDataById,network_reflink=' . $networkId . '%}" target="_blank" title="{%network,getNetworkDataById,network_title=' . $networkId . '%}">{%network,getNetworkDataById,network_title=' . $networkId . '%}</a>';
1372
1373         // Return it
1374         return $output;
1375 }
1376
1377 //------------------------------------------------------------------------------
1378 //               "Translation" functions (can be used in EL code)
1379 //------------------------------------------------------------------------------
1380
1381 // Translates 'translate_name' for e.g. templates
1382 function translateNetworkTranslationName ($name) {
1383         // Return message id
1384         return translateGeneric('ADMIN_NETWORK_TRANSLATE', $name, '_NAME');
1385 }
1386
1387 // Translates the network type id to a handler
1388 function translateNetworkTypeHandlerByTypeId ($typeId) {
1389         // Get the data
1390         $data = getNetworkDataByTypeId($typeId, 'network_type_handler');
1391
1392         // Is data found?
1393         if (is_null($data)) {
1394                 // Not found
1395                 return translateNetworkTypeHandler('UNKNOWN');
1396         } // END - if
1397
1398         // Return actual translation
1399         return translateNetworkTypeHandler($data);
1400 }
1401
1402 // "Translates" give network media output (type)
1403 function translateNetworkMediaOutputType ($mediaOutput) {
1404         // Return message id
1405         return translateGeneric('ADMIN_NETWORK_MEDIA_OUTPUT', $mediaOutput);
1406 }
1407
1408 // Translates the network type handler (e.g. banner, paidmail) for templates
1409 function translateNetworkTypeHandler ($type) {
1410         // Generate id
1411         $messageId = 'ADMIN_NETWORK_TYPE_HANDLER_' . strtoupper($type);
1412
1413         // Is the message id there?
1414         if (!isMessageIdValid($messageId)) {
1415                 // Not valid type
1416                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
1417         } // END - if
1418
1419         // Return message id
1420         return '{--' . $messageId . '--}';
1421 }
1422
1423 // Translates request type
1424 function translateNetworkRequestType ($type) {
1425         // Generate id
1426         $messageId = 'ADMIN_NETWORK_REQUEST_TYPE_' . strtoupper($type) . '';
1427
1428         // Is the message id there?
1429         if (!isMessageIdValid($messageId)) {
1430                 // Not valid type
1431                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
1432         } // END - if
1433
1434         // Return message id
1435         return '{--' . $messageId . '--}';
1436 }
1437
1438 // Translates request parameter
1439 function translateNetworkRequestParameterKey ($param) {
1440         // Generate id
1441         $messageId = 'ADMIN_NETWORK_REQUEST_PARAMETER_' . strtoupper($param) . '';
1442
1443         // Is the message id there?
1444         if (!isMessageIdValid($messageId)) {
1445                 // Not valid param
1446                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
1447         } // END - if
1448
1449         // Return message id
1450         return '{--' . $messageId . '--}';
1451 }
1452
1453 // Translates vheck request parameter
1454 function translateNetworkVcheckParameterKey ($param) {
1455         // Generate id
1456         $messageId = 'ADMIN_NETWORK_VCHECK_PARAMETER_' . strtoupper($param) . '';
1457
1458         // Is the message id there?
1459         if (!isMessageIdValid($messageId)) {
1460                 // Not valid param
1461                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
1462         } // END - if
1463
1464         // Return message id
1465         return '{--' . $messageId . '--}';
1466 }
1467
1468 // Translate text-encoding
1469 function translateNetworkTextEncoding ($encoding) {
1470         // Generate id
1471         $messageId = 'ADMIN_NETWORK_TYPE_TEXT_ENCODING_' . strtoupper($encoding) . '';
1472
1473         // Is the message id there?
1474         if (!isMessageIdValid($messageId)) {
1475                 // Not valid encoding
1476                 reportBug(__FUNCTION__, __LINE__, 'encoding=' . $encoding . ' is invalid.');
1477         } // END - if
1478
1479         // Return message id
1480         return '{--' . $messageId . '--}';
1481 }
1482
1483 // Translates API index
1484 function translateNetworkApiIndex ($index) {
1485         // Is there cache?
1486         if (!isset($GLOBALS['network_array_index'])) {
1487                 // Get an array of all API array indexes
1488                 $GLOBALS['network_array_index'] = array();
1489
1490                 // Get all entries
1491                 $result = SQL_QUERY('SELECT
1492         `network_array_id`,
1493         `network_array_index`,
1494         `network_translation_name`
1495 FROM
1496         `{?_MYSQL_PREFIX?}_network_array_translation`
1497 INNER JOIN
1498         `{?_MYSQL_PREFIX?}_network_translations`
1499 ON
1500         `network_array_index`=`network_translation_id`
1501 ORDER BY
1502         `network_array_sort` ASC', __FUNCTION__, __LINE__);
1503
1504                 // Are there entries?
1505                 if (!SQL_HASZERONUMS($result)) {
1506                         // Get all entries
1507                         while ($row = SQL_FETCHARRAY($result)) {
1508                                 // Add it to our global array
1509                                 $GLOBALS['network_array_index'][$row['network_array_index']] = $row;
1510                         } // END - while
1511                 } // END - if
1512
1513                 // Free result
1514                 SQL_FREERESULT($result);
1515         } // END - if
1516
1517         // Default name is unknown
1518         $name = 'unknown';
1519
1520         // Is the entry there?
1521         if (isset($GLOBALS['network_array_index'][$index])) {
1522                 // Then get the name
1523                 $name = $GLOBALS['network_array_index'][$index]['network_translation_name'];
1524         } // END - if
1525
1526         // Return translation
1527         return translateNetworkTranslationName($name);
1528 }
1529
1530 // Translates network API configuration status (see function isNetworkApiConfigured()) by given id
1531 function translateNetworkApiConfiguredStatusById ($networkId) {
1532         // Is there cache?
1533         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1534                 // By default it is not configured
1535                 $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_CONFIGURED--}';
1536
1537                 // So is it configured?
1538                 if (!isNetworkActiveById($networkId)) {
1539                         // Network is not active
1540                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_ACTIVE--}';
1541                 } elseif (isNetworkApiConfigured($networkId)) {
1542                         // Yes, it is
1543                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_CONFIGURED--}';
1544                 } // END - if
1545         } // END - if
1546
1547         // Return cache
1548         return $GLOBALS[__FUNCTION__][$networkId];
1549 }
1550
1551 /**
1552  * "Translates" given amount of queries; 0 = unlimited
1553  *
1554  * @param       $amount                 Amount of free queries
1555  * @return      $translated             "Translated" value; 0 = unlimited
1556  */
1557 function translateNetworkQueryAmount ($amount) {
1558         // Default is unlimited (good! ;-) )
1559         $translated = '{--UNLIMITED--}';
1560
1561         // Is the amount larger zero?
1562         if ($amount > 0) {
1563                 // Then translate it
1564                 $translated = translateComma($amount);
1565         } // END - if
1566
1567         // Return translated value
1568         return $translated;
1569 }
1570
1571 /**
1572  * "Translates given status (Y/N) to "de-/activated" but only if expert and
1573  * debug mode are enabled.
1574  *
1575  * @param       $status                 Can be one of Y/N
1576  * @return      $translated             "Translated" status
1577  */
1578 function translateNetworkActivationStatus ($status) {
1579         // Is there cache?
1580         if (!isset($GLOBALS[__FUNCTION__][$status])) {
1581                 // Default is not enabled
1582                 $GLOBALS[__FUNCTION__][$status] = '';
1583
1584                 // Is expert + debug mode enabled?
1585                 if ((isAdminsExpertSettingEnabled()) && (isDebugModeEnabled())) {
1586                         // Then "translate" it
1587                         $GLOBALS[__FUNCTION__][$status] = translateActivationStatus($status);
1588                 } // END - if
1589         } // END - if
1590
1591         // Return "translation"
1592         return $GLOBALS[__FUNCTION__][$status];
1593 }
1594
1595 //------------------------------------------------------------------------------
1596 //               Wrapper functions to save data to network tables
1597 //------------------------------------------------------------------------------
1598
1599 // Updates given network (id) with data from array
1600 function doNetworkUpdateDataByArray ($networkId, $networkData) {
1601         // Ids lower one are not accepted
1602         if (!isValidId($networkId)) {
1603                 // Not good, should be fixed
1604                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is smaller than 1.');
1605         } // END - if
1606
1607         // Just call our inner method
1608         return adminSaveSettings($networkData, '_network_data', sprintf("`network_id`=%s", bigintval($networkId)), array(), FALSE, FALSE);
1609 }
1610
1611 // Updates given network type handler (id) with data from array
1612 function doNetworkUpdateTypeByArray ($networkTypeId, $networkTypeData) {
1613         // Ids lower one are not accepted
1614         if (!isValidId($networkTypeId)) {
1615                 // Not good, should be fixed
1616                 reportBug(__FUNCTION__, __LINE__, 'Network type handler id ' . $networkTypeId . ' is smaller than 1.');
1617         } // END - if
1618
1619         // Just call our inner method
1620         return adminSaveSettings($networkTypeData, '_network_types', sprintf("`network_type_id`=%s", bigintval($networkTypeId)), array(), FALSE, FALSE);
1621 }
1622
1623 // Updates given network request parameters (id) with data from array
1624 function doNetworkUpdateParamsByArray ($networkParamsId, $networkParamsData) {
1625         // Ids lower one are not accepted
1626         if (!isValidId($networkParamsId)) {
1627                 // Not good, should be fixed
1628                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkParamsId . ' is smaller than 1.');
1629         } // END - if
1630
1631         // Just call our inner method
1632         return adminSaveSettings($networkParamsData, '_network_request_params', sprintf("`network_request_param_id`=%s", bigintval($networkParamsId)), array(), FALSE, FALSE);
1633 }
1634
1635 // Updates given network array translations (id) with data from array
1636 function doNetworkUpdateArrayTranslationsByArray ($networkTranslationsId, $networkTranslationsData) {
1637         // Ids lower one are not accepted
1638         if (!isValidId($networkTranslationsId)) {
1639                 // Not good, should be fixed
1640                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkTranslationsId . ' is smaller than 1.');
1641         } // END - if
1642
1643         // Just call our inner method
1644         return adminSaveSettings($networkTranslationsData, '_network_array_translation', sprintf("`network_array_id`=%s", bigintval($networkTranslationsId)), array(), FALSE, FALSE);
1645 }
1646
1647 //------------------------------------------------------------------------------
1648 //                 Call-back functions for request parameter keys
1649 //------------------------------------------------------------------------------
1650
1651 // ----------------------- Table: network_api_config -----------------------
1652
1653 // Handles affiliate id
1654 function doHandleNetworkRequestAffiliateIdKey ($networkTypeId) {
1655         // It is assumed that the network + type handler are both configured
1656         // Load full config data (this will be "cached"!)
1657         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1658
1659         // Is the network activated?
1660         if (!isset($configData['network_api_active'])) {
1661                 // Configuration could not be loaded
1662                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1663         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1664                 // Is not activated, so don't handle it in non-debug mode
1665                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1666         } elseif (empty($configData['network_api_affiliate_id'])) {
1667                 // Required element is not set
1668                 reportBug(__FUNCTION__, __LINE__, 'network_api_affiliate_id for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1669         }
1670
1671         // Return configured value
1672         return $configData['network_api_affiliate_id'];
1673 }
1674
1675 // Handles site id
1676 function doHandleNetworkRequestSiteIdKey ($networkTypeId) {
1677         // It is assumed that the network + type handler are both configured
1678         // Load full config data (this will be "cached"!)
1679         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1680
1681         // Is the network activated?
1682         if (!isset($configData['network_api_active'])) {
1683                 // Configuration could not be loaded
1684                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1685         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1686                 // Is not activated, so don't handle it in non-debug mode
1687                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1688         } elseif (empty($configData['network_api_site_id'])) {
1689                 // Required element is not set
1690                 reportBug(__FUNCTION__, __LINE__, 'network_api_site_id for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1691         }
1692
1693         // Return configured value
1694         return $configData['network_api_site_id'];
1695 }
1696
1697 // Handles interface password
1698 function doHandleNetworkRequestPasswordKey ($networkTypeId) {
1699         // It is assumed that the network + type handler are both configured
1700         // Load full config data (this will be "cached"!)
1701         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1702
1703         // Is the network activated?
1704         if (!isset($configData['network_api_active'])) {
1705                 // Configuration could not be loaded
1706                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1707         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1708                 // Is not activated, so don't handle it in non-debug mode
1709                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1710         } elseif (empty($configData['network_api_password'])) {
1711                 // Required element is not set
1712                 reportBug(__FUNCTION__, __LINE__, 'network_api_password for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1713         }
1714
1715         // Return configured value
1716         return $configData['network_api_password'];
1717 }
1718
1719 // ----------------------- Table: network_handler_config -----------------------
1720
1721 // Handles reload lock
1722 function doHandleNetworkRequestReloadKey ($networkTypeId) {
1723         // It is assumed that the network + type handler are both configured
1724         // Load full config data (this will be "cached"!)
1725         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1726
1727         // Is the network activated?
1728         if (!isset($configData['network_api_active'])) {
1729                 // Configuration could not be loaded
1730                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1731         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1732                 // Is not activated, so don't handle it in non-debug mode
1733                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1734         }
1735
1736         // Return configured value
1737         return caluculateTimeUnitValue($configData['network_max_reload_time'], $configData['network_type_reload_time_unit']);
1738 }
1739
1740 // Handles minimum stay
1741 function doHandleNetworkRequestMinimumStayKey ($networkTypeId) {
1742         // It is assumed that the network + type handler are both configured
1743         // Load full config data (this will be "cached"!)
1744         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1745
1746         // Is the network activated?
1747         if (!isset($configData['network_api_active'])) {
1748                 // Configuration could not be loaded
1749                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1750         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1751                 // Is not activated, so don't handle it in non-debug mode
1752                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1753         }
1754
1755         // Return configured value
1756         return $configData['network_min_waiting_time'];
1757 }
1758
1759 // Handles maximum stay
1760 function doHandleNetworkRequestMaximumStayKey ($networkTypeId) {
1761         // It is assumed that the network + type handler are both configured
1762         // Load full config data (this will be "cached"!)
1763         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1764
1765         // Is the network activated?
1766         if (!isset($configData['network_api_active'])) {
1767                 // Configuration could not be loaded
1768                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1769         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1770                 // Is not activated, so don't handle it in non-debug mode
1771                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1772         }
1773
1774         // Return configured value
1775         return $configData['network_max_waiting_time'];
1776 }
1777
1778 // Handles remaining clicks
1779 function doHandleNetworkRequestRemainClicksKey ($networkTypeId) {
1780         // It is assumed that the network + type handler are both configured
1781         // Load full config data (this will be "cached"!)
1782         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1783
1784         // Is the network activated?
1785         if (!isset($configData['network_api_active'])) {
1786                 // Configuration could not be loaded
1787                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1788         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1789                 // Is not activated, so don't handle it in non-debug mode
1790                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1791         }
1792
1793         // Return configured value
1794         return $configData['network_min_remain_clicks'];
1795 }
1796
1797 // Handles remaining budget
1798 function doHandleNetworkRequestRemainBudgetKey ($networkTypeId) {
1799         // It is assumed that the network + type handler are both configured
1800         // Load full config data (this will be "cached"!)
1801         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1802
1803         // Is the network activated?
1804         if (!isset($configData['network_api_active'])) {
1805                 // Configuration could not be loaded
1806                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1807         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1808                 // Is not activated, so don't handle it in non-debug mode
1809                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1810         }
1811
1812         // Return configured value
1813         return $configData['network_min_remain_budget'];
1814 }
1815
1816 // Handles reward (payment)
1817 function doHandleNetworkRequestRewardKey ($networkTypeId) {
1818         // It is assumed that the network + type handler are both configured
1819         // Load full config data (this will be "cached"!)
1820         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1821
1822         // Is the network activated?
1823         if (!isset($configData['network_api_active'])) {
1824                 // Configuration could not be loaded
1825                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1826         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1827                 // Is not activated, so don't handle it in non-debug mode
1828                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1829         } elseif (empty($configData['network_min_payment'])) {
1830                 // Required element is not set
1831                 reportBug(__FUNCTION__, __LINE__, 'network_min_payment for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1832         }
1833
1834         // Return configured value
1835         return $configData['network_min_payment'];
1836 }
1837
1838 // Handles media size
1839 function doHandleNetworkRequestSizeKey ($networkTypeId) {
1840         // It is assumed that the network + type handler are both configured
1841         // Load full config data (this will be "cached"!)
1842         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1843
1844         // Is the network activated?
1845         if (!isset($configData['network_api_active'])) {
1846                 // Configuration could not be loaded
1847                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1848         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1849                 // Is not activated, so don't handle it in non-debug mode
1850                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1851         } elseif (empty($configData['network_media_size'])) {
1852                 // Required element is not set
1853                 reportBug(__FUNCTION__, __LINE__, 'network_media_size for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1854         }
1855
1856         // Return configured value
1857         return $configData['network_media_size'];
1858 }
1859
1860 // Handles media output (type)
1861 function doHandleNetworkRequestTypeKey ($networkTypeId) {
1862         // It is assumed that the network + type handler are both configured
1863         // Load full config data (this will be "cached"!)
1864         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1865
1866         // Is the network activated?
1867         if (!isset($configData['network_api_active'])) {
1868                 // Configuration could not be loaded
1869                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1870         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1871                 // Is not activated, so don't handle it in non-debug mode
1872                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1873         }
1874
1875         // Return configured value
1876         return $configData['network_media_output'];
1877 }
1878
1879 // Handles erotic
1880 function doHandleNetworkRequestEroticKey ($networkTypeId) {
1881         // It is assumed that the network + type handler are both configured
1882         // Load full config data (this will be "cached"!)
1883         $configData = getFullNetworkConfigurationByTypeId($networkTypeId);
1884
1885         // Is the network activated?
1886         if (!isset($configData['network_api_active'])) {
1887                 // Configuration could not be loaded
1888                 reportBug(__FUNCTION__, __LINE__, 'Configuration for networkTypeId=' . $networkTypeId . ' could not be loaded.');
1889         } elseif (($configData['network_api_active'] == 'N') && (!isDebugModeEnabled())) {
1890                 // Is not activated, so don't handle it in non-debug mode
1891                 reportBug(__FUNCTION__, __LINE__, 'Configuration for network_id ' . $configData['network_id'] .',networkTypeId=' . $networkTypeId . ' is not activated.');
1892         } elseif (empty($configData['network_allow_erotic'])) {
1893                 // Required element is not set
1894                 reportBug(__FUNCTION__, __LINE__, 'network_allow_erotic for network_id=' . $configData['network_id'] . ',networkTypeId=' . $networkTypeId . ' is not set.');
1895         }
1896
1897         // Return configured value
1898         return $configData['network_allow_erotic'];
1899 }
1900
1901 // ----------------------- Table: network_request_params -----------------------
1902
1903 //------------------------------------------------------------------------------
1904 //                       Call-back functions for admin area
1905 //------------------------------------------------------------------------------
1906
1907 // Callback function to add new network
1908 function doAdminNetworkProcessAddNetwork () {
1909         // We can say here, the form is sent, so check if the network is already added
1910         if (isNetworkNameValid(postRequestElement('network_short_name'))) {
1911                 // Already there
1912                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ALREADY_ADDED=' . postRequestElement('network_short_name') . '%}');
1913                 return FALSE;
1914         } // END - if
1915
1916         // Add the whole request to database
1917         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_data'), __FUNCTION__, __LINE__);
1918
1919         // Add the id for output only
1920         setPostRequestElement('network_id', SQL_INSERTID());
1921
1922         // Output message
1923         if (!SQL_HASZEROAFFECTED()) {
1924                 // Successfully added
1925                 loadTemplate('admin_network_added', FALSE, postRequestArray());
1926         } else {
1927                 // Not added
1928                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_DATA_NOT_ADDED=' . postRequestElement('network_short_name') . '%}');
1929         }
1930 }
1931
1932 // Displays selected networks for editing
1933 function doAdminNetworkProcessHandleNetworks () {
1934         // Is there selections?
1935         if (ifPostContainsSelections()) {
1936                 // Something has been selected, so start displaying one by one
1937                 $OUT = '';
1938                 foreach (postRequestElement('sel') as $networkId => $sel) {
1939                         // Is this selected?
1940                         if ($sel == 1) {
1941                                 // Load this network's data
1942                                 $networkData = getNetworkDataById($networkId);
1943
1944                                 // Is there found the network?
1945                                 if (count($networkData) > 0) {
1946                                         // Add row template with given form name
1947                                         $OUT .= loadTemplate('admin_' . getNetworkFormName() . '_networks_row', TRUE, $networkData);
1948                                 } // END - if
1949                         } // END - if
1950                 } // END - foreach
1951
1952                 // If we have no rows, we don't need to display the edit form
1953                 if (!empty($OUT)) {
1954                         // Init array with generic element
1955                         $content = array(
1956                                 'rows' => $OUT
1957                         );
1958
1959                         // Output main template
1960                         loadTemplate('admin_' . getNetworkFormName() . '_networks', FALSE, $content);
1961
1962                         // Don't display the list/add new form
1963                         $GLOBALS['network_display'] = FALSE;
1964                 } else {
1965                         // Nothing selected/found
1966                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_FOUND--}');
1967                 }
1968         } // END - if
1969 }
1970
1971 // Handle network type form
1972 function doAdminNetworkProcessHandleNetworkTypes () {
1973         // Is there selections?
1974         if (ifPostContainsSelections()) {
1975                 // Load network data
1976                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1977
1978                 // Something has been selected, so start displaying one by one
1979                 $OUT = '';
1980                 foreach (postRequestElement('sel') as $networkId => $sel) {
1981                         // Is this selected?
1982                         if ($sel == 1) {
1983                                 // Load this network's data
1984                                 $networkTypeData = getNetworkTypeDataByTypeId($networkId);
1985
1986                                 // Is there found the network?
1987                                 if (count($networkTypeData) > 0) {
1988                                         if (getNetworkFormName() == 'edit') {
1989                                                 // Add row template for deleting
1990                                                 $OUT .= loadTemplate('admin_edit_network_types_row', TRUE, $networkTypeData);
1991                                         } elseif (getNetworkFormName() == 'delete') {
1992                                                 // Add row template for deleting
1993                                                 $OUT .= loadTemplate('admin_delete_network_types_row', TRUE, $networkTypeData);
1994                                         } else {
1995                                                 // Problem!
1996                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
1997                                         }
1998                                 } // END - if
1999                         } // END - if
2000                 } // END - foreach
2001
2002                 // If we have no rows, we don't need to display the edit form
2003                 if (!empty($OUT)) {
2004                         // Prepare array with generic elements
2005                         $content = array(
2006                                 'rows'       => $OUT,
2007                                 'network_id' => bigintval(getRequestElement('network_id'))
2008                         );
2009
2010                         // Output main template
2011                         if (getNetworkFormName() == 'edit') {
2012                                 loadTemplate('admin_edit_network_types', FALSE, $content);
2013                         } elseif (getNetworkFormName() == 'delete') {
2014                                 loadTemplate('admin_delete_network_types', FALSE, $content);
2015                         } else {
2016                                 // Problem!
2017                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2018                         }
2019
2020                         // Don't display the list/add new form
2021                         $GLOBALS['network_display'] = FALSE;
2022                 } else {
2023                         // Nothing selected/found
2024                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_FOUND--}');
2025                 }
2026         } // END - if
2027 }
2028
2029 // Handle network request parameter form
2030 function doAdminNetworkProcessHandleRequestParams () {
2031         // Is there selections?
2032         if (ifPostContainsSelections()) {
2033                 // Init cache array
2034                 $GLOBALS['network_request_params_disabled'] = array();
2035
2036                 // Load network data
2037                 $networkData = getNetworkDataById(getRequestElement('network_id'));
2038
2039                 // Something has been selected, so start displaying one by one
2040                 $OUT = '';
2041                 foreach (postRequestElement('sel') as $networkId => $sel) {
2042                         // Is this selected?
2043                         if ($sel == 1) {
2044                                 // Load this network's data
2045                                 $networkRequestData = getNetworkRequestParamsDataById($networkId);
2046
2047                                 // Is there found the network?
2048                                 if (count($networkRequestData) > 0) {
2049                                         if (getNetworkFormName() == 'edit') {
2050                                                 // Add row template for deleting
2051                                                 $OUT .= loadTemplate('admin_edit_network_request_params_row', TRUE, $networkRequestData);
2052                                         } elseif (getNetworkFormName() == 'delete') {
2053                                                 // Get type data
2054                                                 $networkRequestData['network_type_data'] = getNetworkTypeDataByTypeId($networkRequestData['network_type_id']);
2055
2056                                                 // Add row template for deleting
2057                                                 $OUT .= loadTemplate('admin_delete_network_request_params_row', TRUE, $networkRequestData);
2058                                         } else {
2059                                                 // Problem!
2060                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2061                                         }
2062                                 } // END - if
2063                         } // END - if
2064                 } // END - foreach
2065
2066                 // If we have no rows, we don't need to display the edit form
2067                 if (!empty($OUT)) {
2068                         // Prepare array with generic elements
2069                         $content = array(
2070                                 'rows'       => $OUT,
2071                                 'network_id' => bigintval(getRequestElement('network_id'))
2072                         );
2073
2074                         // Output main template
2075                         if (getNetworkFormName() == 'edit') {
2076                                 loadTemplate('admin_edit_network_request_params', FALSE, $content);
2077                         } elseif (getNetworkFormName() == 'delete') {
2078                                 loadTemplate('admin_delete_network_request_params', FALSE, $content);
2079                         } else {
2080                                 // Problem!
2081                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2082                         }
2083
2084                         // Don't display the list/add new form
2085                         $GLOBALS['network_display'] = FALSE;
2086                 } else {
2087                         // Nothing selected/found
2088                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
2089                 }
2090         } // END - if
2091 }
2092
2093 // Changes given networks
2094 function doAdminNetworkProcessChangeNetworks () {
2095         // Is there selections?
2096         if (ifPostContainsSelections()) {
2097                 // By default nothing is updated
2098                 $updated = 0;
2099
2100                 // Something has been selected, so start updating them
2101                 foreach (postRequestElement('sel') as $networkId => $sel) {
2102                         // Update this entry?
2103                         if ($sel == 1) {
2104                                 // Init data array
2105                                 $networkData = array();
2106
2107                                 // Transfer whole array, except 'sel'
2108                                 foreach (postRequestArray() as $key => $entry) {
2109                                         // Skip 'sel' and submit button
2110                                         if (in_array($key, array('sel', 'do_edit'))) {
2111                                                 continue;
2112                                         } // END - if
2113
2114                                         // Is there this enty?
2115                                         if (!isset($entry[$networkId])) {
2116                                                 // Not found, needs fixing
2117                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2118                                         } // END - if
2119
2120                                         // Add this entry
2121                                         $networkData[$key] = $entry[$networkId];
2122                                 } // END - foreach
2123
2124                                 // Update the network data
2125                                 $updated += doNetworkUpdateDataByArray($networkId, $networkData);
2126                         } // END - if
2127                 } // END - foreach
2128
2129                 // Is there updates?
2130                 if ($updated > 0) {
2131                         // Updates done
2132                         displayMessage('{%message,ADMIN_NETWORK_UPDATED=' . $updated . '%}');
2133                 } else {
2134                         // Nothing changed
2135                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_CHANGED--}');
2136                 }
2137         } // END - if
2138 }
2139
2140 // Removes given networks
2141 function doAdminNetworkProcessRemoveNetworks () {
2142         // Is there selections?
2143         if (ifPostContainsSelections()) {
2144                 // By default nothing is removed
2145                 $removed = 0;
2146
2147                 // Something has been selected, so start updating them
2148                 foreach (postRequestElement('sel') as $networkId => $sel) {
2149                         // Update this entry?
2150                         if ($sel == 1) {
2151                                 // Remove this entry
2152                                 $removed += doAdminRemoveNetworkEntry('data', 'network_id', $networkId);
2153                         } // END - if
2154                 } // END - foreach
2155
2156                 // Is there removes?
2157                 if ($removed > 0) {
2158                         // Removals done
2159                         displayMessage('{%message,ADMIN_NETWORK_REMOVED=' . $removed . '%}');
2160                 } else {
2161                         // Nothing removed
2162                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_REMOVED--}');
2163                 }
2164         } // END - if
2165 }
2166
2167 // Add a network type handler if not yet found
2168 function doAdminNetworkProcessAddNetworkType () {
2169         // Is the network type handle already used with given network?
2170         if (isNetworkTypeHandleValid(postRequestElement('network_type_handler'), getRequestElement('network_id'))) {
2171                 // Already added
2172                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_ALREADY_ADDED=' . postRequestElement('network_type_handler') . '%}');
2173
2174                 // ... so abort here
2175                 return FALSE;
2176         } // END - if
2177
2178         // Add id
2179         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2180
2181         // Is network_type_click_url set?
2182         if (!isPostRequestElementSet('network_type_click_url')) {
2183                 // Remove empty value to get a NULL for an optional entry
2184                 unsetPostRequestElement('network_type_click_url');
2185         } // END - if
2186
2187         // Is network_type_banner_url set?
2188         if (!isPostRequestElementSet('network_type_banner_url')) {
2189                 // Remove empty value to get a NULL for an optional entry
2190                 unsetPostRequestElement('network_type_banner_url');
2191         } // END - if
2192
2193         // Add the whole request to database
2194         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_types'), __FUNCTION__, __LINE__);
2195
2196         // Output message
2197         if (!SQL_HASZEROAFFECTED()) {
2198                 // Successfully added
2199                 loadTemplate('admin_network_type_added', FALSE, postRequestArray());
2200         } else {
2201                 // Not added
2202                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_NOT_ADDED=' . postRequestElement('network_type_handler') . '%}');
2203         }
2204 }
2205
2206 // Changes given network type handlers
2207 function doAdminNetworkProcessChangeHandlerTypes () {
2208         // Is there selections?
2209         if (ifPostContainsSelections()) {
2210                 // By default nothing is updated
2211                 $updated = 0;
2212
2213                 // Something has been selected, so start updating them
2214                 foreach (postRequestElement('sel') as $networkId => $sel) {
2215                         // Update this entry?
2216                         if ($sel == 1) {
2217                                 // Init data array
2218                                 $networkTypeData = array();
2219
2220                                 // Transfer whole array, except 'sel'
2221                                 foreach (postRequestArray() as $key => $entry) {
2222                                         // Skip 'sel' and submit button
2223                                         if (in_array($key, array('sel', 'do_edit'))) {
2224                                                 continue;
2225                                         } // END - if
2226
2227                                         // Is there this enty?
2228                                         if (!isset($entry[$networkId])) {
2229                                                 // Not found, needs fixing
2230                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2231                                         } // END - if
2232
2233                                         // Fix empty network_type_click/banner_url to NULL
2234                                         if ((in_array($key, array('network_type_click_url', 'network_type_banner_url'))) && (trim($entry[$networkId]) == '')) {
2235                                                 // Set it to NULL
2236                                                 $entry[$networkId] = NULL;
2237                                         } // END - if
2238
2239                                         // Add this entry
2240                                         $networkTypeData[$key] = $entry[$networkId];
2241                                 } // END - foreach
2242
2243                                 // Update the network data
2244                                 $updated += doNetworkUpdateTypeByArray($networkId, $networkTypeData);
2245                         } // END - if
2246                 } // END - foreach
2247
2248                 // Is there updates?
2249                 if ($updated > 0) {
2250                         // Updates done
2251                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_UPDATED=' . $updated . '%}');
2252                 } else {
2253                         // Nothing changed
2254                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_CHANGED--}');
2255                 }
2256         } // END - if
2257 }
2258
2259 // Changes given network request parameters
2260 function doAdminNetworkProcessChangeRequestParams () {
2261         // Is there selections?
2262         if (ifPostContainsSelections()) {
2263                 // By default nothing is updated
2264                 $updated = 0;
2265
2266                 // Something has been selected, so start updating them
2267                 foreach (postRequestElement('sel') as $networkId => $sel) {
2268                         // Update this entry?
2269                         if ($sel == 1) {
2270                                 // Init data array
2271                                 $networkParamsData = array();
2272
2273                                 // Transfer whole array, except 'sel'
2274                                 foreach (postRequestArray() as $key => $entry) {
2275                                         // Skip 'sel' and submit button
2276                                         if (in_array($key, array('sel', 'do_edit'))) {
2277                                                 continue;
2278                                         } // END - if
2279
2280                                         // Is there this enty?
2281                                         if (!isset($entry[$networkId])) {
2282                                                 // Not found, needs fixing
2283                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2284                                         } // END - if
2285
2286                                         // Fix empty network_request_param_default to NULL
2287                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
2288                                                 // Set it to NULL
2289                                                 $entry[$networkId] = NULL;
2290                                         } // END - if
2291
2292                                         // Add this entry
2293                                         $networkParamsData[$key] = $entry[$networkId];
2294                                 } // END - foreach
2295
2296                                 // Update the network data
2297                                 $updated += doNetworkUpdateParamsByArray($networkId, $networkParamsData);
2298                         } // END - if
2299                 } // END - foreach
2300
2301                 // Is there updates?
2302                 if ($updated > 0) {
2303                         // Updates done
2304                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_UPDATED=' . $updated . '%}');
2305                 } else {
2306                         // Nothing changed
2307                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_CHANGED--}');
2308                 }
2309         } // END - if
2310 }
2311
2312 // Changes given network array translations
2313 function doAdminNetworkProcessChangeArrayTranslation () {
2314         // Is there selections?
2315         if (ifPostContainsSelections()) {
2316                 // By default nothing is updated
2317                 $updated = 0;
2318
2319                 // Something has been selected, so start updating them
2320                 foreach (postRequestElement('sel') as $networkId => $sel) {
2321                         // Update this entry?
2322                         if ($sel == 1) {
2323                                 // Init data array
2324                                 $networkTranslationsData = array();
2325
2326                                 // Transfer whole array, except 'sel'
2327                                 foreach (postRequestArray() as $key => $entry) {
2328                                         // Skip 'sel' and submit button
2329                                         if (in_array($key, array('sel', 'do_edit'))) {
2330                                                 continue;
2331                                         } // END - if
2332
2333                                         // Is there this enty?
2334                                         if (!isset($entry[$networkId])) {
2335                                                 // Not found, needs fixing
2336                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
2337                                         } // END - if
2338
2339                                         // Fix empty network_request_param_default to NULL
2340                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
2341                                                 // Set it to NULL
2342                                                 $entry[$networkId] = NULL;
2343                                         } // END - if
2344
2345                                         // Add this entry
2346                                         $networkTranslationsData[$key] = $entry[$networkId];
2347                                 } // END - foreach
2348
2349                                 // Update the network data
2350                                 $updated += doNetworkUpdateArrayTranslationsByArray($networkId, $networkTranslationsData);
2351                         } // END - if
2352                 } // END - foreach
2353
2354                 // Is there updates?
2355                 if ($updated > 0) {
2356                         // Updates done
2357                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_UPDATED=' . $updated . '%}');
2358                 } else {
2359                         // Nothing changed
2360                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_CHANGED--}');
2361                 }
2362         } // END - if
2363 }
2364
2365 // Removes given network type handlers
2366 function doAdminNetworkProcessRemoveNetworkTypes () {
2367         // Is there selections?
2368         if (ifPostContainsSelections()) {
2369                 // By default nothing is removed
2370                 $removed = 0;
2371
2372                 // Something has been selected, so start updating them
2373                 foreach (postRequestElement('sel') as $networkId => $sel) {
2374                         // Update this entry?
2375                         if ($sel == 1) {
2376                                 // Remove this entry
2377                                 $removed += doAdminRemoveNetworkEntry('types', 'network_type_id', $networkId);
2378                         } // END - if
2379                 } // END - foreach
2380
2381                 // Is there removes?
2382                 if ($removed > 0) {
2383                         // Removals done
2384                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_REMOVED=' . $removed . '%}');
2385                 } else {
2386                         // Nothing removed
2387                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_REMOVED--}');
2388                 }
2389         } // END - if
2390 }
2391
2392 // Removes given network request parameters
2393 function doAdminNetworkProcessRemoveNetworkRequestParams () {
2394         // Is there selections?
2395         if (ifPostContainsSelections()) {
2396                 // By default nothing is removed
2397                 $removed = 0;
2398
2399                 // Something has been selected, so start updating them
2400                 foreach (postRequestElement('sel') as $networkId => $sel) {
2401                         // Update this entry?
2402                         if ($sel == 1) {
2403                                 // Remove this entry
2404                                 $removed += doAdminRemoveNetworkEntry('request_params', 'network_request_param_id', $networkId);
2405                         } // END - if
2406                 } // END - foreach
2407
2408                 // Is there removes?
2409                 if ($removed > 0) {
2410                         // Removals done
2411                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_REMOVED=' . $removed . '%}');
2412                 } else {
2413                         // Nothing removed
2414                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_REMOVED--}');
2415                 }
2416         } // END - if
2417 }
2418
2419 // Removes given network array translations
2420 function doAdminNetworkProcessRemoveNetworkArrayTranslation () {
2421         // Is there selections?
2422         if (ifPostContainsSelections()) {
2423                 // By default nothing is removed
2424                 $removed = 0;
2425
2426                 // Something has been selected, so start updating them
2427                 foreach (postRequestElement('sel') as $networkId => $sel) {
2428                         // Update this entry?
2429                         if ($sel == 1) {
2430                                 // Remove this entry
2431                                 $removed += doAdminRemoveNetworkEntry('array_translation', 'network_array_id', $networkId);
2432                         } // END - if
2433                 } // END - foreach
2434
2435                 // Is there removes?
2436                 if ($removed > 0) {
2437                         // Removals done
2438                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_REMOVED=' . $removed . '%}');
2439                 } else {
2440                         // Nothing removed
2441                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_REMOVED--}');
2442                 }
2443         } // END - if
2444 }
2445
2446 // Adds a request parameter to given network and type
2447 function doAdminNetworkProcessAddRequestParam () {
2448         // Is the request parameter already used with given network?
2449         if (isNetworkRequestElementValid(postRequestElement('network_request_param_key'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
2450                 // Already added
2451                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_request_param_key') . '%}');
2452
2453                 // ... so abort here
2454                 return FALSE;
2455         } // END - if
2456
2457         // Add id
2458         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2459
2460         // Is network_request_param_default set?
2461         if (!isPostRequestElementSet('network_request_param_default')) {
2462                 // Remove empty value to get a NULL for an optional entry
2463                 unsetPostRequestElement('network_request_param_default');
2464         } // END - if
2465
2466         // Add the whole request to database
2467         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_request_params'), __FUNCTION__, __LINE__);
2468
2469         // Output message
2470         if (!SQL_HASZEROAFFECTED()) {
2471                 // Successfully added
2472                 loadTemplate('admin_network_request_param_added', FALSE, postRequestArray());
2473         } else {
2474                 // Not added
2475                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_NOT_ADDED=' . postRequestElement('network_request_param_key') . '%}');
2476         }
2477 }
2478
2479 // Adds a vheck request parameter to given network
2480 function doAdminNetworkProcessAddVcheckParam () {
2481         // Is the request parameter already used with given network?
2482         if (isNetworkVcheckElementValid(postRequestElement('network_vcheck_param_key'), getRequestElement('network_id'))) {
2483                 // Already added
2484                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
2485
2486                 // ... so abort here
2487                 return FALSE;
2488         } // END - if
2489
2490         // Add id
2491         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2492
2493         // Is network_vcheck_param_default set?
2494         if (!isPostRequestElementSet('network_vcheck_param_default')) {
2495                 // Remove empty value to get a NULL for an optional entry
2496                 unsetPostRequestElement('network_vcheck_param_default');
2497         } // END - if
2498
2499         // Add the whole vcheck to database
2500         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_vcheck_params'), __FUNCTION__, __LINE__);
2501
2502         // Output message
2503         if (!SQL_HASZEROAFFECTED()) {
2504                 // Successfully added
2505                 loadTemplate('admin_network_vcheck_param_added', FALSE, postRequestArray());
2506         } else {
2507                 // Not added
2508                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_NOT_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
2509         }
2510 }
2511
2512 // Adds a API response array entry
2513 function doAdminNetworkProcessAddNetworkArrayTranslation () {
2514         // Is the request parameter already used with given network?
2515         if (isNetworkArrayTranslationValid(postRequestElement('network_array_index'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
2516                 // Already added
2517                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_ALREADY_ADDED=' . postRequestElement('network_array_index') . '%}');
2518
2519                 // ... so abort here
2520                 return FALSE;
2521         } // END - if
2522
2523         // Add id
2524         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2525
2526         // Add sorting
2527         setPostRequestElement('network_array_sort', (countSumTotalData(
2528                 bigintval(postRequestElement('network_id')),
2529                 'network_array_translation',
2530                 'network_array_id',
2531                 'network_id',
2532                 true,
2533                 sprintf(" AND `network_type_id`=%s", bigintval(postRequestElement('network_type_id')))
2534         ) + 1));
2535
2536         // Add the whole request to database
2537         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_array_translation'), __FUNCTION__, __LINE__);
2538
2539         // Output message
2540         if (!SQL_HASZEROAFFECTED()) {
2541                 // Successfully added
2542                 loadTemplate('admin_network_array_translation_added', FALSE, postRequestArray());
2543         } else {
2544                 // Not added
2545                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_NOT_ADDED=' . postRequestElement('network_array_index') . '%}');
2546         }
2547 }
2548
2549 // Handle network array translation form
2550 function doAdminNetworkProcessHandleArrayTranslations () {
2551         // Is there selections?
2552         if (ifPostContainsSelections()) {
2553                 // Init cache array
2554                 $GLOBALS['network_array_translation_disabled'] = array();
2555
2556                 // Load network data
2557                 $networkData = getNetworkDataById(getRequestElement('network_id'));
2558
2559                 // Something has been selected, so start displaying one by one
2560                 $OUT = '';
2561                 foreach (postRequestElement('sel') as $networkId => $sel) {
2562                         // Is this selected?
2563                         if ($sel == 1) {
2564                                 // Load this network's data
2565                                 $networkTranslationsData = getNetworkArrayTranslationsDataById($networkId);
2566
2567                                 // Is there found the network?
2568                                 if (count($networkTranslationsData) > 0) {
2569                                         if (getNetworkFormName() == 'edit') {
2570                                                 // Add row template for deleting
2571                                                 $OUT .= loadTemplate('admin_edit_network_array_translation_row', TRUE, $networkTranslationsData);
2572                                         } elseif (getNetworkFormName() == 'delete') {
2573                                                 // Get type data
2574                                                 $networkTranslationsData['network_type_data'] = getNetworkTypeDataByTypeId($networkTranslationsData['network_type_id']);
2575
2576                                                 // Add row template for deleting
2577                                                 $OUT .= loadTemplate('admin_delete_network_array_translation_row', TRUE, $networkTranslationsData);
2578                                         } else {
2579                                                 // Problem!
2580                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2581                                         }
2582                                 } // END - if
2583                         } // END - if
2584                 } // END - foreach
2585
2586                 // If we have no rows, we don't need to display the edit form
2587                 if (!empty($OUT)) {
2588                         // Prepare array with generic elements
2589                         $content = array(
2590                                 'rows'       => $OUT,
2591                                 'network_id' => bigintval(getRequestElement('network_id'))
2592                         );
2593
2594                         // Output main template
2595                         if (getNetworkFormName() == 'edit') {
2596                                 loadTemplate('admin_edit_network_array_translation', FALSE, $content);
2597                         } elseif (getNetworkFormName() == 'delete') {
2598                                 loadTemplate('admin_delete_network_array_translation', FALSE, $content);
2599                         } else {
2600                                 // Problem!
2601                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete. data=<pre>' . print_r(postRequestArray(), TRUE) . '</pre>');
2602                         }
2603
2604                         // Don't display the list/add new form
2605                         $GLOBALS['network_display'] = FALSE;
2606                 } else {
2607                         // Nothing selected/found
2608                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
2609                 }
2610         } // END - if
2611 }
2612
2613 // Adds/update network API configuration
2614 function doAdminNetworkProcessNetworkApiConfig () {
2615         // Add id
2616         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2617
2618         // NULL empty values
2619         foreach (array('network_api_referral_button', 'network_api_visual_pay_check') as $key) {
2620                 // Is it set?
2621                 if (!isPostRequestElementSet($key)) {
2622                         // Remove empty value to get a NULL for an optional entry
2623                         unsetPostRequestElement($key);
2624                 } // END - if
2625         } // END - foreach
2626
2627         // Is there already an entry?
2628         if (isNetworkApiConfigured(getRequestElement('network_id'))) {
2629                 // Generate SQL query
2630                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_api_config', 'network_id', postRequestElement('network_id'), array('network_id'));
2631         } else {
2632                 // Insert new entry
2633                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_api_config');
2634         }
2635
2636         // Run the query
2637         SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2638
2639         // Output message
2640         if (!SQL_HASZEROAFFECTED()) {
2641                 // Successfully added
2642                 displayMessage('{--ADMIN_CONFIG_NETWORK_API_SAVED--}');
2643         } else {
2644                 // Not added
2645                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_API_NOT_SAVED--}');
2646         }
2647 }
2648
2649 // Only adds network type configuration if not yet present
2650 function doAdminNetworkProcessAddHandlerTypesConfig ($displayMessage = TRUE, $convertComma = TRUE) {
2651         // Add both ids
2652         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
2653         setPostRequestElement('network_type_id', bigintval(getRequestElement('network_type_id')));
2654
2655         // Convert comma to dot?
2656         if ($convertComma === TRUE) {
2657                 // Translate German comma to dot
2658                 convertCommaToDotInPostData('network_min_payment');
2659                 convertCommaToDotInPostData('network_min_remain_budget');
2660                 convertCommaToDotInPostData('network_min_remain_clicks');
2661         } // END - if
2662
2663         /*
2664          * Some parameters are optional, at least one must be given so check a bunch
2665          * of parameters.
2666          */
2667         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) {
2668                 // Is this element empty?
2669                 if (!isPostRequestElementSet($element)) {
2670                         // Then unset it to get a NULL for optional parameter
2671                         unsetPostRequestElement($element);
2672                 } // END - if
2673         } // END - foreach
2674
2675         // Convert data in POST array
2676         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
2677
2678         // Is there already an entry?
2679         if (isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
2680                 // This network type handler is already configured
2681                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_ALREADY_CONFIGURED--}');
2682                 return;
2683         } // END - if
2684
2685         // Copy 'set all' and remove it from POST data
2686         $setAll = (postRequestElement('set_all') === 'Y');
2687         unsetPostRequestElement('set_all');
2688
2689         // Shall we set for all?
2690         if ($setAll === TRUE) {
2691                 // Get all handlers
2692                 $result = SQL_QUERY_ESC('SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
2693                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
2694
2695                 // Are there entries?
2696                 if (SQL_HASZERONUMS($result)) {
2697                         // No, then abort here
2698                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
2699                         return;
2700                 } // END - if
2701
2702                 // Init number of rows
2703                 $numRows = 0;
2704
2705                 // Fetch all ids
2706                 while (list($typeId) = SQL_FETCHROW($result)) {
2707                         // Set it in GET data
2708                         setGetRequestElement('network_type_id', $typeId);
2709
2710                         // Call this function again
2711                         $numRows += doAdminNetworkProcessAddHandlerTypesConfig(FALSE, FALSE);
2712                 } // END - while
2713
2714                 // Free result
2715                 SQL_FREERESULT($result);
2716
2717                 // Output message
2718                 if ($numRows > 0) {
2719                         // Something has been updated
2720                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2721                 } else {
2722                         // Nothing has been saved
2723                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2724                 }
2725         } else {
2726                 // Get SQL query for new entry
2727                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_handler_config');
2728
2729                 // Run the query
2730                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2731
2732                 // Shall we display the message?
2733                 if ($displayMessage === TRUE) {
2734                         // Output message
2735                         if (!SQL_HASZEROAFFECTED()) {
2736                                 // Successfully added
2737                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2738                         } else {
2739                                 // Not added
2740                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_SAVED--}');
2741                         }
2742                 } else {
2743                         // Return amount of affected rows (1 or 2)
2744                         return SQL_AFFECTEDROWS();
2745                 }
2746         }
2747 }
2748
2749 // Only changes network type configuration if not yet present
2750 function doAdminNetworkProcessEditHandlerTypesConfig ($displayMessage = TRUE, $convertComma = TRUE) {
2751         // Convert comma to dot?
2752         if ($convertComma === TRUE) {
2753                 // Translate German comma to dot
2754                 convertCommaToDotInPostData('network_min_payment');
2755                 convertCommaToDotInPostData('network_min_remain_budget');
2756                 convertCommaToDotInPostData('network_min_remain_clicks');
2757         } // END - if
2758
2759         /*
2760          * Some parameters are optional, at least one must be given so check a bunch
2761          * of parameters.
2762          */
2763         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) {
2764                 // Is this element empty?
2765                 if (!isPostRequestElementSet($element)) {
2766                         // Then unset it to get a NULL for optional parameter
2767                         unsetPostRequestElement($element);
2768                 } // END - if
2769         } // END - foreach
2770
2771         // Convert time selections in POST data
2772         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
2773
2774         // Is there already an entry?
2775         if (!isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
2776                 // This network type handler is not configured
2777                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_NOT_CONFIGURED--}');
2778                 return;
2779         } // END - if
2780
2781         // Copy 'set all' and remove it from POST data
2782         $setAll = (postRequestElement('set_all') === 'Y');
2783         unsetPostRequestElement('set_all');
2784
2785         // Shall we set for all?
2786         if ($setAll === TRUE) {
2787                 // Get all data entries
2788                 $result = SQL_QUERY_ESC('SELECT `network_data_id` FROM `{?_MYSQL_PREFIX?}_network_handler_config` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
2789                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
2790
2791                 // Are there entries?
2792                 if (SQL_HASZERONUMS($result)) {
2793                         // No, then abort here
2794                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
2795                         return;
2796                 } // END - if
2797
2798                 // Init number of rows
2799                 $numRows = 0;
2800
2801                 // Fetch all ids
2802                 while (list($dataId) = SQL_FETCHROW($result)) {
2803                         // Set it in GET data
2804                         setPostRequestElement('network_data_id', $dataId);
2805
2806                         // Call this function again
2807                         $numRows += doAdminNetworkProcessEditHandlerTypesConfig(FALSE, FALSE);
2808                 } // END - while
2809
2810                 // Free result
2811                 SQL_FREERESULT($result);
2812
2813                 // Output message
2814                 if ($numRows > 0) {
2815                         // Something has been updated
2816                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2817                 } else {
2818                         // Nothing has been saved
2819                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2820                 }
2821         } else {
2822                 // Get SQL query for new entry
2823                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_handler_config', 'network_data_id', postRequestElement('network_data_id'), array('network_data_id'));
2824
2825                 // Run the query
2826                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2827
2828                 // Shall we display the message?
2829                 if ($displayMessage === TRUE) {
2830                         // Output message
2831                         if (!SQL_HASZEROAFFECTED()) {
2832                                 // Successfully added
2833                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2834                         } else {
2835                                 // Not added
2836                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2837                         }
2838                 } else {
2839                         // Return amount of affected rows (1 or 2)
2840                         return SQL_AFFECTEDROWS();
2841                 }
2842         }
2843 }
2844
2845 // Do expression code for this extension
2846 function doExpressionNetwork ($data) {
2847         // Construct replacer
2848         $replacer = sprintf(
2849                 "{DQUOTE} . %s(%s, '%s') . {DQUOTE}",
2850                 $data['callback'],
2851                 $data['matches'][4][$data['key']],
2852                 $data['extra_func']
2853         );
2854
2855         // Check matches[2] as it might contain more clues to look for
2856         $moreData = explode(',', $data['matches'][2][$data['key']]);
2857
2858         // First must be 'network' so unshift it
2859         shift_array($moreData, 'network');
2860
2861         // The second element must be a callable function
2862         if (!is_callable($moreData[0])) {
2863                 // Is not callable!
2864                 reportBug(__FUNCTION__, __LINE__, 'Call-back function ' . $moreData[0] . ' cannot be called.');
2865         } // END - if
2866
2867         // Is the current network id set?
2868         if (isCurrentNetworkIdSet()) {
2869                 // Replace %network_id% with the current network id
2870                 $replacer = str_replace('%network_id%', getCurrentNetworkId(), $replacer);
2871         } // END - if
2872
2873         // Replace the code
2874         $code = replaceExpressionCode($data, $replacer);
2875
2876         // Return it
2877         return $code;
2878 }
2879
2880 // ----------------------------------------------------------------------------
2881 //                     Call-back functions for exporting data
2882 // ----------------------------------------------------------------------------
2883
2884 // Callback function to export network tables
2885 function doAdminNetworkProcessExport () {
2886         // Init table with all valid what->table entries
2887         $validExports = array(
2888                 // General network data
2889                 'list_network_data'              => 'data',
2890                 // Network type handler
2891                 'list_network_types'             => 'types',
2892                 // Network request parameter
2893                 'list_network_request_params'    => 'request_params',
2894                 // Vcheck request parameter
2895                 'list_network_vcheck_params'     => 'vcheck_params',
2896                 // Network API response array index translation
2897                 'list_network_array_translation' => 'array_translation',
2898         );
2899
2900         // Is the 'what' key valid?
2901         if (!isset($validExports[getWhat()])) {
2902                 // Not valid
2903                 reportBug(__FUNCTION__, __LINE__, 'what=' . getWhat() . ' - not supported');
2904         } // END - if
2905
2906         // Generate call-back, some tables require to export not all columns
2907         $callbackName = 'doAdminNetworkExport' . capitalizeUnderscoreString($validExports[getWhat()]);
2908
2909         // Is the call-back function there?
2910         if (!function_exists($callbackName)) {
2911                 // No, this is really bad
2912                 reportBug(__FUNCTION__, __LINE__, 'Invalid call-back function ' . $callbackName . ' detected.');
2913         } elseif (isset($GLOBALS[__FUNCTION__][$callbackName])) {
2914                 // Already called!
2915                 reportBug(__FUNCTION__, __LINE__, 'Double-call of export function ' . $callbackName . ' detected.');
2916         }
2917
2918         // Call the function
2919         call_user_func($callbackName);
2920
2921         // Mark it as called
2922         $GLOBALS[__FUNCTION__][$callbackName] = TRUE;
2923
2924         // Don't display the list/add new form
2925         $GLOBALS['network_display'] = FALSE;
2926 }
2927
2928 // Exports (and displays) the table 'network_data'
2929 function doAdminNetworkExportData () {
2930         // Query for all networks
2931         $result = SQL_QUERY('SELECT
2932         `network_short_name`,
2933         `network_title`,
2934         `network_reflink`,
2935         `network_data_separator`,
2936         `network_row_separator`,
2937         `network_request_type`,
2938         `network_charset`,
2939         `network_require_id_card`,
2940         `network_query_amount`,
2941         `network_active`
2942 FROM
2943         `{?_MYSQL_PREFIX?}_network_data`
2944 ORDER BY
2945         `network_id` ASC',
2946                 __FUNCTION__, __LINE__);
2947
2948         // Start an empty SQL query
2949         $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;
2950
2951         // Load all entries
2952         while ($content = SQL_FETCHARRAY($result)) {
2953                 // Add row
2954                 $SQL .= "('" .
2955                         $content['network_short_name'] . "', '" .
2956                         $content['network_title'] . "', '" .
2957                         $content['network_reflink'] . "', '" .
2958                         $content['network_data_separator'] . "', '" .
2959                         $content['network_row_separator'] . "', '" .
2960                         $content['network_request_type'] . "', '" .
2961                         $content['network_charset'] . "', '" .
2962                         $content['network_require_id_card'] . "', " .
2963                         $content['network_query_amount'] . ", '" .
2964                         $content['network_active'] . "'),\n";
2965         } // END - while
2966
2967         // Remove last commata and close braces
2968         $SQL = substr($SQL, 0, -2);
2969
2970         // Free result
2971         SQL_FREERESULT($result);
2972
2973         // Output the SQL query
2974         loadTemplate('admin_export_network_data', FALSE, $SQL);
2975 }
2976
2977 // Exports (and displays) the table 'network_types'
2978 function doAdminNetworkExportTypes () {
2979         // 'network_id' must be set
2980         if (!isGetRequestElementSet('network_id')) {
2981                 // Only network handlers of one network will be exported per time
2982                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2983         } // END - if
2984
2985         // Get all network types of given network
2986         $result = SQL_QUERY_ESC('SELECT
2987         `network_type_id`,
2988         `network_id`,
2989         `network_type_handler`,
2990         `network_type_api_url`,
2991         `network_type_click_url`,
2992         `network_type_banner_url`,
2993         `network_type_reload_time_unit`,
2994         `network_text_encoding`
2995 FROM
2996         `{?_MYSQL_PREFIX?}_network_types`
2997 WHERE
2998         `network_id`=%s
2999 ORDER BY
3000         `network_type_id` ASC',
3001                 array(
3002                         bigintval(getRequestElement('network_id'))
3003                 ), __FUNCTION__, __LINE__);
3004
3005         // Start an empty SQL query
3006         $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;
3007
3008         // Load all entries
3009         while ($content = SQL_FETCHARRAY($result)) {
3010                 // Add row
3011                 $SQL .= '(' .
3012                         $content['network_type_id'] . ', ' .
3013                         $content['network_id'] . ", '" .
3014                         $content['network_type_handler'] . "', '" .
3015                         $content['network_type_api_url'] . "', ";
3016
3017                 // Is the column NULL?
3018                 if ((is_null($content['network_type_click_url'])) || (empty($content['network_type_click_url']))) {
3019                         // Column is NULL
3020                         $SQL .= 'NULL, ';
3021                 } else {
3022                         // Column is set
3023                         $SQL .= chr(39) . $content['network_type_click_url'] . chr(39) . ', ';
3024                 }
3025
3026                 // Is the column NULL?
3027                 if ((is_null($content['network_type_banner_url'])) || (empty($content['network_type_banner_url']))) {
3028                         // Column is NULL
3029                         $SQL .= 'NULL, ';
3030                 } else {
3031                         // Column is set
3032                         $SQL .= chr(39) . $content['network_type_banner_url'] . chr(39) . ', ';
3033                 }
3034
3035                 // Add more
3036                 $SQL .= chr(39) . $content['network_type_reload_time_unit'] . "','" . $content['network_text_encoding'] . "'),\n";
3037         } // END - while
3038
3039         // Remove last commata and close braces
3040         $SQL = substr($SQL, 0, -2);
3041
3042         // Free result
3043         SQL_FREERESULT($result);
3044
3045         // Output the SQL query
3046         loadTemplate('admin_export_network_types', FALSE, $SQL);
3047 }
3048
3049 // Exports (and displays) the table 'network_request_params'
3050 function doAdminNetworkExportRequestParams () {
3051         // 'network_id' must be set
3052         if (!isGetRequestElementSet('network_id')) {
3053                 // Only network request parameters of one network will be exported per time
3054                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3055         } // END - if
3056
3057         // Get all network types of given network
3058         $result = SQL_QUERY_ESC('SELECT
3059         `network_id`,
3060         `network_type_id`,
3061         `network_request_param_key`,
3062         `network_request_param_value`,
3063         `network_request_param_default`
3064 FROM
3065         `{?_MYSQL_PREFIX?}_network_request_params`
3066 WHERE
3067         `network_id`=%s
3068 ORDER BY
3069         `network_type_id` ASC ,
3070         `network_request_param_id` ASC',
3071                 array(
3072                         bigintval(getRequestElement('network_id'))
3073                 ), __FUNCTION__, __LINE__);
3074
3075         // Start an empty SQL query
3076         $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;
3077
3078         // Load all entries
3079         while ($content = SQL_FETCHARRAY($result)) {
3080                 // Add row
3081                 $SQL .= '(' .
3082                         $content['network_id'] . ', ' .
3083                         $content['network_type_id'] . ", '" .
3084                         $content['network_request_param_key'] . "', '" .
3085                         $content['network_request_param_value'] . "', ";
3086                 
3087                 // Is the column NULL?
3088                 if (is_null($content['network_request_param_default'])) {
3089                         // Column is NULL
3090                         $SQL .= "NULL),\n";
3091                 } else {
3092                         // Column is set
3093                         $SQL .= chr(39) . $content['network_request_param_default'] . "'),\n";
3094                 }
3095         } // END - while
3096
3097         // Remove last commata and close braces
3098         $SQL = substr($SQL, 0, -2);
3099
3100         // Free result
3101         SQL_FREERESULT($result);
3102
3103         // Output the SQL query
3104         loadTemplate('admin_export_network_request_params', FALSE, $SQL);
3105 }
3106
3107 // Exports (and displays) the table 'network_vcheck_params'
3108 function doAdminNetworkExportVcheckParams () {
3109         // 'network_id' must be set
3110         if (!isGetRequestElementSet('network_id')) {
3111                 // Only network vcheck parameters of one network will be exported per time
3112                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3113         } // END - if
3114
3115         // Get all network types of given network
3116         $result = SQL_QUERY_ESC('SELECT
3117         `network_id`,
3118         `network_vcheck_param_key`,
3119         `network_vcheck_param_value`,
3120         `network_vcheck_param_default`
3121 FROM
3122         `{?_MYSQL_PREFIX?}_network_vcheck_params`
3123 WHERE
3124         `network_id`=%s
3125 ORDER BY
3126         `network_vcheck_param_id` ASC',
3127                 array(
3128                         bigintval(getRequestElement('network_id'))
3129                 ), __FUNCTION__, __LINE__);
3130
3131         // Start an empty SQL query
3132         $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;
3133
3134         // Load all entries
3135         while ($content = SQL_FETCHARRAY($result)) {
3136                 // Add row
3137                 $SQL .= '(' .
3138                         $content['network_id'] . ", '" .
3139                         $content['network_vcheck_param_key'] . "', '" .
3140                         $content['network_vcheck_param_value'] . "', ";
3141                 
3142                 // Is the column NULL?
3143                 if (is_null($content['network_vcheck_param_default'])) {
3144                         // Column is NULL
3145                         $SQL .= "NULL),\n";
3146                 } else {
3147                         // Column is set
3148                         $SQL .= chr(39) . $content['network_vcheck_param_default'] . "'),\n";
3149                 }
3150         } // END - while
3151
3152         // Remove last commata and close braces
3153         $SQL = substr($SQL, 0, -2);
3154
3155         // Free result
3156         SQL_FREERESULT($result);
3157
3158         // Output the SQL query
3159         loadTemplate('admin_export_network_vcheck_params', FALSE, $SQL);
3160 }
3161
3162 // Exports (and displays) the table 'network_array_translation'
3163 function doAdminNetworkExportArrayTranslation () {
3164         // 'network_id' must be set
3165         if (!isGetRequestElementSet('network_id')) {
3166                 // Only network API array index translations of one network will be exported per time
3167                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
3168         } // END - if
3169
3170         // Get all network types of given network
3171         $result = SQL_QUERY_ESC('SELECT
3172         `network_id`,
3173         `network_type_id`,
3174         `network_array_index`,
3175         `network_array_sort`
3176 FROM
3177         `{?_MYSQL_PREFIX?}_network_array_translation`
3178 WHERE
3179         `network_id`=%s
3180 ORDER BY
3181         `network_type_id` ASC,
3182         `network_array_sort` ASC',
3183                 array(
3184                         bigintval(getRequestElement('network_id'))
3185                 ), __FUNCTION__, __LINE__);
3186
3187         // Start an empty SQL query
3188         $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;
3189
3190         // Load all entries
3191         while ($content = SQL_FETCHARRAY($result)) {
3192                 // Add row
3193                 $SQL .= '(' .
3194                         $content['network_id'] . ', ' .
3195                         $content['network_type_id'] . ', ' .
3196                         $content['network_array_index'] . ', ' .
3197                         $content['network_array_sort'] . "),\n";
3198         } // END - while
3199
3200         // Remove last commata and close braces
3201         $SQL = substr($SQL, 0, -2);
3202
3203         // Free result
3204         SQL_FREERESULT($result);
3205
3206         // Output the SQL query
3207         loadTemplate('admin_export_network_array_translation', FALSE, $SQL);
3208 }
3209
3210 // ----------------------------------------------------------------------------
3211 //                     Call-back functions for AJAX requests
3212 // ----------------------------------------------------------------------------
3213
3214 // AJAX call-back function for quering a single API
3215 function doAjaxAdminNetworkQuerySingleApi () {
3216         // This must be be done only by admins
3217         if (!isAdmin()) {
3218                 // Only allowed for admins
3219                 reportBug(__FUNCTION__, __LINE__, 'Only allowed for admins.');
3220         } elseif (!isPostRequestElementSet('network_type_id')) {
3221                 // Required POST field 'network_type_id' is not there
3222                 reportBug(__FUNCTION__, __LINE__, 'Required POST field &quot;network_type_id&quot; is missing.');
3223         }
3224
3225         // Get network + type handler data
3226         $networkData = getNetworkDataByTypeId(postRequestElement('network_type_id'));
3227
3228         // Is it set?
3229         if (is_null($networkData)) {
3230                 // Provided type id is not found
3231                 reportBug(__FUNCTION__, __LINE__, 'Requested network type id ' . postRequestElement('network_type_id') . ' does not exist.');
3232         } elseif ((!isDebugModeEnabled()) && ($networkData['network_active'] == 'N')) {
3233                 // Network not active
3234                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' is not active. network_id=' . $networkData['network_id'] . ',network_type_id=' . postRequestElement('network_type_id'));
3235         } elseif (!isNetworkApiConfigured($networkData['network_id'])) {
3236                 // Network not configured
3237                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' is not configured yet. network_id=' . $networkData['network_id'] . ',network_type_id=' . postRequestElement('network_type_id'));
3238         } elseif (!isNetworkTypeHandlerConfigured($networkData['network_id'], postRequestElement('network_type_id'))) {
3239                 // Network type handler not configured
3240                 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'));
3241         }
3242
3243         // Now load request parameters
3244         $requestParams = getNetworkRequestParametersByTypeId(postRequestElement('network_type_id'));
3245
3246         // Is there at least one entry?
3247         if (count($requestParams) == 0) {
3248                 // No entry found, please setup some first
3249                 reportBug(__FUNCTION__, __LINE__, 'Network ' . $networkData['network_title'] . ' with id ' . $networkData['network_id'] . ' has no request parameters.');
3250         } // END - if
3251
3252         // Handle all keys
3253         handleNetworkRequestParameterKeys($requestParams);
3254
3255         /*
3256          * Array element network_request_param_value contains the request parameter
3257          * keys, network_request_param_default contains values. Now the request can
3258          * be build.
3259          */
3260         $requestData = array();
3261         foreach ($requestParams as $key => $params) {
3262                 // Add id
3263                 $requestData[$params['network_request_param_value']] = $params['network_request_param_default'];
3264         } // END - foreach
3265
3266         // Everything is setup and ready to send out to the affiliate network's API
3267         $response = queryNetworkApi($networkData, $requestData);
3268
3269         // Is the returned HTTP status '200 OK'?
3270         if (!isHttpStatusOkay($response[0])) {
3271                 // Not HTTP/1.x 200 OK
3272                 reportBug(__FUNCTION__, __LINE__, 'HTTP response code is not 200 OK, have: ' . $response[0]);
3273         } // END - if
3274
3275         // Load "success" message
3276         setAjaxReplyContent('{%message,ADMIN_NETWORK_QUERY_TYPE_OKAY=' . $networkData['network_title'] . '%}');
3277
3278         // All fine
3279         setHttpStatus('200 OK');
3280 }
3281
3282 // AJAX call-back function to return a JSON with all network type handler ids
3283 function doAjaxAdminNetworkListById () {
3284         // This must be be done only by admins
3285         if (!isAdmin()) {
3286                 // Only allowed for admins
3287                 reportBug(__FUNCTION__, __LINE__, 'Only allowed for admins.');
3288         } elseif (!isPostRequestElementSet('network_id')) {
3289                 // Required POST field 'network_id' is not there
3290                 reportBug(__FUNCTION__, __LINE__, 'Required POST field &quot;network_id&quot; is missing.');
3291         }
3292
3293         // Load all network type handlers by given network id and extract only network_type_id
3294         $networkTypes = getArrayFromArrayIndex(getNetworkTypeDataById(postRequestElement('network_id')), 'network_type_id');
3295
3296         // Set generated array
3297         setAjaxReplyContent(encodeJson($networkTypes));
3298
3299         // All fine
3300         setHttpStatus('200 OK');
3301 }
3302
3303 // [EOF]
3304 ?>