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