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