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