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