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