]> git.mxchange.org Git - mailer.git/blob - inc/mysql-manager.php
fetchUserData() does not accept NULL, please report any findings
[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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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         // Fix empty 'what'
47         if (empty($what)) {
48                 $what = getIndexHome();
49         } elseif ((isGetRequestParameterSet('action')) && ($column == 'what')) {
50                 // Get it from action
51                 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
52         } elseif ($what == 'overview') {
53                 // Overview page
54                 return '{--WHAT_IS_OVERVIEW--}';
55         }
56
57         // Default is not found
58         $data['title'] = '??? (' . $what . ')';
59
60         // Look for title
61         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
62                 array(
63                         $mode,
64                         $column,
65                         $what
66                 ), __FUNCTION__, __LINE__);
67
68         // Is there an entry?
69         if (SQL_NUMROWS($result) == 1) {
70                 // Fetch the title
71                 $data = SQL_FETCHARRAY($result);
72         } // END - if
73
74         // Free result
75         SQL_FREERESULT($result);
76
77         // Return it
78         return $data['title'];
79 }
80
81 // Add link into output stream (or return it) for 'You Are Here' navigation
82 function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
83         // Use only filename of the FQFN...
84         $file = basename($FQFN);
85
86         // Init variables
87         $LINK_ADD = '';
88         $OUT = '';
89         $ADD = '';
90         $prefix = '';
91
92         // First we have to do some analysis...
93         if (substr($file, 0, 7) == 'action-') {
94                 // This is an action file!
95                 $type = 'action';
96                 $search = substr($file, 7);
97
98                 // Get access level from it
99                 $modCheck = getModuleFromFileName($file, $accessLevel);
100
101                 // Add what
102                 $ADD = " AND (`what`='' OR `what` IS NULL)";
103         } elseif (substr($file, 0, 5) == 'what-') {
104                 // This is a 'what file'!
105                 $type = 'what';
106                 $search = substr($file, 5);
107
108                 // Get access level from it
109                 $modCheck = getModuleFromFileName($file, $accessLevel);
110
111                 // Do we have admin? Then display all
112                 $ADD = " AND `visible`='Y' AND `locked`='N'";
113                 if (isAdmin()) {
114                         // Display all!
115                         $ADD = '';
116                 } // END - if
117
118                 $dummy = substr($search, 0, -4);
119                 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
120         } elseif ($accessLevel == 'sponsor') {
121                 // Sponsor menu
122                 $type     = 'what';
123                 $search   = $file;
124                 $modCheck = getModule();
125                 $ADD      = '';
126         } else {
127                 // Other
128                 $type     = 'menu';
129                 $search   = $file;
130                 $modCheck = getModule();
131                 $ADD      = '';
132         }
133
134         // Begin the navigation line
135         if (!isset($GLOBALS['nav_depth'])) {
136                 // Init nav_depth
137                 $GLOBALS['nav_depth'] = '0';
138
139                 // Run the pre-filter chain
140                 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => '', 'add' => $ADD));
141
142                 // Add pre-content
143                 $prefix = $ret['content'];
144
145                 // Add default content
146                 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--}&nbsp;<strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $LINK_ADD . '%}">Home</a></strong>';
147         } elseif ($return === false) {
148                 // Count depth
149                 $GLOBALS['nav_depth']++;
150         }
151
152         $prefix .= '&nbsp;-&gt;&nbsp;';
153
154         // We need to remove .php and the end
155         if (substr($search, -4, 4) == '.php') {
156                 // Remove the .php
157                 $search = substr($search, 0, -4);
158         } // END - if
159
160         if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
161                 // Output HTML code
162                 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&amp;' . $type . '=' . $search . $LINK_ADD . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
163
164                 // Can we close the you-are-here navigation?
165                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . 'getWhat()=' . getWhat());
166                 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
167                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
168                         // Add closing div and br-tag
169                         $GLOBALS['nav_depth'] = '0';
170
171                         // Run the post-filter chain
172                         $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => $OUT, 'add' => $ADD));
173
174                         // Get content from filter back
175                         $OUT = $ret['content'];
176
177                         // Close div-tag, so not the filters have to do it
178                         $OUT .= '</div>';
179                 } // END - if
180         } // END - if
181
182         // Return or output HTML code?
183         if ($return === true) {
184                 // Return HTML code
185                 return $OUT;
186         } else {
187                 // Output HTML code here
188                 outputHtml($OUT);
189         }
190 }
191
192 // Adds a menu (mode = guest/member/admin/sponsor) to output
193 function addMenu ($mode, $action, $what) {
194         // Init some variables
195         $main_cnt = '0';
196
197         // is the menu action valid?
198         if (!isMenuActionValid($mode, $action, $what, true)) {
199                 return getCode('MENU_NOT_VALID');
200         } // END - if
201
202         // Non-admin shall not see all menus
203         $ADD = " AND `visible`='Y' AND `locked`='N'";
204         if (isAdmin()) {
205                 // Is admin, so make all visible
206                 $ADD = '';
207         } // END - if
208
209         // Load SQL data and add the menu to the output stream...
210         $result_main = SQL_QUERY_ESC("SELECT
211         `title`,`what`,`action`,`visible`,`locked`
212 FROM
213         `{?_MYSQL_PREFIX?}_%s_menu`
214 WHERE
215         (`what`='' OR `what` IS NULL)
216         ".$ADD."
217 ORDER BY
218         `sort` ASC",
219                 array($mode), __FUNCTION__, __LINE__);
220
221         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
222         if (!SQL_HASZERONUMS($result_main)) {
223                 // There are menus available, so we simply display them... :)
224                 $GLOBALS['rows'] = '';
225                 while ($content = SQL_FETCHARRAY($result_main)) {
226                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
227                         // Disable the block-mode
228                         enableBlockMode(false);
229
230                         // Load menu header template
231                         $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
232
233                         // Sub menu
234                         $result_sub = SQL_QUERY_ESC("SELECT
235         `title` AS `sub_title`,
236         `what` AS `sub_what`,
237         `visible` AS `sub_visible`,
238         `locked` AS `sub_locked`
239 FROM
240         `{?_MYSQL_PREFIX?}_%s_menu`
241 WHERE
242         `action`='%s' AND
243         `what` != '' AND
244         `what` IS NOT NULL
245         ".$ADD."
246 ORDER BY
247         `sort` ASC",
248                                 array($mode, $content['action']), __FUNCTION__, __LINE__);
249
250                         // Do we have some entries?
251                         if (!SQL_HASZERONUMS($result_sub)) {
252                                 // Init counter
253                                 $count = '0';
254
255                                 // Load all sub menus
256                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
257                                         // Merge both arrays in one
258                                         $content = merge_array($content, $content2);
259
260                                         // Init content
261                                         $OUT = '';
262
263                                         // Full file name for checking menu
264                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
265                                         $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
266                                         if (isIncludeReadable($inc)) {
267                                                 // Mark currently selected menu - open
268                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
269                                                         $OUT = '<strong>';
270                                                 } // END - if
271
272                                                 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
273                                                 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
274                                                         // Use index.php as link
275                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
276                                                 } else {
277                                                         // Regular navigation link
278                                                         $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&amp;what=' . $content['sub_what'] . '%}" target="_self">';
279                                                 }
280                                         } else {
281                                                 // Not found - open
282                                                 $OUT .= '<em style="cursor:help" class="notice" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
283                                         }
284
285                                         // Menu title
286                                         $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
287
288                                         if (isIncludeReadable($inc)) {
289                                                 $OUT .= '</a>';
290
291                                                 // Mark currently selected menu - close
292                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
293                                                         $OUT .= '</strong>';
294                                                 } // END - if
295                                         } else {
296                                                 // Not found - close
297                                                 $OUT .= '</em>';
298                                         }
299
300                                         // Cunt it up
301                                         $count++;
302
303                                         // Rewrite array
304                                         $content = array(
305                                                 'menu'    => $OUT,
306                                                 'what'    => $content['sub_what'],
307                                                 'visible' => $content['sub_visible'],
308                                                 'locked'  => $content['locked'],
309                                         );
310
311                                         // Add regular menu row or bottom row?
312                                         if ($count < SQL_NUMROWS($result_sub)) {
313                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
314                                         } else {
315                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
316                                         }
317                                 } // END - while
318                         } else {
319                                 // This is a menu block... ;-)
320                                 enableBlockMode();
321
322                                 // Load menu block
323                                 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
324                                 if (isFileReadable($INC)) {
325                                         // Load include file
326                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
327                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
328                                         loadInclude($INC);
329                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
330                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
331                                 }
332                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
333                         }
334
335                         // Free result
336                         SQL_FREERESULT($result_sub);
337
338                         // Count one up
339                         $main_cnt++;
340
341                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
342                         if (SQL_NUMROWS($result_main) > $main_cnt) {
343                                 // Add seperator
344                                 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
345
346                                 // Should we display adverts in this menu?
347                                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
348                                         // Display advert template
349                                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
350
351                                         // Add seperator again
352                                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
353                                 } // END - if
354                         } // END - if
355                 } // END - while
356
357                 // Free memory
358                 SQL_FREERESULT($result_main);
359
360                 // Should we display adverts in this menu?
361                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
362                         // Add seperator again
363                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
364
365                         // Display advert template
366                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
367                 } // END - if
368
369                 // Prepare data
370                 $content = array(
371                         'rows' => $GLOBALS['rows'],
372                         'mode' => $mode
373                 );
374
375                 // Load main template
376                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
377                 loadTemplate('menu_table', false, $content);
378         } // END - if
379 }
380
381 // Checks wether the current user is a member
382 function isMember () {
383         // By default no member
384         $ret = false;
385
386         // Fix missing 'last_online' array, damn stupid code :(((
387         // @TODO Try to rewrite this to one or more functions
388         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
389                 $GLOBALS['last_online'] = array();
390         } // END - if
391
392         // Is the cache entry there?
393         if (isset($GLOBALS[__FUNCTION__])) {
394                 // Then return it
395                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
396                 return $GLOBALS[__FUNCTION__];
397         } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
398                 // Destroy any existing user session data
399                 destroyMemberSession();
400                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
401
402                 // Abort further processing
403                 return false;
404         }
405
406         // Get userid secured from session
407         setMemberId(getSession('userid'));
408
409         // ... and set it as currently handled user id
410         setCurrentUserId(getMemberId());
411
412         // Init user data array
413         initUserData();
414
415         // Fix "deleted" cookies first
416         fixDeletedCookies(array('userid', 'u_hash'));
417
418         // Are cookies set and can the member data be loaded?
419         if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
420                 // Validate password by created the difference of it and the secret key
421                 $valPass = encodeHashForCookie(getUserData('password'));
422
423                 // So did we now have valid data and an unlocked user?
424                 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
425                         // Transfer last module and online time
426                         $GLOBALS['last_online']['module'] = getUserData('last_module');
427                         $GLOBALS['last_online']['online'] = getUserData('last_online');
428
429                         // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
430                         $ret = true;
431                 } // END - if
432         } // END - if
433
434         // Is $ret still false?
435         if ($ret === false) {
436                 // Yes, so destroy the session
437                 destroyMemberSession();
438         } // END - if
439
440         // Cache status
441         $GLOBALS[__FUNCTION__] = $ret;
442
443         // Return status
444         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
445         return $ret;
446 }
447
448 // Fetch user data for given user id
449 function fetchUserData ($value, $column = 'userid') {
450         // Extension ext-user must be there at any case
451         if (!isExtensionActive('user')) {
452                 // Absent ext-user is really not good
453                 return false;
454         } elseif (is_null($value)) {
455                 // This shall never happen, so please report it
456                 debug_report_bug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
457         }
458
459         // If we should look for userid secure&set it here
460         if (substr($column, -2, 2) == 'id') {
461                 // Secure userid
462                 $value = bigintval($value);
463
464                 // Set it here
465                 setCurrentUserId($value);
466
467                 // Don't look for invalid userids...
468                 if (!isValidUserId($value)) {
469                         // Invalid, so abort here
470                         debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
471                 } elseif (isUserDataValid()) {
472                         // Use cache, so it is fine
473                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
474                         return true;
475                 }
476         } elseif (isUserDataValid())  {
477                 // Using cache is fine
478                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
479                 return true;
480         }
481
482         // By default none was found
483         $found = false;
484
485         // Extra statements
486         $ADD = '';
487         if (isExtensionInstalledAndNewer('user', '0.3.5')) {
488                 $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
489         } // END - if
490
491         // Query for the user
492         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
493                 array($column, $value), __FUNCTION__, __LINE__);
494
495         // Do we have a record?
496         if (SQL_NUMROWS($result) == 1) {
497                 // Load data from cookies
498                 $data = SQL_FETCHARRAY($result);
499
500                 // Set the userid for later use
501                 setCurrentUserId($data['userid']);
502
503                 // And cache the data for this userid
504                 $GLOBALS['user_data'][getCurrentUserId()] = $data;
505
506                 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
507                 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
508                         // Backup the raw one and zero it
509                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
510                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
511
512                         // Is it not zero?
513                         if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
514                                 // Seperate data/time
515                                 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
516
517                                 // Seperate data and time again
518                                 $array['date'] = explode('-', $array[0]);
519                                 $array['time'] = explode(':', $array[1]);
520
521                                 // Now pass it to mktime()
522                                 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
523                                         $array['time'][0],
524                                         $array['time'][1],
525                                         $array['time'][2],
526                                         $array['date'][1],
527                                         $array['date'][2],
528                                         $array['date'][0]
529                                 );
530                         } // END - if
531                 } // END - if
532
533                 // Found, but valid?
534                 $found = isUserDataValid();
535         } // END - if
536
537         // Free memory
538         SQL_FREERESULT($result);
539
540         // Return result
541         return $found;
542 }
543
544 // This patched function will reduce many SELECT queries for the specified or current admin login
545 function isAdmin () {
546         // No admin in installation phase!
547         if ((isInstallationPhase()) || (!isAdminRegistered())) {
548                 return false;
549         } // END - if
550
551         // Init variables
552         $ret = false;
553         $adminId = '0';
554         $passCookie = '';
555         $valPass = '';
556         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
557
558         // If admin login is not given take current from cookies...
559         if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
560                 // Get admin login and password from session/cookies
561                 $adminId    = getCurrentAdminId();
562                 $passCookie = getAdminMd5();
563         } // END - if
564         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mainId=' . $adminId . 'passCookie=' . $passCookie);
565
566         // Abort if admin id is zero
567         if ($adminId == '0') {
568                 return false;
569         } // END - if
570
571         // Do we have cache?
572         if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
573                 // Init it with failed
574                 $GLOBALS[__FUNCTION__][$adminId] = false;
575
576                 // Search in array for entry
577                 if (isset($GLOBALS['admin_hash'])) {
578                         // Use cached string
579                         $valPass = $GLOBALS['admin_hash'];
580                 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
581                         // Login data is valid or not?
582                         $valPass = encodeHashForCookie(getAdminHash($adminId));
583
584                         // Cache it away
585                         $GLOBALS['admin_hash'] = $valPass;
586
587                         // Count cache hits
588                         incrementStatsEntry('cache_hits');
589                 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
590                         // Get admin hash and hash it
591                         $valPass = encodeHashForCookie(getAdminHash($adminId));
592
593                         // Cache it away
594                         $GLOBALS['admin_hash'] = $valPass;
595                 }
596
597                 if (!empty($valPass)) {
598                         // Check if password is valid
599                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
600                         $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
601                 } // END - if
602         } // END - if
603
604         // Return result of comparision
605         return $GLOBALS[__FUNCTION__][$adminId];
606 }
607
608 // Generates a list of "max receiveable emails per day"
609 function addMaxReceiveList ($mode, $default = '', $return = false) {
610         $OUT = '';
611         $result = false;
612
613         switch ($mode) {
614                 case 'guest':
615                         // Guests (in the registration form) are not allowed to select 0 mails per day.
616                         $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
617                         __FUNCTION__, __LINE__);
618                         break;
619
620                 case 'member':
621                         // Members are allowed to set to zero mails per day (we will change this soon!)
622                         $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
623                         __FUNCTION__, __LINE__);
624                         break;
625
626                 default: // Invalid!
627                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
628                         break;
629         }
630
631         // Some entries are found?
632         if (!SQL_HASZERONUMS($result)) {
633                 $OUT = '';
634                 while ($content = SQL_FETCHARRAY($result)) {
635                         $OUT .= '      <option value="' . $content['value'] . '"';
636                         if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
637                         $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
638                         if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
639                         $OUT .= '</option>';
640                 }
641
642                 // Load template
643                 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
644         } else {
645                 // Maybe the admin has to setup some maximum values?
646                 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
647         }
648
649         // Free result
650         SQL_FREERESULT($result);
651
652         if ($return === true) {
653                 // Return generated HTML code
654                 return $OUT;
655         } else {
656                 // Output directly (default)
657                 outputHtml($OUT);
658         }
659 }
660
661 // Checks wether the given email address is used.
662 function isEmailTaken ($email) {
663         // Replace dot with {DOT}
664         $email = str_replace('.', '{DOT}', $email);
665
666         // Query the database
667         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' LIMIT 1",
668                 array($email), __FUNCTION__, __LINE__);
669
670         // Is the email there?
671         $isTaken = (SQL_NUMROWS($result) == 1);
672
673         // Free the result
674         SQL_FREERESULT($result);
675
676         // Return result
677         return $isTaken;
678 }
679
680 // Validate the given menu action
681 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
682         // Is the cache entry there and we shall not update?
683         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
684                 // Count cache hit
685                 incrementStatsEntry('cache_hits');
686
687                 // Then use this cache
688                 return $GLOBALS['action_valid'][$mode][$action][$what];
689         } // END - if
690
691         // By default nothing is valid
692         $ret = false;
693
694         // Look in all menus or only unlocked
695         $add = '';
696         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
697
698         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
699         if (($mode != 'admin') && ($updateEntry === true)) {
700                 // Update guest or member menu
701                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
702                         array(
703                                 $mode,
704                                 $action,
705                                 $what
706                         ), __FUNCTION__, __LINE__, false);
707         } elseif (($what != 'overview') && (!empty($what))) {
708                 // Other actions
709                 $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",
710                         array(
711                                 $mode,
712                                 $action,
713                                 $what
714                         ), __FUNCTION__, __LINE__, false);
715         } else {
716                 // Admin login overview
717                 $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",
718                         array(
719                                 $mode,
720                                 $action
721                         ), __FUNCTION__, __LINE__, false);
722         }
723
724         // Run SQL command
725         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
726
727         // Should we look for affected rows (only update) or found rows?
728         if ($updateEntry === true) {
729                 // Check updated/affected rows
730                 $ret = (!SQL_HASZEROAFFECTED());
731         } else {
732                 // Check found rows
733                 $ret = (!SQL_HASZERONUMS($result));
734         }
735
736         // Free memory
737         SQL_FREERESULT($result);
738
739         // Set cache entry
740         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
741
742         // Return result
743         return $ret;
744 }
745
746 // Get action value from mode (admin/guest/member) and what-value
747 function getActionFromModuleWhat ($module, $what) {
748         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
749         // Init status
750         $data['action'] = '';
751
752         if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
753                 // sql_patches is missing so choose depending on mode
754                 if (isWhatSet()) {
755                         // Use setted what
756                         $what = getWhat();
757                 } elseif ($module == 'admin') {
758                         // Admin area
759                         $what = 'overview';
760                 } else {
761                         // Everywhere else
762                         $what = 'welcome';
763                 }
764         } elseif ((empty($what)) && ($module != 'admin')) {
765                 // Use configured 'home'
766                 $what = getIndexHome();
767         } // END - if
768
769         if ($module == 'admin') {
770                 // Action value for admin area
771                 if (isGetRequestParameterSet('action')) {
772                         // Use from request!
773                         return getRequestParameter('action');
774                 } elseif (isActionSet()) {
775                         // Get it directly from URL
776                         return getAction();
777                 } elseif (($what == 'overview') || (!isWhatSet())) {
778                         // Default value for admin area
779                         $data['action'] = 'login';
780                 }
781         } elseif (isActionSet()) {
782                 // Get it directly from URL
783                 return getAction();
784         }
785         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
786
787         // Does the module have a menu?
788         if (ifModuleHasMenu($module)) {
789                 // Rewriting modules to menu
790                 $module = mapModuleToTable($module);
791
792                 // Guest and member menu is 'main' as the default
793                 if (empty($data['action'])) $data['action'] = 'main';
794
795                 // Load from database
796                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
797                         array($module, $what), __FUNCTION__, __LINE__);
798                 if (SQL_NUMROWS($result) == 1) {
799                         // Load action value and pray that this one is the right you want... ;-)
800                         $data = SQL_FETCHARRAY($result);
801                 } // END - if
802
803                 // Free memory
804                 SQL_FREERESULT($result);
805         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
806                 // No sql_patches installed, but maybe we need to register an admin?
807                 if (isAdminRegistered()) {
808                         // Redirect to admin area
809                         redirectToUrl('admin.php');
810                 } // END - if
811         }
812
813         // Return action value
814         return $data['action'];
815 }
816
817 // Get category name back
818 function getCategory ($cid) {
819         // Default is not found
820         $data['cat'] = '{--_CATEGORY_404--}';
821
822         // Is the category id set?
823         if ($cid == '0') {
824                 // No category
825                 $data['cat'] = '{--_CATEGORY_NONE--}';
826         } elseif ($cid > 0) {
827                 // Lookup the category in database
828                 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
829                         array(bigintval($cid)), __FUNCTION__, __LINE__);
830                 if (SQL_NUMROWS($result) == 1) {
831                         // Category found... :-)
832                         $data = SQL_FETCHARRAY($result);
833                 } // END - if
834
835                 // Free result
836                 SQL_FREERESULT($result);
837         } // END - if
838
839         // Return result
840         return $data['cat'];
841 }
842
843 // Get a string of "mail title" and price back
844 function getPaymentTitlePrice ($pid, $full=false) {
845         // Default is not found
846         $ret = '{--_PAYMENT_404--}';
847
848         // Load payment data
849         $result = SQL_QUERY_ESC("SELECT `mail_title`,`price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
850                 array(bigintval($pid)), __FUNCTION__, __LINE__);
851
852         // Do we have an entry?
853         if (SQL_NUMROWS($result) == 1) {
854                 // Payment type found... :-)
855                 $data = SQL_FETCHARRAY($result);
856
857                 // Only title or also including price?
858                 if ($full === false) {
859                         $ret = $data['mail_title'];
860                 } else {
861                         $ret = $data['mail_title'] . ' / {%pipe,translateComma=' . $data['price'] . '%} {?POINTS?}';
862                 }
863         } // END - if
864
865         // Free result
866         SQL_FREERESULT($result);
867
868         // Return result
869         return $ret;
870 }
871
872 // Get (basicly) the price of given payment id
873 function getPaymentPoints ($pid, $lookFor = 'price') {
874         // Default value...
875         $data[$lookFor] = -1;
876
877         // Search for it in database
878         $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
879                 array($lookFor, $pid), __FUNCTION__, __LINE__);
880
881         // Is the entry there?
882         if (SQL_NUMROWS($result) == 1) {
883                 // Payment type found... :-)
884                 $data = SQL_FETCHARRAY($result);
885         } // END - if
886
887         // Free result
888         SQL_FREERESULT($result);
889
890         // Return value
891         return $data[$lookFor];
892 }
893
894 // Remove a receiver's id from $receivers and add a link for him to confirm
895 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = 0, $isBonusMail = false) {
896         // Default is not removed
897         $ret = 'failed';
898
899         // Is the userid valid?
900         if (isValidUserId($userid)) {
901                 // Remove entry from array
902                 unset($receivers[$key]);
903
904                 // Is there already a line for this user available?
905                 if ($stats_id > 0) {
906                         // Default is 'normal' mail
907                         $type = 'NORMAL';
908                         $rowName = 'stats_id';
909
910                         // Only when we got a real stats id continue searching for the entry
911                         if ($isBonusMail === true) {
912                                 $type = 'BONUS';
913                                 $rowName = 'bonus_id';
914                         } // END - if
915
916                         // Try to look the entry up
917                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
918                                 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
919
920                         // Was it *not* found?
921                         if (SQL_HASZERONUMS($result)) {
922                                 // So we add one!
923                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES ('%s','%s','%s')",
924                                         array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
925
926                                 // Update 'mails_sent' if sql_patches is updated
927                                 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
928                                         // Update the pool
929                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1",
930                                                 array(bigintval($pool_id)), __FUNCTION__, __LINE__);
931                                 } // END - if
932                                 $ret = 'done';
933                         } else {
934                                 // Already found
935                                 $ret = 'already';
936                         }
937
938                         // Free memory
939                         SQL_FREERESULT($result);
940                 } // END - if
941         } // END - if
942
943         // Return status for sending routine
944         return $ret;
945 }
946
947 // Calculate sum (default) or count records of given criteria
948 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
949         // Init count/sum
950         $data['res'] = '0';
951
952         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
953         if ((empty($search)) && ($search != '0')) {
954                 // Count or sum whole table?
955                 if ($countRows === true) {
956                         // Count whole table
957                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
958                                 array(
959                                         $lookFor,
960                                         $tableName
961                                 ), __FUNCTION__, __LINE__);
962                 } else {
963                         // Sum whole table
964                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`".$add,
965                                 array(
966                                         $lookFor,
967                                         $tableName
968                                 ), __FUNCTION__, __LINE__);
969                 }
970         } elseif (($countRows === true) || ($lookFor == 'userid')) {
971                 // Count rows
972                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
973                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'".$add,
974                         array(
975                                 $lookFor,
976                                 $tableName,
977                                 $whereStatement,
978                                 $mode,
979                                 $search
980                         ), __FUNCTION__, __LINE__);
981         } else {
982                 // Add all rows
983                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
984                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'".$add,
985                         array(
986                                 $lookFor,
987                                 $tableName,
988                                 $whereStatement,
989                                 $mode,
990                                 $search
991                         ), __FUNCTION__, __LINE__);
992         }
993
994         // Load row
995         $data = SQL_FETCHARRAY($result);
996
997         // Free result
998         SQL_FREERESULT($result);
999
1000         // Fix empty values
1001         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1002                 // Float number
1003                 $data['res'] = '0.00000';
1004         } elseif (''.$data['res'].'' == '') {
1005                 // Fix empty result
1006                 $data['res'] = '0';
1007         }
1008
1009         // Return value
1010         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1011         return $data['res'];
1012 }
1013
1014 // Sends out mail to all administrators. This function is no longer obsolete
1015 // because we need it when there is no ext-admins installed
1016 function sendAdminEmails ($subj, $message) {
1017         // Load all admin email addresses
1018         $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1019         while ($content = SQL_FETCHARRAY($result)) {
1020                 // Send the email out
1021                 sendEmail($content['email'], $subj, $message);
1022         } // END - if
1023
1024         // Free result
1025         SQL_FREERESULT($result);
1026
1027         // Really simple... ;-)
1028 }
1029
1030 // Get id number from administrator's login name
1031 function getAdminId ($adminLogin) {
1032         // By default no admin is found
1033         $data['id'] = -1;
1034
1035         // Check cache
1036         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1037                 // Use it if found to save SQL queries
1038                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1039
1040                 // Update cache hits
1041                 incrementStatsEntry('cache_hits');
1042         } elseif (!isExtensionActive('cache')) {
1043                 // Load from database
1044                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1045                         array($adminLogin), __FUNCTION__, __LINE__);
1046
1047                 // Do we have an entry?
1048                 if (SQL_NUMROWS($result) == 1) {
1049                         // Get it
1050                         $data = SQL_FETCHARRAY($result);
1051                 } // END - if
1052
1053                 // Free result
1054                 SQL_FREERESULT($result);
1055         }
1056
1057         // Return the id
1058         return $data['id'];
1059 }
1060
1061 // "Getter" for current admin id
1062 function getCurrentAdminId () {
1063         // Log debug message
1064         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1065
1066         // Do we have cache?
1067         if (!isset($GLOBALS['current_admin_id'])) {
1068                 // Get the admin login from session
1069                 $adminId = getSession('admin_id');
1070
1071                 // Remember in cache securely
1072                 setCurrentAdminId(bigintval($adminId));
1073         } // END - if
1074
1075         // Return it
1076         return $GLOBALS['current_admin_id'];
1077 }
1078
1079 // Setter for current admin id
1080 function setCurrentAdminId ($currentAdminId) {
1081         // Set it secured
1082         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1083 }
1084
1085 // Get password hash from administrator's login name
1086 function getAdminHash ($adminId) {
1087         // By default an invalid hash is returned
1088         $data['password'] = -1;
1089
1090         if (isAdminHashSet($adminId)) {
1091                 // Check cache
1092                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1093
1094                 // Update cache hits
1095                 incrementStatsEntry('cache_hits');
1096         } elseif (!isExtensionActive('cache')) {
1097                 // Load from database
1098                 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1099                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1100
1101                 // Do we have an entry?
1102                 if (SQL_NUMROWS($result) == 1) {
1103                         // Fetch data
1104                         $data = SQL_FETCHARRAY($result);
1105
1106                         // Set cache
1107                         setAdminHash($adminId, $data['password']);
1108                 } // END - if
1109
1110                 // Free result
1111                 SQL_FREERESULT($result);
1112         }
1113
1114         // Return password hash
1115         return $data['password'];
1116 }
1117
1118 // "Getter" for admin login
1119 function getAdminLogin ($adminId) {
1120         // By default a non-existent login is returned (other functions react on this!)
1121         $data['login'] = '***';
1122
1123         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1124                 // Get cache
1125                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1126
1127                 // Update cache hits
1128                 incrementStatsEntry('cache_hits');
1129         } elseif (!isExtensionActive('cache')) {
1130                 // Load from database
1131                 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1132                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1133
1134                 // Entry found?
1135                 if (SQL_NUMROWS($result) == 1) {
1136                         // Fetch data
1137                         $data = SQL_FETCHARRAY($result);
1138
1139                         // Set cache
1140                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1141                 } // END - if
1142
1143                 // Free memory
1144                 SQL_FREERESULT($result);
1145         }
1146
1147         // Return the result
1148         return $data['login'];
1149 }
1150
1151 // Get email address of admin id
1152 function getAdminEmail ($adminId) {
1153         // By default an invalid emails is returned
1154         $data['email'] = '***';
1155
1156         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1157                 // Get cache
1158                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1159
1160                 // Update cache hits
1161                 incrementStatsEntry('cache_hits');
1162         } elseif (!isExtensionActive('cache')) {
1163                 // Load from database
1164                 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1165                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1166
1167                 // Entry found?
1168                 if (SQL_NUMROWS($result_admin_id) == 1) {
1169                         // Get data
1170                         $data = SQL_FETCHARRAY($result_admin_id);
1171
1172                         // Set cache
1173                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1174                 } // END - if
1175
1176                 // Free result
1177                 SQL_FREERESULT($result_admin_id);
1178         }
1179
1180         // Return email
1181         return $data['email'];
1182 }
1183
1184 // Get default ACL  of admin id
1185 function getAdminDefaultAcl ($adminId) {
1186         // By default an invalid ACL value is returned
1187         $data['default_acl'] = 'NO-ACL';
1188
1189         // Is sql_patches there and was it found in cache?
1190         if (!isExtensionActive('sql_patches')) {
1191                 // Not found, which is bad, so we need to allow all
1192                 $data['default_acl'] =  'allow';
1193         } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1194                 // Use cache
1195                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1196
1197                 // Update cache hits
1198                 incrementStatsEntry('cache_hits');
1199         } elseif (!isExtensionActive('cache')) {
1200                 // Load from database
1201                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1202                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1203
1204                 // Do we have an entry?
1205                 if (SQL_NUMROWS($result_admin_id) == 1) {
1206                         // Fetch data
1207                         $data = SQL_FETCHARRAY($result_admin_id);
1208
1209                         // Set cache
1210                         $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1211                 }
1212
1213                 // Free result
1214                 SQL_FREERESULT($result_admin_id);
1215         }
1216
1217         // Return default ACL
1218         return $data['default_acl'];
1219 }
1220
1221 // Generates an option list from various parameters
1222 function generateOptionList ($table, $id, $name, $default = '', $special = '', $where = '', $disabled = array(), $callback = '') {
1223         $ret = '';
1224         if ($table == '/ARRAY/') {
1225                 // Selection from array
1226                 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1227                         // Both are arrays
1228                         foreach ($id as $idx => $value) {
1229                                 $ret .= '<option value="' . $value . '"';
1230                                 if ($default == $value) {
1231                                         // Selected by default
1232                                         $ret .= ' selected="selected"';
1233                                 } elseif (isset($disabled[$value])) {
1234                                         // Disabled!
1235                                         $ret .= ' disabled="disabled"';
1236                                 }
1237
1238                                 // Is the call-back function set?
1239                                 if (!empty($callback)) {
1240                                         // Call it
1241                                         $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1242                                 } // END - if
1243
1244                                 // Finish option tag
1245                                 $ret .= '>' . $name[$idx] . '</option>';
1246                         } // END - foreach
1247                 } else {
1248                         // Problem in request
1249                         debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1250                 }
1251         } else {
1252                 // Data from database
1253                 $SPEC = ', `' . $id . '`';
1254                 if (!empty($special)) {
1255                         $SPEC = ', `' . $special . '`';
1256                 } // END - if
1257
1258                 // Query the database
1259                 $result = SQL_QUERY_ESC("SELECT `%s`,`%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1260                         array(
1261                                 $id,
1262                                 $name,
1263                                 $table,
1264                                 $name
1265                         ), __FUNCTION__, __LINE__);
1266
1267                 // Do we have rows?
1268                 if (!SQL_HASZERONUMS($result)) {
1269                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1270                         // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1271                         while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1272                                 if (empty($special)) $add = '';
1273                                 $ret .= '<option value="' . $value . '"';
1274                                 if ($default == $value) {
1275                                         // Selected by default
1276                                         $ret .= ' selected="selected"';
1277                                 } elseif (isset($disabled[$value])) {
1278                                         // Disabled!
1279                                         $ret .= ' disabled="disabled"';
1280                                 }
1281
1282                                 // Add it, if set
1283                                 if (!empty($add)) {
1284                                         $add = ' ('.$add.')';
1285                                 } // END - if
1286
1287                                 // Is the call-back function set?
1288                                 if (!empty($callback)) {
1289                                         // Call it
1290                                         $title = call_user_func_array($callback, array($title));
1291                                 } // END - if
1292
1293                                 // Finish option list
1294                                 $ret .= '>' . $title . $add . '</option>';
1295                         } // END - while
1296                 } else {
1297                         // No data found
1298                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1299                 }
1300
1301                 // Free memory
1302                 SQL_FREERESULT($result);
1303         }
1304
1305         // Return - hopefully - the requested data
1306         return $ret;
1307 }
1308
1309 // Deletes a user account with given reason
1310 function deleteUserAccount ($userid, $reason) {
1311         // Init points
1312         $data['points'] = '0';
1313
1314         // Search for the points and user data
1315         $result = SQL_QUERY_ESC("SELECT
1316         (SUM(p.`points`) - d.`used_points`) AS `points`
1317 FROM
1318         `{?_MYSQL_PREFIX?}_user_points` AS p
1319 LEFT JOIN
1320         `{?_MYSQL_PREFIX?}_user_data` AS d
1321 ON
1322         p.`userid`=d.`userid`
1323 WHERE
1324         p.`userid`=%s
1325 LIMIT 1",
1326                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1327
1328         // Do we have an entry?
1329         if (SQL_NUMROWS($result) == 1) {
1330                 // Save his points to add them to the jackpot
1331                 $data = SQL_FETCHARRAY($result);
1332
1333                 // Delete points entries as well
1334                 // @TODO Rewrite these lines to a filter
1335                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1336                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1337
1338                 // Update mediadata as well
1339                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1340                         // Update database
1341                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1342                 } // END - if
1343
1344                 // Now, when we have all his points adds them do the jackpot!
1345                 if (isExtensionActive('jackpot')) {
1346                         addPointsToJackpot($data['points']);
1347                 } // END - if
1348         } // END - if
1349
1350         // Free the result
1351         SQL_FREERESULT($result);
1352
1353         // Delete category selections as well...
1354         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1355                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1356
1357         // Remove from rallye if found
1358         // @TODO Rewrite this to a filter
1359         if (isExtensionActive('rallye')) {
1360                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1361                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1362         } // END - if
1363
1364         // Add reason and translate points
1365         $data['text']   = $reason;
1366
1367         // Now a mail to the user and that's all...
1368         $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1369         sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1370
1371         // Ok, delete the account!
1372         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1373 }
1374
1375 // Gets the matching what name from module
1376 function getWhatFromModule ($modCheck) {
1377         // Is the request element set?
1378         if (isGetRequestParameterSet('what')) {
1379                 // Then return this!
1380                 return getRequestParameter('what');
1381         } // END - if
1382
1383         // Default is empty
1384         $what = '';
1385
1386         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1387         switch ($modCheck) {
1388                 case 'admin':
1389                         $what = 'overview';
1390                         break;
1391
1392                 case 'login':
1393                 case 'index':
1394                         // Is ext-sql_patches installed and newer than 0.0.5?
1395                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1396                                 // Use it from config
1397                                 $what = getIndexHome();
1398                         } else {
1399                                 // Use default 'welcome'
1400                                 $what = 'welcome';
1401                         }
1402                         break;
1403
1404                 default:
1405                         $what = '';
1406                         break;
1407         } // END - switch
1408
1409         // Return what value
1410         return $what;
1411 }
1412
1413 // Returns HTML code with an option list of all categories
1414 function generateCategoryOptionsList ($mode) {
1415         // Prepare WHERE statement
1416         $whereStatement = " WHERE `visible`='Y'";
1417         if (isAdmin()) $whereStatement = '';
1418
1419         // Initialize array...
1420         $CATS = array(
1421                 'id'   => array(),
1422                 'name' => array(),
1423                 'userids' => array()
1424         );
1425
1426         // Get categories
1427         $result = SQL_QUERY('SELECT `id`,`cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1428                 __FUNCTION__, __LINE__);
1429
1430         // Do we have entries?
1431         if (!SQL_HASZERONUMS($result)) {
1432                 // ... and begin loading stuff
1433                 while ($content = SQL_FETCHARRAY($result)) {
1434                         // Transfer some data
1435                         $CATS['id'][]   = $content['id'];
1436                         $CATS['name'][] = $content['cat'];
1437
1438                         // Check which users are in this category
1439                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1440                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1441
1442                         // Init count
1443                         $userid_cnt = '0';
1444
1445                         // Start adding all
1446                         while ($data = SQL_FETCHARRAY($result_userids)) {
1447                                 // Add user count
1448                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1449                         } // END - while
1450
1451                         // Free memory
1452                         SQL_FREERESULT($result_userids);
1453
1454                         // Add counter
1455                         $CATS['userids'][] = $userid_cnt;
1456                 } // END - while
1457
1458                 // Free memory
1459                 SQL_FREERESULT($result);
1460
1461                 // Generate options
1462                 $OUT = '';
1463                 foreach ($CATS['id'] as $key => $value) {
1464                         if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1465                         $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1466                 } // END - foreach
1467         } else {
1468                 // No cateogries are defined yet
1469                 $OUT = '<option class="notice">{--MEMBER_NO_CATEGORIES--}</option>';
1470         }
1471
1472         // Return HTML code
1473         return $OUT;
1474 }
1475
1476 // Add bonus mail to queue
1477 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1478         // Is admin or bonus extension there?
1479         if (!isAdmin()) {
1480                 // Abort here
1481                 return false;
1482         } elseif (!isExtensionActive('bonus')) {
1483                 // Abort here
1484                 return false;
1485         }
1486
1487         // Calculcate target sent
1488         $target = countSelection(explode(';', $receiverList));
1489
1490         // Receiver is zero?
1491         if ($receiver == '0') {
1492                 // Then auto-fix it
1493                 $receiver = $target;
1494         } // END - if
1495
1496         // HTML extension active?
1497         if (isExtensionActive('html_mail')) {
1498                 // Determine if we have HTML mode active
1499                 $HTML = convertBooleanToYesNo($mode == 'html');
1500
1501                 // Add HTML mail
1502                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1503 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`,`html_msg`)
1504 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s,'%s')",
1505                 array(
1506                         $subject,
1507                         $text,
1508                         $receiverList,
1509                         $points,
1510                         bigintval($seconds),
1511                         $url,
1512                         bigintval($categoryId),
1513                         $target,
1514                         bigintval($receiver),
1515                         $HTML
1516                 ), __FUNCTION__, __LINE__);
1517         } else {
1518                 // Add regular mail
1519                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1520 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`)
1521 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s)",
1522                 array(
1523                         $subject,
1524                         $text,
1525                         $receiverList,
1526                         $points,
1527                         bigintval($seconds),
1528                         $url,
1529                         bigintval($categoryId),
1530                         $target,
1531                         bigintval($receiver),
1532                 ), __FUNCTION__, __LINE__);
1533         }
1534 }
1535
1536 // Generate a receiver list for given category and maximum receivers
1537 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1538         // Init variables
1539         $CAT_TABS     = '';
1540         $CAT_WHERE    = '';
1541         $receiverList = '';
1542         $result       = false;
1543
1544         // Secure data
1545         $categoryId = bigintval($categoryId);
1546         $receiver   = bigintval($receiver);
1547
1548         // Is the receiver zero and mode set?
1549         if (($receiver == '0') && (!empty($mode))) {
1550                 // Auto-fix receiver maximum
1551                 $receiver = getTotalReceivers($mode);
1552         } // END - if
1553
1554         // Category given?
1555         if ($categoryId > 0) {
1556                 // Select category
1557                 $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1558                 $CAT_WHERE = sprintf(" AND c.`cat_id`=%s", $categoryId);
1559         } // END - if
1560
1561         // Exclude users in holiday?
1562         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1563                 // Add something for the holiday extension
1564                 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1565         } // END - if
1566
1567         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1568                 // Only include HTML receivers
1569                 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1570                         array(
1571                                 $receiver
1572                         ), __FUNCTION__, __LINE__);
1573         } else {
1574                 // Include all
1575                 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1576                         array(
1577                                 $receiver
1578                         ), __FUNCTION__, __LINE__);
1579         }
1580
1581         // Entries found?
1582         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1583                 // Load all entries
1584                 while ($content = SQL_FETCHARRAY($result)) {
1585                         // Add receiver when not empty
1586                         if (!empty($content['userid'])) {
1587                                 $receiverList .= $content['userid'] . ';';
1588                         } // END - if
1589                 } // END - while
1590
1591                 // Free memory
1592                 SQL_FREERESULT($result);
1593
1594                 // Remove trailing semicolon
1595                 $receiverList = substr($receiverList, 0, -1);
1596         } // END - if
1597
1598         // Return list
1599         return $receiverList;
1600 }
1601
1602 // Recuce the amount of received emails for the receipients for given email
1603 function reduceRecipientReceivedMails ($column, $id, $count) {
1604         // Search for mail in database
1605         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1606                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1607
1608         // Are there entries?
1609         if (!SQL_HASZERONUMS($result)) {
1610                 // Now load all userids for one big query!
1611                 $userids = array();
1612                 while ($data = SQL_FETCHARRAY($result)) {
1613                         // By default we want to reduce and have no mails found
1614                         $num = 0;
1615
1616                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1617                         // @TODO Rewrite this to a filter
1618                         if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1619                                 // User email
1620                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1621                         } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1622                                 // Bonus mail
1623                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1624                         }
1625
1626                         // Reduce this users total received emails?
1627                         if ($num === 0) {
1628                                 $userids[$data['userid']] = $data['userid'];
1629                         } // END - if
1630                 } // END - while
1631
1632                 if (count($userids) > 0) {
1633                         // Now update all user accounts
1634                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1635                                 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1636                 } else {
1637                         // Nothing deleted
1638                         displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1639                 }
1640         } // END - if
1641
1642         // Free result
1643         SQL_FREERESULT($result);
1644 }
1645
1646 // Creates a new task
1647 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = '0', $strip = true) {
1648         // Insert the task data into the database
1649         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())",
1650                 array(
1651                         $adminId,
1652                         $userid,
1653                         $taskType,
1654                         $subject,
1655                         $notes
1656                 ), __FUNCTION__, __LINE__, true, $strip);
1657
1658         // Return insert id which is the task id
1659         return SQL_INSERTID();
1660 }
1661
1662 // Updates last module / online time
1663 // @TODO Fix inconsistency between last_module and getWhat()
1664 function updateLastActivity($userid) {
1665         // Run the update query
1666         SQL_QUERY_ESC("UPDATE
1667         `{?_MYSQL_PREFIX?}_user_data`
1668 SET
1669         `last_module`='%s',
1670         `last_online`=UNIX_TIMESTAMP(),
1671         `REMOTE_ADDR`='%s'
1672 WHERE
1673         `userid`=%s
1674 LIMIT 1",
1675                 array(
1676                         getWhat(),
1677                         detectRemoteAddr(),
1678                         bigintval($userid)
1679                 ), __FUNCTION__, __LINE__);
1680 }
1681
1682 // [EOF]
1683 ?>