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