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