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