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