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