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