]> git.mxchange.org Git - mailer.git/blob - inc/mysql-manager.php
Speed up of isAdmin()
[mailer.git] / inc / mysql-manager.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/26/2003 *
4  * ===================                          Last change: 11/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : mysql-manager.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : All database-related functions                   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle datenbank-relevanten Funktionen             *
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 // "Getter" for module description
44 // @TODO Can we cache this?
45 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD = '') {
46         // Debug message
47         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
48
49         // Fix empty 'what'
50         if (empty($what)) {
51                 $what = getIndexHome();
52         } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
53                 // Get it from action
54                 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
55         } elseif ($what == 'welcome') {
56                 // Overview page
57                 return '{--WHAT_IS_WELCOME--}';
58         }
59
60         // Default is not found
61         $data['title'] = '??? (' . $what . ')';
62
63         // Look for title
64         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
65                 array(
66                         $mode,
67                         $column,
68                         $what
69                 ), __FUNCTION__, __LINE__);
70
71         // Is there an entry?
72         if (SQL_NUMROWS($result) == 1) {
73                 // Fetch the title
74                 $data = SQL_FETCHARRAY($result);
75         } // END - if
76
77         // Free result
78         SQL_FREERESULT($result);
79
80         // Return it
81         return $data['title'];
82 }
83
84 // Add link into output stream (or return it) for 'You Are Here' navigation
85 function addYouAreHereLink ($accessLevel, $FQFN, $return = FALSE) {
86         // Use only filename of the FQFN...
87         $file = basename($FQFN);
88
89         // Init variables
90         $linkAdd = '';
91         $OUT = '';
92         $ADD = '';
93         $prefix = '';
94
95         // First we have to do some analysis...
96         if (substr($file, 0, 7) == 'action-') {
97                 // This is an action file!
98                 $type = 'action';
99                 $search = substr($file, 7);
100
101                 // Get access level from it
102                 $modCheck = getModuleFromFileName($file, $accessLevel);
103
104                 // Add what
105                 $ADD = " AND (`what`='' OR `what` IS NULL)";
106         } elseif (substr($file, 0, 5) == 'what-') {
107                 // This is a 'what file'!
108                 $type = 'what';
109                 $search = substr($file, 5);
110
111                 // Get access level from it
112                 $modCheck = getModuleFromFileName($file, $accessLevel);
113
114                 // Is there admin? Then display all
115                 $ADD = " AND `visible`='Y' AND `locked`='N'";
116                 if (isAdmin()) {
117                         // Display all!
118                         $ADD = '';
119                 } // END - if
120
121                 $dummy = substr($search, 0, -4);
122                 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
123         } elseif ($accessLevel == 'sponsor') {
124                 // Sponsor menu
125                 $type     = 'what';
126                 $search   = $file;
127                 $modCheck = getModule();
128         } else {
129                 // Other
130                 $type     = 'menu';
131                 $search   = $file;
132                 $modCheck = getModule();
133         }
134
135         // Begin the navigation line
136         if (!isset($GLOBALS['nav_depth'])) {
137                 // Init nav_depth
138                 $GLOBALS['nav_depth'] = '0';
139
140                 // Run the pre-filter chain
141                 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => '', 'add' => $ADD));
142
143                 // Add pre-content
144                 $prefix = $ret['content'];
145
146                 // Add default content
147                 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--}&nbsp;<strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $linkAdd . '%}">Home</a></strong>';
148         } elseif ($return === FALSE) {
149                 // Count depth
150                 $GLOBALS['nav_depth']++;
151         }
152
153         // Add arrow
154         $prefix .= '&nbsp;-&gt;&nbsp;';
155
156         // We need to remove .php and the end
157         if (substr($search, -4, 4) == '.php') {
158                 // Remove the .php
159                 $search = substr($search, 0, -4);
160         } // END - if
161
162         // Is ext-sql_patches installed?
163         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getConfig('youre_here') . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
164         if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
165                 // Output HTML code
166                 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&amp;' . $type . '=' . $search . $linkAdd . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
167
168                 // Can we close the you-are-here navigation?
169                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',accessLevel=' . $accessLevel . ',isWhatSet()=' . intval(isWhatSet()));
170                 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (($accessLevel == 'admin') && (getWhat() == 'welcome'))))) {
171                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
172                         // Add closing div and br-tag
173                         $GLOBALS['nav_depth'] = '0';
174
175                         // Run the post-filter chain
176                         $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => $OUT, 'add' => $ADD));
177
178                         // Get content from filter back
179                         $OUT = $ret['content'];
180
181                         // Close div-tag, so not the filters have to do it
182                         $OUT .= '</div>';
183                 } // END - if
184         } // END - if
185
186         // Return or output HTML code?
187         if ($return === TRUE) {
188                 // Return HTML code
189                 return $OUT;
190         } else {
191                 // Output HTML code here
192                 outputHtml($OUT);
193         }
194 }
195
196 // Adds a menu (mode = guest/member/admin/sponsor) to output
197 function addMenu ($mode, $action, $what) {
198         // Init some variables
199         $main_cnt = '0';
200
201         // is the menu action valid?
202         if (!isMenuActionValid($mode, $action, $what, TRUE)) {
203                 return getCode('MENU_NOT_VALID');
204         } // END - if
205
206         // Non-admin shall not see all menus
207         $ADD = " AND `visible`='Y' AND `locked`='N'";
208         if (isAdmin()) {
209                 // Is admin, so make all visible
210                 $ADD = '';
211         } // END - if
212
213         // Load SQL data and add the menu to the output stream...
214         $result_main = SQL_QUERY_ESC("SELECT
215         `title`,
216         `what`,
217         `action`,
218         `visible`,
219         `locked`
220 FROM
221         `{?_MYSQL_PREFIX?}_%s_menu`
222 WHERE
223         (`what`='' OR `what` IS NULL)
224         ".$ADD."
225 ORDER BY
226         `sort` ASC",
227                 array($mode), __FUNCTION__, __LINE__);
228
229         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
230         if (!SQL_HASZERONUMS($result_main)) {
231                 // There are menus available, so we simply display them... :)
232                 $GLOBALS['rows'] = '';
233                 while ($content = SQL_FETCHARRAY($result_main)) {
234                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
235                         // Disable the block-mode
236                         enableBlockMode(FALSE);
237
238                         // Load menu header template
239                         $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', TRUE, $content);
240
241                         // Sub menu
242                         $result_sub = SQL_QUERY_ESC("SELECT
243         `title` AS `sub_title`,
244         `what` AS `sub_what`,
245         `visible` AS `sub_visible`,
246         `locked` AS `sub_locked`
247 FROM
248         `{?_MYSQL_PREFIX?}_%s_menu`
249 WHERE
250         `action`='%s' AND
251         `what` != '' AND
252         `what` IS NOT NULL
253         " . $ADD . "
254 ORDER BY
255         `sort` ASC",
256                                 array(
257                                         $mode,
258                                         $content['action']
259                                 ), __FUNCTION__, __LINE__);
260
261                         // Are there some entries?
262                         if (!SQL_HASZERONUMS($result_sub)) {
263                                 // Init counter
264                                 $count = '0';
265
266                                 // Load all sub menus
267                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
268                                         // Merge both arrays in one
269                                         $content = merge_array($content, $content2);
270
271                                         // Init content
272                                         $OUT = '';
273
274                                         // Full file name for checking menu
275                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
276                                         $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
277                                         if (isIncludeReadable($inc)) {
278                                                 // Mark currently selected menu - open
279                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
280                                                         $OUT = '<strong>';
281                                                 } // END - if
282
283                                                 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
284                                                 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
285                                                         // Use index.php as link
286                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
287                                                 } else {
288                                                         // Regular navigation link
289                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&amp;what=' . $content['sub_what'] . '%}" target="_self">';
290                                                 }
291                                         } else {
292                                                 // Not found - open
293                                                 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
294                                         }
295
296                                         // Menu title
297                                         $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
298
299                                         if (isIncludeReadable($inc)) {
300                                                 $OUT .= '</a>';
301
302                                                 // Mark currently selected menu - close
303                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
304                                                         $OUT .= '</strong>';
305                                                 } // END - if
306                                         } else {
307                                                 // Not found - close
308                                                 $OUT .= '</span>';
309                                         }
310
311                                         // Cunt it up
312                                         $count++;
313
314                                         // Rewrite array
315                                         $content = array(
316                                                 'menu'    => $OUT,
317                                                 'what'    => $content['sub_what'],
318                                                 'visible' => $content['sub_visible'],
319                                                 'locked'  => $content['locked'],
320                                         );
321
322                                         // Add regular menu row or bottom row?
323                                         if ($count < SQL_NUMROWS($result_sub)) {
324                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', TRUE, $content);
325                                         } else {
326                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', TRUE, $content);
327                                         }
328                                 } // END - while
329                         } else {
330                                 // This is a menu block... ;-)
331                                 enableBlockMode();
332
333                                 // Load menu block
334                                 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
335                                 if (isFileReadable($INC)) {
336                                         // Load include file
337                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', TRUE, $mode);
338                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
339                                         loadInclude($INC);
340                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
341                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', TRUE, $mode);
342                                 }
343                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
344                         }
345
346                         // Free result
347                         SQL_FREERESULT($result_sub);
348
349                         // Count one up
350                         $main_cnt++;
351
352                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353                         if (SQL_NUMROWS($result_main) > $main_cnt) {
354                                 // Add separator
355                                 $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
356
357                                 // Should we display adverts in this menu?
358                                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
359                                         // Display advert template
360                                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, TRUE);
361
362                                         // Add separator again
363                                         $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
364                                 } // END - if
365                         } // END - if
366                 } // END - while
367
368                 // Free memory
369                 SQL_FREERESULT($result_main);
370
371                 // Should we display adverts in this menu?
372                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
373                         // Add separator again
374                         $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
375
376                         // Display advert template
377                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', TRUE);
378                 } // END - if
379
380                 // Prepare data
381                 $content = array(
382                         'rows'      => $GLOBALS['rows'],
383                         'menu_mode' => $mode
384                 );
385
386                 // Load main template
387                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
388                 loadTemplate('menu_table', FALSE, $content);
389         } // END - if
390 }
391
392 // Checks whether the current user is a member
393 function isMember () {
394         // By default no member
395         $ret = FALSE;
396
397         // Fix missing 'last_online' array, damn stupid code :(((
398         // @TODO Try to rewrite this to one or more functions
399         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
400                 $GLOBALS['last_online'] = array();
401         } // END - if
402
403         // Is the cache entry there?
404         if (isset($GLOBALS[__FUNCTION__])) {
405                 // Then return it
406                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
407                 return $GLOBALS[__FUNCTION__];
408         } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
409                 // Destroy any existing user session data
410                 destroyMemberSession();
411                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
412
413                 // Abort further processing
414                 return FALSE;
415         }
416
417         // Get userid secured from session
418         setMemberId(getSession('userid'));
419
420         // ... and set it as currently handled user id
421         setCurrentUserId(getMemberId());
422
423         // Init user data array
424         initUserData();
425
426         // Fix "deleted" cookies
427         fixDeletedCookies(array('userid', 'u_hash'));
428
429         // Are cookies set and can the member data be loaded?
430         if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === TRUE)) {
431                 // Validate password by created the difference of it and the secret key
432                 $valPass = encodeHashForCookie(getUserData('password'));
433
434                 // So did we now have valid data and an unlocked user?
435                 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
436                         // Transfer last module and online time
437                         $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
438                         $GLOBALS['last_online']['online'] = getUserData('last_online');
439
440                         // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
441                         $ret = TRUE;
442                 } // END - if
443         } // END - if
444
445         // Is $ret still false?
446         if ($ret === FALSE) {
447                 // Yes, so destroy the session
448                 destroyMemberSession();
449         } // END - if
450
451         // Cache status
452         $GLOBALS[__FUNCTION__] = $ret;
453
454         // Return status
455         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
456         return $ret;
457 }
458
459 // Fetch user data for given user id
460 function fetchUserData ($value, $column = 'userid') {
461         // Extension ext-user must be there at any case
462         if (!isExtensionActive('user')) {
463                 // Absent ext-user is really not good
464                 return FALSE;
465         } elseif (is_null($value)) {
466                 // This shall never happen, so please report it
467                 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
468         }
469
470         // If we should look for userid secure&set it here
471         if (substr($column, -2, 2) == 'id') {
472                 // Secure userid
473                 $value = bigintval($value);
474
475                 // Don't look for invalid userids...
476                 if (!isValidUserId($value)) {
477                         // Invalid, so abort here
478                         reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
479                 } // END - if
480
481                 // Unset cached values if found and different
482                 if ((isCurrentUserIdSet()) && (getCurrentUserId() != $value)) {
483                         // Unset it
484                         unsetCurrentUserId();
485                 } elseif (isUserDataValid()) {
486                         // Use cache, so it is fine
487                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
488                         return TRUE;
489                 } // END - if
490         } elseif (isUserDataValid()) {
491                 // Using cache is fine
492                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
493                 return TRUE;
494         }
495
496         // By default none was found
497         $found = FALSE;
498
499         // Extra SQL statements
500         $ADD = runFilterChain('convert_user_data_columns', ' ');
501
502         // Query for the user
503         $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
504                 array(
505                         $column,
506                         $value
507                 ), __FUNCTION__, __LINE__);
508
509         // Is there a record?
510         if (SQL_NUMROWS($result) == 1) {
511                 // Load data from cookies
512                 $data = SQL_FETCHARRAY($result);
513
514                 // Set the userid for later use
515                 setCurrentUserId($data['userid']);
516
517                 // And cache the data for this userid
518                 $GLOBALS['user_data'][getCurrentUserId()] = $data;
519
520                 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
521                 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
522                         // Backup the raw one and zero it
523                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
524                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
525
526                         // Is it not zero?
527                         if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
528                                 // Seperate data/time
529                                 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
530
531                                 // Seperate data and time again
532                                 $array['date'] = explode('-', $array[0]);
533                                 $array['time'] = explode(':', $array[1]);
534
535                                 // Now pass it to mktime()
536                                 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
537                                         $array['time'][0],
538                                         $array['time'][1],
539                                         $array['time'][2],
540                                         $array['date'][1],
541                                         $array['date'][2],
542                                         $array['date'][0]
543                                 );
544                         } // END - if
545                 } // END - if
546
547                 // Found, but valid?
548                 $found = isUserDataValid();
549         } // END - if
550
551         // Free memory
552         SQL_FREERESULT($result);
553
554         // Return result
555         return $found;
556 }
557
558 /*
559  * Checks whether the current session bears a valid admin id and password hash.
560  *
561  * This patched function will reduce many SELECT queries for the current admin
562  * login.
563  */
564 function isAdmin () {
565         // Is there cache?
566         if (isset($GLOBALS[__FUNCTION__])) {
567                 // Return it
568                 return $GLOBALS[__FUNCTION__];
569         } // END - if
570
571         // No admin in installation phase!
572         if ((isInstallationPhase()) || (!isAdminRegistered())) {
573                 $GLOBALS[__FUNCTION__] = FALSE;
574                 return FALSE;
575         } // END - if
576
577         // Init variables
578         $ret = FALSE;
579         $adminId = '0';
580         $passwordFromCookie = '';
581         $valPass = '';
582         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
583
584         // If admin login is not given take current from cookies...
585         if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
586                 // Get admin login and password from session/cookies
587                 $adminId    = getCurrentAdminId();
588                 $passwordFromCookie = getAdminMd5();
589         } // END - if
590         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . 'passwordFromCookie=' . $passwordFromCookie);
591
592         // Abort if admin id is zero
593         if ($adminId == '0') {
594                 // A very noisy debug message ...
595                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
596
597                 // Abort here now
598                 $GLOBALS[__FUNCTION__] = FALSE;
599                 return FALSE;
600         } // END - if
601
602         // Init it with failed
603         $GLOBALS[__FUNCTION__] = FALSE;
604
605         // Search in array for entry
606         if (isset($GLOBALS['admin_hash'])) {
607                 // Use cached string
608                 $valPass = $GLOBALS['admin_hash'];
609         } elseif ((!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === TRUE) && (!empty($adminId))) {
610                 // Login data is valid or not?
611                 $valPass = encodeHashForCookie(getAdminHash($adminId));
612
613                 // Cache it away
614                 $GLOBALS['admin_hash'] = $valPass;
615
616                 // Count cache hits
617                 incrementStatsEntry('cache_hits');
618         } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === FALSE))) {
619                 // Get admin hash and hash it
620                 $valPass = encodeHashForCookie(getAdminHash($adminId));
621
622                 // Cache it away
623                 $GLOBALS['admin_hash'] = $valPass;
624         }
625
626         // $valPass shall not be empty. If so, the admin has not found.
627         if (!empty($valPass)) {
628                 // Check if password is valid
629                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passwordFromCookie . ')='.intval($valPass == $passwordFromCookie));
630                 $GLOBALS[__FUNCTION__] = ($GLOBALS['admin_hash'] == $passwordFromCookie);
631         } // END - if
632
633         // Return result of comparision
634         return $GLOBALS[__FUNCTION__];
635 }
636
637 // Generates a list of "max receiveable emails per day"
638 function addMaxReceiveList ($mode, $default = '') {
639         $OUT = '';
640         $result = FALSE;
641
642         switch ($mode) {
643                 case 'guest':
644                         // Guests (in the registration form) are not allowed to select 0 mails per day.
645                         $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
646                         __FUNCTION__, __LINE__);
647                         break;
648
649                 case 'admin':
650                 case 'member':
651                         // Members are allowed to set to zero mails per day (we will change this soon!)
652                         $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
653                         __FUNCTION__, __LINE__);
654                         break;
655
656                 default: // Invalid!
657                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
658                         break;
659         }
660
661         // Some entries are found?
662         if (!SQL_HASZERONUMS($result)) {
663                 $OUT = '';
664                 while ($content = SQL_FETCHARRAY($result)) {
665                         $OUT .= '      <option value="' . $content['value'] . '"';
666
667                         if (postRequestElement('max_mails') == $content['value']) {
668                                 $OUT .= ' selected="selected"';
669                         } // END - if
670
671                         $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
672                         if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
673                         $OUT .= '</option>';
674                 }
675
676                 // Load template
677                 $OUT = loadTemplate(($mode . '_receive_table'), TRUE, $OUT);
678         } else {
679                 // Maybe the admin has to setup some maximum values?
680                 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
681         }
682
683         // Free result
684         SQL_FREERESULT($result);
685
686         // Return generated HTML code
687         return $OUT;
688 }
689
690 // Checks whether the given email address is used.
691 function isEmailTaken ($email) {
692         // Default is no userid
693         $useridSql = ' IS NOT NULL';
694
695         // Is a member logged in?
696         if (isMember()) {
697                 // Get userid
698                 $useridSql = '!= ' . bigintval(getMemberId());
699         } // END - if
700
701         // Replace dot with {DOT}
702         $email = str_replace('.', '{DOT}', $email);
703
704         // Query the database
705         $result = SQL_QUERY_ESC("SELECT
706         COUNT(`userid`) AS `cnt`
707 FROM
708         `{?_MYSQL_PREFIX?}_user_data`
709 WHERE
710         '%s' REGEXP `email` AND
711         `userid` %s
712 LIMIT 1",
713                 array(
714                         $email,
715                         $useridSql
716                 ), __FUNCTION__, __LINE__);
717
718         // Is the email there?
719         list($count) = SQL_FETCHROW($result);
720
721         // Free the result
722         SQL_FREERESULT($result);
723
724         // Return result
725         return ($count == 1);
726 }
727
728 // Validate the given menu action
729 function isMenuActionValid ($mode, $action, $what, $updateEntry = FALSE) {
730         // Is the cache entry there and we shall not update?
731         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === FALSE)) {
732                 // Count cache hit
733                 incrementStatsEntry('cache_hits');
734
735                 // Then use this cache
736                 return $GLOBALS['action_valid'][$mode][$action][$what];
737         } // END - if
738
739         // By default nothing is valid
740         $ret = FALSE;
741
742         // Look in all menus or only unlocked
743         $add = '';
744         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
745
746         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
747         if (($mode != 'admin') && ($updateEntry === TRUE)) {
748                 // Update guest or member menu
749                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
750                         array(
751                                 $mode,
752                                 $action,
753                                 $what
754                         ), __FUNCTION__, __LINE__, FALSE);
755         } elseif (($what != 'welcome') && (!empty($what))) {
756                 // Other actions
757                 $sql = SQL_QUERY_ESC("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what`='%s'".$add." ORDER BY `action` DESC LIMIT 1",
758                         array(
759                                 $mode,
760                                 $action,
761                                 $what
762                         ), __FUNCTION__, __LINE__, FALSE);
763         } else {
764                 // Admin login overview
765                 $sql = SQL_QUERY_ESC("SELECT `id`, `what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND (`what`='' OR `what` IS NULL)".$add." ORDER BY `action` DESC LIMIT 1",
766                         array(
767                                 $mode,
768                                 $action
769                         ), __FUNCTION__, __LINE__, FALSE);
770         }
771
772         // Run SQL command
773         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
774
775         // Should we look for affected rows (only update) or found rows?
776         if ($updateEntry === TRUE) {
777                 // Check updated/affected rows
778                 $ret = (!SQL_HASZEROAFFECTED());
779         } else {
780                 // Check found rows
781                 $ret = (!SQL_HASZERONUMS($result));
782         }
783
784         // Free memory
785         SQL_FREERESULT($result);
786
787         // Set cache entry
788         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
789
790         // Return result
791         return $ret;
792 }
793
794 // Get action value from mode (admin/guest/member) and what-value
795 function getActionFromModuleWhat ($module, $what) {
796         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
797         // Init status
798         $data['action'] = '';
799
800         if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
801                 // ext-sql_patches is missing so choose depending on mode
802                 $what = determineWhat($module);
803         } elseif ((empty($what)) && ($module != 'admin')) {
804                 // Use configured 'home'
805                 $what = getIndexHome();
806         } // END - if
807
808         if ($module == 'admin') {
809                 // Action value for admin area
810                 if (isGetRequestElementSet('action')) {
811                         // Use from request!
812                         return getRequestElement('action');
813                 } elseif (isActionSet()) {
814                         // Get it directly from URL
815                         return getAction();
816                 } elseif (($what == 'welcome') || (!isWhatSet())) {
817                         // Default value for admin area
818                         $data['action'] = 'login';
819                 }
820         } elseif (isActionSet()) {
821                 // Get it directly from URL
822                 return getAction();
823         }
824         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
825
826         // Does the module have a menu?
827         if (ifModuleHasMenu($module)) {
828                 // Rewriting modules to menu
829                 $module = mapModuleToTable($module);
830
831                 // Guest and member menu is 'main' as the default
832                 if (empty($data['action'])) {
833                         $data['action'] = 'main';
834                 } // END - if
835
836                 // Load from database
837                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
838                         array(
839                                 $module,
840                                 $what
841                         ), __FUNCTION__, __LINE__);
842                 if (SQL_NUMROWS($result) == 1) {
843                         // Load action value and pray that this one is the right you want... ;-)
844                         $data = SQL_FETCHARRAY($result);
845                 } // END - if
846
847                 // Free memory
848                 SQL_FREERESULT($result);
849         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
850                 // No ext-sql_patches installed, but maybe we need to register an admin?
851                 if (isAdminRegistered()) {
852                         // Redirect to admin area
853                         redirectToUrl('admin.php');
854                 } // END - if
855         }
856
857         // Return action value
858         return $data['action'];
859 }
860
861 // Get category name back
862 function getCategory ($cid) {
863         // Default is not found
864         $data['cat'] = '{--_CATEGORY_404--}';
865
866         // Is the category id set?
867         if ($cid == '0') {
868                 // No category
869                 $data['cat'] = '{--_CATEGORY_NONE--}';
870         } elseif ($cid > 0) {
871                 // Lookup the category in database
872                 $result = SQL_QUERY_ESC('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
873                         array(bigintval($cid)), __FUNCTION__, __LINE__);
874                 if (SQL_NUMROWS($result) == 1) {
875                         // Category found... :-)
876                         $data = SQL_FETCHARRAY($result);
877                 } // END - if
878
879                 // Free result
880                 SQL_FREERESULT($result);
881         } // END - if
882
883         // Return result
884         return $data['cat'];
885 }
886
887 // Get a string of "mail title" and price back
888 function getPaymentTitlePrice ($paymentsId, $full = FALSE) {
889         // Only title or also including price?
890         if ($full === FALSE) {
891                 $ret = getPaymentData($paymentsId, 'main_title');
892         } else {
893                 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
894         }
895
896         // Return result
897         return $ret;
898 }
899
900 // "Getter" for payment data (cached)
901 function getPaymentData ($paymentsId, $lookFor = 'price') {
902         // Default value...
903         $data[$lookFor] = NULL;
904
905         // Is there cache?
906         if (isset($GLOBALS['cache_array']['payments'][$lookFor][$paymentsId])) {
907                 // Use it if found to save SQL queries
908                 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
909
910                 // Update cache hits
911                 incrementStatsEntry('cache_hits');
912         } elseif (!isExtensionActive('cache')) {
913                 // Search for it in database
914                 $result = SQL_QUERY_ESC('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
915                         array(
916                                 $lookFor,
917                                 bigintval($paymentsId)
918                         ), __FUNCTION__, __LINE__);
919
920                 // Is the entry there?
921                 if (SQL_NUMROWS($result) == 1) {
922                         // Payment type found... :-)
923                         $data = SQL_FETCHARRAY($result);
924                 } // END - if
925
926                 // Free result
927                 SQL_FREERESULT($result);
928         }
929
930         // Return value
931         return $data[$lookFor];
932 }
933
934 // Remove a receiver's id from $receivers and add a link for him to confirm
935 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = FALSE) {
936         // Default is not removed
937         $ret = 'failed';
938
939         // Is the userid valid?
940         if (isValidUserId($userid)) {
941                 // Remove entry from array
942                 unset($receivers[$key]);
943
944                 // Is there already a line for this user available?
945                 if ($statsId > 0) {
946                         // Default is 'normal' mail
947                         $type = 'NORMAL';
948                         $rowName = 'stats_id';
949
950                         // Only when we got a real stats id continue searching for the entry
951                         if ($isBonusMail === TRUE) {
952                                 $type = 'BONUS';
953                                 $rowName = 'bonus_id';
954                         } // END - if
955
956                         // Try to look the entry up
957                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
958                                 array(
959                                         $rowName,
960                                         bigintval($statsId),
961                                         bigintval($userid),
962                                         $type
963                                 ), __FUNCTION__, __LINE__);
964
965                         // Was it *not* found?
966                         if (SQL_HASZERONUMS($result)) {
967                                 // So we add one!
968                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES (%s,%s,'%s')",
969                                         array(
970                                                 $rowName,
971                                                 bigintval($statsId),
972                                                 bigintval($userid),
973                                                 $type
974                                         ), __FUNCTION__, __LINE__);
975
976                                 // Update 'mails_sent' if ext-sql_patches is updated
977                                 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
978                                         // Update the pool
979                                         SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1',
980                                                 array(bigintval($poolId)), __FUNCTION__, __LINE__);
981                                 } // END - if
982                                 $ret = 'done';
983                         } else {
984                                 // Already found
985                                 $ret = 'already';
986                         }
987
988                         // Free memory
989                         SQL_FREERESULT($result);
990                 } // END - if
991         } // END - if
992
993         // Return status for sending routine
994         return $ret;
995 }
996
997 // Calculate sum (default) or count records of given criteria
998 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = FALSE, $add = '', $mode = '=') {
999         // Debug message
1000         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
1001         if ((empty($search)) && ($search != '0')) {
1002                 // Count or sum whole table?
1003                 if ($countRows === TRUE) {
1004                         // Count whole table
1005                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1006                         $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1007                                 array(
1008                                         $lookFor,
1009                                         $tableName
1010                                 ), __FUNCTION__, __LINE__);
1011                 } else {
1012                         // Sum whole table
1013                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1014                         $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1015                                 array(
1016                                         $lookFor,
1017                                         $tableName
1018                                 ), __FUNCTION__, __LINE__);
1019                 }
1020         } elseif (($countRows === TRUE) || ($lookFor == 'userid')) {
1021                 // Count rows
1022                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1023                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1024                         array(
1025                                 $lookFor,
1026                                 $tableName,
1027                                 $whereStatement,
1028                                 $mode,
1029                                 $search
1030                         ), __FUNCTION__, __LINE__);
1031         } else {
1032                 // Add all rows
1033                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1034                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1035                         array(
1036                                 $lookFor,
1037                                 $tableName,
1038                                 $whereStatement,
1039                                 $mode,
1040                                 $search
1041                         ), __FUNCTION__, __LINE__);
1042         }
1043
1044         // Load row
1045         $data = SQL_FETCHARRAY($result);
1046
1047         // Free result
1048         SQL_FREERESULT($result);
1049
1050         // Fix empty values
1051         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1052                 // Float number
1053                 $data['res'] = '0.00000';
1054         } elseif (''.$data['res'].'' == '') {
1055                 // Fix empty result
1056                 $data['res'] = '0';
1057         }
1058
1059         // Return value
1060         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1061         return $data['res'];
1062 }
1063
1064 /**
1065  * Sends out mail to all administrators. This function is no longer obsolete
1066  * because we need it when there is no ext-admins installed
1067  */
1068 function sendAdminEmails ($subject, $message, $isBugReport = FALSE) {
1069         // Default is no special header
1070         $mailHeader = '';
1071
1072         // Is it a bug report?
1073         if ($isBugReport === TRUE) {
1074                 // Then add a reply-to line back to the author (me)
1075                 $mailHeader = 'Reply-To: webmaster@mxchange.org' . chr(10);
1076         } // END - if
1077
1078         // Load all admin email addresses
1079         $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1080
1081         // And send the notification to all of them
1082         while ($content = SQL_FETCHARRAY($result)) {
1083                 // Send the email out
1084                 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1085         } // END - if
1086
1087         // Free result
1088         SQL_FREERESULT($result);
1089
1090         // Really simple... ;-)
1091 }
1092
1093 // Get id number from administrator's login name
1094 function getAdminId ($adminLogin) {
1095         // By default no admin is found
1096         $data['id'] = -1;
1097
1098         // Check cache
1099         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1100                 // Use it if found to save SQL queries
1101                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1102
1103                 // Update cache hits
1104                 incrementStatsEntry('cache_hits');
1105         } elseif (!isExtensionActive('cache')) {
1106                 // Load from database
1107                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1108                         array($adminLogin), __FUNCTION__, __LINE__);
1109
1110                 // Is there an entry?
1111                 if (SQL_NUMROWS($result) == 1) {
1112                         // Get it
1113                         $data = SQL_FETCHARRAY($result);
1114                 } // END - if
1115
1116                 // Free result
1117                 SQL_FREERESULT($result);
1118         }
1119
1120         // Return the id
1121         return $data['id'];
1122 }
1123
1124 // "Getter" for current admin id
1125 function getCurrentAdminId () {
1126         // Log debug message
1127         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1128
1129         // Is there cache?
1130         if (!isset($GLOBALS['current_admin_id'])) {
1131                 // Get the admin login from session
1132                 $adminId = getSession('admin_id');
1133
1134                 // Remember in cache securely
1135                 setCurrentAdminId(bigintval($adminId));
1136         } // END - if
1137
1138         // Return it
1139         return $GLOBALS['current_admin_id'];
1140 }
1141
1142 // Setter for current admin id
1143 function setCurrentAdminId ($currentAdminId) {
1144         // Set it secured
1145         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1146 }
1147
1148 // Get password hash from administrator's login name
1149 function getAdminHash ($adminId) {
1150         // By default an invalid hash is returned
1151         $data['password'] = -1;
1152
1153         if (isAdminHashSet($adminId)) {
1154                 // Check cache
1155                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1156
1157                 // Update cache hits
1158                 incrementStatsEntry('cache_hits');
1159         } elseif (!isExtensionActive('cache')) {
1160                 // Load from database
1161                 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1162                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1163
1164                 // Is there an entry?
1165                 if (SQL_NUMROWS($result) == 1) {
1166                         // Fetch data
1167                         $data = SQL_FETCHARRAY($result);
1168
1169                         // Set cache
1170                         setAdminHash($adminId, $data['password']);
1171                 } // END - if
1172
1173                 // Free result
1174                 SQL_FREERESULT($result);
1175         }
1176
1177         // Return password hash
1178         return $data['password'];
1179 }
1180
1181 // "Getter" for admin login
1182 function getAdminLogin ($adminId) {
1183         // By default a non-existent login is returned (other functions react on this!)
1184         $data['login'] = '***';
1185
1186         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1187                 // Get cache
1188                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1189
1190                 // Update cache hits
1191                 incrementStatsEntry('cache_hits');
1192         } elseif (!isExtensionActive('cache')) {
1193                 // Load from database
1194                 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1195                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1196
1197                 // Entry found?
1198                 if (SQL_NUMROWS($result) == 1) {
1199                         // Fetch data
1200                         $data = SQL_FETCHARRAY($result);
1201
1202                         // Set cache
1203                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1204                 } // END - if
1205
1206                 // Free memory
1207                 SQL_FREERESULT($result);
1208         }
1209
1210         // Return the result
1211         return $data['login'];
1212 }
1213
1214 // Get email address of admin id
1215 function getAdminEmail ($adminId) {
1216         // By default an invalid emails is returned
1217         $data['email'] = '***';
1218
1219         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1220                 // Get cache
1221                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1222
1223                 // Update cache hits
1224                 incrementStatsEntry('cache_hits');
1225         } elseif (!isExtensionActive('cache')) {
1226                 // Load from database
1227                 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1228                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1229
1230                 // Entry found?
1231                 if (SQL_NUMROWS($result_admin_id) == 1) {
1232                         // Get data
1233                         $data = SQL_FETCHARRAY($result_admin_id);
1234
1235                         // Set cache
1236                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1237                 } // END - if
1238
1239                 // Free result
1240                 SQL_FREERESULT($result_admin_id);
1241         }
1242
1243         // Return email
1244         return $data['email'];
1245 }
1246
1247 // Get default ACL of admin id
1248 function getAdminDefaultAcl ($adminId) {
1249         // By default an invalid ACL value is returned
1250         $data['default_acl'] = 'NO-ACL';
1251
1252         // Is ext-sql_patches there and was it found in cache?
1253         if (!isExtensionActive('sql_patches')) {
1254                 // Not found, which is bad, so we need to allow all
1255                 $data['default_acl'] =  'allow';
1256         } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1257                 // Use cache
1258                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1259
1260                 // Update cache hits
1261                 incrementStatsEntry('cache_hits');
1262         } elseif (!isExtensionActive('cache')) {
1263                 // Load from database
1264                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1265                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1266
1267                 // Is there an entry?
1268                 if (SQL_NUMROWS($result_admin_id) == 1) {
1269                         // Fetch data
1270                         $data = SQL_FETCHARRAY($result_admin_id);
1271
1272                         // Set cache
1273                         $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1274                 }
1275
1276                 // Free result
1277                 SQL_FREERESULT($result_admin_id);
1278         }
1279
1280         // Return default ACL
1281         return $data['default_acl'];
1282 }
1283
1284 // Get menu mode (la_mode) of admin id
1285 function getAdminMenuMode ($adminId) {
1286         // By default an invalid mode
1287         $data['la_mode'] = 'INVALID';
1288
1289         // Is ext-sql_patches there and was it found in cache?
1290         if (!isExtensionActive('sql_patches')) {
1291                 // Not found, which is bad, so we need to allow all
1292                 $data['la_mode'] =  'global';
1293         } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1294                 // Use cache
1295                 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1296
1297                 // Update cache hits
1298                 incrementStatsEntry('cache_hits');
1299         } elseif (!isExtensionActive('cache')) {
1300                 // Load from database
1301                 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1302                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1303
1304                 // Is there an entry?
1305                 if (SQL_NUMROWS($result_admin_id) == 1) {
1306                         // Fetch data
1307                         $data = SQL_FETCHARRAY($result_admin_id);
1308
1309                         // Set cache
1310                         $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1311                 }
1312
1313                 // Free result
1314                 SQL_FREERESULT($result_admin_id);
1315         }
1316
1317         // Return default ACL
1318         return $data['la_mode'];
1319 }
1320
1321 // Generates an option list from various parameters
1322 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '') {
1323         $ret = '';
1324         if ($table == '/ARRAY/') {
1325                 // Selection from array
1326                 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1327                         // Both are arrays
1328                         foreach ($key as $idx => $optionValue) {
1329                                 $ret .= '<option value="' . $optionValue . '"';
1330                                 if ($default == $optionValue) {
1331                                         // Selected by default
1332                                         $ret .= ' selected="selected"';
1333                                 } elseif (isset($disabled[$optionValue])) {
1334                                         // Disabled!
1335                                         $ret .= ' disabled="disabled"';
1336                                 }
1337
1338                                 // Is the call-back function set?
1339                                 if (!empty($callback)) {
1340                                         // Call it
1341                                         $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1342                                 } // END - if
1343
1344                                 // Finish option tag
1345                                 $ret .= '>' . $value[$idx] . '</option>';
1346                         } // END - foreach
1347                 } else {
1348                         // Problem in request
1349                         reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1350                 }
1351         } else {
1352             ///////////////////////
1353                 // Data from database /
1354                 ///////////////////////
1355
1356                 // Init extra column (if requested)
1357                 $extraColumn = '';
1358                 if (!empty($extra)) {
1359                         $extraColumn = ',`' . $extra . '` AS `extra`';
1360                 } // END - if
1361
1362                 // Run SQL query
1363                 $result = SQL_QUERY_ESC("SELECT `%s` AS `key`, `%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1364                         array(
1365                                 $key,
1366                                 $value,
1367                                 $table,
1368                                 $value
1369                         ), __FUNCTION__, __LINE__);
1370
1371                 // Is there rows?
1372                 if (!SQL_HASZERONUMS($result)) {
1373                         // Found data so add them as OPTION lines
1374                         while ($content = SQL_FETCHARRAY($result)) {
1375                                 // Is extra set?
1376                                 if (!isset($content['extra'])) {
1377                                         // Set it to empty
1378                                         $content['extra'] = '';
1379                                 } // END - if
1380
1381                                 $ret .= '<option value="' . $content['key'] . '"';
1382
1383                                 if ($default == $content['key']) {
1384                                         // Selected by default
1385                                         $ret .= ' selected="selected"';
1386                                 } elseif (isset($disabled[$content['key']])) {
1387                                         // Disabled!
1388                                         $ret .= ' disabled="disabled"';
1389                                 }
1390
1391                                 // Add it, if set
1392                                 if (!empty($content['extra'])) {
1393                                         $content['extra'] = ' (' . $content['extra'] . ')';
1394                                 } // END - if
1395
1396                                 // Is the call-back function set?
1397                                 if (!empty($callback)) {
1398                                         // Call it
1399                                         $content['value'] = call_user_func_array($callback, array($content['value']));
1400                                 } // END - if
1401
1402                                 // Finish option list
1403                                 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1404                         } // END - while
1405                 } else {
1406                         // No data found
1407                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1408                 }
1409
1410                 // Free memory
1411                 SQL_FREERESULT($result);
1412         }
1413
1414         // Return - hopefully - the requested data
1415         return $ret;
1416 }
1417
1418 // Deletes a user account with given reason
1419 function deleteUserAccount ($userid, $reason) {
1420         // Init points
1421         $data['points'] = '0';
1422
1423         // Search for the points and user data
1424         $result = SQL_QUERY_ESC("SELECT
1425         (SUM(p.`points`) - d.`used_points`) AS `points`
1426 FROM
1427         `{?_MYSQL_PREFIX?}_user_points` AS `p`
1428 LEFT JOIN
1429         `{?_MYSQL_PREFIX?}_user_data` AS `d`
1430 ON
1431         p.`userid`=d.`userid`
1432 WHERE
1433         p.`userid`=%s
1434 LIMIT 1",
1435                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1436
1437         // Is there an entry?
1438         if (SQL_NUMROWS($result) == 1) {
1439                 // Save his points to add them to the jackpot
1440                 $data = SQL_FETCHARRAY($result);
1441
1442                 // Delete points entries as well
1443                 // @TODO Rewrite these lines to a filter
1444                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1445                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1446
1447                 // Update mediadata as well
1448                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1449                         // Update database
1450                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1451                 } // END - if
1452
1453                 // Now, when we have all his points adds them do the jackpot!
1454                 if (isExtensionActive('jackpot')) {
1455                         addPointsToJackpot($data['points']);
1456                 } // END - if
1457         } // END - if
1458
1459         // Free the result
1460         SQL_FREERESULT($result);
1461
1462         // Delete category selections as well...
1463         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1464                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1465
1466         // Remove from rallye if found
1467         // @TODO Rewrite this to a filter
1468         if (isExtensionActive('rallye')) {
1469                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1470                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1471         } // END - if
1472
1473         // Add reason and translate points
1474         $data['text'] = $reason;
1475
1476         // Now a mail to the user and that's all...
1477         $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1478         sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1479
1480         // Ok, delete the account!
1481         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1482 }
1483
1484 // Gets the matching what name from module
1485 function getWhatFromModule ($modCheck) {
1486         // Is the request element set?
1487         if (isGetRequestElementSet('what')) {
1488                 // Then return this!
1489                 return getRequestElement('what');
1490         } // END - if
1491
1492         // Default is empty
1493         $what = '';
1494
1495         // Check on given module
1496         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1497         switch ($modCheck) {
1498                 case 'index': // Guest area
1499                         // Is ext-sql_patches installed and newer than 0.0.5?
1500                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1501                                 // Use it from config
1502                                 $what = getIndexHome();
1503                         } else {
1504                                 // Use default 'welcome'
1505                                 $what = 'welcome';
1506                         }
1507                         break;
1508
1509                 default: // Default for all other menus (getIndexHome() is for index module only)
1510                         $what = 'welcome';
1511                         break;
1512         } // END - switch
1513
1514         // Return what value
1515         return $what;
1516 }
1517
1518 // Returns HTML code with an option list of all categories
1519 function generateCategoryOptionsList ($mode, $userid = NULL) {
1520         // Prepare WHERE statement
1521         $whereStatement = " WHERE `visible`='Y'";
1522         if (isAdmin()) $whereStatement = '';
1523
1524         // Initialize array...
1525         $categories = array(
1526                 'id'      => array(),
1527                 'name'    => array(),
1528                 'userids' => array()
1529         );
1530
1531         // Get categories
1532         $result = SQL_QUERY('SELECT
1533         `id`,
1534         `cat`
1535 FROM
1536         `{?_MYSQL_PREFIX?}_cats`
1537 ' . $whereStatement . '
1538 ORDER BY
1539         `sort` ASC',
1540                 __FUNCTION__, __LINE__);
1541
1542         // Are there entries?
1543         if (!SQL_HASZERONUMS($result)) {
1544                 // ... and begin loading stuff
1545                 while ($content = SQL_FETCHARRAY($result)) {
1546                         // Transfer some data
1547                         $categories['id'][]   = $content['id'];
1548                         array_push($categories['name'], $content['cat']);
1549
1550                         // Check which users are in this category
1551                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1552                                 array(
1553                                         bigintval($content['id']),
1554                                         convertNullToZero($userid)
1555                                 ), __FUNCTION__, __LINE__);
1556
1557                         // Init count
1558                         $userid_cnt = '0';
1559
1560                         // Start adding all
1561                         while ($data = SQL_FETCHARRAY($result_userids)) {
1562                                 // Add user count
1563                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', TRUE, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1564                         } // END - while
1565
1566                         // Free memory
1567                         SQL_FREERESULT($result_userids);
1568
1569                         // Add counter
1570                         array_push($categories['userids'], $userid_cnt);
1571                 } // END - while
1572
1573                 // Free memory
1574                 SQL_FREERESULT($result);
1575
1576                 // Generate options
1577                 $OUT = '';
1578                 foreach ($categories['id'] as $key => $value) {
1579                         $OUT .= '      <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1580                 } // END - foreach
1581         } else {
1582                 // No cateogries are defined yet
1583                 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1584         }
1585
1586         // Return HTML code
1587         return $OUT;
1588 }
1589
1590 // Add bonus mail to queue
1591 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1592         // Is admin or bonus extension there?
1593         if (!isAdmin()) {
1594                 // Abort here
1595                 return FALSE;
1596         } elseif (!isExtensionActive('bonus')) {
1597                 // Abort here
1598                 return FALSE;
1599         }
1600
1601         // Calculcate target sent
1602         $target = countSelection(explode(';', $receiverList));
1603
1604         // Receiver is zero?
1605         if ($receiver == '0') {
1606                 // Then auto-fix it
1607                 $receiver = $target;
1608         } // END - if
1609
1610         // HTML extension active?
1611         if (isExtensionActive('html_mail')) {
1612                 // Add HTML mail
1613                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1614         `subject`,
1615         `text`,
1616         `receivers`,
1617         `points`,
1618         `time`,
1619         `data_type`,
1620         `timestamp`,
1621         `url`,
1622         `cat_id`,
1623         `target_send`,
1624         `mails_sent`,
1625         `html_msg`
1626 ) VALUES (
1627         '%s',
1628         '%s',
1629         '%s',
1630         %s,
1631         %s,
1632         'NEW',
1633         UNIX_TIMESTAMP(),
1634         '%s',
1635         %s,
1636         %s,
1637         %s,
1638         '%s'
1639 )",
1640                 array(
1641                         $subject,
1642                         $text,
1643                         $receiverList,
1644                         $points,
1645                         bigintval($seconds),
1646                         $url,
1647                         bigintval($categoryId),
1648                         $target,
1649                         bigintval($receiver),
1650                         convertBooleanToYesNo($mode == 'html')
1651                 ), __FUNCTION__, __LINE__);
1652         } else {
1653                 // Add regular mail
1654                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1655         `subject`,
1656         `text`,
1657         `receivers`,
1658         `points`,
1659         `time`,
1660         `data_type`,
1661         `timestamp`,
1662         `url`,
1663         `cat_id`,
1664         `target_send`,
1665         `mails_sent`
1666 ) VALUES (
1667         '%s',
1668         '%s',
1669         '%s',
1670         %s,
1671         %s,
1672         'NEW',
1673         UNIX_TIMESTAMP(),
1674         '%s',
1675         %s,
1676         %s,
1677         %s
1678 )",
1679                 array(
1680                         $subject,
1681                         $text,
1682                         $receiverList,
1683                         $points,
1684                         bigintval($seconds),
1685                         $url,
1686                         bigintval($categoryId),
1687                         $target,
1688                         bigintval($receiver),
1689                 ), __FUNCTION__, __LINE__);
1690         }
1691 }
1692
1693 // Generate a receiver list for given category and maximum receivers
1694 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1695         // Init variables
1696         $extraColumns = '';
1697         $receiverList = '';
1698         $result       = FALSE;
1699
1700         // Secure data
1701         $categoryId = bigintval($categoryId);
1702         $receiver   = bigintval($receiver);
1703
1704         // Is the receiver zero and mode set?
1705         if (($receiver == '0') && (!empty($mode))) {
1706                 // Auto-fix receiver maximum
1707                 $receiver = getTotalReceivers($mode);
1708         } // END - if
1709
1710         // Exclude (maybe exclude) testers
1711         $addWhere = runFilterChain('user_exclusion_sql', ' ');
1712
1713         // Category given?
1714         if ($categoryId > 0) {
1715                 // Select category
1716                 $extraColumns  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1717                 $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
1718         } // END - if
1719
1720         // Exclude users in holiday?
1721         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1722                 // Add something for the holiday extension
1723                 $addWhere .= " AND d.`holiday_active`='N'";
1724         } // END - if
1725
1726         // Include only HTML recipients?
1727         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1728                 $addWhere .= " AND d.`html`='Y'";
1729         } // END - if
1730
1731         // Run query
1732         $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$extraColumns." WHERE d.`status`='CONFIRMED' ".$addWhere." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1733                 array(
1734                         $receiver
1735                 ), __FUNCTION__, __LINE__);
1736
1737         // Entries found?
1738         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1739                 // Load all entries
1740                 while ($content = SQL_FETCHARRAY($result)) {
1741                         // Add receiver when not empty
1742                         if (!empty($content['userid'])) {
1743                                 $receiverList .= $content['userid'] . ';';
1744                         } // END - if
1745                 } // END - while
1746
1747                 // Free memory
1748                 SQL_FREERESULT($result);
1749
1750                 // Remove trailing semicolon
1751                 $receiverList = substr($receiverList, 0, -1);
1752         } // END - if
1753
1754         // Return list
1755         return $receiverList;
1756 }
1757
1758 // Recuce the amount of received emails for the receipients for given email
1759 function reduceRecipientReceivedMails ($column, $id, $count) {
1760         // Search for mail in database
1761         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1762                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1763
1764         // Are there entries?
1765         if (!SQL_HASZERONUMS($result)) {
1766                 // Now load all userids for one big query!
1767                 $userids = array();
1768                 while ($data = SQL_FETCHARRAY($result)) {
1769                         // By default we want to reduce and have no mails found
1770                         $num = 0;
1771
1772                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1773                         // @TODO Rewrite this to a filter
1774                         if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1775                                 // User email
1776                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1777                         } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1778                                 // Bonus mail
1779                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1780                         }
1781
1782                         // Reduce this users total received emails?
1783                         if ($num === 0) {
1784                                 $userids[$data['userid']] = $data['userid'];
1785                         } // END - if
1786                 } // END - while
1787
1788                 if (count($userids) > 0) {
1789                         // Now update all user accounts
1790                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1791                                 array(
1792                                         implode(',', $userids),
1793                                         count($userids)
1794                                 ), __FUNCTION__, __LINE__);
1795                 } else {
1796                         // Nothing deleted
1797                         displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1798                 }
1799         } // END - if
1800
1801         // Free result
1802         SQL_FREERESULT($result);
1803 }
1804
1805 // Creates a new task
1806 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
1807         // Insert the task data into the database
1808         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_task_system` (`assigned_admin`, `userid`, `status`, `task_type`, `subject`, `text`, `task_created`) VALUES (%s, %s, 'NEW', '%s', '%s', '%s', UNIX_TIMESTAMP())",
1809                 array(
1810                         convertZeroToNull($adminId),
1811                         convertZeroToNull($userid),
1812                         $taskType,
1813                         $subject,
1814                         $notes
1815                 ), __FUNCTION__, __LINE__, TRUE, $strip);
1816
1817         // Return insert id which is the task id
1818         return SQL_INSERTID();
1819 }
1820
1821 // Updates last module / online time
1822 function updateLastActivity ($userid) {
1823         // Is 'what' set?
1824         if (isWhatSet()) {
1825                 // Run the update query
1826                 SQL_QUERY_ESC("UPDATE
1827         `{?_MYSQL_PREFIX?}_user_data`
1828 SET
1829         `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
1830         `last_online`=UNIX_TIMESTAMP(),
1831         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1832 WHERE
1833         `userid`=%s
1834 LIMIT 1",
1835                 array(
1836                         bigintval($userid)
1837                 ), __FUNCTION__, __LINE__);
1838         } else {
1839                 // No what set, needs to be ignored (last_module is last_what)
1840                 SQL_QUERY_ESC("UPDATE
1841         `{?_MYSQL_PREFIX?}_user_data`
1842 SET
1843         `{%%pipe,getUserLastWhatName%%}`=NULL,
1844         `last_online`=UNIX_TIMESTAMP(),
1845         `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1846 WHERE
1847         `userid`=%s
1848 LIMIT 1",
1849                 array(
1850                         bigintval($userid)
1851                 ), __FUNCTION__, __LINE__);
1852         }
1853 }
1854
1855 // List all given rows (callback function from XML)
1856 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array()) {
1857         // Verify that tableName and columns are not empty
1858         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1859                 // No tableName specified
1860                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1861         } elseif (count($columns) == 0) {
1862                 // No columns specified
1863                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1864         }
1865
1866         // This is the minimum query, so at least columns and tableName must have entries
1867         $sql = 'SELECT ';
1868
1869         // Get the sql part back from given array
1870         $sql .= getSqlPartFromXmlArray($columns);
1871
1872         // Remove last commata and add FROM statement
1873         $sql .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1874
1875         // Are there entries from whereColumns to add?
1876         if (count($whereColumns) > 0) {
1877                 // Then add these as well
1878                 if (count($whereColumns) == 1) {
1879                         // One entry found
1880                         $sql .= ' WHERE ';
1881
1882                         // Table/alias included?
1883                         if (!empty($whereColumns[0]['table'])) {
1884                                 // Add it as well
1885                                 $sql .= $whereColumns[0]['table'] . '.';
1886                         } // END - if
1887
1888                         // Add the rest
1889                         $sql .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
1890                 } elseif ((count($whereColumns > 1)) && (count($conditions) > 0)) {
1891                         // More than one "WHERE" + condition found
1892                         foreach ($whereColumns as $idx => $columnArray) {
1893                                 // Default is WHERE
1894                                 $condition = ' WHERE ';
1895
1896                                 // Is the condition element there?
1897                                 if (isset($conditions[$columnArray['column']])) {
1898                                         // Assume the condition
1899                                         $condition = ' ' . $conditions[$columnArray['column']] . ' ';
1900                                 } // END - if
1901
1902                                 // Add to SQL query
1903                                 $sql .= $condition;
1904
1905                                 // Table/alias included?
1906                                 if (!empty($whereColumns[$idx]['table'])) {
1907                                         // Add it as well
1908                                         $sql .= $whereColumns[$idx]['table'] . '.';
1909                                 } // END - if
1910
1911                                 // Add the rest
1912                                 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
1913                         } // END - foreach
1914                 } else {
1915                         // Did not set $conditions
1916                         reportBug(__FUNCTION__, __LINE__, 'Supplied more than &quot;whereColumns&quot; entries but no conditions! Please fix your XML template.');
1917                 }
1918         } // END - if
1919
1920         // Are there entries from orderByColumns to add?
1921         if (count($orderByColumns) > 0) {
1922                 // Add them as well
1923                 $sql .= ' ORDER BY ';
1924                 foreach ($orderByColumns as $orderByColumn => $array) {
1925                         // Get keys (table/alias) and values (sorting itself)
1926                         $table   = trim(implode('', array_keys($array)));
1927                         $sorting = trim(implode('', array_values($array)));
1928
1929                         // table/alias can be omitted
1930                         if (!empty($table)) {
1931                                 // table/alias is given
1932                                 $sql .= $table . '.';
1933                         } // END - if
1934
1935                         // Add order-by column
1936                         $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
1937                 } // END - foreach
1938
1939                 // Remove last column
1940                 $sql = substr($sql, 0, -1);
1941         } // END - if
1942
1943         // Now handle all over to the inner function which will execute the listing
1944         doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1945 }
1946
1947 // Do the listing of entries
1948 function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1949         // Run the SQL query
1950         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
1951
1952         // Are there some URLs left?
1953         if (!SQL_HASZERONUMS($result)) {
1954                 // List all URLs
1955                 $OUT = '';
1956                 while ($content = SQL_FETCHARRAY($result)) {
1957                         // "Translate" content
1958                         foreach ($callbackColumns as $columnName => $callbackName) {
1959                                 // Fill the callback arguments
1960                                 $args = array($content[$columnName]);
1961
1962                                 // Is there more to add?
1963                                 if (isset($extraParameters[$columnName])) {
1964                                         // Add them as well
1965                                         $args = merge_array($args, $extraParameters[$columnName]);
1966                                 } // END - if
1967
1968                                 // Call the callback-function
1969                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, TRUE).'</pre>');
1970                                 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1971                                 $content[$columnName] = call_user_func_array($callbackName, $args);
1972                         } // END - foreach
1973
1974                         // Load row template
1975                         $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $content);
1976                 } // END - while
1977
1978                 // Load main template
1979                 loadTemplate(trim($tableTemplate[0]), FALSE, $OUT);
1980         } else {
1981                 // No URLs in surfbar
1982                 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1983         }
1984
1985         // Free result
1986         SQL_FREERESULT($result);
1987 }
1988
1989 // Adds a given entry to the database
1990 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1991         //* DEBUG: */ die(__FUNCTION__.':columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,timeColumns=<pre>'.print_r($timeColumns,TRUE).'</pre>,columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>,POST=<pre>'.print_r($_POST,TRUE).'</pre>');
1992         // Verify that tableName and columns are not empty
1993         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1994                 // No tableName specified
1995                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1996         } elseif (count($columns) == 0) {
1997                 // No columns specified
1998                 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1999         }
2000
2001         // Init columns and value elements
2002         $sqlColumns = array();
2003         $sqlValues  = array();
2004
2005         // Default is that all went fine
2006         $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
2007
2008         // Is there "time columns"?
2009         if (count($timeColumns) > 0) {
2010                 // Then "walk" through all entries
2011                 foreach ($timeColumns as $column) {
2012                         // Convert all (possible) selections
2013                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2014                 } // END - foreach
2015         } // END - if
2016
2017         // Add columns and values
2018         foreach ($columns as $key => $columnName) {
2019                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2020                 // Is columnIndex set?
2021                 if (!is_null($columnIndex)) {
2022                         // Check conditions
2023                         //* DEBUG: */ die('columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>'.debug_get_printable_backtrace());
2024                         assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2025
2026                         // Then use that index "blindly"
2027                         $columnName = $columnName[$columnIndex];
2028                 } // END - if
2029
2030                 // Debug message
2031                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName[' . gettype($columnName) . ']=' . $columnName . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . intval(isset($extraValues[$key])) . ',extraValuesName=' . intval(isset($extraValues[$columnName . '_list'])));
2032
2033                 // Copy entry securely to the final arrays
2034                 $sqlColumns[$key] = SQL_ESCAPE($columnName);
2035                 $sqlValues[$key]  = SQL_ESCAPE(postRequestElement($columnName));
2036
2037                 // Try to handle call-back functions and/or extra values on the list
2038                 $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key . '_list', $sqlValues[$key], $userIdColumn, key(search_array($columns, 'column', $key)));
2039
2040                 // Is the value not a number?
2041                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key]);
2042                 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
2043                         // Add quotes around it
2044                         $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
2045                 } // END - if
2046
2047                 // Is the value false?
2048                 if ($sqlValues[$key] === FALSE) {
2049                         // One "parser" didn't like it
2050                         $GLOBALS['__XML_PARSE_RESULT'] = FALSE;
2051                         break;
2052                 } // END - if
2053         } // END - foreach
2054
2055         // If all values are okay, continue
2056         if ($sqlValues[$key] !== FALSE) {
2057                 // Build the SQL query
2058                 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
2059
2060                 // Run the SQL query
2061                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2062
2063                 // Add id number
2064                 setPostRequestElement('id', SQL_INSERTID());
2065
2066                 // Prepare filter data array
2067                 $filterData = array(
2068                         'mode'          => 'add',
2069                         'table_name'    => $tableName,
2070                         'content'       => postRequestArray(),
2071                         'id'            => SQL_INSERTID(),
2072                         'subject'       => '',
2073                         // @TODO Used generic 'userid' here
2074                         'userid_column' => array('userid'),
2075                         'raw_userid'    => array('userid'),
2076                         'affected'      => SQL_AFFECTEDROWS(),
2077                         'sql'           => $sql,
2078                 );
2079
2080                 // Send "build mail" out
2081                 runFilterChain('send_build_mail', $filterData);
2082         } // END - if
2083 }
2084
2085 // Edit rows by given id numbers
2086 function doGenericEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $subject = '') {
2087         // Is there "time columns"?
2088         if (count($timeColumns) > 0) {
2089                 // Then "walk" through all entries
2090                 foreach ($timeColumns as $column) {
2091                         // Convert all (possible) selections
2092                         convertSelectionsToEpocheTimeInPostData($column . '_ye');
2093                 } // END - foreach
2094         } // END - if
2095
2096         // Change them all
2097         $affected = '0';
2098         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2099                 // Secure id number
2100                 $id = bigintval($id);
2101
2102                 // Prepare content array (new values)
2103                 $content = array();
2104
2105                 // Prepare SQL for this row
2106                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2107                         SQL_ESCAPE($tableName[0])
2108                 );
2109
2110                 // "Walk" through all entries
2111                 foreach (postRequestArray() as $key => $entries) {
2112                         // Skip raw userid which is always invalid
2113                         if (($key == $rawUserId[0]) || ($key == 'do_edit')) {
2114                                 // Continue with next field
2115                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2116                                 continue;
2117                         } // END - if
2118
2119                         // Debug message
2120                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',id=' . $id . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,TRUE).'</pre>');
2121
2122                         // Is entries an array?
2123                         if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2124                                 // Search for the right array index
2125                                 $search = key(search_array($columns, 'column', $key));
2126
2127                                 // Add this entry to content
2128                                 $content[$key] = $entries[$id];
2129
2130                                 // Debug message
2131                                 //* BUG: */ die($key.'/'.$id.'/'.$search.'=<pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre>');
2132
2133                                 // Handle possible call-back functions and/or extra values
2134                                 $entries[$id] = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries[$id], $userIdColumn, $search);
2135
2136                                 // Add key/value pair to SQL string
2137                                 $sql .= addKeyValueSql($key, $entries[$id]);
2138                         } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2139                                 // Search for it
2140                                 $search = key(search_array($columns, 'column', $key));
2141                                 //* BUG: */ die($key.'/<pre>'.print_r($search, TRUE).'</pre>=<pre>'.print_r($columns, TRUE).'</pre>');
2142
2143                                 // Debug message
2144                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - BEFORE!');
2145
2146                                 // Add normal entries as well
2147                                 $content[$key] = $entries;
2148
2149                                 // Handle possible call-back functions and/or extra values
2150                                 $entries = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search);
2151
2152                                 // Debug message
2153                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - AFTER!');
2154
2155                                 // Add key/value pair to SQL string
2156                                 $sql .= addKeyValueSql($key, $entries);
2157                         }
2158                 } // END - foreach
2159
2160                 // Finish SQL command
2161                 $sql = substr($sql, 0, -1) . " WHERE `" . SQL_ESCAPE($idColumn[0]) . "`=" . bigintval($id);
2162                 if ((isset($rawUserId[0])) && (isPostRequestElementSet($rawUserId[0])) && (isset($userIdColumn[0]))) {
2163                         // Add user id as well
2164                         $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2165                 } // END - if
2166                 $sql .= " LIMIT 1";
2167
2168                 // Run this query
2169                 //* BUG: */ die($sql.'<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
2170                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2171
2172                 // Add affected rows
2173                 $edited = SQL_AFFECTEDROWS();
2174                 $affected += $edited;
2175
2176                 // Load all data from that id
2177                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2178                         array(
2179                                 $tableName[0],
2180                                 $idColumn[0],
2181                                 $id
2182                         ), __FUNCTION__, __LINE__);
2183
2184                 // Fetch the data and merge it into $content
2185                 $content = merge_array($content, SQL_FETCHARRAY($result));
2186
2187                 // Prepare filter data array
2188                 $filterData = array(
2189                         'mode'          => 'edit',
2190                         'table_name'    => $tableName,
2191                         'content'       => $content,
2192                         'id'            => $id,
2193                         'subject'       => $subject,
2194                         'userid_column' => $userIdColumn,
2195                         'raw_userid'    => $rawUserId,
2196                         'affected'      => $edited,
2197                         'sql'           => $sql,
2198                 );
2199
2200                 // Send "build mail" out
2201                 runFilterChain('send_build_mail', $filterData);
2202
2203                 // Free the result
2204                 SQL_FREERESULT($result);
2205         } // END - foreach
2206
2207         // Delete cache?
2208         if ((count($cacheFiles) > 0) && (!empty($cacheFiles[0]))) {
2209                 // Delete cache file(s)
2210                 foreach ($cacheFiles as $cache) {
2211                         // Skip any empty entries
2212                         if (empty($cache)) {
2213                                 // This may cause trouble in loadCacheFile()
2214                                 continue;
2215                         } // END - if
2216
2217                         // Is the cache file loadable?
2218                         if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2219                                 // Then remove it
2220                                 $GLOBALS['cache_instance']->removeCacheFile();
2221                         } // END - if
2222                 } // END - foreach
2223         } // END - if
2224
2225         // Return affected rows
2226         return $affected;
2227 }
2228
2229 // Delete rows by given id numbers
2230 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2231         // The base SQL command:
2232         $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2233
2234         // Is a user id provided?
2235         //* BUG: */ die('<pre>'.print_r($rawUserId,TRUE).'</pre><pre>'.print_r($userIdColumn,TRUE).'</pre>');
2236         if ((isset($rawUserId[0])) && (isPostRequestElementSet($rawUserId[0])) && (isset($userIdColumn[0]))) {
2237                 // Add user id as well
2238                 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2239         } // END - if
2240
2241         // $idColumn[0] in POST must be an array again
2242         if (!is_array(postRequestElement($idColumn[0]))) {
2243                 // This indicates that you have conflicting form field naming with XML names
2244                 reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
2245         } // END - if
2246
2247         // Delete them all
2248         //* BUG: */ die($sql.'<pre>'.print_r($tableName,TRUE).'</pre><pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre><pre>'.print_r($extraValues,TRUE).'</pre><pre>'.print_r($deleteNow,TRUE).'</pre><pre>'.print_r($idColumn,TRUE).'</pre>');
2249         $idList = '';
2250         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2251                 // Is id zero?
2252                 if ($id == '0') {
2253                         // Then skip this
2254                         continue;
2255                 } // END - if
2256
2257                 // Is there a userid?
2258                 if (isPostRequestElementSet($userIdColumn[0])) {
2259                         // Load all data from that id
2260                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2261                                 array(
2262                                         $tableName[0],
2263                                         $idColumn[0],
2264                                         $id
2265                                 ), __FUNCTION__, __LINE__);
2266
2267                         // Fetch the data
2268                         $content = SQL_FETCHARRAY($result);
2269
2270                         // Free the result
2271                         SQL_FREERESULT($result);
2272
2273                         // Send "build mails" out
2274                         sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2275                 } // END - if
2276
2277                 // Add id number
2278                 $idList .= $id . ',';
2279         } // END - foreach
2280
2281         // Run the query
2282         SQL_QUERY_ESC($sql,
2283                 array(
2284                         $tableName[0],
2285                         $idColumn[0],
2286                         convertNullToZero(substr($idList, 0, -1))
2287                 ), __FUNCTION__, __LINE__);
2288
2289         // Return affected rows
2290         return SQL_AFFECTEDROWS();
2291 }
2292
2293 // Build a special template list
2294 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
2295         // $tableName and $idColumn must bove be arrays!
2296         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2297                 // $tableName is no array
2298                 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2299         } elseif (!is_array($idColumn)) {
2300                 // $idColumn is no array
2301                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2302         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2303                 // $tableName is no array
2304                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2305         }
2306
2307         // Init row output
2308         $OUT = '';
2309
2310         // "Walk" through all entries
2311         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,TRUE).'</pre>,tableName<pre>'.print_r($tableName,TRUE).'</pre>,columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,idColumn=<pre>'.print_r($idColumn,TRUE).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,TRUE).'</pre>,rawUserId=<pre>'.print_r($rawUserId,TRUE).'</pre>');
2312         foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2313                 // Secure id number
2314                 $id = bigintval($id);
2315
2316                 // Get result from a given column array and table name
2317                 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2318
2319                 // Is there one entry?
2320                 if (SQL_NUMROWS($result) == 1) {
2321                         // Load all data
2322                         $content = SQL_FETCHARRAY($result);
2323
2324                         // Filter all data
2325                         foreach ($content as $key => $value) {
2326                                 // Search index
2327                                 $idx = searchXmlArray($key, $columns, 'column');
2328
2329                                 // Skip any missing entries
2330                                 if ($idx === FALSE) {
2331                                         // Skip this one
2332                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2333                                         continue;
2334                                 } // END - if
2335
2336                                 // Is there a userid?
2337                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2338                                 if ($key == $userIdColumn[0]) {
2339                                         // Add it again as raw id
2340                                         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2341                                         $content[$userIdColumn[0]] = convertZeroToNull($value);
2342                                         $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
2343                                 } // END - if
2344
2345                                 // If the key matches the idColumn variable, we need to temporary remember it
2346                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2347                                 if ($key == $idColumn[0]) {
2348                                         /*
2349                                          * Found, so remember it securely (to make sure only id
2350                                          * numbers can pass, don't use alpha-numerical values!)
2351                                          */
2352                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2353                                         $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2354                                 } // END - if
2355
2356                                 // Try to handle call-back functions and/or extra values
2357                                 $content[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $content[$key], $userIdColumn, $idx);
2358                         } // END - foreach
2359
2360                         // Then list it
2361                         $OUT .= loadTemplate(sprintf("%s_%s_%s_row",
2362                                 $prefix,
2363                                 $listType,
2364                                 $tableName[0]
2365                                 ), TRUE, $content
2366                         );
2367                 } // END - if
2368
2369                 // Free the result
2370                 SQL_FREERESULT($result);
2371         } // END - foreach
2372
2373         // Load master template
2374         loadTemplate(sprintf("%s_%s_%s",
2375                 $prefix,
2376                 $listType,
2377                 $tableName[0]
2378                 ), FALSE, $OUT
2379         );
2380 }
2381
2382 // Checks whether given URL is blacklisted
2383 function isUrlBlacklisted ($url) {
2384         // Mark it as not listed by default
2385         $listed = FALSE;
2386
2387         // Is black-listing enbaled?
2388         if (!isUrlBlacklistEnabled()) {
2389                 // No, then all URLs are not in this list
2390                 return FALSE;
2391         } elseif (!isset($GLOBALS['blacklist_data'][$url])) {
2392                 // Check black-list for given URL
2393                 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`timestamp`) AS `blist_timestamp` FROM `{?_MYSQL_PREFIX?}_url_blacklist` WHERE `url`='%s' LIMIT 1",
2394                         array($url), __FILE__, __LINE__);
2395
2396                 // Is there an entry?
2397                 if (SQL_NUMROWS($result) == 1) {
2398                         // Jupp, we got one listed
2399                         $GLOBALS['blacklist_data'][$url] = SQL_FETCHARRAY($result);
2400
2401                         // Mark it as listed
2402                         $listed = TRUE;
2403                 } // END - if
2404
2405                 // Free result
2406                 SQL_FREERESULT($result);
2407         } else {
2408                 // Is found in cache -> black-listed
2409                 $listed = TRUE;
2410         }
2411
2412         // Return result
2413         return $listed;
2414 }
2415
2416 // Adds key/value pair to a working SQL string together
2417 function addKeyValueSql ($key, $value) {
2418         // Init SQL
2419         $sql = '';
2420
2421         // Is it NULL?
2422         if (($value == 'NULL') || (is_null($value))) {
2423                 // Add key with NULL
2424                 $sql .= sprintf(' `%s`=NULL,',
2425                         SQL_ESCAPE($key)
2426                 );
2427         } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
2428                 // Is a number, so addd it directly
2429                 $sql .= sprintf(" `%s`=%s,",
2430                         SQL_ESCAPE($key),
2431                         $value
2432                 );
2433         } else {
2434                 // Else add the value escape'd
2435                 $sql .= sprintf(" `%s`='%s',",
2436                         SQL_ESCAPE($key),
2437                         SQL_ESCAPE($value)
2438                 );
2439         }
2440
2441         // Return SQL string
2442         return $sql;
2443 }
2444
2445 // [EOF]
2446 ?>