Mailer project continued (heavy refactoring):
[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                                 'halfbanner',
747                                 'halfbanner_click',
748                                 'halfbanner_view',
749                                 'layer',
750                                 'layer_click',
751                                 'layer_view',
752                                 'popup',
753                                 'popdown',
754                                 'textmail',
755                                 'htmlmail',
756                                 'lead',
757                                 'sale',
758                                 'lead_sale',
759                                 'payperactive',
760                                 'pagepeel',
761                                 'traffic',
762                                 'signature',
763                                 'signature_click',
764                                 'signature_view',
765                         ),
766                         array(),
767                         $defaultType,
768                         '', '',
769                         $GLOBALS['network_types_disabled'],
770                         'translateNetworkTypeHandler'
771                 );
772         } // END - if
773
774         // Return content
775         return $GLOBALS[__FUNCTION__][$defaultType];
776 }
777
778 // Generates an options list of all available (hard-coded) text encoders
779 function generateNetworkTextEncodingAvailableOptions ($defaultEncoding = NULL) {
780         // Is it cached?
781         if (!isset($GLOBALS[__FUNCTION__][$defaultEncoding])) {
782                 // Generate list
783                 $GLOBALS[__FUNCTION__][$defaultEncoding] = generateOptions(
784                         '/ARRAY/',
785                         array(
786                                 'NONE',
787                                 'BASE64',
788                         ),
789                         array(),
790                         $defaultEncoding,
791                         '', '',
792                         array(),
793                         'translateNetworkTextEncoding'
794                 );
795         } // END - if
796
797         // Return content
798         return $GLOBALS[__FUNCTION__][$defaultEncoding];
799 }
800
801 // Generates an options list (somewhat getter) for request keys
802 function generateNetworkRequestKeyOptions () {
803         // Is it cached?
804         if (!isset($GLOBALS[__FUNCTION__])) {
805                 // Generate and cache it
806                 $GLOBALS[__FUNCTION__] = generateOptions(
807                         '/ARRAY/',
808                         array(
809                                 'affiliate_id',
810                                 'sid',
811                                 'hash',
812                                 'password',
813                                 'reload',
814                                 'maximum_stay',
815                                 'minimum_stay',
816                                 'currency',
817                                 'type',
818                                 'remain',
819                                 'reward',
820                                 'size',
821                                 'erotic',
822                                 'extra',
823                                 'country'
824                         ),
825                         array(),
826                         '',
827                         '', '',
828                         $GLOBALS['network_request_params_disabled'],
829                         'translateNetworkRequestParameterKey'
830                 );
831         } // END - if
832
833         // Return content
834         return $GLOBALS[__FUNCTION__];
835 }
836
837 // Generates an options list for vcheck request keys
838 function generateNetworkVcheckKeyOptions () {
839         // Is it cached?
840         if (!isset($GLOBALS[__FUNCTION__])) {
841                 // Generate and cache it
842                 $GLOBALS[__FUNCTION__] = generateOptions(
843                         '/ARRAY/',
844                         array(
845                                 'network_key',
846                                 'sid',
847                                 'payment',
848                                 'remote_address',
849                                 'campaign_id',
850                                 'status',
851                                 'reason',
852                                 'type',
853                                 'network_name',
854                                 'extra_value1',
855                                 'extra_value2',
856                                 'extra_value3',
857                                 'extra_value4',
858                         ),
859                         array(),
860                         '',
861                         '', '',
862                         $GLOBALS['network_vcheck_params_disabled'],
863                         'translateNetworkVcheckParameterKey'
864                 );
865         } // END - if
866
867         // Return content
868         return $GLOBALS[__FUNCTION__];
869 }
870
871 // Generator (somewhat getter) for (return) array translation
872 function generateNetworkTranslationOptions ($default = '') {
873         // Is it cached?
874         if (!isset($GLOBALS[__FUNCTION__][$default])) {
875                 // Generate and cache it
876                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
877                         'network_translations',
878                         'network_translation_id',
879                         'network_translation_name',
880                         $default,
881                         '',
882                         '',
883                         $GLOBALS['network_array_translation_disabled'],
884                         'translateNetworkTranslationName'
885                 );
886         } // END - if
887
888         // Return content
889         return $GLOBALS[__FUNCTION__][$default];
890 }
891
892 // Generates an option list of request types
893 function generateNetworkRequestTypeOptions ($default = '') {
894         // Is there cache?
895         if (!isset($GLOBALS[__FUNCTION__][$default])) {
896                 // Generate the list
897                 $GLOBALS[__FUNCTION__][$default] = generateOptions(
898                         '/ARRAY/',
899                         array(
900                                 'GET',
901                                 'POST'
902                         ),
903                         array(
904                                 '{--ADMIN_NETWORK_REQUEST_TYPE_GET--}',
905                                 '{--ADMIN_NETWORK_REQUEST_TYPE_POST--}'
906                         ),
907                         $default
908                 );
909         } // END - if
910
911         // Return cache
912         return $GLOBALS[__FUNCTION__][$default];
913 }
914
915 // Generates an option list of network_api_active
916 function generateNetworkApiActiveOptions ($default = '') {
917         // Is there cache?
918         if (!isset($GLOBALS[__FUNCTION__][$default])) {
919                 // Generate the list
920                 $GLOBALS[__FUNCTION__][$default] = generateYesNoOptions($default);
921         } // END - if
922
923         // Return cache
924         return $GLOBALS[__FUNCTION__][$default];
925 }
926
927 // Translates 'translate_name' for e.g. templates
928 function translateNetworkTranslationName ($name) {
929         // Generate id
930         $messageId = 'ADMIN_NETWORK_TRANSLATE_' . strtoupper($name) . '_NAME';
931
932         // Is the message id there?
933         if (!isMessageIdValid($messageId)) {
934                 // Not valid name
935                 reportBug(__FUNCTION__, __LINE__, 'name=' . $name . ' is invalid.');
936         } // END - if
937
938         // Return message id
939         return '{--' . $messageId . '--}';
940 }
941
942 // Translates the network type handler (e.g. banner, paidmail) for templates
943 function translateNetworkTypeHandler ($type) {
944         // Generate id
945         $messageId = 'ADMIN_NETWORK_TYPE_HANDLER_' . strtoupper($type);
946
947         // Is the message id there?
948         if (!isMessageIdValid($messageId)) {
949                 // Not valid type
950                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
951         } // END - if
952
953         // Return message id
954         return '{--' . $messageId . '--}';
955 }
956
957 // Translates request type
958 function translateNetworkRequestType ($type) {
959         // Generate id
960         $messageId = 'ADMIN_NETWORK_REQUEST_TYPE_' . strtoupper($type) . '';
961
962         // Is the message id there?
963         if (!isMessageIdValid($messageId)) {
964                 // Not valid type
965                 reportBug(__FUNCTION__, __LINE__, 'type=' . $type . ' is invalid.');
966         } // END - if
967
968         // Return message id
969         return '{--' . $messageId . '--}';
970 }
971
972 // Translates request parameter
973 function translateNetworkRequestParameterKey ($param) {
974         // Generate id
975         $messageId = 'ADMIN_NETWORK_REQUEST_PARAMETER_' . strtoupper($param) . '';
976
977         // Is the message id there?
978         if (!isMessageIdValid($messageId)) {
979                 // Not valid param
980                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
981         } // END - if
982
983         // Return message id
984         return '{--' . $messageId . '--}';
985 }
986
987 // Translates vheck request parameter
988 function translateNetworkVcheckParameterKey ($param) {
989         // Generate id
990         $messageId = 'ADMIN_NETWORK_VCHECK_PARAMETER_' . strtoupper($param) . '';
991
992         // Is the message id there?
993         if (!isMessageIdValid($messageId)) {
994                 // Not valid param
995                 reportBug(__FUNCTION__, __LINE__, 'param=' . $param . ' is invalid.');
996         } // END - if
997
998         // Return message id
999         return '{--' . $messageId . '--}';
1000 }
1001
1002 // Translate text-encoding
1003 function translateNetworkTextEncoding ($encoding) {
1004         // Generate id
1005         $messageId = 'ADMIN_NETWORK_TYPE_TEXT_ENCODING_' . strtoupper($encoding) . '';
1006
1007         // Is the message id there?
1008         if (!isMessageIdValid($messageId)) {
1009                 // Not valid encoding
1010                 reportBug(__FUNCTION__, __LINE__, 'encoding=' . $encoding . ' is invalid.');
1011         } // END - if
1012
1013         // Return message id
1014         return '{--' . $messageId . '--}';
1015 }
1016
1017 // Translates API index
1018 function translateNetworkApiIndex ($index) {
1019         // Is there cache?
1020         if (!isset($GLOBALS['network_array_index'])) {
1021                 // Get an array of all API array indexes
1022                 $GLOBALS['network_array_index'] = array();
1023
1024                 // Get all entries
1025                 $result = SQL_QUERY('SELECT
1026         `network_array_id`,
1027         `network_array_index`,
1028         `network_translation_name`
1029 FROM
1030         `{?_MYSQL_PREFIX?}_network_array_translation`
1031 INNER JOIN
1032         `{?_MYSQL_PREFIX?}_network_translations`
1033 ON
1034         `network_array_index`=`network_translation_id`
1035 ORDER BY
1036         `network_array_sort` ASC', __FUNCTION__, __LINE__);
1037
1038                 // Are there entries?
1039                 if (!SQL_HASZERONUMS($result)) {
1040                         // Get all entries
1041                         while ($row = SQL_FETCHARRAY($result)) {
1042                                 // Add it to our global array
1043                                 $GLOBALS['network_array_index'][$row['network_array_index']] = $row;
1044                         } // END - while
1045                 } // END - if
1046
1047                 // Free result
1048                 SQL_FREERESULT($result);
1049         } // END - if
1050
1051         // Default name is unknown
1052         $name = 'unknown';
1053
1054         // Is the entry there?
1055         if (isset($GLOBALS['network_array_index'][$index])) {
1056                 // Then get the name
1057                 $name = $GLOBALS['network_array_index'][$index]['network_translation_name'];
1058         } // END - if
1059
1060         // Return translation
1061         return translateNetworkTranslationName($name);
1062 }
1063
1064 // Translates network API configuration status (see function isNetworkApiConfigured()) by given id
1065 function translateNetworkApiConfiguredStatusById ($networkId) {
1066         // Is there cache?
1067         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1068                 // By default it is not configured
1069                 $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_CONFIGURED--}';
1070
1071                 // So is it configured?
1072                 if (!isNetworkActiveById($networkId)) {
1073                         // Network is not active
1074                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_NOT_ACTIVE--}';
1075                 } elseif (isNetworkApiConfigured($networkId)) {
1076                         // Yes, it is
1077                         $GLOBALS[__FUNCTION__][$networkId] = '{--ADMIN_NETWORK_API_CONFIGURED--}';
1078                 } // END - if
1079         } // END - if
1080
1081         // Return cache
1082         return $GLOBALS[__FUNCTION__][$networkId];
1083 }
1084
1085 // Checks if the given network is configured by looking its API configuration entry up
1086 function isNetworkApiConfigured ($networkId) {
1087         // Is there cache?
1088         if (!isset($GLOBALS[__FUNCTION__][$networkId])) {
1089                 // Check for an entry in network_api_config
1090                 $GLOBALS[__FUNCTION__][$networkId] = (countSumTotalData(
1091                         bigintval($networkId),
1092                         'network_api_config',
1093                         'network_id',
1094                         'network_id',
1095                         true
1096                 ) == 1);
1097         } // END - if
1098
1099         // Return cache
1100         return $GLOBALS[__FUNCTION__][$networkId];
1101 }
1102
1103 // Checks whether the given network type handler is configured
1104 function isNetworkTypeHandlerConfigured ($networkId, $networkTypeId) {
1105         // Is there cache?
1106         if (!isset($GLOBALS[__FUNCTION__][$networkId][$networkTypeId])) {
1107                 // Determine it
1108                 $GLOBALS[__FUNCTION__][$networkId][$networkTypeId] = (countSumTotalData(
1109                         bigintval($networkTypeId),
1110                         'network_types_config',
1111                         'network_data_id',
1112                         'network_type_id',
1113                         true,
1114                         sprintf(' AND `network_id`=%s', bigintval($networkId))
1115                 ) == 1);
1116         } // END - if
1117
1118         // Return cache
1119         return $GLOBALS[__FUNCTION__][$networkId][$networkTypeId];
1120 }
1121
1122 // Handles the network-payment-check request
1123 function handleNetworkPaymentCheckRequest () {
1124         // @TODO Implement this function, don't forget to set HTTP status back to '200 OK' if everything went fine
1125         reportBug(__FUNCTION__, __LINE__, 'Not yet implemented.');
1126 }
1127
1128 //------------------------------------------------------------------------------
1129 //                             Call-back functions
1130 //------------------------------------------------------------------------------
1131
1132 // Callback function to add new network
1133 function doAdminNetworkProcessAddNetwork () {
1134         // We can say here, the form is sent, so check if the network is already added
1135         if (isNetworkNameValid(postRequestElement('network_short_name'))) {
1136                 // Already there
1137                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ALREADY_ADDED=' . postRequestElement('network_short_name') . '%}');
1138                 return FALSE;
1139         } // END - if
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                         // Init array with generic element
1183                         $content = array(
1184                                 'rows' => $OUT
1185                         );
1186
1187                         // Output main template
1188                         loadTemplate('admin_' . $GLOBALS['network_form_name'] . '_networks', FALSE, $content);
1189
1190                         // Don't display the list/add new form
1191                         $GLOBALS['network_display'] = FALSE;
1192                 } else {
1193                         // Nothing selected/found
1194                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_FOUND--}');
1195                 }
1196         } // END - if
1197 }
1198
1199 // Handle network type form
1200 function doAdminNetworkProcessHandleNetworkTypes () {
1201         // Is there selections?
1202         if (ifPostContainsSelections()) {
1203                 // Load network data
1204                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1205
1206                 // Something has been selected, so start displaying one by one
1207                 $OUT = '';
1208                 foreach (postRequestElement('sel') as $networkId => $sel) {
1209                         // Is this selected?
1210                         if ($sel == 1) {
1211                                 // Load this network's data
1212                                 $networkTypeData = getNetworkTypeDataById($networkId);
1213
1214                                 // Is there found the network?
1215                                 if (count($networkTypeData) > 0) {
1216                                         if (isFormSent('edit')) {
1217                                                 // Add row template for deleting
1218                                                 $OUT .= loadTemplate('admin_edit_network_types_row', TRUE, $networkTypeData);
1219                                         } elseif (isFormSent('delete')) {
1220                                                 // Add row template for deleting
1221                                                 $OUT .= loadTemplate('admin_delete_network_types_row', TRUE, $networkTypeData);
1222                                         } else {
1223                                                 // Problem!
1224                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1225                                         }
1226                                 } // END - if
1227                         } // END - if
1228                 } // END - foreach
1229
1230                 // If we have no rows, we don't need to display the edit form
1231                 if (!empty($OUT)) {
1232                         // Prepare array with generic elements
1233                         $content = array(
1234                                 'rows'       => $OUT,
1235                                 'network_id' => bigintval(getRequestElement('network_id'))
1236                         );
1237
1238                         // Output main template
1239                         if (isFormSent('edit')) {
1240                                 loadTemplate('admin_edit_network_types', FALSE, $content);
1241                         } elseif (isFormSent('delete')) {
1242                                 loadTemplate('admin_delete_network_types', FALSE, $content);
1243                         } else {
1244                                 // Problem!
1245                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1246                         }
1247
1248                         // Don't display the list/add new form
1249                         $GLOBALS['network_display'] = FALSE;
1250                 } else {
1251                         // Nothing selected/found
1252                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_FOUND--}');
1253                 }
1254         } // END - if
1255 }
1256
1257 // Handle network request parameter form
1258 function doAdminNetworkProcessHandleRequestParams () {
1259         // Is there selections?
1260         if (ifPostContainsSelections()) {
1261                 // Init cache array
1262                 $GLOBALS['network_request_params_disabled'] = array();
1263
1264                 // Load network data
1265                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1266
1267                 // Something has been selected, so start displaying one by one
1268                 $OUT = '';
1269                 foreach (postRequestElement('sel') as $networkId => $sel) {
1270                         // Is this selected?
1271                         if ($sel == 1) {
1272                                 // Load this network's data
1273                                 $networkRequestData = getNetworkRequestParamsDataById($networkId);
1274
1275                                 // Is there found the network?
1276                                 if (count($networkRequestData) > 0) {
1277                                         if (isFormSent('edit')) {
1278                                                 // Add row template for deleting
1279                                                 $OUT .= loadTemplate('admin_edit_network_request_params_row', TRUE, $networkRequestData);
1280                                         } elseif (isFormSent('delete')) {
1281                                                 // Get type data
1282                                                 $networkRequestData['network_type_data'] = getNetworkTypeDataById($networkRequestData['network_type_id']);
1283
1284                                                 // Add row template for deleting
1285                                                 $OUT .= loadTemplate('admin_delete_network_request_params_row', TRUE, $networkRequestData);
1286                                         } else {
1287                                                 // Problem!
1288                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1289                                         }
1290                                 } // END - if
1291                         } // END - if
1292                 } // END - foreach
1293
1294                 // If we have no rows, we don't need to display the edit form
1295                 if (!empty($OUT)) {
1296                         // Prepare array with generic elements
1297                         $content = array(
1298                                 'rows'       => $OUT,
1299                                 'network_id' => bigintval(getRequestElement('network_id'))
1300                         );
1301
1302                         // Output main template
1303                         if (isFormSent('edit')) {
1304                                 loadTemplate('admin_edit_network_request_params', FALSE, $content);
1305                         } elseif (isFormSent('delete')) {
1306                                 loadTemplate('admin_delete_network_request_params', FALSE, $content);
1307                         } else {
1308                                 // Problem!
1309                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1310                         }
1311
1312                         // Don't display the list/add new form
1313                         $GLOBALS['network_display'] = FALSE;
1314                 } else {
1315                         // Nothing selected/found
1316                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
1317                 }
1318         } // END - if
1319 }
1320
1321 // Changes given networks
1322 function doAdminNetworkProcessChangeNetworks () {
1323         // Is there selections?
1324         if (ifPostContainsSelections()) {
1325                 // By default nothing is updated
1326                 $updated = 0;
1327
1328                 // Something has been selected, so start updating them
1329                 foreach (postRequestElement('sel') as $networkId => $sel) {
1330                         // Update this entry?
1331                         if ($sel == 1) {
1332                                 // Init data array
1333                                 $networkData = array();
1334
1335                                 // Transfer whole array, except 'sel'
1336                                 foreach (postRequestArray() as $key => $entry) {
1337                                         // Skip 'sel' and submit button
1338                                         if (in_array($key, array('sel', 'do_edit'))) {
1339                                                 continue;
1340                                         } // END - if
1341
1342                                         // Is there this enty?
1343                                         if (!isset($entry[$networkId])) {
1344                                                 // Not found, needs fixing
1345                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1346                                         } // END - if
1347
1348                                         // Add this entry
1349                                         $networkData[$key] = $entry[$networkId];
1350                                 } // END - foreach
1351
1352                                 // Update the network data
1353                                 $updated += doNetworkUpdateDataByArray($networkId, $networkData);
1354                         } // END - if
1355                 } // END - foreach
1356
1357                 // Is there updates?
1358                 if ($updated > 0) {
1359                         // Updates done
1360                         displayMessage('{%message,ADMIN_NETWORK_UPDATED=' . $updated . '%}');
1361                 } else {
1362                         // Nothing changed
1363                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_CHANGED--}');
1364                 }
1365         } // END - if
1366 }
1367
1368 // Removes given networks
1369 function doAdminNetworkProcessRemoveNetworks () {
1370         // Is there selections?
1371         if (ifPostContainsSelections()) {
1372                 // By default nothing is removed
1373                 $removed = 0;
1374
1375                 // Something has been selected, so start updating them
1376                 foreach (postRequestElement('sel') as $networkId => $sel) {
1377                         // Update this entry?
1378                         if ($sel == 1) {
1379                                 // Remove this entry
1380                                 $removed += doAdminRemoveNetworkEntry('data', 'network_id', $networkId);
1381                         } // END - if
1382                 } // END - foreach
1383
1384                 // Is there removes?
1385                 if ($removed > 0) {
1386                         // Removals done
1387                         displayMessage('{%message,ADMIN_NETWORK_REMOVED=' . $removed . '%}');
1388                 } else {
1389                         // Nothing removed
1390                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_NOTHING_REMOVED--}');
1391                 }
1392         } // END - if
1393 }
1394
1395 // Add a network type handler if not yet found
1396 function doAdminNetworkProcessAddNetworkType () {
1397         // Is the network type handle already used with given network?
1398         if (isNetworkTypeHandleValid(postRequestElement('network_type_handler'), getRequestElement('network_id'))) {
1399                 // Already added
1400                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_ALREADY_ADDED=' . postRequestElement('network_type_handler') . '%}');
1401
1402                 // ... so abort here
1403                 return FALSE;
1404         } // END - if
1405
1406         // Remove the 'ok' part
1407         unsetPostRequestElement('ok');
1408
1409         // Add id
1410         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1411
1412         // Is network_type_banner_url set?
1413         if (postRequestElement('network_type_banner_url') == '') {
1414                 // Remove empty value to get a NULL for an optional entry
1415                 unsetPostRequestElement('network_type_banner_url');
1416         } // END - if
1417
1418         // Add the whole request to database
1419         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_types'), __FUNCTION__, __LINE__);
1420
1421         // Output message
1422         if (!SQL_HASZEROAFFECTED()) {
1423                 // Successfully added
1424                 loadTemplate('admin_network_type_added', FALSE, postRequestArray());
1425         } else {
1426                 // Not added
1427                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_TYPE_HANDLER_NOT_ADDED=' . postRequestElement('network_type_handler') . '%}');
1428         }
1429 }
1430
1431 // Changes given network type handlers
1432 function doAdminNetworkProcessChangeHandlerTypes () {
1433         // Is there selections?
1434         if (ifPostContainsSelections()) {
1435                 // By default nothing is updated
1436                 $updated = 0;
1437
1438                 // Something has been selected, so start updating them
1439                 foreach (postRequestElement('sel') as $networkId => $sel) {
1440                         // Update this entry?
1441                         if ($sel == 1) {
1442                                 // Init data array
1443                                 $networkTypeData = array();
1444
1445                                 // Transfer whole array, except 'sel'
1446                                 foreach (postRequestArray() as $key => $entry) {
1447                                         // Skip 'sel' and submit button
1448                                         if (in_array($key, array('sel', 'do_edit'))) {
1449                                                 continue;
1450                                         } // END - if
1451
1452                                         // Is there this enty?
1453                                         if (!isset($entry[$networkId])) {
1454                                                 // Not found, needs fixing
1455                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1456                                         } // END - if
1457
1458                                         // Fix empty network_type_banner_url to NULL
1459                                         if (($key == 'network_type_banner_url') && (trim($entry[$networkId]) == '')) {
1460                                                 // Set it to NULL
1461                                                 $entry[$networkId] = NULL;
1462                                         } // END - if
1463
1464                                         // Add this entry
1465                                         $networkTypeData[$key] = $entry[$networkId];
1466                                 } // END - foreach
1467
1468                                 // Update the network data
1469                                 $updated += doNetworkUpdateTypeByArray($networkId, $networkTypeData);
1470                         } // END - if
1471                 } // END - foreach
1472
1473                 // Is there updates?
1474                 if ($updated > 0) {
1475                         // Updates done
1476                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_UPDATED=' . $updated . '%}');
1477                 } else {
1478                         // Nothing changed
1479                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_CHANGED--}');
1480                 }
1481         } // END - if
1482 }
1483
1484 // Changes given network request parameters
1485 function doAdminNetworkProcessChangeRequestParams () {
1486         // Is there selections?
1487         if (ifPostContainsSelections()) {
1488                 // By default nothing is updated
1489                 $updated = 0;
1490
1491                 // Something has been selected, so start updating them
1492                 foreach (postRequestElement('sel') as $networkId => $sel) {
1493                         // Update this entry?
1494                         if ($sel == 1) {
1495                                 // Init data array
1496                                 $networkParamsData = array();
1497
1498                                 // Transfer whole array, except 'sel'
1499                                 foreach (postRequestArray() as $key => $entry) {
1500                                         // Skip 'sel' and submit button
1501                                         if (in_array($key, array('sel', 'do_edit'))) {
1502                                                 continue;
1503                                         } // END - if
1504
1505                                         // Is there this enty?
1506                                         if (!isset($entry[$networkId])) {
1507                                                 // Not found, needs fixing
1508                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1509                                         } // END - if
1510
1511                                         // Fix empty network_request_param_default to NULL
1512                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
1513                                                 // Set it to NULL
1514                                                 $entry[$networkId] = NULL;
1515                                         } // END - if
1516
1517                                         // Add this entry
1518                                         $networkParamsData[$key] = $entry[$networkId];
1519                                 } // END - foreach
1520
1521                                 // Update the network data
1522                                 $updated += doNetworkUpdateParamsByArray($networkId, $networkParamsData);
1523                         } // END - if
1524                 } // END - foreach
1525
1526                 // Is there updates?
1527                 if ($updated > 0) {
1528                         // Updates done
1529                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_UPDATED=' . $updated . '%}');
1530                 } else {
1531                         // Nothing changed
1532                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_CHANGED--}');
1533                 }
1534         } // END - if
1535 }
1536
1537 // Changes given network array translations
1538 function doAdminNetworkProcessChangeArrayTranslations () {
1539         // Is there selections?
1540         if (ifPostContainsSelections()) {
1541                 // By default nothing is updated
1542                 $updated = 0;
1543
1544                 // Something has been selected, so start updating them
1545                 foreach (postRequestElement('sel') as $networkId => $sel) {
1546                         // Update this entry?
1547                         if ($sel == 1) {
1548                                 // Init data array
1549                                 $networkTranslationsData = array();
1550
1551                                 // Transfer whole array, except 'sel'
1552                                 foreach (postRequestArray() as $key => $entry) {
1553                                         // Skip 'sel' and submit button
1554                                         if (in_array($key, array('sel', 'do_edit'))) {
1555                                                 continue;
1556                                         } // END - if
1557
1558                                         // Is there this enty?
1559                                         if (!isset($entry[$networkId])) {
1560                                                 // Not found, needs fixing
1561                                                 reportBug(__FUNCTION__, __LINE__, 'No entry in key=' . $key . ', id=' . $networkId . ' found.');
1562                                         } // END - if
1563
1564                                         // Fix empty network_request_param_default to NULL
1565                                         if (($key == 'network_request_param_default') && (trim($entry[$networkId]) == '')) {
1566                                                 // Set it to NULL
1567                                                 $entry[$networkId] = NULL;
1568                                         } // END - if
1569
1570                                         // Add this entry
1571                                         $networkTranslationsData[$key] = $entry[$networkId];
1572                                 } // END - foreach
1573
1574                                 // Update the network data
1575                                 $updated += doNetworkUpdateArrayTranslationsByArray($networkId, $networkTranslationsData);
1576                         } // END - if
1577                 } // END - foreach
1578
1579                 // Is there updates?
1580                 if ($updated > 0) {
1581                         // Updates done
1582                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_UPDATED=' . $updated . '%}');
1583                 } else {
1584                         // Nothing changed
1585                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_CHANGED--}');
1586                 }
1587         } // END - if
1588 }
1589
1590 // Removes given network type handlers
1591 function doAdminNetworkProcessRemoveNetworkTypes () {
1592         // Is there selections?
1593         if (ifPostContainsSelections()) {
1594                 // By default nothing is removed
1595                 $removed = 0;
1596
1597                 // Something has been selected, so start updating them
1598                 foreach (postRequestElement('sel') as $networkId => $sel) {
1599                         // Update this entry?
1600                         if ($sel == 1) {
1601                                 // Remove this entry
1602                                 $removed += doAdminRemoveNetworkEntry('types', 'network_type_id', $networkId);
1603                         } // END - if
1604                 } // END - foreach
1605
1606                 // Is there removes?
1607                 if ($removed > 0) {
1608                         // Removals done
1609                         displayMessage('{%message,ADMIN_NETWORK_TYPE_HANDLER_REMOVED=' . $removed . '%}');
1610                 } else {
1611                         // Nothing removed
1612                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_TYPE_HANDLER_NOTHING_REMOVED--}');
1613                 }
1614         } // END - if
1615 }
1616
1617 // Removes given network request parameters
1618 function doAdminNetworkProcessRemoveNetworkRequestParams () {
1619         // Is there selections?
1620         if (ifPostContainsSelections()) {
1621                 // By default nothing is removed
1622                 $removed = 0;
1623
1624                 // Something has been selected, so start updating them
1625                 foreach (postRequestElement('sel') as $networkId => $sel) {
1626                         // Update this entry?
1627                         if ($sel == 1) {
1628                                 // Remove this entry
1629                                 $removed += doAdminRemoveNetworkEntry('request_params', 'network_request_param_id', $networkId);
1630                         } // END - if
1631                 } // END - foreach
1632
1633                 // Is there removes?
1634                 if ($removed > 0) {
1635                         // Removals done
1636                         displayMessage('{%message,ADMIN_NETWORK_REQUEST_PARAMETER_REMOVED=' . $removed . '%}');
1637                 } else {
1638                         // Nothing removed
1639                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_REMOVED--}');
1640                 }
1641         } // END - if
1642 }
1643
1644 // Removes given network array translations
1645 function doAdminNetworkProcessRemoveNetworkArrayTranslation () {
1646         // Is there selections?
1647         if (ifPostContainsSelections()) {
1648                 // By default nothing is removed
1649                 $removed = 0;
1650
1651                 // Something has been selected, so start updating them
1652                 foreach (postRequestElement('sel') as $networkId => $sel) {
1653                         // Update this entry?
1654                         if ($sel == 1) {
1655                                 // Remove this entry
1656                                 $removed += doAdminRemoveNetworkEntry('array_translation', 'network_array_id', $networkId);
1657                         } // END - if
1658                 } // END - foreach
1659
1660                 // Is there removes?
1661                 if ($removed > 0) {
1662                         // Removals done
1663                         displayMessage('{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_REMOVED=' . $removed . '%}');
1664                 } else {
1665                         // Nothing removed
1666                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_ARRAY_TRANSLATION_NOTHING_REMOVED--}');
1667                 }
1668         } // END - if
1669 }
1670
1671 // Adds a request parameter to given network and type
1672 function doAdminNetworkProcessAddRequestParam () {
1673         // Is the request parameter already used with given network?
1674         if (isNetworkRequestElementValid(postRequestElement('network_request_param_key'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
1675                 // Already added
1676                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_request_param_key') . '%}');
1677
1678                 // ... so abort here
1679                 return FALSE;
1680         } // END - if
1681
1682         // Remove the 'ok' part
1683         unsetPostRequestElement('ok');
1684
1685         // Add id
1686         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1687
1688         // Is network_request_param_default set?
1689         if (postRequestElement('network_request_param_default') == '') {
1690                 // Remove empty value to get a NULL for an optional entry
1691                 unsetPostRequestElement('network_request_param_default');
1692         } // END - if
1693
1694         // Add the whole request to database
1695         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_request_params'), __FUNCTION__, __LINE__);
1696
1697         // Output message
1698         if (!SQL_HASZEROAFFECTED()) {
1699                 // Successfully added
1700                 loadTemplate('admin_network_request_param_added', FALSE, postRequestArray());
1701         } else {
1702                 // Not added
1703                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_REQUEST_PARAMETER_NOT_ADDED=' . postRequestElement('network_request_param_key') . '%}');
1704         }
1705 }
1706
1707 // Adds a vheck request parameter to given network
1708 function doAdminNetworkProcessAddVcheckParam () {
1709         // Is the request parameter already used with given network?
1710         if (isNetworkVcheckElementValid(postRequestElement('network_vcheck_param_key'), getRequestElement('network_id'))) {
1711                 // Already added
1712                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_ALREADY_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
1713
1714                 // ... so abort here
1715                 return FALSE;
1716         } // END - if
1717
1718         // Remove the 'ok' part
1719         unsetPostRequestElement('ok');
1720
1721         // Add id
1722         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1723
1724         // Is network_vcheck_param_default set?
1725         if (postRequestElement('network_vcheck_param_default') == '') {
1726                 // Remove empty value to get a NULL for an optional entry
1727                 unsetPostRequestElement('network_vcheck_param_default');
1728         } // END - if
1729
1730         // Add the whole vcheck to database
1731         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_vcheck_params'), __FUNCTION__, __LINE__);
1732
1733         // Output message
1734         if (!SQL_HASZEROAFFECTED()) {
1735                 // Successfully added
1736                 loadTemplate('admin_network_vcheck_param_added', FALSE, postRequestArray());
1737         } else {
1738                 // Not added
1739                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_VCHECK_PARAMETER_NOT_ADDED=' . postRequestElement('network_vcheck_param_key') . '%}');
1740         }
1741 }
1742
1743 // Adds a API response array entry
1744 function doAdminNetworkProcessAddNetworkArrayTranslation () {
1745         // Is the request parameter already used with given network?
1746         if (isNetworkArrayTranslationValid(postRequestElement('network_array_index'), postRequestElement('network_type_id'), getRequestElement('network_id'))) {
1747                 // Already added
1748                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_ALREADY_ADDED=' . postRequestElement('network_array_index') . '%}');
1749
1750                 // ... so abort here
1751                 return FALSE;
1752         } // END - if
1753
1754         // Remove the 'ok' part
1755         unsetPostRequestElement('ok');
1756
1757         // Add id
1758         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1759
1760         // Add sorting
1761         setPostRequestElement('network_array_sort', (countSumTotalData(
1762                 bigintval(postRequestElement('network_id')),
1763                 'network_array_translation',
1764                 'network_array_id',
1765                 'network_id',
1766                 true,
1767                 sprintf(" AND `network_type_id`=%s", bigintval(postRequestElement('network_type_id')))
1768         ) + 1));
1769
1770         // Add the whole request to database
1771         SQL_QUERY(getInsertSqlFromArray(postRequestArray(), 'network_array_translation'), __FUNCTION__, __LINE__);
1772
1773         // Output message
1774         if (!SQL_HASZEROAFFECTED()) {
1775                 // Successfully added
1776                 loadTemplate('admin_network_array_translation_added', FALSE, postRequestArray());
1777         } else {
1778                 // Not added
1779                 loadTemplate('admin_settings_unsaved', FALSE, '{%message,ADMIN_NETWORK_ARRAY_TRANSLATION_NOT_ADDED=' . postRequestElement('network_array_index') . '%}');
1780         }
1781 }
1782
1783 // Handle network array translation form
1784 function doAdminNetworkProcessHandleArrayTranslations () {
1785         // Is there selections?
1786         if (ifPostContainsSelections()) {
1787                 // Init cache array
1788                 $GLOBALS['network_array_translation_disabled'] = array();
1789
1790                 // Load network data
1791                 $networkData = getNetworkDataById(getRequestElement('network_id'));
1792
1793                 // Something has been selected, so start displaying one by one
1794                 $OUT = '';
1795                 foreach (postRequestElement('sel') as $networkId => $sel) {
1796                         // Is this selected?
1797                         if ($sel == 1) {
1798                                 // Load this network's data
1799                                 $networkTranslationsData = getNetworkArrayTranslationsDataById($networkId);
1800
1801                                 // Is there found the network?
1802                                 if (count($networkTranslationsData) > 0) {
1803                                         if (isFormSent('edit')) {
1804                                                 // Add row template for deleting
1805                                                 $OUT .= loadTemplate('admin_edit_network_array_translation_row', TRUE, $networkTranslationsData);
1806                                         } elseif (isFormSent('delete')) {
1807                                                 // Get type data
1808                                                 $networkTranslationsData['network_type_data'] = getNetworkTypeDataById($networkTranslationsData['network_type_id']);
1809
1810                                                 // Add row template for deleting
1811                                                 $OUT .= loadTemplate('admin_delete_network_array_translation_row', TRUE, $networkTranslationsData);
1812                                         } else {
1813                                                 // Problem!
1814                                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1815                                         }
1816                                 } // END - if
1817                         } // END - if
1818                 } // END - foreach
1819
1820                 // If we have no rows, we don't need to display the edit form
1821                 if (!empty($OUT)) {
1822                         // Prepare array with generic elements
1823                         $content = array(
1824                                 'rows'       => $OUT,
1825                                 'network_id' => bigintval(getRequestElement('network_id'))
1826                         );
1827
1828                         // Output main template
1829                         if (isFormSent('edit')) {
1830                                 loadTemplate('admin_edit_network_array_translation', FALSE, $content);
1831                         } elseif (isFormSent('delete')) {
1832                                 loadTemplate('admin_delete_network_array_translation', FALSE, $content);
1833                         } else {
1834                                 // Problem!
1835                                 reportBug(__FUNCTION__, __LINE__, 'Cannot detect edit/delete.');
1836                         }
1837
1838                         // Don't display the list/add new form
1839                         $GLOBALS['network_display'] = FALSE;
1840                 } else {
1841                         // Nothing selected/found
1842                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_NETWORK_REQUEST_PARAMETER_NOTHING_FOUND--}');
1843                 }
1844         } // END - if
1845 }
1846
1847 // Adds/update network API configuration
1848 function doAdminNetworkProcessNetworkApiConfig () {
1849         // Remove the 'ok' part
1850         unsetPostRequestElement('ok');
1851
1852         // Add id
1853         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1854
1855         // Is network_api_referral_button set?
1856         if (postRequestElement('network_api_referral_button') == '') {
1857                 // Remove empty value to get a NULL for an optional entry
1858                 unsetPostRequestElement('network_api_referral_button');
1859         } // END - if
1860
1861         // Is there already an entry?
1862         if (isNetworkApiConfigured(getRequestElement('network_id'))) {
1863                 // Generate SQL query
1864                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_api_config', 'network_id', postRequestElement('network_id'), array('network_id'));
1865         } else {
1866                 // Insert new entry
1867                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_api_config');
1868         }
1869
1870         // Run the query
1871         SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1872
1873         // Output message
1874         if (!SQL_HASZEROAFFECTED()) {
1875                 // Successfully added
1876                 displayMessage('{--ADMIN_CONFIG_NETWORK_API_SAVED--}');
1877         } else {
1878                 // Not added
1879                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_API_NOT_SAVED--}');
1880         }
1881 }
1882
1883 // Only adds network type configuration if not yet present
1884 function doAdminNetworkProcessAddHandlerTypesConfig ($displayMessage = TRUE) {
1885         // Remove the 'ok' part
1886         unsetPostRequestElement('ok');
1887
1888         // Add both ids
1889         setPostRequestElement('network_id', bigintval(getRequestElement('network_id')));
1890         setPostRequestElement('network_type_id', bigintval(getRequestElement('network_type_id')));
1891
1892         /*
1893          * Some parameters are optional, at least one must be given so check a bunch
1894          * of parameters.
1895          */
1896         foreach (array('network_min_waiting_time', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic') as $element) {
1897                 // Is this element empty?
1898                 if (postRequestElement($element) == '') {
1899                         // Then unset it to get a NULL for optional parameter
1900                         unsetPostRequestElement($element);
1901                 } // END - if
1902         } // END - foreach
1903
1904         // Convert data in POST array
1905         convertSelectionsToEpocheTimeInPostData($content, 'network_max_reload_time_ye', $skip);
1906
1907         // Is there already an entry?
1908         if (isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
1909                 // This network type handler is already configured
1910                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_ALREADY_CONFIGURED--}');
1911                 return;
1912         } // END - if
1913
1914         // Copy 'set all' and remove it from POST data
1915         $setAll = (postRequestElement('set_all') === 'Y');
1916         unsetPostRequestElement('set_all');
1917
1918         // Shall we set for all?
1919         if ($setAll === TRUE) {
1920                 // Get all handlers
1921                 $result = SQL_QUERY_ESC('SELECT `network_type_id` FROM `{?_MYSQL_PREFIX?}_network_types` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
1922                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
1923
1924                 // Are there entries?
1925                 if (SQL_HASZERONUMS($result)) {
1926                         // No, then abort here
1927                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
1928                         return;
1929                 } // END - if
1930
1931                 // Init number of rows
1932                 $numRows = 0;
1933
1934                 // Fetch all ids
1935                 while (list($typeId) = SQL_FETCHROW($result)) {
1936                         // Set it in GET data
1937                         setGetRequestElement('network_type_id', $typeId);
1938
1939                         // Call this function again
1940                         $numRows += doAdminNetworkProcessAddHandlerTypesConfig(FALSE);
1941                 } // END - while
1942
1943                 // Free result
1944                 SQL_FREERESULT($result);
1945
1946                 // Output message
1947                 if ($numRows > 0) {
1948                         // Something has been updated
1949                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
1950                 } else {
1951                         // Nothing has been saved
1952                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
1953                 }
1954         } else {
1955                 // Get SQL query for new entry
1956                 $SQL = getInsertSqlFromArray(postRequestArray(), 'network_types_config');
1957
1958                 // Run the query
1959                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1960
1961                 // Shall we display the message?
1962                 if ($displayMessage === TRUE) {
1963                         // Output message
1964                         if (!SQL_HASZEROAFFECTED()) {
1965                                 // Successfully added
1966                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
1967                         } else {
1968                                 // Not added
1969                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_SAVED--}');
1970                         }
1971                 } else {
1972                         // Return amount of affected rows (1 or 2)
1973                         return SQL_AFFECTEDROWS();
1974                 }
1975         }
1976 }
1977
1978 // Only changes network type configuration if not yet present
1979 function doAdminNetworkProcessEditHandlerTypesConfig ($displayMessage = TRUE) {
1980         // Remove the 'ok' part
1981         unsetPostRequestElement('ok');
1982
1983         /*
1984          * Some parameters are optional, at least one must be given so check a bunch
1985          * of parameters.
1986          */
1987         foreach (array('network_min_waiting_time', 'network_min_remain_clicks', 'network_min_payment', 'network_allow_erotic') as $element) {
1988                 // Is this element empty?
1989                 if (postRequestElement($element) == '') {
1990                         // Then unset it to get a NULL for optional parameter
1991                         unsetPostRequestElement($element);
1992                 } // END - if
1993         } // END - foreach
1994
1995         // Convert time selections in POST data
1996         convertSelectionsToEpocheTimeInPostData('network_max_reload_time_ye');
1997
1998         // Is there already an entry?
1999         if (!isNetworkTypeHandlerConfigured(getRequestElement('network_id'), getRequestElement('network_type_id'))) {
2000                 // This network type handler is not configured
2001                 displayMessage('{--ADMIN_NETWORK_HANDLER_TYPE_HANDLER_NOT_CONFIGURED--}');
2002                 return;
2003         } // END - if
2004
2005         // Copy 'set all' and remove it from POST data
2006         $setAll = (postRequestElement('set_all') === 'Y');
2007         unsetPostRequestElement('set_all');
2008
2009         // Shall we set for all?
2010         if ($setAll === TRUE) {
2011                 // Get all data entries
2012                 $result = SQL_QUERY_ESC('SELECT `network_data_id` FROM `{?_MYSQL_PREFIX?}_network_types_config` WHERE `network_id`=%s ORDER BY `network_type_id` ASC',
2013                         array(bigintval(getRequestElement('network_id'))), __FUNCTION__, __LINE__);
2014
2015                 // Are there entries?
2016                 if (SQL_HASZERONUMS($result)) {
2017                         // No, then abort here
2018                         displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_SET_ALL_404--}');
2019                         return;
2020                 } // END - if
2021
2022                 // Init number of rows
2023                 $numRows = 0;
2024
2025                 // Fetch all ids
2026                 while (list($dataId) = SQL_FETCHROW($result)) {
2027                         // Set it in GET data
2028                         setPostRequestElement('network_data_id', $dataId);
2029
2030                         // Call this function again
2031                         $numRows += doAdminNetworkProcessEditHandlerTypesConfig(FALSE);
2032                 } // END - while
2033
2034                 // Free result
2035                 SQL_FREERESULT($result);
2036
2037                 // Output message
2038                 if ($numRows > 0) {
2039                         // Something has been updated
2040                         displayMessage('{%message,ADMIN_CONFIG_NETWORK_HANDLER_TYPE_ALL_HANDLER_SAVED=' . bigintval($numRows) . '%}');
2041                 } else {
2042                         // Nothing has been saved
2043                         loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2044                 }
2045         } else {
2046                 // Get SQL query for new entry
2047                 $SQL = getUpdateSqlFromArray(postRequestArray(), 'network_types_config', 'network_data_id', postRequestElement('network_data_id'), array('network_data_id'));
2048
2049                 // Run the query
2050                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
2051
2052                 // Shall we display the message?
2053                 if ($displayMessage === TRUE) {
2054                         // Output message
2055                         if (!SQL_HASZEROAFFECTED()) {
2056                                 // Successfully added
2057                                 displayMessage('{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_SAVED--}');
2058                         } else {
2059                                 // Not added
2060                                 loadTemplate('admin_settings_unsaved', FALSE, '{--ADMIN_CONFIG_NETWORK_HANDLER_TYPE_HANDLER_NOT_CHANGED--}');
2061                         }
2062                 } else {
2063                         // Return amount of affected rows (1 or 2)
2064                         return SQL_AFFECTEDROWS();
2065                 }
2066         }
2067 }
2068
2069 // Do expression code for this extension
2070 function doExpressionNetwork ($data) {
2071         // Construct replacer
2072         $replacer = sprintf(
2073                 "{DQUOTE} . %s(%s, '%s') . {DQUOTE}",
2074                 $data['callback'],
2075                 $data['matches'][4][$data['key']],
2076                 $data['extra_func']
2077         );
2078
2079         // Replace %network_id% with the current network id
2080         $replacer = str_replace('%network_id%', getCurrentNetworkId(), $replacer);
2081
2082         // Replace the code
2083         $code = replaceExpressionCode($data, $replacer);
2084
2085         // Return it
2086         return $code;
2087 }
2088
2089 // ----------------------------------------------------------------------------
2090 //                     Call-back functions for exporting data
2091 // ----------------------------------------------------------------------------
2092
2093 // Callback function to export network tables
2094 function doAdminNetworkProcessExport () {
2095         // Init table with all valid what->table entries
2096         $validExports = array(
2097                 // General network data
2098                 'list_network_data'              => 'data',
2099                 // Network type handler
2100                 'list_network_types'             => 'types',
2101                 // Network request parameter
2102                 'list_network_request_params'    => 'request_params',
2103                 // Vcheck request parameter
2104                 'list_network_vcheck_params'     => 'vcheck_params',
2105                 // Network API response array index translation
2106                 'list_network_array_translation' => 'array_translation',
2107         );
2108
2109         // Is the 'what' key valid?
2110         if (!isset($validExports[getWhat()])) {
2111                 // Not valid
2112                 reportBug(__FUNCTION__, __LINE__, 'what=' . getWhat() . ' - not supported');
2113         } // END - if
2114
2115         // Generate call-back, some tables require to export not all columns
2116         $callbackName = 'doAdminNetworkExport' . capitalizeUnderscoreString($validExports[getWhat()]);
2117
2118         // Is the call-back function there?
2119         if (!function_exists($callbackName)) {
2120                 // No, this is really bad
2121                 reportBug(__FUNCTION__, __LINE__, 'Invalid call-back function ' . $callbackName . ' detected.');
2122         } elseif (isset($GLOBALS[__FUNCTION__][$callbackName])) {
2123                 // Already called!
2124                 reportBug(__FUNCTION__, __LINE__, 'Double-call of export function ' . $callbackName . ' detected.');
2125         }
2126
2127         // Call the function
2128         call_user_func($callbackName);
2129
2130         // Mark it as called
2131         $GLOBALS[__FUNCTION__][$callbackName] = TRUE;
2132
2133         // Don't display the list/add new form
2134         $GLOBALS['network_display'] = FALSE;
2135 }
2136
2137 // Exports (and displays) the table 'network_data'
2138 function doAdminNetworkExportData () {
2139         // Query for all networks
2140         $result = SQL_QUERY('SELECT
2141         `network_short_name`,
2142         `network_title`,
2143         `network_reflink`,
2144         `network_data_separator`,
2145         `network_row_separator`,
2146         `network_request_type`,
2147         `network_charset`,
2148         `network_require_id_card`,
2149         `network_query_amount`,
2150         `network_active`
2151 FROM
2152         `{?_MYSQL_PREFIX?}_network_data`
2153 ORDER BY
2154         `network_id` ASC',
2155                 __FUNCTION__, __LINE__);
2156
2157         // Start an empty SQL query
2158         $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";
2159
2160         // Load all entries
2161         while ($content = SQL_FETCHARRAY($result)) {
2162                 // Add row
2163                 $SQL .= "('" .
2164                         $content['network_short_name'] . "', '" .
2165                         $content['network_title'] . "', '" .
2166                         $content['network_reflink'] . "', '" .
2167                         $content['network_data_separator'] . "', '" .
2168                         $content['network_row_separator'] . "', '" .
2169                         $content['network_request_type'] . "', '" .
2170                         $content['network_charset'] . "', '" .
2171                         $content['network_require_id_card'] . "', " .
2172                         $content['network_query_amount'] . ", '" .
2173                         $content['network_active'] . "'),\n";
2174         } // END - while
2175
2176         // Remove last commata and close braces
2177         $SQL = substr($SQL, 0, -2);
2178
2179         // Free result
2180         SQL_FREERESULT($result);
2181
2182         // Output the SQL query
2183         loadTemplate('admin_export_network_data', FALSE, $SQL);
2184 }
2185
2186 // Exports (and displays) the table 'network_types'
2187 function doAdminNetworkExportTypes () {
2188         // 'network_id' must be set
2189         if (!isGetRequestElementSet('network_id')) {
2190                 // Only network handlers of one network will be exported per time
2191                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2192         } // END - if
2193
2194         // Get all network types of given network
2195         $result = SQL_QUERY_ESC('SELECT
2196         `network_type_id`,
2197         `network_id`,
2198         `network_type_handler`,
2199         `network_type_api_url`,
2200         `network_type_click_url`,
2201         `network_type_banner_url`,
2202         `network_type_reload_time_unit`,
2203         `network_text_encoding`
2204 FROM
2205         `{?_MYSQL_PREFIX?}_network_types`
2206 WHERE
2207         `network_id`=%s
2208 ORDER BY
2209         `network_type_id` ASC',
2210                 array(
2211                         bigintval(getRequestElement('network_id'))
2212                 ), __FUNCTION__, __LINE__);
2213
2214         // Start an empty SQL query
2215         $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";
2216
2217         // Load all entries
2218         while ($content = SQL_FETCHARRAY($result)) {
2219                 // Add row
2220                 $SQL .= '(' .
2221                         $content['network_type_id'] . ', ' .
2222                         $content['network_id'] . ", '" .
2223                         $content['network_type_handler'] . "', '" .
2224                         $content['network_type_api_url'] . "', '" .
2225                         $content['network_type_click_url'] . "', ";
2226                 
2227                 // Is the column NULL?
2228                 if (is_null($content['network_type_banner_url'])) {
2229                         // Column is NULL
2230                         $SQL .= 'NULL';
2231                 } else {
2232                         // Column is set
2233                         $SQL .= chr(39) . $content['network_type_banner_url'] . chr(39);
2234                 }
2235
2236                 // Add more
2237                 $SQL .= ",'" . $content['network_type_reload_time_unit'] . "','" . $content['network_text_encoding'] . "'),\n";
2238         } // END - while
2239
2240         // Remove last commata and close braces
2241         $SQL = substr($SQL, 0, -2);
2242
2243         // Free result
2244         SQL_FREERESULT($result);
2245
2246         // Output the SQL query
2247         loadTemplate('admin_export_network_types', FALSE, $SQL);
2248 }
2249
2250 // Exports (and displays) the table 'network_request_params'
2251 function doAdminNetworkExportRequestParams () {
2252         // 'network_id' must be set
2253         if (!isGetRequestElementSet('network_id')) {
2254                 // Only network request parameters of one network will be exported per time
2255                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2256         } // END - if
2257
2258         // Get all network types of given network
2259         $result = SQL_QUERY_ESC('SELECT
2260         `network_id`,
2261         `network_type_id`,
2262         `network_request_param_key`,
2263         `network_request_param_value`,
2264         `network_request_param_default`
2265 FROM
2266         `{?_MYSQL_PREFIX?}_network_request_params`
2267 WHERE
2268         `network_id`=%s
2269 ORDER BY
2270         `network_type_id` ASC ,
2271         `network_request_param_id` ASC',
2272                 array(
2273                         bigintval(getRequestElement('network_id'))
2274                 ), __FUNCTION__, __LINE__);
2275
2276         // Start an empty SQL query
2277         $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";
2278
2279         // Load all entries
2280         while ($content = SQL_FETCHARRAY($result)) {
2281                 // Add row
2282                 $SQL .= '(' .
2283                         $content['network_id'] . ', ' .
2284                         $content['network_type_id'] . ", '" .
2285                         $content['network_request_param_key'] . "', '" .
2286                         $content['network_request_param_value'] . "', ";
2287                 
2288                 // Is the column NULL?
2289                 if (is_null($content['network_request_param_default'])) {
2290                         // Column is NULL
2291                         $SQL .= "NULL),\n";
2292                 } else {
2293                         // Column is set
2294                         $SQL .= chr(39) . $content['network_request_param_default'] . "'),\n";
2295                 }
2296         } // END - while
2297
2298         // Remove last commata and close braces
2299         $SQL = substr($SQL, 0, -2);
2300
2301         // Free result
2302         SQL_FREERESULT($result);
2303
2304         // Output the SQL query
2305         loadTemplate('admin_export_network_request_params', FALSE, $SQL);
2306 }
2307
2308 // Exports (and displays) the table 'network_vcheck_params'
2309 function doAdminNetworkExportVcheckParams () {
2310         // 'network_id' must be set
2311         if (!isGetRequestElementSet('network_id')) {
2312                 // Only network vcheck parameters of one network will be exported per time
2313                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2314         } // END - if
2315
2316         // Get all network types of given network
2317         $result = SQL_QUERY_ESC('SELECT
2318         `network_id`,
2319         `network_vcheck_param_key`,
2320         `network_vcheck_param_value`,
2321         `network_vcheck_param_default`
2322 FROM
2323         `{?_MYSQL_PREFIX?}_network_vcheck_params`
2324 WHERE
2325         `network_id`=%s
2326 ORDER BY
2327         `network_vcheck_param_id` ASC',
2328                 array(
2329                         bigintval(getRequestElement('network_id'))
2330                 ), __FUNCTION__, __LINE__);
2331
2332         // Start an empty SQL query
2333         $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";
2334
2335         // Load all entries
2336         while ($content = SQL_FETCHARRAY($result)) {
2337                 // Add row
2338                 $SQL .= '(' .
2339                         $content['network_id'] . ", '" .
2340                         $content['network_vcheck_param_key'] . "', '" .
2341                         $content['network_vcheck_param_value'] . "', ";
2342                 
2343                 // Is the column NULL?
2344                 if (is_null($content['network_vcheck_param_default'])) {
2345                         // Column is NULL
2346                         $SQL .= "NULL),\n";
2347                 } else {
2348                         // Column is set
2349                         $SQL .= chr(39) . $content['network_vcheck_param_default'] . "'),\n";
2350                 }
2351         } // END - while
2352
2353         // Remove last commata and close braces
2354         $SQL = substr($SQL, 0, -2);
2355
2356         // Free result
2357         SQL_FREERESULT($result);
2358
2359         // Output the SQL query
2360         loadTemplate('admin_export_network_vcheck_params', FALSE, $SQL);
2361 }
2362
2363 // Exports (and displays) the table 'network_array_translation'
2364 function doAdminNetworkExportArrayTranslation () {
2365         // 'network_id' must be set
2366         if (!isGetRequestElementSet('network_id')) {
2367                 // Only network API array index translations of one network will be exported per time
2368                 reportBug(__FUNCTION__, __LINE__, 'network_id not provided, please fix your links.');
2369         } // END - if
2370
2371         // Get all network types of given network
2372         $result = SQL_QUERY_ESC('SELECT
2373         `network_id`,
2374         `network_type_id`,
2375         `network_array_index`,
2376         `network_array_sort`
2377 FROM
2378         `{?_MYSQL_PREFIX?}_network_array_translation`
2379 WHERE
2380         `network_id`=%s
2381 ORDER BY
2382         `network_type_id` ASC,
2383         `network_array_sort` ASC',
2384                 array(
2385                         bigintval(getRequestElement('network_id'))
2386                 ), __FUNCTION__, __LINE__);
2387
2388         // Start an empty SQL query
2389         $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";
2390
2391         // Load all entries
2392         while ($content = SQL_FETCHARRAY($result)) {
2393                 // Add row
2394                 $SQL .= '(' .
2395                         $content['network_id'] . ', ' .
2396                         $content['network_type_id'] . ', ' .
2397                         $content['network_array_index'] . ', ' .
2398                         $content['network_array_sort'] . "),\n";
2399         } // END - while
2400
2401         // Remove last commata and close braces
2402         $SQL = substr($SQL, 0, -2);
2403
2404         // Free result
2405         SQL_FREERESULT($result);
2406
2407         // Output the SQL query
2408         loadTemplate('admin_export_network_array_translation', FALSE, $SQL);
2409 }
2410
2411 // [EOF]
2412 ?>