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