2a52309768c51b950fef9e855b15ce58e1e3fa72
[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 // Detects if a supported form has been sent
54 function detectNetworkProcessForm () {
55         // 'do' must be provided in URL
56         if (!isGetRequestElementSet('do')) {
57                 // Not provided!
58                 reportBug(__FUNCTION__, __LINE__, 'No "do" has been provided. Please fix your templates.');
59         } // END - if
60
61         // Default is invalid
62         $GLOBALS['network_form_name'] = 'invalid';
63
64         // Now search all valid
65         foreach (array('ok', 'edit', 'delete', 'do_edit', 'do_delete') as $form) {
66                 // Is it detected
67                 if (isFormSent($form)) {
68                         // Use this form name
69                         $GLOBALS['network_form_name'] = $form;
70
71                         // Abort loop
72                         break;
73                 } // END - if
74         } // END - foreach
75
76         // Has the form being detected?
77         if ($GLOBALS['network_form_name'] == 'invalid') {
78                 // Not supported
79                 reportBug(__FUNCTION__, __LINE__, 'POST form could not be detected.');
80         } // END - if
81 }
82
83 // Handle a (maybe) sent form here
84 function doNetworkHandleForm () {
85         // Is there a form sent?
86         if (countRequestPost() > 0) {
87                 // Detect sent POST form
88                 detectNetworkProcessForm();
89         } elseif (!isGetRequestElementSet('do')) {
90                 // Skip any further requests
91                 return;
92         }
93
94         // Process the request
95         doAdminNetworkProcessForm();
96 }
97
98 // Processes an admin form
99 function doAdminNetworkProcessForm () {
100         // Create function name
101         $functionName = sprintf("doAdminNetworkProcess%s", capitalizeUnderscoreString(getRequestElement('do')));
102
103         // Is the function valid?
104         if (!function_exists($functionName)) {
105                 // Invalid function name
106                 reportBug(__FUNCTION__, __LINE__, 'Invalid do ' . getRequestElement('do') . ', function ' . $functionName .' does not exist.', FALSE);
107         } // END - if
108
109         // Init global arrays
110         $GLOBALS['network_types_disabled'] = array();
111
112         // Call-back the method handling our request
113         call_user_func($functionName);
114 }
115
116 // Checks whether the (short) network name is already used (valid)
117 function isNetworkNameValid ($name) {
118         // Is there cache?
119         if (!isset($GLOBALS[__FUNCTION__][$name])) {
120                 // Does it exist?
121                 $GLOBALS[__FUNCTION__][$name] = (countSumTotalData($name, 'network_data', 'network_id', 'network_short_name', TRUE) == 1);
122         } // END - if
123
124         // Return result
125         return $GLOBALS[__FUNCTION__][$name];
126 }
127
128 // Checks whether the (short) named network is activated
129 function isNetworkActiveByShortName ($name) {
130         // Is there cache?
131         if (!isset($GLOBALS[__FUNCTION__][$name])) {
132                 // Does it exist?
133                 $GLOBALS[__FUNCTION__][$name] = ((isNetworkNameValid($name)) && (countSumTotalData($name, 'network_data', 'network_id', 'network_short_name', TRUE, " AND `network_active`='Y'") == 1));
134         } // END - if
135
136         // Return result
137         return $GLOBALS[__FUNCTION__][$name];
138 }
139
140 // Checks whether the network by given id is activated
141 function isNetworkActiveById ($networkId) {
142         // Is there cache?
143         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
144                 // Does it exist?
145                 $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(bigintval($networkId), 'network_data', 'network_id', 'network_id', TRUE, " AND `network_active`='Y'") == 1);
146         } // END - if
147
148         // Return result
149         return $GLOBALS[__FUNCTION__][$networkId];
150 }
151
152 // "Getter" for 'network_activated' column depending on current administrator's expert setting
153 function getNetworkActivatedColumn ($whereAnd = 'WHERE', $table = '') {
154         // Is there cache?
155         if (!isset($GLOBALS[__FUNCTION__][$whereAnd][$table])) {
156                 // Default is exclude deactivated networks
157                 $GLOBALS[__FUNCTION__][$whereAnd][$table] = ' ' . $whereAnd . ' ' . $table . "`network_active`='Y'";
158
159                 // Is the export setting on?
160                 if (isAdminsExpertSettingEnabled()) {
161                         // Then allow all networks
162                         $GLOBALS[__FUNCTION__][$whereAnd][$table] = '';
163                 } // END - if
164         } // END - if
165
166         // Return cache
167         return $GLOBALS[__FUNCTION__][$whereAnd][$table];
168 }
169
170 // Checks whether the given network type is already used (valid)
171 function isNetworkTypeHandleValid ($type, $networkId) {
172         // Query for it
173         $result = SQL_QUERY_ESC("SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s AND `network_type_handler`='%s' LIMIT 1",
174                 array(
175                         $networkId,
176                         $type
177                 ), __FUNCTION__, __LINE__);
178
179         // Does it exist?
180         $isValid = (SQL_NUMROWS($result) == 1);
181
182         // Free result
183         SQL_FREERESULT($result);
184
185         // Return result
186         return $isValid;
187 }
188
189 // Checks whether the given network request parameter is already used (valid)
190 function isNetworkRequestElementValid ($key, $type, $networkId) {
191         // Query for it
192         $result = SQL_QUERY_ESC("SELECT `network_request_param_id` FROM `{?_MYSQL_PREFIX?}_network_request_params` WHERE `network_id`=%s AND `network_type_id`=%s AND `network_request_param_key`='%s' LIMIT 1",
193                 array(
194                         $networkId,
195                         $type,
196                         $key
197                 ), __FUNCTION__, __LINE__);
198
199         // Does it exist?
200         $isValid = (SQL_NUMROWS($result) == 1);
201
202         // Free result
203         SQL_FREERESULT($result);
204
205         // Return result
206         return $isValid;
207 }
208
209 // Checks whether the given vcheck request parameter is already used (valid)
210 function isNetworkVcheckElementValid ($key, $networkId) {
211         // Query for it
212         $result = SQL_QUERY_ESC("SELECT `network_vcheck_param_id` FROM `{?_MYSQL_PREFIX?}_network_vcheck_params` WHERE `network_id`=%s AND `network_vcheck_param_key`='%s' LIMIT 1",
213                 array(
214                         $networkId,
215                         $key
216                 ), __FUNCTION__, __LINE__);
217
218         // Does it exist?
219         $isValid = (SQL_NUMROWS($result) == 1);
220
221         // Free result
222         SQL_FREERESULT($result);
223
224         // Return result
225         return $isValid;
226 }
227
228 // Checks whether the given network API array translation
229 function isNetworkArrayTranslationValid ($key, $type, $networkId) {
230         // Query for it
231         $result = SQL_QUERY_ESC("SELECT `network_array_id` FROM `{?_MYSQL_PREFIX?}_network_array_translation` WHERE `network_id`=%s AND `network_type_id`=%s AND `network_array_index`='%s' LIMIT 1",
232                 array(
233                         $networkId,
234                         $type,
235                         $key
236                 ), __FUNCTION__, __LINE__);
237
238         // Does it exist?
239         $isValid = (SQL_NUMROWS($result) == 1);
240
241         // Free result
242         SQL_FREERESULT($result);
243
244         // Return result
245         return $isValid;
246 }
247
248 // "Getter" for a network's data by provided id number
249 function getNetworkDataById ($networkId, $column = '') {
250         // Ids lower one are not accepted
251         if ($networkId < 1) {
252                 // Not good, should be fixed
253                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is smaller than 1.');
254         } elseif ((!isNetworkActiveById($networkId)) && (!isAdminsExpertSettingEnabled())) {
255                 // Do not load inactive network data
256                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is not active.');
257         }
258
259         // Set current network id
260         setCurrentNetworkId($networkId);
261
262         // Is it cached?
263         if (!isset($GLOBALS['network_data'][$networkId])) {
264                 // By default we have no data
265                 $GLOBALS['network_data'][$networkId] = array();
266
267                 // Query for the network data
268                 $result = SQL_QUERY_ESC('SELECT
269         `network_id`,
270         `network_short_name`,
271         `network_title`,
272         `network_reflink`,
273         `network_data_separator`,
274         `network_row_separator`,
275         `network_request_type`,
276         `network_charset`,
277         `network_require_id_card`,
278         `network_query_amount`
279 FROM
280         `{?_MYSQL_PREFIX?}_network_data`
281 WHERE
282         `network_id`=%s
283 LIMIT 1',
284                         array(bigintval($networkId)), __FUNCTION__, __LINE__);
285
286                 // Is there an entry?
287                 if (SQL_NUMROWS($result) == 1) {
288                         // Then get it
289                         $GLOBALS['network_data'][$networkId] = SQL_FETCHARRAY($result);
290                 } // END - if
291
292                 // Free result
293                 SQL_FREERESULT($result);
294         } // END - if
295
296         // Return result
297         if ((empty($column)) && (isset($GLOBALS['network_data'][$networkId]))) {
298                 // Return array
299                 return $GLOBALS['network_data'][$networkId];
300         } elseif (isset($GLOBALS['network_data'][$networkId][$column])) {
301                 // Return column
302                 return $GLOBALS['network_data'][$networkId][$column];
303         }
304
305         // Return NULL
306         return NULL;
307 }
308
309 // "Getter" for a network's data by provided type id number
310 function getNetworkDataByTypeId ($networkId, $column = '') {
311         // Ids lower one are not accepted
312         if ($networkId < 1) {
313                 // Not good, should be fixed
314                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkId . ' is smaller than 1.');
315         } elseif ((!isNetworkActiveById($networkId)) && (!isAdminsExpertSettingEnabled())) {
316                 // Do not load inactive network data
317                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is not active.');
318         }
319
320         // Set current network id
321         setCurrentNetworkId($networkId);
322
323         // Is it cached?
324         if (!isset($GLOBALS['network_data'][$networkId])) {
325                 // By default we have no data
326                 $GLOBALS['network_data'][$networkId] = array();
327
328                 // Query for the network data
329                 $result = SQL_QUERY_ESC('SELECT
330         d.`network_id`,
331         d.`network_short_name`,
332         d.`network_title`,
333         d.`network_reflink`,
334         d.`network_data_separator`,
335         d.`network_row_separator`,
336         d.`network_request_type`,
337         d.`network_charset`,
338         d.`network_require_id_card`,
339         d.`network_query_amount`,
340         t.`network_type_handler`,
341         t.`network_type_api_url`,
342         t.`network_type_click_url`,
343         t.`network_type_banner_url`,
344         t.`network_text_encoding`
345 FROM
346         `{?_MYSQL_PREFIX?}_network_data` AS d
347 LEFT JOIN
348         `{?_MYSQL_PREFIX?}_network_types` AS t
349 ON
350         d.`network_id`=t.`network_id`
351 WHERE
352         t.`network_type_id`=%s
353 LIMIT 1',
354                         array(bigintval($networkId)), __FUNCTION__, __LINE__);
355
356                 // Is there an entry?
357                 if (SQL_NUMROWS($result) == 1) {
358                         // Then get it
359                         $GLOBALS['network_data'][$networkId] = SQL_FETCHARRAY($result);
360                 } // END - if
361
362                 // Free result
363                 SQL_FREERESULT($result);
364         } // END - if
365
366         // Return result
367         if (empty($column)) {
368                 // Return array
369                 return $GLOBALS['network_data'][$networkId];
370         } else {
371                 // Return column
372                 return $GLOBALS['network_data'][$networkId][$column];
373         }
374 }
375
376 // "Getter" for a network type data by provided id number
377 function getNetworkTypeDataById ($networkTypeId) {
378         // Ids lower one are not accepted
379         if ($networkTypeId < 1) {
380                 // Not good, should be fixed
381                 reportBug(__FUNCTION__, __LINE__, 'Network type id ' . $networkTypeId . ' is smaller than 1.');
382         } // END - if
383
384         // By default we have no data
385         $GLOBALS['network_type_data'][$networkTypeId] = array();
386
387         // Query for the network data
388         $result = SQL_QUERY_ESC('SELECT
389         `network_type_id`,
390         `network_id`,
391         `network_type_handler`,
392         `network_type_api_url`,
393         `network_type_click_url`,
394         `network_type_banner_url`
395 FROM
396         `{?_MYSQL_PREFIX?}_network_types`
397 WHERE
398         `network_type_id`=%s
399 LIMIT 1',
400                 array(bigintval($networkTypeId)), __FUNCTION__, __LINE__);
401
402         // Is there an entry?
403         if (SQL_NUMROWS($result) == 1) {
404                 // Then get it
405                 $GLOBALS['network_type_data'][$networkTypeId] = SQL_FETCHARRAY($result);
406         } // END - if
407
408         // Free result
409         SQL_FREERESULT($result);
410
411         // Return result
412         return $GLOBALS['network_type_data'][$networkTypeId];
413 }
414
415 // "Getter" for a network request parameter data by provided id number
416 function getNetworkRequestParamsDataById ($networkRequestId) {
417         // Ids lower one are not accepted
418         if ($networkRequestId < 1) {
419                 // Not good, should be fixed
420                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkRequestId . ' is smaller than 1.');
421         } // END - if
422
423         // By default we have no data
424         $networkRequestData = array();
425
426         // Query for the network data
427         $result = SQL_QUERY_ESC('SELECT
428         `network_request_param_id`,
429         `network_id`,
430         `network_type_id`,
431         `network_request_param_key`,
432         `network_request_param_value`,
433         `network_request_param_default`
434 FROM
435         `{?_MYSQL_PREFIX?}_network_request_params`
436 WHERE
437         `network_request_param_id`=%s
438 LIMIT 1',
439                 array(bigintval($networkRequestId)), __FUNCTION__, __LINE__);
440
441         // Is there an entry?
442         if (SQL_NUMROWS($result) == 1) {
443                 // Then get it
444                 $networkRequestData = SQL_FETCHARRAY($result);
445         } // END - if
446
447         // Free result
448         SQL_FREERESULT($result);
449
450         // Return result
451         return $networkRequestData;
452 }
453
454 // "Getter" for a network array translation data by provided id number
455 function getNetworkArrayTranslationsDataById ($networkTranslationId) {
456         // Ids lower one are not accepted
457         if ($networkTranslationId < 1) {
458                 // Not good, should be fixed
459                 reportBug(__FUNCTION__, __LINE__, 'Network array translation id ' . $networkTranslationId . ' is smaller than 1.');
460         } // END - if
461
462         // By default we have no data
463         $networkTranslationData = array();
464
465         // Query for the network data
466         $result = SQL_QUERY_ESC('SELECT
467         `network_array_id`,
468         `network_id`,
469         `network_type_id`,
470         `network_array_index`,
471         `network_array_sort`
472 FROM
473         `{?_MYSQL_PREFIX?}_network_array_translation`
474 WHERE
475         `network_array_id`=%s
476 LIMIT 1',
477                 array(bigintval($networkTranslationId)), __FUNCTION__, __LINE__);
478
479         // Is there an entry?
480         if (SQL_NUMROWS($result) == 1) {
481                 // Then get it
482                 $networkTranslationData = SQL_FETCHARRAY($result);
483         } // END - if
484
485         // Free result
486         SQL_FREERESULT($result);
487
488         // Return result
489         return $networkTranslationData;
490 }
491
492 // Updates given network (id) with data from array
493 function doNetworkUpdateDataByArray ($networkId, $networkData) {
494         // Ids lower one are not accepted
495         if ($networkId < 1) {
496                 // Not good, should be fixed
497                 reportBug(__FUNCTION__, __LINE__, 'Network id ' . $networkId . ' is smaller than 1.');
498         } // END - if
499
500         // Just call our inner method
501         return adminSaveSettings($networkData, '_network_data', sprintf("`network_id`=%s", bigintval($networkId)), array(), FALSE, FALSE);
502 }
503
504 // Updates given network type handler (id) with data from array
505 function doNetworkUpdateTypeByArray ($networkTypeId, $networkTypeData) {
506         // Ids lower one are not accepted
507         if ($networkTypeId < 1) {
508                 // Not good, should be fixed
509                 reportBug(__FUNCTION__, __LINE__, 'Network type handler id ' . $networkTypeId . ' is smaller than 1.');
510         } // END - if
511
512         // Just call our inner method
513         return adminSaveSettings($networkTypeData, '_network_types', sprintf("`network_type_id`=%s", bigintval($networkTypeId)), array(), FALSE, FALSE);
514 }
515
516 // Updates given network request parameters (id) with data from array
517 function doNetworkUpdateParamsByArray ($networkParamsId, $networkParamsData) {
518         // Ids lower one are not accepted
519         if ($networkParamsId < 1) {
520                 // Not good, should be fixed
521                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkParamsId . ' is smaller than 1.');
522         } // END - if
523
524         // Just call our inner method
525         return adminSaveSettings($networkParamsData, '_network_request_params', sprintf("`network_request_param_id`=%s", bigintval($networkParamsId)), array(), FALSE, FALSE);
526 }
527
528 // Updates given network array translations (id) with data from array
529 function doNetworkUpdateArrayTranslationsByArray ($networkTranslationsId, $networkTranslationsData) {
530         // Ids lower one are not accepted
531         if ($networkTranslationsId < 1) {
532                 // Not good, should be fixed
533                 reportBug(__FUNCTION__, __LINE__, 'Network request parameter id ' . $networkTranslationsId . ' is smaller than 1.');
534         } // END - if
535
536         // Just call our inner method
537         return adminSaveSettings($networkTranslationsData, '_network_array_translation', sprintf("`network_array_id`=%s", bigintval($networkTranslationsId)), array(), FALSE, FALSE);
538 }
539
540 // Removes given network entry
541 function doAdminRemoveNetworkEntry ($table, $column, $id, $limit = 1) {
542         // Remove the entry
543         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_network_%s` WHERE `%s`=%s LIMIT %s",
544                 array(
545                         $table,
546                         $column,
547                         $id,
548                         $limit
549                 ), __FUNCTION__, __LINE__);
550
551         // Return affected rows
552         return SQL_AFFECTEDROWS();
553 }
554
555 // Generates a list of networks for given script and returns it
556 function generateAdminNetworkList () {
557         // Init output
558         $content = '';
559
560         // Query for all networks
561         $result = SQL_QUERY('SELECT
562         `network_id`,
563         `network_short_name`,
564         `network_title`
565 FROM
566         `{?_MYSQL_PREFIX?}_network_data`
567 ' . getNetworkActivatedColumn() . '
568 ORDER BY
569         `network_short_name` ASC', __FUNCTION__, __LINE__);
570
571         // Are there entries?
572         if (!SQL_HASZERONUMS($result)) {
573                 // List all entries
574                 $rows = array();
575                 while ($row = SQL_FETCHARRAY($result)) {
576                         // Is this valid, then add it
577                         if ((is_array($row)) && (isset($row['network_id']))) {
578                                 // Add entry
579                                 $rows[$row['network_id']] = $row;
580                         } // END - if
581                 } // END - while
582
583                 // Generate the selection box
584                 $content = generateSelectionBoxFromArray($rows, 'network_id', 'network_id', '', '', 'network');
585         } else {
586                 // Nothing selected
587                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
588         }
589
590         // Free the result
591         SQL_FREERESULT($result);
592
593         // Return the list
594         return $content;
595 }
596
597 // Generator (somewhat getter) for a list of network types for given network id
598 function generateAdminNetworkTypeList ($networkId) {
599         // Init content
600         $content = '';
601
602         // Query all types of this network
603         $result = SQL_QUERY_ESC('SELECT
604         `network_type_id`,
605         `network_type_handler`
606 FROM
607         `{?_MYSQL_PREFIX?}_network_types`
608 WHERE
609         `network_id`=%s
610         ' . getNetworkActivatedColumn('AND') . '
611 ORDER BY
612         `network_type_handler` ASC',
613                 array(
614                         bigintval($networkId)
615                 ), __FUNCTION__, __LINE__);
616
617         // Are there entries?
618         if (!SQL_HASZERONUMS($result)) {
619                 // List all entries
620                 $rows = array();
621                 while ($row = SQL_FETCHARRAY($result)) {
622                         // Is this valid, then add it
623                         if ((is_array($row)) && (isset($row['network_type_id']))) {
624                                 // Add entry
625                                 $rows[$row['network_type_id']] = $row;
626                         } // END - if
627                 } // END - while
628
629                 // Generate the selection box
630                 $content = generateSelectionBoxFromArray($rows, 'network_type', 'network_type_id');
631         } else {
632                 // Nothing selected
633                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
634         }
635
636         // Free the result
637         SQL_FREERESULT($result);
638
639         // Return content
640         return $content;
641 }
642
643 // Generator (somewhat getter) for a list of network types for all types
644 function generateAdminDistinctNetworkTypeList () {
645         // Init content
646         $content = '';
647
648         // Query all types of this network
649         $result = SQL_QUERY('SELECT
650         t.`network_type_id`,
651         t.`network_type_handler`,
652         d.`network_title`
653 FROM
654         `{?_MYSQL_PREFIX?}_network_types` AS t
655 LEFT JOIN
656         `{?_MYSQL_PREFIX?}_network_data` AS d
657 ON
658         t.`network_id`=d.`network_id`
659 ' . getNetworkActivatedColumn('WHERE', 'd') . '
660 ORDER BY
661         d.`network_short_name` ASC,
662         t.`network_type_handler` ASC', __FUNCTION__, __LINE__);
663
664         // Are there entries?
665         if (!SQL_HASZERONUMS($result)) {
666                 // List all entries
667                 $rows = array();
668                 while ($row = SQL_FETCHARRAY($result)) {
669                         // Is this valid, then add it
670                         if ((is_array($row)) && (isset($row['network_type_id']))) {
671                                 // Add entry
672                                 $rows[$row['network_type_id']] = $row;
673                         } // END - if
674                 } // END - while
675
676                 // Generate the selection box
677                 $content = generateSelectionBoxFromArray($rows, 'network_type', 'network_type_id', '', '_title');
678         } else {
679                 // Nothing selected
680                 $content = loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_ENTRIES_404--}');
681         }
682
683         // Free the result
684         SQL_FREERESULT($result);
685         //* DEBUG: */ die('<pre>'.encodeEntities($content).'</pre>');
686
687         // Return content
688         return $content;
689 }
690
691 // Generator (somewhat getter) for network type options
692 function generateNetworkTypeOptions ($networkId) {
693         // Is this an array, then we just came back from edit/delete actions
694         if (is_array($networkId)) {
695                 // Set it as empty string
696                 $networkId = '';
697         } // END - if
698
699         // Is this cached?
700         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
701                 // Generate output and cache it
702                 $GLOBALS[__FUNCTION__][$networkId] = generateOptions(
703                         'network_types',
704                         'network_type_id',
705                         'network_type_handler',
706                         $networkId,
707                         '',
708                         sprintf(
709                                 "WHERE `network_id`=%s" . getNetworkActivatedColumn('AND'),
710                                 bigintval(getRequestElement('network_id'))
711                         ),
712                         '',
713                         'translateNetworkTypeHandler'
714                 );
715         } // END - if
716
717         // Return content
718         return $GLOBALS[__FUNCTION__][$networkId];
719 }
720
721 // Generates an options list of all available (hard-coded) handlers
722 function generateNetworkTypesAvailableOptions ($defaultType = NULL) {
723         // Is it cached?
724         if (!isset($GLOBALS[__FUNCTION__][$defaultType])) {
725                 // Generate list
726                 $GLOBALS[__FUNCTION__][$defaultType] = generateOptions(
727                         '/ARRAY/',
728                         array(
729                                 'banner',
730                                 'banner_click',
731                                 'banner_view',
732                                 'button',
733                                 'button_click',
734                                 'button_view',
735                                 'surfbar',
736                                 'surfbar_click',
737                                 'surfbar_view',
738                                 'forcedbanner',
739                                 'forcedtextlink',
740                                 'textlink',
741                                 'textlink_click',
742                                 'textlink_view',
743                                 'skybanner',
744                                 'skybanner_click',
745                                 'skybanner_view',
746                                 'layer',
747                                 'layer_click',
748                                 'layer_view',
749                                 'popup',
750                                 'popdown',
751                                 'textmail',
752                                 'htmlmail',
753                                 'lead',
754                                 'sale',
755                                 'payperactive',
756                                 'pagepeel',
757                                 'traffic',
758                                 'signature',
759                                 'signature_click',
760                                 'signature_view',
761                         ),
762                         array(),
763                         $defaultType,
764                         '', '',
765                         $GLOBALS['network_types_disabled'],
766                         'translateNetworkTypeHandler'
767                 );
768         } // END - if
769
770         // Return content
771         return $GLOBALS[__FUNCTION__][$defaultType];
772 }
773
774 // Generates an options list of all available (hard-coded) text encoders
775 function generateNetworkTextEncodingAvailableOptions ($defaultEncoding = NULL) {
776         // Is it cached?
777         if (!isset($GLOBALS[__FUNCTION__][$defaultEncoding])) {
778                 // Generate list
779                 $GLOBALS[__FUNCTION__][$defaultEncoding] = generateOptions(
780                         '/ARRAY/',
781                         array(
782                                 'NONE',
783                                 'BASE64',
784                         ),
785                         array(),
786                         $defaultEncoding,
787                         '', '',
788                         array(),
789                         'translateNetworkTextEncoding'
790                 );
791         } // END - if
792
793         // Return content
794         return $GLOBALS[__FUNCTION__][$defaultEncoding];
795 }
796
797 // Generates an options list (somewhat getter) for request keys
798 function generateNetworkRequestKeyOptions () {
799         // Is it cached?
800         if (!isset($GLOBALS[__FUNCTION__])) {
801                 // Generate and cache it
802                 $GLOBALS[__FUNCTION__] = generateOptions(
803                         '/ARRAY/',
804                         array(
805                                 'affiliate_id',
806                                 'sid',
807                                 'hash',
808                                 'password',
809                                 'reload',
810                                 'maximum_stay',
811                                 'minimum_stay',
812                                 'currency',
813                                 'type',
814                                 'remain',
815                                 'reward',
816                                 'size',
817                                 'erotic',
818                                 'extra',
819                                 'country'
820                         ),
821                         array(),
822                         '',
823                         '', '',
824                         $GLOBALS['network_request_params_disabled'],
825                         'translateNetworkRequestParameterKey'
826                 );
827         } // END - if
828
829         // Return content
830         return $GLOBALS[__FUNCTION__];
831 }
832
833 // Generates an options list for vcheck request keys
834 function generateNetworkVcheckKeyOptions () {
835         // Is it cached?
836         if (!isset($GLOBALS[__FUNCTION__])) {
837                 // Generate and cache it
838                 $GLOBALS[__FUNCTION__] = generateOptions(
839                         '/ARRAY/',
840                         array(
841                                 'network_key',
842                                 'sid',
843                                 'payment',
844                                 'remote_address',
845                                 'campaign_id',
846                                 'status',
847                                 'reason',
848                                 'type',
849                                 'network_name',
850                                 'extra_value1',
851                                 'extra_value2',
852                                 'extra_value3',
853                                 'extra_value4',
854                         ),
855                         array(),
856                         '',
857                         '', '',
858                         $GLOBALS['network_vcheck_params_disabled'],
859                         'translateNetworkVcheckParameterKey'
860                 );
861         } // END - if
862
863         // Return content
864         return $GLOBALS[__FUNCTION__];
865 }
866
867 // Generator (somewhat getter) for (return) array translation
868 function generateNetworkTranslationOptions ($default = '') {
869         // Is it cached?
870         if (!isset($GLOBALS[__FUNCTION__][$default])) {
871                 // Generate and cache it
872                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
873                         'network_translations',
874                         'network_translation_id',
875                         'network_translation_name',
876                         $default,
877                         '',
878                         '',
879                         $GLOBALS['network_array_translation_disabled'],
880                         'translateNetworkTranslationName'
881                 );
882         } // END - if
883
884         // Return content
885         return $GLOBALS[__FUNCTION__][$default];
886 }
887
888 // Generates an option list of request types
889 function generateNetworkRequestTypeOptions ($default = '') {
890         // Is there cache?
891         if (!isset($GLOBALS[__FUNCTION__][$default])) {
892                 // Generate the list
893                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
894                         '/ARRAY/',
895                         array(
896                                 'GET',
897                                 'POST'
898                         ),
899                         array(
900                                 '{--ADMIN_NETWORK_REQUEST_TYPE_GET--}',
901                                 '{--ADMIN_NETWORK_REQUEST_TYPE_POST--}'
902                         ),
903                         $default
904                 );
905         } // END - if
906
907         // Return cache
908         return $GLOBALS[__FUNCTION__][$default];
909 }
910
911 // Generates an option list of network_api_active
912 function generateNetworkApiActiveOptions ($default = '') {
913         // Is there cache?
914         if (!isset($GLOBALS[__FUNCTION__][$default])) {
915                 // Generate the list
916                 $GLOBALS[__FUNCTION__][$default] = generateYesNoOptions($default);
917         } // END - if
918
919         // Return cache
920         return $GLOBALS[__FUNCTION__][$default];
921 }
922
923 // Translates 'translate_name' for e.g. templates
924 function translateNetworkTranslationName ($name) {
925         // Generate id
926         $messageId = 'ADMIN_NETWORK_TRANSLATE_' . strtoupper($name) . '_NAME';
927
928         // Is the message id there?
929         if (!isMessageIdValid($messageId)) {
930                 // Not valid name
931                 reportBug(__FUNCTION__, __LINE__, 'name=' . $name . ' is invalid.');
932         } // END - if
933
934         // Return message id
935         return '{--' . $messageId . '--}';
936 }
937
938 // Translates the network type handler (e.g. banner, paidmail) for templates
939 function translateNetworkTypeHandler ($type) {
940         // Generate id
941         $messageId = 'ADMIN_NETWORK_TYPE_HANDLER_' . strtoupper($type);
942
943         // Is the message id there?
944         if (!isMessageIdValid($messageId)) {
945                 // Not valid type
946                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
947         } // END - if
948
949         // Return message id
950         return '{--' . $messageId . '--}';
951 }
952
953 // Translates request type
954 function translateNetworkRequestType ($type) {
955         // Generate id
956         $messageId = 'ADMIN_NETWORK_REQUEST_TYPE_' . strtoupper($type) . '';
957
958         // Is the message id there?
959         if (!isMessageIdValid($messageId)) {
960                 // Not valid type
961                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
962         } // END - if
963
964         // Return message id
965         return '{--' . $messageId . '--}';
966 }
967
968 // Translates request parameter
969 function translateNetworkRequestParameterKey ($param) {
970         // Generate id
971         $messageId = 'ADMIN_NETWORK_REQUEST_PARAMETER_' . strtoupper($param) . '';
972
973         // Is the message id there?
974         if (!isMessageIdValid($messageId)) {
975                 // Not valid param
976                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
977         } // END - if
978
979         // Return message id
980         return '{--' . $messageId . '--}';
981 }
982
983 // Translates vheck request parameter
984 function translateNetworkVcheckParameterKey ($param) {
985         // Generate id
986         $messageId = 'ADMIN_NETWORK_VCHECK_PARAMETER_' . strtoupper($param) . '';
987
988         // Is the message id there?
989         if (!isMessageIdValid($messageId)) {
990                 // Not valid param
991                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
992         } // END - if
993
994         // Return message id
995         return '{--' . $messageId . '--}';
996 }
997
998 // Translate text-encoding
999 function translateNetworkTextEncoding ($encoding) {
1000         // Generate id
1001         $messageId = 'ADMIN_NETWORK_TYPE_TEXT_ENCODING_' . strtoupper($encoding) . '';
1002
1003         // Is the message id there?
1004         if (!isMessageIdValid($messageId)) {
1005                 // Not valid encoding
1006                 reportBug(__FUNCTION__, __LINE__, 'encoding=' . $encoding . ' is invalid.');
1007         } // END - if
1008
1009         // Return message id
1010         return '{--' . $messageId . '--}';
1011 }
1012
1013 // Translates API index
1014 function translateNetworkApiIndex ($index) {
1015         // Is there cache?
1016         if (!isset($GLOBALS['network_array_index'])) {
1017                 // Get an array of all API array indexes
1018                 $GLOBALS['network_array_index'] = array();
1019
1020                 // Get all entries
1021                 $result = SQL_QUERY('SELECT
1022         `network_array_id`,
1023         `network_array_index`,
1024         `network_translation_name`
1025 FROM
1026         `{?_MYSQL_PREFIX?}_network_array_translation`
1027 INNER JOIN
1028         `{?_MYSQL_PREFIX?}_network_translations`
1029 ON
1030         `network_array_index`=`network_translation_id`
1031 ORDER BY
1032         `network_array_sort` ASC', __FUNCTION__, __LINE__);
1033
1034                 // Are there entries?
1035                 if (!SQL_HASZERONUMS($result)) {
1036                         // Get all entries
1037                         while ($row = SQL_FETCHARRAY($result)) {
1038                                 // Add it to our global array
1039                                 $GLOBALS['network_array_index'][$row['network_array_index']] = $row;
1040                         } // END - while
1041                 } // END - if
1042
1043                 // Free result
1044                 SQL_FREERESULT($result);
1045         } // END - if
1046
1047         // Default name is unknown
1048         $name = 'unknown';
1049
1050         // Is the entry there?
1051         if (isset($GLOBALS['network_array_index'][$index])) {
1052                 // Then get the name
1053                 $name = $GLOBALS['network_array_index'][$index]['network_translation_name'];
1054         } // END - if
1055
1056         // Return translation
1057         return translateNetworkTranslationName($name);
1058 }
1059
1060 // Translates network API configuration status (see function isNetworkApiConfigured()) by given id
1061 function translateNetworkApiConfiguredStatusById ($networkId) {
1062         // Is there cache?
1063         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1064                 // By default it is not configured
1065                 $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_CONFIGURED--}';
1066
1067                 // So is it configured?
1068                 if (!isNetworkActiveById($networkId)) {
1069                         // Network is not active
1070                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_ACTIVE--}';
1071                 } elseif (isNetworkApiConfigured($networkId)) {
1072                         // Yes, it is
1073                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_CONFIGURED--}';
1074                 } // END - if
1075         } // END - if
1076
1077         // Return cache
1078         return $GLOBALS[__FUNCTION__][$networkId];
1079 }
1080
1081 // Checks if the given network is configured by looking its API configuration entry up
1082 function isNetworkApiConfigured ($networkId) {
1083         // Is there cache?
1084         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1085                 // Check for an entry in network_api_config
1086                 $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(
1087                         bigintval($networkId),
1088                         'network_api_config',
1089                         'network_id',
1090                         'network_id',
1091                         true
1092                 ) == 1);
1093         } // END - if
1094
1095         // Return cache
1096         return $GLOBALS[__FUNCTION__][$networkId];
1097 }
1098
1099 // Checks whether the given network type handler is configured
1100 function isNetworkTypeHandlerConfigured ($networkId, $networkTypeId) {
1101         // Is there cache?
1102         if (!isset($GLOBALS[__FUNCTION__][$networkId][$networkTypeId])) {
1103                 // Determine it
1104                 $GLOBALS[__FUNCTION__][$networkId][$networkTypeId] = (countSumTotalData(
1105                         bigintval($networkTypeId),
1106                         'network_types_config',
1107                         'network_data_id',
1108                         'network_type_id',
1109                         true,
1110                         sprintf(' AND `network_id`=%s', bigintval($networkId))
1111                 ) == 1);
1112         } // END - if
1113
1114         // Return cache
1115         return $GLOBALS[__FUNCTION__][$networkId][$networkTypeId];
1116 }
1117
1118 // Handles the network-payment-check request
1119 function handleNetworkPaymentCheckRequest () {
1120         // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
1121         reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
1122 }
1123
1124 //------------------------------------------------------------------------------
1125 //                             Call-back functions
1126 //------------------------------------------------------------------------------
1127
1128 // Callback function to add new network
1129 function doAdminNetworkProcessAddNetwork () {
1130         // We can say here, the form is sent, so check if the network is already added
1131         if (isNetworkNameValid(postRequestElement('network_short_name'))) {
1132                 // Already there
1133                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ALREADY_ADDED=' . postRequestElement('network_short_name') . '%}');
1134                 return FALSE;
1135         } elseif (!isNetworkActiveByShortName(postRequestElement('network_short_name'))) {
1136                 // Network is not active
1137                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_NOT_ACTIVE=' . postRequestElement('network_short_name') . '%}');
1138                 return FALSE;
1139         }
1140
1141         // Remove the 'ok' part
1142         unsetPostRequestElement('ok');
1143
1144         // Add the whole request to database
1145         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_data'), __FUNCTION__, __LINE__);
1146
1147         // Add the id for output only
1148         setPostRequestElement('network_id', SQL_INSERTID());
1149
1150         // Output message
1151         if (!SQL_HASZEROAFFECTED()) {
1152                 // Successfully added
1153                 loadTemplate('admin_network_added', FALSE, postRequestArray());
1154         } else {
1155                 // Not added
1156                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_DATA_NOT_ADDED=' . postRequestElement('network_short_name') . '%}');
1157         }
1158 }
1159
1160 // Displays selected networks for editing
1161 function doAdminNetworkProcessHandleNetworks () {
1162         // Is there selections?
1163         if (ifPostContainsSelections()) {
1164                 // Something has been selected, so start displaying one by one
1165                 $OUT = '';
1166                 foreach (postRequestElement('sel') as $networkId => $sel) {
1167                         // Is this selected?
1168                         if ($sel == 1) {
1169                                 // Load this network's data
1170                                 $networkData = getNetworkDataById($networkId);
1171
1172                                 // Is there found the network?
1173                                 if (count($networkData) > 0) {
1174                                         // Add row template with given form name
1175                                         $OUT .= loadTemplate('admin_' . $GLOBALS['network_form_name'] . '_networks_row', TRUE, $networkData);
1176                                 } // END - if
1177                         } // END - if
1178                 } // END - foreach
1179
1180                 // If we have no rows, we don't need to display the edit form
1181                 if (!empty($OUT)) {
1182                         // Output main template
1183                         loadTemplate('admin_' . $GLOBALS['network_form_name'] . '_networks', FALSE, $OUT);
1184
1185                         // Don't display the list/add new form
1186                         $GLOBALS['network_display'] = FALSE;
1187                 } else {
1188                         // Nothing selected/found
1189                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_FOUND--}');
1190                 }
1191         } // END - if
1192 }
1193
1194 // Handle network type form
1195 function doAdminNetworkProcessHandleNetworkTypes () {
1196         // Is there selections?
1197         if (ifPostContainsSelections()) {
1198                 // Load network data
1199                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1200
1201                 // Something has been selected, so start displaying one by one
1202                 $OUT = '';
1203                 foreach (postRequestElement('sel') as $networkId => $sel) {
1204                         // Is this selected?
1205                         if ($sel == 1) {
1206                                 // Load this network's data
1207                                 $networkTypeData = getNetworkTypeDataById($networkId);
1208
1209                                 // Is there found the network?
1210                                 if (count($networkTypeData) > 0) {
1211                                         if (isFormSent('edit')) {
1212                                                 // Add row template for deleting
1213                                                 $OUT .= loadTemplate('admin_edit_network_types_row', TRUE, $networkTypeData);
1214                                         } elseif (isFormSent('delete')) {
1215                                                 // Add row template for deleting
1216                                                 $OUT .= loadTemplate('admin_delete_network_types_row', TRUE, $networkTypeData);
1217                                         } else {
1218                                                 // Problem!
1219                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1220                                         }
1221                                 } // END - if
1222                         } // END - if
1223                 } // END - foreach
1224
1225                 // If we have no rows, we don't need to display the edit form
1226                 if (!empty($OUT)) {
1227                         // Output main template
1228                         if (isFormSent('edit')) {
1229                                 loadTemplate('admin_edit_network_types', FALSE, $OUT);
1230                         } elseif (isFormSent('delete')) {
1231                                 loadTemplate('admin_delete_network_types', FALSE, $OUT);
1232                         } else {
1233                                 // Problem!
1234                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1235                         }
1236
1237                         // Don't display the list/add new form
1238                         $GLOBALS['network_display'] = FALSE;
1239                 } else {
1240                         // Nothing selected/found
1241                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_FOUND--}');
1242                 }
1243         } // END - if
1244 }
1245
1246 // Handle network request parameter form
1247 function doAdminNetworkProcessHandleRequestParams () {
1248         // Is there selections?
1249         if (ifPostContainsSelections()) {
1250                 // Init cache array
1251                 $GLOBALS['network_request_params_disabled'] = array();
1252
1253                 // Load network data
1254                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1255
1256                 // Something has been selected, so start displaying one by one
1257                 $OUT = '';
1258                 foreach (postRequestElement('sel') as $networkId => $sel) {
1259                         // Is this selected?
1260                         if ($sel == 1) {
1261                                 // Load this network's data
1262                                 $networkRequestData = getNetworkRequestParamsDataById($networkId);
1263
1264                                 // Is there found the network?
1265                                 if (count($networkRequestData) > 0) {
1266                                         if (isFormSent('edit')) {
1267                                                 // Add row template for deleting
1268                                                 $OUT .= loadTemplate('admin_edit_network_request_params_row', TRUE, $networkRequestData);
1269                                         } elseif (isFormSent('delete')) {
1270                                                 // Get type data
1271                                                 $networkRequestData['network_type_data'] = getNetworkTypeDataById($networkRequestData['network_type_id']);
1272
1273                                                 // Add row template for deleting
1274                                                 $OUT .= loadTemplate('admin_delete_network_request_params_row', TRUE, $networkRequestData);
1275                                         } else {
1276                                                 // Problem!
1277                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1278                                         }
1279                                 } // END - if
1280                         } // END - if
1281                 } // END - foreach
1282
1283                 // If we have no rows, we don't need to display the edit form
1284                 if (!empty($OUT)) {
1285                         // Output main template
1286                         if (isFormSent('edit')) {
1287                                 loadTemplate('admin_edit_network_request_params', FALSE, $OUT);
1288                         } elseif (isFormSent('delete')) {
1289                                 loadTemplate('admin_delete_network_request_params', FALSE, $OUT);
1290                         } else {
1291                                 // Problem!
1292                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1293                         }
1294
1295                         // Don't display the list/add new form
1296                         $GLOBALS['network_display'] = FALSE;
1297                 } else {
1298                         // Nothing selected/found
1299                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
1300                 }
1301         } // END - if
1302 }
1303
1304 // Changes given networks
1305 function doAdminNetworkProcessChangeNetworks () {
1306         // Is there selections?
1307         if (ifPostContainsSelections()) {
1308                 // By default nothing is updated
1309                 $updated = 0;
1310
1311                 // Something has been selected, so start updating them
1312                 foreach (postRequestElement('sel') as $networkId => $sel) {
1313                         // Update this entry?
1314                         if ($sel == 1) {
1315                                 // Init data array
1316                                 $networkData = array();
1317
1318                                 // Transfer whole array, except 'sel'
1319                                 foreach (postRequestArray() as $key => $entry) {
1320                                         // Skip 'sel' and submit button
1321                                         if (in_array($key, array('sel', 'do_edit'))) {
1322                                                 continue;
1323                                         } // END - if
1324
1325                                         // Is there this enty?
1326                                         if (!isset($entry[$networkId])) {
1327                                                 // Not found, needs fixing
1328                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1329                                         } // END - if
1330
1331                                         // Add this entry
1332                                         $networkData[$key] = $entry[$networkId];
1333                                 } // END - foreach
1334
1335                                 // Update the network data
1336                                 $updated += doNetworkUpdateDataByArray($networkId, $networkData);
1337                         } // END - if
1338                 } // END - foreach
1339
1340                 // Is there updates?
1341                 if ($updated > 0) {
1342                         // Updates done
1343                         displayMessage('{%message,ADMIN_NETWORK_UPDATED=' . $updated . '%}');
1344                 } else {
1345                         // Nothing changed
1346                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_CHANGED--}');
1347                 }
1348         } // END - if
1349 }
1350
1351 // Removes given networks
1352 function doAdminNetworkProcessRemoveNetworks () {
1353         // Is there selections?
1354         if (ifPostContainsSelections()) {
1355                 // By default nothing is removed
1356                 $removed = 0;
1357
1358                 // Something has been selected, so start updating them
1359                 foreach (postRequestElement('sel') as $networkId => $sel) {
1360                         // Update this entry?
1361                         if ($sel == 1) {
1362                                 // Remove this entry
1363                                 $removed += doAdminRemoveNetworkEntry('data', 'network_id', $networkId);
1364                         } // END - if
1365                 } // END - foreach
1366
1367                 // Is there removes?
1368                 if ($removed > 0) {
1369                         // Removals done
1370                         displayMessage('{%message,ADMIN_NETWORK_REMOVED=' . $removed . '%}');
1371                 } else {
1372                         // Nothing removed
1373                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_REMOVED--}');
1374                 }
1375         } // END - if
1376 }
1377
1378 // Add a network type handler if not yet found
1379 function doAdminNetworkProcessAddNetworkType () {
1380         // Is the network type handle already used with given network?
1381         if (isNetworkTypeHandleValid(postRequestElement('network_type_handler'), getRequestElement('network_id'))) {
1382                 // Already added
1383                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_ALREADY_ADDED=' . postRequestElement('network_type_handler') . '%}');
1384
1385                 // ... so abort here
1386                 return FALSE;
1387         } // END - if
1388
1389         // Remove the 'ok' part
1390         unsetPostRequestElement('ok');
1391
1392         // Add id
1393         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1394
1395         // Is network_type_banner_url set?
1396         if (postRequestElement('network_type_banner_url') == '') {
1397                 // Remove empty value to get a NULL for an optional entry
1398                 unsetPostRequestElement('network_type_banner_url');
1399         } // END - if
1400
1401         // Add the whole request to database
1402         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_types'), __FUNCTION__, __LINE__);
1403
1404         // Output message
1405         if (!SQL_HASZEROAFFECTED()) {
1406                 // Successfully added
1407                 loadTemplate('admin_network_type_added', FALSE, postRequestArray());
1408         } else {
1409                 // Not added
1410                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_NOT_ADDED=' . postRequestElement('network_type_handler') . '%}');
1411         }
1412 }
1413
1414 // Changes given network type handlers
1415 function doAdminNetworkProcessChangeHandlerTypes () {
1416         // Is there selections?
1417         if (ifPostContainsSelections()) {
1418                 // By default nothing is updated
1419                 $updated = 0;
1420
1421                 // Something has been selected, so start updating them
1422                 foreach (postRequestElement('sel') as $networkId => $sel) {
1423                         // Update this entry?
1424                         if ($sel == 1) {
1425                                 // Init data array
1426                                 $networkTypeData = array();
1427
1428                                 // Transfer whole array, except 'sel'
1429                                 foreach (postRequestArray() as $key => $entry) {
1430                                         // Skip 'sel' and submit button
1431                                         if (in_array($key, array('sel', 'do_edit'))) {
1432                                                 continue;
1433                                         } // END - if
1434
1435                                         // Is there this enty?
1436                                         if (!isset($entry[$networkId])) {
1437                                                 // Not found, needs fixing
1438                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1439                                         } // END - if
1440
1441                                         // Fix empty network_type_banner_url to NULL
1442                                         if (($key == 'network_type_banner_url') && (trim($entry[$networkId]) == '')) {
1443                                                 // Set it to NULL
1444                                                 $entry[$networkId] = NULL;
1445                                         } // END - if
1446
1447                                         // Add this entry
1448                                         $networkTypeData[$key] = $entry[$networkId];
1449                                 } // END - foreach
1450
1451                                 // Update the network data
1452                                 $updated += doNetworkUpdateTypeByArray($networkId, $networkTypeData);
1453                         } // END - if
1454                 } // END - foreach
1455
1456                 // Is there updates?
1457                 if ($updated > 0) {
1458                         // Updates done
1459                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_UPDATED=' . $updated . '%}');
1460                 } else {
1461                         // Nothing changed
1462                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_CHANGED--}');
1463                 }
1464         } // END - if
1465 }
1466
1467 // Changes given network request parameters
1468 function doAdminNetworkProcessChangeRequestParams () {
1469         // Is there selections?
1470         if (ifPostContainsSelections()) {
1471                 // By default nothing is updated
1472                 $updated = 0;
1473
1474                 // Something has been selected, so start updating them
1475                 foreach (postRequestElement('sel') as $networkId => $sel) {
1476                         // Update this entry?
1477                         if ($sel == 1) {
1478                                 // Init data array
1479                                 $networkParamsData = array();
1480
1481                                 // Transfer whole array, except 'sel'
1482                                 foreach (postRequestArray() as $key => $entry) {
1483                                         // Skip 'sel' and submit button
1484                                         if (in_array($key, array('sel', 'do_edit'))) {
1485                                                 continue;
1486                                         } // END - if
1487
1488                                         // Is there this enty?
1489                                         if (!isset($entry[$networkId])) {
1490                                                 // Not found, needs fixing
1491                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1492                                         } // END - if
1493
1494                                         // Fix empty network_request_param_default to NULL
1495                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
1496                                                 // Set it to NULL
1497                                                 $entry[$networkId] = NULL;
1498                                         } // END - if
1499
1500                                         // Add this entry
1501                                         $networkParamsData[$key] = $entry[$networkId];
1502                                 } // END - foreach
1503
1504                                 // Update the network data
1505                                 $updated += doNetworkUpdateParamsByArray($networkId, $networkParamsData);
1506                         } // END - if
1507                 } // END - foreach
1508
1509                 // Is there updates?
1510                 if ($updated > 0) {
1511                         // Updates done
1512                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_UPDATED=' . $updated . '%}');
1513                 } else {
1514                         // Nothing changed
1515                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_CHANGED--}');
1516                 }
1517         } // END - if
1518 }
1519
1520 // Changes given network array translations
1521 function doAdminNetworkProcessChangeArrayTranslations () {
1522         // Is there selections?
1523         if (ifPostContainsSelections()) {
1524                 // By default nothing is updated
1525                 $updated = 0;
1526
1527                 // Something has been selected, so start updating them
1528                 foreach (postRequestElement('sel') as $networkId => $sel) {
1529                         // Update this entry?
1530                         if ($sel == 1) {
1531                                 // Init data array
1532                                 $networkTranslationsData = array();
1533
1534                                 // Transfer whole array, except 'sel'
1535                                 foreach (postRequestArray() as $key => $entry) {
1536                                         // Skip 'sel' and submit button
1537                                         if (in_array($key, array('sel', 'do_edit'))) {
1538                                                 continue;
1539                                         } // END - if
1540
1541                                         // Is there this enty?
1542                                         if (!isset($entry[$networkId])) {
1543                                                 // Not found, needs fixing
1544                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1545                                         } // END - if
1546
1547                                         // Fix empty network_request_param_default to NULL
1548                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
1549                                                 // Set it to NULL
1550                                                 $entry[$networkId] = NULL;
1551                                         } // END - if
1552
1553                                         // Add this entry
1554                                         $networkTranslationsData[$key] = $entry[$networkId];
1555                                 } // END - foreach
1556
1557                                 // Update the network data
1558                                 $updated += doNetworkUpdateArrayTranslationsByArray($networkId, $networkTranslationsData);
1559                         } // END - if
1560                 } // END - foreach
1561
1562                 // Is there updates?
1563                 if ($updated > 0) {
1564                         // Updates done
1565                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_UPDATED=' . $updated . '%}');
1566                 } else {
1567                         // Nothing changed
1568                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_CHANGED--}');
1569                 }
1570         } // END - if
1571 }
1572
1573 // Removes given network type handlers
1574 function doAdminNetworkProcessRemoveNetworkTypes () {
1575         // Is there selections?
1576         if (ifPostContainsSelections()) {
1577                 // By default nothing is removed
1578                 $removed = 0;
1579
1580                 // Something has been selected, so start updating them
1581                 foreach (postRequestElement('sel') as $networkId => $sel) {
1582                         // Update this entry?
1583                         if ($sel == 1) {
1584                                 // Remove this entry
1585                                 $removed += doAdminRemoveNetworkEntry('types', 'network_type_id', $networkId);
1586                         } // END - if
1587                 } // END - foreach
1588
1589                 // Is there removes?
1590                 if ($removed > 0) {
1591                         // Removals done
1592                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_REMOVED=' . $removed . '%}');
1593                 } else {
1594                         // Nothing removed
1595                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_REMOVED--}');
1596                 }
1597         } // END - if
1598 }
1599
1600 // Removes given network request parameters
1601 function doAdminNetworkProcessRemoveNetworkRequestParams () {
1602         // Is there selections?
1603         if (ifPostContainsSelections()) {
1604                 // By default nothing is removed
1605                 $removed = 0;
1606
1607                 // Something has been selected, so start updating them
1608                 foreach (postRequestElement('sel') as $networkId => $sel) {
1609                         // Update this entry?
1610                         if ($sel == 1) {
1611                                 // Remove this entry
1612                                 $removed += doAdminRemoveNetworkEntry('request_params', 'network_request_param_id', $networkId);
1613                         } // END - if
1614                 } // END - foreach
1615
1616                 // Is there removes?
1617                 if ($removed > 0) {
1618                         // Removals done
1619                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_REMOVED=' . $removed . '%}');
1620                 } else {
1621                         // Nothing removed
1622                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_REMOVED--}');
1623                 }
1624         } // END - if
1625 }
1626
1627 // Removes given network array translations
1628 function doAdminNetworkProcessRemoveNetworkArrayTranslation () {
1629         // Is there selections?
1630         if (ifPostContainsSelections()) {
1631                 // By default nothing is removed
1632                 $removed = 0;
1633
1634                 // Something has been selected, so start updating them
1635                 foreach (postRequestElement('sel') as $networkId => $sel) {
1636                         // Update this entry?
1637                         if ($sel == 1) {
1638                                 // Remove this entry
1639                                 $removed += doAdminRemoveNetworkEntry('array_translation', 'network_array_id', $networkId);
1640                         } // END - if
1641                 } // END - foreach
1642
1643                 // Is there removes?
1644                 if ($removed > 0) {
1645                         // Removals done
1646                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_REMOVED=' . $removed . '%}');
1647                 } else {
1648                         // Nothing removed
1649                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_REMOVED--}');
1650                 }
1651         } // END - if
1652 }
1653
1654 // Adds a request parameter to given network and type
1655 function doAdminNetworkProcessAddRequestParam () {
1656         // Is the request parameter already used with given network?
1657         if (isNetworkRequestElementValid(postRequestElement('network_request_param_key'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
1658                 // Already added
1659                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_request_param_key') . '%}');
1660
1661                 // ... so abort here
1662                 return FALSE;
1663         } // END - if
1664
1665         // Remove the 'ok' part
1666         unsetPostRequestElement('ok');
1667
1668         // Add id
1669         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1670
1671         // Is network_request_param_default set?
1672         if (postRequestElement('network_request_param_default') == '') {
1673                 // Remove empty value to get a NULL for an optional entry
1674                 unsetPostRequestElement('network_request_param_default');
1675         } // END - if
1676
1677         // Add the whole request to database
1678         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_request_params'), __FUNCTION__, __LINE__);
1679
1680         // Output message
1681         if (!SQL_HASZEROAFFECTED()) {
1682                 // Successfully added
1683                 loadTemplate('admin_network_request_param_added', FALSE, postRequestArray());
1684         } else {
1685                 // Not added
1686                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_NOT_ADDED=' . postRequestElement('network_request_param_key') . '%}');
1687         }
1688 }
1689
1690 // Adds a vheck request parameter to given network
1691 function doAdminNetworkProcessAddVcheckParam () {
1692         // Is the request parameter already used with given network?
1693         if (isNetworkVcheckElementValid(postRequestElement('network_vcheck_param_key'), getRequestElement('network_id'))) {
1694                 // Already added
1695                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
1696
1697                 // ... so abort here
1698                 return FALSE;
1699         } // END - if
1700
1701         // Remove the 'ok' part
1702         unsetPostRequestElement('ok');
1703
1704         // Add id
1705         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1706
1707         // Is network_vcheck_param_default set?
1708         if (postRequestElement('network_vcheck_param_default') == '') {
1709                 // Remove empty value to get a NULL for an optional entry
1710                 unsetPostRequestElement('network_vcheck_param_default');
1711         } // END - if
1712
1713         // Add the whole vcheck to database
1714         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_vcheck_params'), __FUNCTION__, __LINE__);
1715
1716         // Output message
1717         if (!SQL_HASZEROAFFECTED()) {
1718                 // Successfully added
1719                 loadTemplate('admin_network_vcheck_param_added', FALSE, postRequestArray());
1720         } else {
1721                 // Not added
1722                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_NOT_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
1723         }
1724 }
1725
1726 // Adds a API response array entry
1727 function doAdminNetworkProcessAddNetworkArrayTranslation () {
1728         // Is the request parameter already used with given network?
1729         if (isNetworkArrayTranslationValid(postRequestElement('network_array_index'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
1730                 // Already added
1731                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_ALREADY_ADDED=' . postRequestElement('network_array_index') . '%}');
1732
1733                 // ... so abort here
1734                 return FALSE;
1735         } // END - if
1736
1737         // Remove the 'ok' part
1738         unsetPostRequestElement('ok');
1739
1740         // Add id
1741         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1742
1743         // Add sorting
1744         setPostRequestElement('network_array_sort', (countSumTotalData(
1745                 bigintval(postRequestElement('network_id')),
1746                 'network_array_translation',
1747                 'network_array_id',
1748                 'network_id',
1749                 true,
1750                 sprintf(" AND `network_type_id`=%s", bigintval(postRequestElement('network_type_id')))
1751         ) + 1));
1752
1753         // Add the whole request to database
1754         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_array_translation'), __FUNCTION__, __LINE__);
1755
1756         // Output message
1757         if (!SQL_HASZEROAFFECTED()) {
1758                 // Successfully added
1759                 loadTemplate('admin_network_array_translation_added', FALSE, postRequestArray());
1760         } else {
1761                 // Not added
1762                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_NOT_ADDED=' . postRequestElement('network_array_index') . '%}');
1763         }
1764 }
1765
1766 // Handle network array translation form
1767 function doAdminNetworkProcessHandleArrayTranslations () {
1768         // Is there selections?
1769         if (ifPostContainsSelections()) {
1770                 // Init cache array
1771                 $GLOBALS['network_array_translation_disabled'] = array();
1772
1773                 // Load network data
1774                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1775
1776                 // Something has been selected, so start displaying one by one
1777                 $OUT = '';
1778                 foreach (postRequestElement('sel') as $networkId => $sel) {
1779                         // Is this selected?
1780                         if ($sel == 1) {
1781                                 // Load this network's data
1782                                 $networkTranslationsData = getNetworkArrayTranslationsDataById($networkId);
1783
1784                                 // Is there found the network?
1785                                 if (count($networkTranslationsData) > 0) {
1786                                         if (isFormSent('edit')) {
1787                                                 // Add row template for deleting
1788                                                 $OUT .= loadTemplate('admin_edit_network_array_translation_row', TRUE, $networkTranslationsData);
1789                                         } elseif (isFormSent('delete')) {
1790                                                 // Get type data
1791                                                 $networkTranslationsData['network_type_data'] = getNetworkTypeDataById($networkTranslationsData['network_type_id']);
1792
1793                                                 // Add row template for deleting
1794                                                 $OUT .= loadTemplate('admin_delete_network_array_translation_row', TRUE, $networkTranslationsData);
1795                                         } else {
1796                                                 // Problem!
1797                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1798                                         }
1799                                 } // END - if
1800                         } // END - if
1801                 } // END - foreach
1802
1803                 // If we have no rows, we don't need to display the edit form
1804                 if (!empty($OUT)) {
1805                         // Output main template
1806                         if (isFormSent('edit')) {
1807                                 loadTemplate('admin_edit_network_array_translation', FALSE, $OUT);
1808                         } elseif (isFormSent('delete')) {
1809                                 loadTemplate('admin_delete_network_array_translation', FALSE, $OUT);
1810                         } else {
1811                                 // Problem!
1812                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1813                         }
1814
1815                         // Don't display the list/add new form
1816                         $GLOBALS['network_display'] = FALSE;
1817                 } else {
1818                         // Nothing selected/found
1819                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
1820                 }
1821         } // END - if
1822 }
1823
1824 // Adds/update network API configuration
1825 function doAdminNetworkProcessNetworkApiConfig () {
1826         // Remove the 'ok' part
1827         unsetPostRequestElement('ok');
1828
1829         // Add id
1830         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1831
1832         // Is network_api_referral_button set?
1833         if (postRequestElement('network_api_referral_button') == '') {
1834                 // Remove empty value to get a NULL for an optional entry
1835                 unsetPostRequestElement('network_api_referral_button');
1836         } // END - if
1837
1838         // Is there already an entry?
1839         if (isNetworkApiConfigured(getRequestElement('network_id'))) {
1840                 // Generate SQL query
1841                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_api_config', 'network_id', postRequestElement('network_id'), array('network_id'));
1842         } else {
1843                 // Insert new entry
1844                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_api_config');
1845         }
1846
1847         // Run the query
1848         SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1849
1850         // Output message
1851         if (!SQL_HASZEROAFFECTED()) {
1852                 // Successfully added
1853                 displayMessage('{--ADMIN_CONFIG_NETWORK_API_SAVED--}');
1854         } else {
1855                 // Not added
1856                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_API_NOT_SAVED--}');
1857         }
1858 }
1859
1860 // Only adds network type configuration if not yet present
1861 function doAdminNetworkProcessAddHandlerTypesConfig ($displayMessage = TRUE) {
1862         // Remove the 'ok' part
1863         unsetPostRequestElement('ok');
1864
1865         // Add both ids
1866         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1867         setPostRequestElement('network_type_id', bigintval(getRequestElement('network_type_id')));
1868
1869         /*
1870          * Some parameters are optional, at least one must be given so check a bunch
1871          * of parameters.
1872          */
1873         foreach (array('network_min_waiting_time', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic') as $element) {
1874                 // Is this element empty?
1875                 if (postRequestElement($element) == '') {
1876                         // Then unset it to get a NULL for optional parameter
1877                         unsetPostRequestElement($element);
1878                 } // END - if
1879         } // END - foreach
1880
1881         // Convert data in POST array
1882         convertSelectionsToEpocheTimeInPostData($content, 'network_max_reload_time_ye', $skip);
1883
1884         // Is there already an entry?
1885         if (isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
1886                 // This network type handler is already configured
1887                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_ALREADY_CONFIGURED--}');
1888                 return;
1889         } // END - if
1890
1891         // Copy 'set all' and remove it from POST data
1892         $setAll = (postRequestElement('set_all') === 'Y');
1893         unsetPostRequestElement('set_all');
1894
1895         // Shall we set for all?
1896         if ($setAll === TRUE) {
1897                 // Get all handlers
1898                 $result = SQL_QUERY_ESC('SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
1899                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
1900
1901                 // Are there entries?
1902                 if (SQL_HASZERONUMS($result)) {
1903                         // No, then abort here
1904                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
1905                         return;
1906                 } // END - if
1907
1908                 // Init number of rows
1909                 $numRows = 0;
1910
1911                 // Fetch all ids
1912                 while (list($typeId) = SQL_FETCHROW($result)) {
1913                         // Set it in GET data
1914                         setGetRequestElement('network_type_id', $typeId);
1915
1916                         // Call this function again
1917                         $numRows += doAdminNetworkProcessAddHandlerTypesConfig(FALSE);
1918                 } // END - while
1919
1920                 // Free result
1921                 SQL_FREERESULT($result);
1922
1923                 // Output message
1924                 if ($numRows > 0) {
1925                         // Something has been updated
1926                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
1927                 } else {
1928                         // Nothing has been saved
1929                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
1930                 }
1931         } else {
1932                 // Get SQL query for new entry
1933                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_types_config');
1934
1935                 // Run the query
1936                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1937
1938                 // Shall we display the message?
1939                 if ($displayMessage === TRUE) {
1940                         // Output message
1941                         if (!SQL_HASZEROAFFECTED()) {
1942                                 // Successfully added
1943                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
1944                         } else {
1945                                 // Not added
1946                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_SAVED--}');
1947                         }
1948                 } else {
1949                         // Return amount of affected rows (1 or 2)
1950                         return SQL_AFFECTEDROWS();
1951                 }
1952         }
1953 }
1954
1955 // Only changes network type configuration if not yet present
1956 function doAdminNetworkProcessEditHandlerTypesConfig ($displayMessage = TRUE) {
1957         // Remove the 'ok' part
1958         unsetPostRequestElement('ok');
1959
1960         /*
1961          * Some parameters are optional, at least one must be given so check a bunch
1962          * of parameters.
1963          */
1964         foreach (array('network_min_waiting_time', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic') as $element) {
1965                 // Is this element empty?
1966                 if (postRequestElement($element) == '') {
1967                         // Then unset it to get a NULL for optional parameter
1968                         unsetPostRequestElement($element);
1969                 } // END - if
1970         } // END - foreach
1971
1972         // Convert time selections in POST data
1973         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
1974
1975         // Is there already an entry?
1976         if (!isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
1977                 // This network type handler is not configured
1978                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_NOT_CONFIGURED--}');
1979                 return;
1980         } // END - if
1981
1982         // Copy 'set all' and remove it from POST data
1983         $setAll = (postRequestElement('set_all') === 'Y');
1984         unsetPostRequestElement('set_all');
1985
1986         // Shall we set for all?
1987         if ($setAll === TRUE) {
1988                 // Get all data entries
1989                 $result = SQL_QUERY_ESC('SELECT `network_data_id` FROM `{?_MYSQL_PREFIX?}_network_types_config` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
1990                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
1991
1992                 // Are there entries?
1993                 if (SQL_HASZERONUMS($result)) {
1994                         // No, then abort here
1995                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
1996                         return;
1997                 } // END - if
1998
1999                 // Init number of rows
2000                 $numRows = 0;
2001
2002                 // Fetch all ids
2003                 while (list($dataId) = SQL_FETCHROW($result)) {
2004                         // Set it in GET data
2005                         setPostRequestElement('network_data_id', $dataId);
2006
2007                         // Call this function again
2008                         $numRows += doAdminNetworkProcessEditHandlerTypesConfig(FALSE);
2009                 } // END - while
2010
2011                 // Free result
2012                 SQL_FREERESULT($result);
2013
2014                 // Output message
2015                 if ($numRows > 0) {
2016                         // Something has been updated
2017                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2018                 } else {
2019                         // Nothing has been saved
2020                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2021                 }
2022         } else {
2023                 // Get SQL query for new entry
2024                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_types_config', 'network_data_id', postRequestElement('network_data_id'), array('network_data_id'));
2025
2026                 // Run the query
2027                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2028
2029                 // Shall we display the message?
2030                 if ($displayMessage === TRUE) {
2031                         // Output message
2032                         if (!SQL_HASZEROAFFECTED()) {
2033                                 // Successfully added
2034                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2035                         } else {
2036                                 // Not added
2037                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2038                         }
2039                 } else {
2040                         // Return amount of affected rows (1 or 2)
2041                         return SQL_AFFECTEDROWS();
2042                 }
2043         }
2044 }
2045
2046 // Do expression code for this extension
2047 function doExpressionNetwork ($data) {
2048         // Construct replacer
2049         $replacer = sprintf(
2050                 "{DQUOTE} . %s(%s, '%s') . {DQUOTE}",
2051                 $data['callback'],
2052                 $data['matches'][4][$data['key']],
2053                 $data['extra_func']
2054         );
2055
2056         // Replace %network_id% with the current network id
2057         $replacer = str_replace('%network_id%', getCurrentNetworkId(), $replacer);
2058
2059         // Replace the code
2060         $code = replaceExpressionCode($data, $replacer);
2061
2062         // Return it
2063         return $code;
2064 }
2065
2066 // ----------------------------------------------------------------------------
2067 //                     Call-back functions for exporting data
2068 // ----------------------------------------------------------------------------
2069
2070 // Callback function to export network tables
2071 function doAdminNetworkProcessExport () {
2072         // Init table with all valid what->table entries
2073         $validExports = array(
2074                 // General network data
2075                 'list_network_data'              => 'data',
2076                 // Network type handler
2077                 'list_network_types'             => 'types',
2078                 // Network request parameter
2079                 'list_network_request_params'    => 'request_params',
2080                 // Vcheck request parameter
2081                 'list_network_vcheck_params'     => 'vcheck_params',
2082                 // Network API response array index translation
2083                 'list_network_array_translation' => 'array_translation',
2084         );
2085
2086         // Is the 'what' key valid?
2087         if (!isset($validExports[getWhat()])) {
2088                 // Not valid
2089                 reportBug(__FUNCTION__, __LINE__, 'what=' . getWhat() . ' - not supported');
2090         } // END - if
2091
2092         // Generate call-back, some tables require to export not all columns
2093         $callbackName = 'doAdminNetworkExport' . capitalizeUnderscoreString($validExports[getWhat()]);
2094
2095         // Is the call-back function there?
2096         if (!function_exists($callbackName)) {
2097                 // No, this is really bad
2098                 reportBug(__FUNCTION__, __LINE__, 'Invalid call-back function ' . $callbackName . ' detected.');
2099         } elseif (isset($GLOBALS[__FUNCTION__][$callbackName])) {
2100                 // Already called!
2101                 reportBug(__FUNCTION__, __LINE__, 'Double-call of export function ' . $callbackName . ' detected.');
2102         }
2103
2104         // Call the function
2105         call_user_func($callbackName);
2106
2107         // Mark it as called
2108         $GLOBALS[__FUNCTION__][$callbackName] = TRUE;
2109
2110         // Don't display the list/add new form
2111         $GLOBALS['network_display'] = FALSE;
2112 }
2113
2114 // Exports (and displays) the table 'network_data'
2115 function doAdminNetworkExportData () {
2116         // Query for all networks
2117         $result = SQL_QUERY('SELECT
2118         `network_short_name`,
2119         `network_title`,
2120         `network_reflink`,
2121         `network_data_separator`,
2122         `network_row_separator`,
2123         `network_request_type`,
2124         `network_charset`,
2125         `network_require_id_card`,
2126         `network_query_amount`,
2127         `network_active`
2128 FROM
2129         `{?_MYSQL_PREFIX?}_network_data`
2130 ORDER BY
2131         `network_id` ASC',
2132                 __FUNCTION__, __LINE__);
2133
2134         // Start an empty SQL query
2135         $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\n";
2136
2137         // Load all entries
2138         while ($content = SQL_FETCHARRAY($result)) {
2139                 // Add row
2140                 $SQL .= "('" .
2141                         $content['network_short_name'] . "', '" .
2142                         $content['network_title'] . "', '" .
2143                         $content['network_reflink'] . "', '" .
2144                         $content['network_data_separator'] . "', '" .
2145                         $content['network_row_separator'] . "', '" .
2146                         $content['network_request_type'] . "', '" .
2147                         $content['network_charset'] . "', '" .
2148                         $content['network_require_id_card'] . "', " .
2149                         $content['network_query_amount'] . ", '" .
2150                         $content['network_active'] . "'),\n";
2151         } // END - while
2152
2153         // Remove last commata and close braces
2154         $SQL = substr($SQL, 0, -2);
2155
2156         // Free result
2157         SQL_FREERESULT($result);
2158
2159         // Output the SQL query
2160         loadTemplate('admin_export_network_data', FALSE, $SQL);
2161 }
2162
2163 // Exports (and displays) the table 'network_types'
2164 function doAdminNetworkExportTypes () {
2165         // 'network_id' must be set
2166         if (!isGetRequestElementSet('network_id')) {
2167                 // Only network handlers of one network will be exported per time
2168                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2169         } // END - if
2170
2171         // Get all network types of given network
2172         $result = SQL_QUERY_ESC('SELECT
2173         `network_type_id`,
2174         `network_id`,
2175         `network_type_handler`,
2176         `network_type_api_url`,
2177         `network_type_click_url`,
2178         `network_type_banner_url`,
2179         `network_type_reload_time_unit`,
2180         `network_text_encoding`
2181 FROM
2182         `{?_MYSQL_PREFIX?}_network_types`
2183 WHERE
2184         `network_id`=%s
2185 ORDER BY
2186         `network_type_id` ASC',
2187                 array(
2188                         bigintval(getRequestElement('network_id'))
2189                 ), __FUNCTION__, __LINE__);
2190
2191         // Start an empty SQL query
2192         $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\n";
2193
2194         // Load all entries
2195         while ($content = SQL_FETCHARRAY($result)) {
2196                 // Add row
2197                 $SQL .= '(' .
2198                         $content['network_type_id'] . ', ' .
2199                         $content['network_id'] . ", '" .
2200                         $content['network_type_handler'] . "', '" .
2201                         $content['network_type_api_url'] . "', '" .
2202                         $content['network_type_click_url'] . "', ";
2203                 
2204                 // Is the column NULL?
2205                 if (is_null($content['network_type_banner_url'])) {
2206                         // Column is NULL
2207                         $SQL .= 'NULL';
2208                 } else {
2209                         // Column is set
2210                         $SQL .= chr(39) . $content['network_type_banner_url'] . chr(39);
2211                 }
2212
2213                 // Add more
2214                 $SQL .= ",'" . $content['network_type_reload_time_unit'] . "','" . $content['network_text_encoding'] . "'),\n";
2215         } // END - while
2216
2217         // Remove last commata and close braces
2218         $SQL = substr($SQL, 0, -2);
2219
2220         // Free result
2221         SQL_FREERESULT($result);
2222
2223         // Output the SQL query
2224         loadTemplate('admin_export_network_types', FALSE, $SQL);
2225 }
2226
2227 // Exports (and displays) the table 'network_request_params'
2228 function doAdminNetworkExportRequestParams () {
2229         // 'network_id' must be set
2230         if (!isGetRequestElementSet('network_id')) {
2231                 // Only network request parameters of one network will be exported per time
2232                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2233         } // END - if
2234
2235         // Get all network types of given network
2236         $result = SQL_QUERY_ESC('SELECT
2237         `network_id`,
2238         `network_type_id`,
2239         `network_request_param_key`,
2240         `network_request_param_value`,
2241         `network_request_param_default`
2242 FROM
2243         `{?_MYSQL_PREFIX?}_network_request_params`
2244 WHERE
2245         `network_id`=%s
2246 ORDER BY
2247         `network_type_id` ASC ,
2248         `network_request_param_id` ASC',
2249                 array(
2250                         bigintval(getRequestElement('network_id'))
2251                 ), __FUNCTION__, __LINE__);
2252
2253         // Start an empty SQL query
2254         $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\n";
2255
2256         // Load all entries
2257         while ($content = SQL_FETCHARRAY($result)) {
2258                 // Add row
2259                 $SQL .= '(' .
2260                         $content['network_id'] . ', ' .
2261                         $content['network_type_id'] . ", '" .
2262                         $content['network_request_param_key'] . "', '" .
2263                         $content['network_request_param_value'] . "', ";
2264                 
2265                 // Is the column NULL?
2266                 if (is_null($content['network_request_param_default'])) {
2267                         // Column is NULL
2268                         $SQL .= "NULL),\n";
2269                 } else {
2270                         // Column is set
2271                         $SQL .= chr(39) . $content['network_request_param_default'] . "'),\n";
2272                 }
2273         } // END - while
2274
2275         // Remove last commata and close braces
2276         $SQL = substr($SQL, 0, -2);
2277
2278         // Free result
2279         SQL_FREERESULT($result);
2280
2281         // Output the SQL query
2282         loadTemplate('admin_export_network_request_params', FALSE, $SQL);
2283 }
2284
2285 // Exports (and displays) the table 'network_vcheck_params'
2286 function doAdminNetworkExportVcheckParams () {
2287         // 'network_id' must be set
2288         if (!isGetRequestElementSet('network_id')) {
2289                 // Only network vcheck parameters of one network will be exported per time
2290                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2291         } // END - if
2292
2293         // Get all network types of given network
2294         $result = SQL_QUERY_ESC('SELECT
2295         `network_id`,
2296         `network_vcheck_param_key`,
2297         `network_vcheck_param_value`,
2298         `network_vcheck_param_default`
2299 FROM
2300         `{?_MYSQL_PREFIX?}_network_vcheck_params`
2301 WHERE
2302         `network_id`=%s
2303 ORDER BY
2304         `network_vcheck_param_id` ASC',
2305                 array(
2306                         bigintval(getRequestElement('network_id'))
2307                 ), __FUNCTION__, __LINE__);
2308
2309         // Start an empty SQL query
2310         $SQL = "INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_vcheck_params` (`network_id`, `network_vcheck_param_key`, `network_vcheck_param_value`, `network_vcheck_param_default`) VALUES\n";
2311
2312         // Load all entries
2313         while ($content = SQL_FETCHARRAY($result)) {
2314                 // Add row
2315                 $SQL .= '(' .
2316                         $content['network_id'] . ", '" .
2317                         $content['network_vcheck_param_key'] . "', '" .
2318                         $content['network_vcheck_param_value'] . "', ";
2319                 
2320                 // Is the column NULL?
2321                 if (is_null($content['network_vcheck_param_default'])) {
2322                         // Column is NULL
2323                         $SQL .= "NULL),\n";
2324                 } else {
2325                         // Column is set
2326                         $SQL .= chr(39) . $content['network_vcheck_param_default'] . "'),\n";
2327                 }
2328         } // END - while
2329
2330         // Remove last commata and close braces
2331         $SQL = substr($SQL, 0, -2);
2332
2333         // Free result
2334         SQL_FREERESULT($result);
2335
2336         // Output the SQL query
2337         loadTemplate('admin_export_network_vcheck_params', FALSE, $SQL);
2338 }
2339
2340 // Exports (and displays) the table 'network_array_translation'
2341 function doAdminNetworkExportArrayTranslation () {
2342         // 'network_id' must be set
2343         if (!isGetRequestElementSet('network_id')) {
2344                 // Only network API array index translations of one network will be exported per time
2345                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2346         } // END - if
2347
2348         // Get all network types of given network
2349         $result = SQL_QUERY_ESC('SELECT
2350         `network_id`,
2351         `network_type_id`,
2352         `network_array_index`,
2353         `network_array_sort`
2354 FROM
2355         `{?_MYSQL_PREFIX?}_network_array_translation`
2356 WHERE
2357         `network_id`=%s
2358 ORDER BY
2359         `network_type_id` ASC,
2360         `network_array_sort` ASC',
2361                 array(
2362                         bigintval(getRequestElement('network_id'))
2363                 ), __FUNCTION__, __LINE__);
2364
2365         // Start an empty SQL query
2366         $SQL = "INSERT INTO `&#123;&#63;_MYSQL_PREFIX&#63;&#125;_network_array_translation` (`network_id`, `network_type_id`, `network_array_index`, `network_array_sort`) VALUES\n";
2367
2368         // Load all entries
2369         while ($content = SQL_FETCHARRAY($result)) {
2370                 // Add row
2371                 $SQL .= '(' .
2372                         $content['network_id'] . ', ' .
2373                         $content['network_type_id'] . ', ' .
2374                         $content['network_array_index'] . ', ' .
2375                         $content['network_array_sort'] . "),\n";
2376         } // END - while
2377
2378         // Remove last commata and close braces
2379         $SQL = substr($SQL, 0, -2);
2380
2381         // Free result
2382         SQL_FREERESULT($result);
2383
2384         // Output the SQL query
2385         loadTemplate('admin_export_network_array_translation', FALSE, $SQL);
2386 }
2387
2388 // [EOF]
2389 ?>