debug_report_bug() should be used as a replacement for app_die() calls
[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 MySQL-related functions                      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle MySQL-Relevanten Funktionen                 *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // "Getter" for module title
46 function getModuleTitle ($module) {
47         // Init variables
48         $data['title'] = '';
49         $result = false;
50
51         // Is the script installed?
52         if (isInstalled()) {
53                 // Check if cache is valid
54                 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($module, $GLOBALS['cache_array']['modules']['module']))) {
55                         // Load from cache
56                         $data['title'] = $GLOBALS['cache_array']['modules']['title'][$module];
57
58                         // Update cache hits
59                         incrementStatsEntry('cache_hits');
60                 } elseif (!isExtensionActive('cache')) {
61                         // Load from database
62                         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
63                                 array($module), __FUNCTION__, __LINE__);
64
65                         // Is the entry there?
66                         if (SQL_NUMROWS($result)) {
67                                 // Get the title from database
68                                 $data = SQL_FETCHARRAY($result);
69                         } // END - if
70
71                         // Free the result
72                         SQL_FREERESULT($result);
73                 }
74         } // END - if
75
76         // Trim name
77         $data['title'] = trim($data['title']);
78
79         // Still no luck or empty title?
80         if (empty($data['title'])) {
81                 // No name found
82                 $data['title'] = getMaskedMessage('UNKNOWN_MODULE_DETECTED', $module);
83                 if ((is_resource($result)) && (SQL_HASZERONUMS($result))) {
84                         // Add module to database
85                         $dummy = checkModulePermissions($module);
86                 } // END - if
87         } // END - if
88
89         // Return name
90         return $data['title'];
91 }
92
93 // "Getter" for module description
94 // @TODO Can we cache this?
95 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
96         // Fix empty 'what'
97         if (empty($what)) {
98                 $what = getConfig('index_home');
99         } // END - if
100
101         // Default is not found
102         $data['title'] = '??? (' . $what . ')';
103
104         // Look for title
105         $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
106                 array(
107                         $mode,
108                         $column,
109                         $what
110                 ), __FUNCTION__, __LINE__);
111
112         // Is there an entry?
113         if (SQL_NUMROWS($result) == 1) {
114                 // Fetch the title
115                 $data = SQL_FETCHARRAY($result);
116         } // END - if
117
118         // Free result
119         SQL_FREERESULT($result);
120
121         // Return it
122         return $data['title'];
123 }
124
125 // Check validity of a given module name (no file extension)
126 function checkModulePermissions ($module = '') {
127         // Is it empty (default), then take the current one
128         if (empty($module)) $module = getModule();
129
130         // Do we have cache?
131         if (isset($GLOBALS['module_status'][$module])) {
132                 // Then use it
133                 return $GLOBALS['module_status'][$module];
134         } // END - if
135
136         // Filter module name (names with low chars and underlines are fine!)
137         $module = preg_replace('/[^a-z_]/', '', $module);
138
139         // Check for prefix is a extension...
140         $modSplit = explode('_', $module);
141         $extension = ''; $module_chk = $module;
142         //* DEBUG: */ print(__LINE__."*".count($modSplit)."*/".$module."*<br />");
143         if (count($modSplit) == 2) {
144                 // Okay, there is a seperator (_) in the name so is the first part a module?
145                 //* DEBUG: */ print(__LINE__."*".$modSplit[0]."*<br />");
146                 if (isExtensionActive($modSplit[0])) {
147                         // The prefix is an extension's name, so let's set it
148                         $extension = $modSplit[0]; $module = $modSplit[1];
149                 } // END - if
150         } // END - if
151
152         // Major error in module registry is the default
153         $ret = 'major';
154
155         // Check if script is installed if not return a 'done' to prevent some errors
156         if ((isInstallationPhase()) || (!isAdminRegistered())) {
157                 // Not installed or no admin registered or in installation phase
158                 return 'done';
159         } // END - if
160
161         // Init data array
162         $data = array(
163                 'locked'     => 'Y',
164                 'hidden'     => 'N',
165                 'admin_only' => 'N',
166                 'mem_only'   => 'N'
167         );
168
169         // By default nothing is found
170         $found  = false;
171
172         // Check if cache is latest version
173         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
174                 // Is the cache there?
175                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
176                 if (isset($GLOBALS['cache_array']['modules']['locked'][$module_chk])) {
177                         // Check cache
178                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache found.');
179                         $data['locked']     = $GLOBALS['cache_array']['modules']['locked'][$module_chk];
180                         $data['hidden']     = $GLOBALS['cache_array']['modules']['hidden'][$module_chk];
181                         $data['admin_only'] = $GLOBALS['cache_array']['modules']['admin_only'][$module_chk];
182                         $data['mem_only']   = $GLOBALS['cache_array']['modules']['mem_only'][$module_chk];
183
184                         // Update cache hits
185                         incrementStatsEntry('cache_hits');
186                         $found = true;
187                 } else {
188                         // No, then we have to update it!
189                         $ret = 'cache_miss';
190                 }
191         } elseif (!isExtensionActive('cache')) {
192                 // Check for module in database
193                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
194                 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
195                         array($module_chk), __FUNCTION__, __LINE__);
196                 if (SQL_NUMROWS($result) == 1) {
197                         // Read data
198                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Entry found.');
199                         $data = SQL_FETCHARRAY($result);
200                         $found = true;
201                 } elseif (isDebugModeEnabled()) {
202                         // Debug message only in debug-mode...
203                         logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $module_chk . ' not found!');
204                 }
205
206                 // Free result
207                 SQL_FREERESULT($result);
208         }
209         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
210
211         // Is the module found?
212         if ($found === true) {
213                 // Check returned values against current access permissions
214                 //
215                 //  Admin access                   ----- Guest access -----                                     --- Guest   or   member? ---
216                 if ((isAdmin()) || (($data['locked'] != 'Y') && ($data['admin_only'] != 'Y') && (($data['mem_only'] != 'Y') || (isMember())))) {
217                         // If you are admin you are welcome for everything!
218                         $ret = 'done';
219                 } elseif ($data['locked'] == 'Y') {
220                         // Module is locked
221                         $ret = 'locked';
222                 } elseif (($data['mem_only'] == 'Y') && (!isMember())) {
223                         // You have to login first!
224                         $ret = 'mem_only';
225                 } elseif (($data['admin_only'] == 'Y') && (!isAdmin())) {
226                         // Only the Admin is allowed to enter this module!
227                         $ret = 'admin_only';
228                 } else {
229                         // @TODO Nothing helped???
230                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
231                                 $ret,
232                                 $data['locked'],
233                                 $data['admin_only'],
234                                 $data['mem_only']
235                         ));
236                 }
237         } // END - if
238
239         // Still no luck or not found?
240         if (($found === false) && (!isExtensionActive('cache')) && ($ret != 'done'))  {
241                 //              ----- Legacy module -----                                               ---- Module in base folder  ----                       --- Module with extension's name ---
242                 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $module))) || (isIncludeReadable(sprintf("%s.php", $module))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $module)))) {
243                         // Data is missing so we add it
244                         if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
245                                 // Since 0.3.6 we have a has_menu column, this took me a half hour
246                                 // to find a loop here... *sigh*
247                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
248 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
249 ('%s','Y','N','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
250                         } else {
251                                 // Wrong/missing sql_patches!
252                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
253 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
254 ('%s','Y','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
255                         }
256
257                         // Everthing is fine?
258                         if (SQL_AFFECTEDROWS() < 1) {
259                                 // Something bad happend!
260                                 return 'major';
261                         } // END - if
262
263                         // Destroy cache here
264                         // @TODO Rewrite this to a filter
265                         if ((getOutputMode() == '0') || (getOutputMode() == -1)) rebuildCache('modules', 'modules');
266
267                         // And reload data
268                         unset($GLOBALS['module_status'][$module]);
269                         $ret = checkModulePermissions($module_chk);
270                 } else {
271                         // Module not found we don't add it to the database
272                         $ret = '404';
273                 }
274         } elseif (($ret == 'cache_miss') && (getOutputMode() == '0')) {
275                 // Rebuild the cache files
276                 rebuildCache('modules', 'modules');
277         } elseif ($found === false) {
278                 // Problem with module detected
279                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s",
280                         $module,
281                         $ret,
282                         $data['locked'],
283                         $data['hidden'],
284                         $data['mem_only'],
285                         $data['admin_only'],
286                         getOutputMode()
287                 ));
288         }
289
290         // Return the value
291         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
292         $GLOBALS['module_status'][$module] = $ret;
293         return $ret;
294 }
295
296 // Add menu description pending on given file name (without path!)
297 function addMenuDescription ($accessLevel, $FQFN, $return = false) {
298         // Use only filename of the FQFN...
299         $file = basename($FQFN);
300
301         // Init variables
302         $LINK_ADD = '';
303         $OUT = '';
304         $ADD = '';
305
306         // First we have to do some analysis...
307         if (substr($file, 0, 7) == 'action-') {
308                 // This is an action file!
309                 $type = 'action';
310                 $search = substr($file, 7);
311
312                 // Get access level from it
313                 $modCheck = getModuleFromFileName($file, $accessLevel);
314
315                 // Add what
316                 $ADD = " AND (`what`='' OR `what` IS NULL)";
317         } elseif (substr($file, 0, 5) == 'what-') {
318                 // This is a 'what file'!
319                 $type = 'what';
320                 $search = substr($file, 5);
321                 $ADD = " AND `visible`='Y' AND `locked`='N'";
322
323                 // Get access level from it
324                 $modCheck = getModuleFromFileName($file, $accessLevel);
325
326                 // Do we have admin? Then display all
327                 if (isAdmin()) $ADD = '';
328
329                 $dummy = substr($search, 0, -4);
330                 $ADD .= " AND `action`='".getActionFromModuleWhat($accessLevel, $dummy)."'";
331         } elseif (($accessLevel == 'sponsor') || ($accessLevel == 'engine')) {
332                 // Sponsor / engine menu
333                 $type     = 'what';
334                 $search   = $file;
335                 $modCheck = getModule();
336                 $ADD      = '';
337         } else {
338                 // Other
339                 $type     = 'menu';
340                 $search   = $file;
341                 $modCheck = getModule();
342                 $ADD      = '';
343         }
344
345         // Begin the navigation line
346         if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
347                 $GLOBALS['nav_depth'] = '0';
348                 $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>';
349         } else {
350                 if ($return === false) $GLOBALS['nav_depth']++;
351                 $prefix = '';
352         }
353
354         $prefix .= '&nbsp;-&gt;&nbsp;';
355
356         // We need to remove .php and the end
357         if (substr($search, -4, 4) == '.php') {
358                 // Remove the .php
359                 $search = substr($search, 0, -4);
360         } // END - i
361
362         if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
363                 // Output HTML code
364                 $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>';
365
366                 // Can we close the you-are-here navigation?
367                 //* DEBUG: */ print(__LINE__."*".$type.'/'.getWhat()."*<br />");
368                 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
369                         //* DEBUG: */ print(__LINE__.'+'.$type."+<br />");
370                         // Add closing div and br-tag
371                         $OUT .= '</div><br />';
372                         $GLOBALS['nav_depth'] = '0';
373
374                         // Run the filter chain
375                         $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
376
377                         // Add additional content
378                         $OUT .= $ret['content'];
379                 } // END - if
380         }
381
382         // Return or output HTML code?
383         if ($return === true) {
384                 // Return HTML code
385                 return $OUT;
386         } else {
387                 // Output HTML code here
388                 outputHtml($OUT);
389         }
390 }
391
392 // Adds a menu (mode = guest/member/admin/sponsor) to output
393 function addMenu ($mode, $action, $what) {
394         // Init some variables
395         $main_cnt = '0';
396         $ADD = '';
397
398         // is the menu action valid?
399         if (!isMenuActionValid($mode, $action, $what, true)) {
400                 return getCode('MENU_NOT_VALID');
401         } // END - if
402
403         // Non-admin shall not see all menus
404         if (!isAdmin()) {
405                 $ADD = " AND `visible`='Y' AND `locked`='N'";
406         } // END - if
407
408         // Load SQL data and add the menu to the output stream...
409         $result_main = SQL_QUERY_ESC("SELECT `title`, `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$ADD." ORDER BY `sort` ASC",
410                 array($mode), __FUNCTION__, __LINE__);
411
412         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
413         if (SQL_NUMROWS($result_main) > 0) {
414                 // There are menus available, so we simply display them... :)
415                 $GLOBALS['rows'] = '';
416                 while ($content = SQL_FETCHARRAY($result_main)) {
417                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*<br />");
418                         // Init variables
419                         enableBlockMode(false);
420                         $action = $content['action'];
421
422                         // Load menu header template
423                         $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
424
425                         // Sub menu
426                         $result_sub = SQL_QUERY_ESC("SELECT `title` AS sub_title, `what` AS sub_what FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$ADD." ORDER BY `sort`",
427                                 array($mode, $content['action']), __FUNCTION__, __LINE__);
428
429                         // Get number of rows
430                         $totalWhats = SQL_NUMROWS($result_sub);
431
432                         // Do we have some entries?
433                         if ($totalWhats > 0) {
434                                 // Init counter
435                                 $cnt = '0';
436
437                                 // Load all sub menus
438                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
439                                         // Merge both arrays in one
440                                         $content = merge_array($content, $content2);
441
442                                         // Init content
443                                         $OUT = '';
444
445                                         // Full file name for checking menu
446                                         //* DEBUG: */ print(__LINE__.":!!!!".$content['sub_what']."!!!<br />");
447                                         $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
448                                         if (isIncludeReadable($inc)) {
449                                                 // Mark currently selected menu - open
450                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
451                                                         $OUT = '<strong>';
452                                                 } // END - if
453
454                                                 // Navigation link
455                                                 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&amp;what=' . $content['sub_what'] . '%}" target="_self">';
456                                         } else {
457                                                 // Not found! - open
458                                                 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
459                                         }
460
461                                         // Menu title
462                                         $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
463
464                                         if (isIncludeReadable($inc)) {
465                                                 $OUT .= '</a>';
466
467                                                 // Mark currently selected menu - close
468                                                 if ((!empty($what)) && (($what == $content['sub_what']))) {
469                                                         $OUT .= '</strong>';
470                                                 } // END - if
471                                         } else {
472                                                 // Not found! - close
473                                                 $OUT .= '</em>';
474                                         }
475
476                                         // Cunt it up
477                                         $cnt++;
478
479                                         // Rewrite array
480                                         $content =  array(
481                                                 'menu' => $OUT,
482                                                 'what' => $content['sub_what']
483                                         );
484
485                                         // Add regular menu row or bottom row?
486                                         if ($cnt < $totalWhats) {
487                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
488                                         } else {
489                                                 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
490                                         }
491                                 }
492                         } else {
493                                 // This is a menu block... ;-)
494                                 enableBlockMode();
495
496                                 // Load menu block
497                                 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
498                                 if (isFileReadable($INC)) {
499                                         // Load include file
500                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
501                                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
502                                         loadInclude($INC);
503                                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*<br />");
504                                         if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
505                                 }
506                                 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
507                         }
508
509                         $main_cnt++;
510
511                         //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*<br />");
512                         if (SQL_NUMROWS($result_main) > $main_cnt) {
513                                 // Add seperator
514                                 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
515
516                                 // Should we display adverts in this menu?
517                                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
518                                         // Display advert template
519                                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
520
521                                         // Add seperator again
522                                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
523                                 } // END - if
524                         } // END - if
525                 } // END - while
526
527                 // Free memory
528                 SQL_FREERESULT($result_main);
529
530                 // Should we display adverts in this menu?
531                 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
532                         // Add seperator again
533                         $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
534
535                         // Display advert template
536                         $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
537                 } // END - if
538
539                 // Prepare data
540                 $content = array(
541                         'rows' => $GLOBALS['rows'],
542                         'mode' => $mode
543                 );
544
545                 // Load main template
546                 //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />");
547                 loadTemplate('menu_table', false, $content);
548         } // END - if
549 }
550
551 // Checks wether the current user is a member
552 function isMember () {
553         // By default no member
554         $ret = false;
555
556         // Fix missing 'last_online' array, damn stupid code :(((
557         // @TODO Try to rewrite this to one or more functions
558         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
559
560         // is the cache entry there?
561         if (isset($GLOBALS['is_member'])) {
562                 // Then return it
563                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS['is_member']) . ')');
564                 return $GLOBALS['is_member'];
565         } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
566                 // No member
567                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
568                 return false;
569         } else {
570                 // Get it secured from session
571                 setMemberId(getSession('userid'));
572                 setCurrentUserId(getMemberId());
573                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . getSession('userid') . ' used from cookie/session.');
574         }
575
576         // Init user data array
577         initUserData();
578
579         // Fix "deleted" cookies first
580         fixDeletedCookies(array('userid', 'u_hash'));
581
582         // Are cookies set?
583         if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
584                 // Cookies are set with values, but are they valid?
585                 if (fetchUserData(getMemberId()) === true) {
586                         // Validate password by created the difference of it and the secret key
587                         $valPass = encodeHashForCookie(getUserData('password'));
588
589                         // Transfer last module and online time
590                         $GLOBALS['last_online']['module'] = getUserData('last_module');
591                         $GLOBALS['last_online']['online'] = getUserData('last_online');
592
593                         // So did we now have valid data and an unlocked user?
594                         if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
595                                 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
596                                 $ret = true;
597                         } else {
598                                 // Maybe got locked etc.
599                                 //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status') . ',' . $valPass . '(' . strlen($valPass) . ')/' . getSession('u_hash') . '(' . strlen(getSession('u_hash')) . ')/' . getUserData('password') . '(' . strlen(getUserData('password')) . ')');
600                                 destroyMemberSession();
601                         }
602                 } else {
603                         // Cookie data is invalid!
604                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data invalid or user not found.');
605                         destroyMemberSession();
606                 }
607         } else {
608                 // Cookie data is invalid!
609                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data not complete.');
610                 destroyMemberSession();
611         }
612
613         // Cache status
614         $GLOBALS['is_member'] = $ret;
615
616         // Return status
617         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
618         return $ret;
619 }
620
621 // Fetch user data for given user id
622 function fetchUserData ($userid, $column = 'userid') {
623         // If we should look for userid secure&set it here
624         if (substr($column, -2, 2) == 'id') {
625                 // Secure userid
626                 $userid = bigintval($userid);
627
628                 // Set it here
629                 setCurrentUserId($userid);
630
631                 // Don't look for invalid userids...
632                 if ($userid < 1) {
633                         // Invalid, so abort here
634                         debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
635                 } elseif (isUserDataValid()) {
636                         // Use cache, so it is fine
637                         return true;
638                 }
639         } elseif (isUserDataValid()) {
640                 // Use cache, so it is fine
641                 return true;
642         }
643
644
645         // By default none was found
646         $found = false;
647
648         // Extra statements
649         $ADD = '';
650         if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
651
652         // Query for the user
653         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
654                 array($column, $userid), __FUNCTION__, __LINE__);
655
656         // Do we have a record?
657         if (SQL_NUMROWS($result) == 1) {
658                 // Load data from cookies
659                 $data = SQL_FETCHARRAY($result);
660
661                 // Set the userid for later use
662                 setCurrentUserId($data['userid']);
663                 $GLOBALS['user_data'][getCurrentUserId()] = $data;
664
665                 // Rewrite 'last_failure' if found
666                 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
667                         // Backup the raw one and zero it
668                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
669                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0';
670
671                         // Is it not zero?
672                         if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
673                                 // Seperate data/time
674                                 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
675
676                                 // Seperate data and time again
677                                 $array['date'] = explode('-', $array[0]);
678                                 $array['time'] = explode(':', $array[1]);
679
680                                 // Now pass it to mktime()
681                                 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
682                                         $array['time'][0],
683                                         $array['time'][1],
684                                         $array['time'][2],
685                                         $array['date'][1],
686                                         $array['date'][2],
687                                         $array['date'][0]
688                                 );
689                         } // END - if
690                 } // END - if
691
692                 // Found, but valid?
693                 $found = isUserDataValid();
694         } // END - if
695
696         // Free memory
697         SQL_FREERESULT($result);
698
699         // Return result
700         return $found;
701 }
702
703 // This patched function will reduce many SELECT queries for the specified or current admin login
704 function isAdmin ($adminLogin = '') {
705         // No admin in installation phase!
706         if ((isInstallationPhase()) || (!isAdminRegistered())) {
707                 return false;
708         } // END - if
709
710         // Init variables
711         $ret = false;
712         $passCookie = '';
713         $valPass = '';
714         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminLogin.'<br />');
715
716         // If admin login is not given take current from cookies...
717         if ((empty($adminLogin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
718                 // Get admin login and password from session/cookies
719                 $adminLogin = getSession('admin_login');
720                 $passCookie = getSession('admin_md5');
721         } // END - if
722         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminLogin.'/'.$passCookie.'<br />');
723
724         // Do we have cache?
725         if (!isset($GLOBALS['is_admin'][$adminLogin])) {
726                 // Init it with failed
727                 $GLOBALS['is_admin'][$adminLogin] = false;
728
729                 // Search in array for entry
730                 if (isset($GLOBALS['admin_hash'])) {
731                         // Use cached string
732                         $valPass = $GLOBALS['admin_hash'];
733                 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminLogin) === true) && (!empty($adminLogin))) {
734                         // Login data is valid or not?
735                         $valPass = encodeHashForCookie(getAdminHash($adminLogin));
736
737                         // Cache it away
738                         $GLOBALS['admin_hash'] = $valPass;
739
740                         // Count cache hits
741                         incrementStatsEntry('cache_hits');
742                 } elseif ((!empty($adminLogin)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminLogin) === false))) {
743                         // Get admin hash and hash it
744                         $valPass = encodeHashForCookie(getAdminHash($adminLogin));
745
746                         // Cache it away
747                         $GLOBALS['admin_hash'] = $valPass;
748                 }
749
750                 if (!empty($valPass)) {
751                         // Check if password is valid
752                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
753                         $GLOBALS['is_admin'][$adminLogin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
754                 } // END - if
755         } // END - if
756
757         // Return result of comparision
758         return $GLOBALS['is_admin'][$adminLogin];
759 }
760
761 // Generates a list of "max receiveable emails per day"
762 function addMaxReceiveList ($mode, $default = '', $return = false) {
763         $OUT = '';
764         $result = false;
765
766         switch ($mode) {
767                 case 'guest':
768                         // Guests (in the registration form) are not allowed to select 0 mails per day.
769                         $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC",
770                         __FUNCTION__, __LINE__);
771                         break;
772
773                 case 'member':
774                         // Members are allowed to set to zero mails per day (we will change this soon!)
775                         $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC",
776                         __FUNCTION__, __LINE__);
777                         break;
778
779                 default: // Invalid!
780                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
781                         break;
782         }
783
784         // Some entries are found?
785         if (SQL_NUMROWS($result) > 0) {
786                 $OUT = '';
787                 while ($content = SQL_FETCHARRAY($result)) {
788                         $OUT .= '      <option value="' . $content['value'] . '"';
789                         if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
790                         $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
791                         if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
792                         $OUT .= '</option>';
793                 }
794
795                 // Load template
796                 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
797         } else {
798                 // Maybe the admin has to setup some maximum values?
799                 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
800         }
801
802         // Free result
803         SQL_FREERESULT($result);
804
805         if ($return === true) {
806                 // Return generated HTML code
807                 return $OUT;
808         } else {
809                 // Output directly (default)
810                 outputHtml($OUT);
811         }
812 }
813
814 // Checks wether the given email address is used.
815 function isEmailTaken ($email) {
816         // Query the database
817         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '{PER}%s{PER}' OR `email` LIKE '{PER}%s{PER}' LIMIT 1",
818                 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
819
820         // Is the email there?
821         $ret = (SQL_NUMROWS($result) == 1);
822
823         // Free the result
824         SQL_FREERESULT($result);
825
826         // Return result
827         return $ret;
828 }
829
830 // Validate the given menu action
831 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
832         // Is the cache entry there and we shall not update?
833         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
834                 // Count cache hit
835                 incrementStatsEntry('cache_hits');
836
837                 // Then use this cache
838                 return $GLOBALS['action_valid'][$mode][$action][$what];
839         } // END - if
840
841         // By default nothing is valid
842         $ret = false;
843
844         // Look in all menus or only unlocked
845         $add = '';
846         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
847
848         //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*<br />");
849         if (($mode != 'admin') && ($updateEntry === true)) {
850                 // Update guest or member menu
851                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
852                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
853         } elseif (($what != 'overview') && (!empty($what))) {
854                 // Other actions
855                 $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",
856                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
857         } else {
858                 // Admin login overview
859                 $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",
860                         array($mode, $action), __FUNCTION__, __LINE__, false);
861         }
862
863         // Run SQL command
864         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
865
866         // Should we look for affected rows (only update) or found rows?
867         if ($updateEntry === true) {
868                 // Check updated/affected rows
869                 $ret = (SQL_AFFECTEDROWS() == 1);
870         } else {
871                 // Check found rows
872                 $ret = (SQL_NUMROWS($result) == 1);
873         }
874
875         // Free memory
876         SQL_FREERESULT($result);
877
878         // Set cache entry
879         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
880
881         // Return result
882         return $ret;
883 }
884
885 // Get action value from mode (admin/guest/member) and what-value
886 function getActionFromModuleWhat ($module, $what) {
887         // Init status
888         $data['action'] = '';
889
890         //* DEBUG: */ print(__LINE__.'='.$module.'/'.$what.'/'.getAction()."=<br />");
891         if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
892                 // sql_patches is missing so choose depending on mode
893                 if (isWhatSet()) {
894                         // Use setted what
895                         $what = getWhat();
896                 } elseif ($module == 'admin') {
897                         // Admin area
898                         $what = 'overview';
899                 } else {
900                         // Everywhere else
901                         $what = 'welcome';
902                 }
903         } elseif ((empty($what)) && ($module != 'admin')) {
904                 // Use configured 'home'
905                 $what = getConfig('index_home');
906         } // END - if
907
908         if ($module == 'admin') {
909                 // Action value for admin area
910                 if (isGetRequestParameterSet('action')) {
911                         // Use from request!
912                         return getRequestParameter('action');
913                 } elseif (isActionSet()) {
914                         // Get it directly from URL
915                         return getAction();
916                 } elseif (($what == 'overview') || (!isWhatSet())) {
917                         // Default value for admin area
918                         $data['action'] = 'login';
919                 }
920         } elseif (isActionSet()) {
921                 // Get it directly from URL
922                 return getAction();
923         }
924         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ret=' . $data['action'] . '<br />');
925
926         // Does the module have a menu?
927         if (ifModuleHasMenu($module)) {
928                 // Rewriting modules to menu
929                 $module = mapModuleToTable($module);
930
931                 // Guest and member menu is 'main' as the default
932                 if (empty($data['action'])) $data['action'] = 'main';
933
934                 // Load from database
935                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
936                         array($module, $what), __FUNCTION__, __LINE__);
937                 if (SQL_NUMROWS($result) == 1) {
938                         // Load action value and pray that this one is the right you want... ;-)
939                         $data = SQL_FETCHARRAY($result);
940                 } // END - if
941
942                 // Free memory
943                 SQL_FREERESULT($result);
944         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
945                 // No sql_patches installed, but maybe we need to register an admin?
946                 if (isAdminRegistered()) {
947                         // Redirect to admin area
948                         redirectToUrl('admin.php');
949                 } // END - if
950         }
951
952         // Return action value
953         return $data['action'];
954 }
955
956 // Get category name back
957 function getCategory ($cid) {
958         // Default is not found
959         $data['cat'] = getMessage('_CATEGORY_404');
960
961         // Is the category id set?
962         if ($cid == '0') {
963                 // No category
964                 $data['cat'] = getMessage('_CATEGORY_NONE');
965         } elseif ($cid > 0) {
966                 // Lookup the category in database
967                 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
968                         array(bigintval($cid)), __FUNCTION__, __LINE__);
969                 if (SQL_NUMROWS($result) == 1) {
970                         // Category found... :-)
971                         $data = SQL_FETCHARRAY($result);
972                 } // END - if
973
974                 // Free result
975                 SQL_FREERESULT($result);
976         } // END - if
977
978         // Return result
979         return $data['cat'];
980 }
981
982 // Get a string of "mail title" and price back
983 function getPaymentTitlePrice ($pid, $full=false) {
984         // Default is not found
985         $ret = getMessage('_PAYMENT_404');
986
987         // Load payment data
988         $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
989                 array(bigintval($pid)), __FUNCTION__, __LINE__);
990         if (SQL_NUMROWS($result) == 1) {
991                 // Payment type found... :-)
992                 $data = SQL_FETCHARRAY($result);
993
994                 // Only title or also including price?
995                 if ($full === false) {
996                         $ret = $data['mail_title'];
997                 } else {
998                         $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
999                 }
1000         }
1001
1002         // Free result
1003         SQL_FREERESULT($result);
1004
1005         // Return result
1006         return $ret;
1007 }
1008
1009 // Get (basicly) the price of given payment id
1010 function getPaymentPoints ($pid, $lookFor = 'price') {
1011         // Default value...
1012         $data[$lookFor] = '-1';
1013
1014         // Search for it in database
1015         $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1016                 array($lookFor, $pid), __FUNCTION__, __LINE__);
1017
1018         // Is the entry there?
1019         if (SQL_NUMROWS($result) == 1) {
1020                 // Payment type found... :-)
1021                 $data = SQL_FETCHARRAY($result);
1022         } // END - if
1023
1024         // Free result
1025         SQL_FREERESULT($result);
1026
1027         // Return value
1028         return $data[$lookFor];
1029 }
1030
1031 // Remove a receiver's id from $receivers and add a link for him to confirm
1032 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1033         // Default is not removed
1034         $ret = 'failed';
1035
1036         // Is the userid valid?
1037         if ($userid > 0) {
1038                 // Remove entry from array
1039                 unset($receivers[$key]);
1040
1041                 // Is there already a line for this user available?
1042                 if ($stats_id > 0) {
1043                         // Only when we got a real stats id continue searching for the entry
1044                         $type = 'NORMAL'; $rowName = 'stats_id';
1045                         if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1046
1047                         // Try to look the entry up
1048                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1049                                 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1050
1051                         // Was it *not* found?
1052                         if (SQL_HASZERONUMS($result)) {
1053                                 // So we add one!
1054                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1055                                         array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1056                                 $ret = 'done';
1057                         } else {
1058                                 // Already found
1059                                 $ret = 'already';
1060                         }
1061
1062                         // Free memory
1063                         SQL_FREERESULT($result);
1064                 }
1065         }
1066
1067         // Return status for sending routine
1068         return $ret;
1069 }
1070
1071 // Calculate sum (default) or count records of given criteria
1072 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1073         // Init count/sum
1074         $data['res'] = '0';
1075
1076         //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />');
1077         if ((empty($search)) && ($search != '0')) {
1078                 // Count or sum whole table?
1079                 if ($countRows === true) {
1080                         // Count whole table
1081                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1082                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1083                 } else {
1084                         // Sum whole table
1085                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1086                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1087                 }
1088         } elseif (($countRows === true) || ($lookFor == 'userid')) {
1089                 // Count rows
1090                 //* DEBUG: */ print("COUNT!<br />");
1091                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1092                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1093         } else {
1094                 // Add all rows
1095                 //* DEBUG: */ print("SUM!<br />");
1096                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1097                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1098         }
1099
1100         // Load row
1101         $data = SQL_FETCHARRAY($result);
1102
1103         // Free result
1104         SQL_FREERESULT($result);
1105
1106         // Fix empty values
1107         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1108                 // Float number
1109                 $data['res'] = '0.00000';
1110         } elseif (''.$data['res'].'' == '') {
1111                 // Fix empty result
1112                 $data['res'] = '0';
1113         }
1114
1115         // Return value
1116         //* DEBUG: */ print 'ret=' . $data['res'] . '<br />';
1117         return $data['res'];
1118 }
1119 // Getter fro ref level percents
1120 function getReferalLevelPercents ($level) {
1121         // Default is zero
1122         $data['percents'] = '0';
1123
1124         // Do we have cache?
1125         if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1126                 // First look for level
1127                 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1128                 if ($key !== false) {
1129                         // Entry found!
1130                         $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1131
1132                         // Count cache hit
1133                         incrementStatsEntry('cache_hits');
1134                 } // END - if
1135         } elseif (!isExtensionActive('cache')) {
1136                 // Get referal data
1137                 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1138                         array(bigintval($level)), __FUNCTION__, __LINE__);
1139
1140                 // Entry found?
1141                 if (SQL_NUMROWS($result_level) == 1) {
1142                         // Get percents
1143                         $data = SQL_FETCHARRAY($result_level);
1144                 } // END - if
1145
1146                 // Free result
1147                 SQL_FREERESULT($result_level);
1148         }
1149
1150         // Return percent
1151         return $data['percents'];
1152 }
1153
1154 /**
1155  *
1156  * Dynamic referal system, can also send mails!
1157  *
1158  * subject     = Subject line, write in lower-case letters and underscore is allowed
1159  * userid         = Referal id wich should receive...
1160  * points      = ... xxx points
1161  * sendNotify  = shall I send the referal an email or not?
1162  * rid         = inc/modules/guest/what-confirm.php need this
1163  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
1164  * add_mode    = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1165  *               for default value will cause no referal will get points ever!!!)
1166  */
1167 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1168         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1169         // Convert mode to lower-case
1170         $add_mode = strtolower($add_mode);
1171
1172         // When $userid = '0' add points to jackpot
1173         if (($userid == '0') && (isExtensionActive('jackpot'))) {
1174                 // Add points to jackpot
1175                 addPointsToJackpot($points);
1176                 return;
1177         } // END - if
1178
1179         // Prepare data for the filter
1180         $filterData = array(
1181                 'subject'  => $subject,
1182                 'userid'   => $userid,
1183                 'points'   => $points,
1184                 'notify'   => $sendNotify,
1185                 'rid'      => $rid,
1186                 'locked'   => $locked,
1187                 'mode'     => 'add',
1188                 'sub_mode' => $add_mode,
1189         );
1190
1191         // Filter it now
1192         runFilterChain('add_points', $filterData);
1193
1194         // Count up referal depth
1195         if (!isset($GLOBALS['ref_level'])) {
1196                 // Initialialize referal system
1197                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>): Referal system initialized!<br />");
1198                 $GLOBALS['ref_level'] = '0';
1199         } else {
1200                 // Increase referal level
1201                 $GLOBALS['ref_level']++;
1202                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />");
1203         }
1204
1205         // Default is 'normal' points
1206         $data = 'points';
1207
1208         // Which points, locked or normal?
1209         if ($locked === true) $data = 'locked_points';
1210
1211         // Check user account
1212         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points}<br />");
1213         if (fetchUserData($userid)) {
1214                 // This is the user and his ref
1215                 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1216
1217                 // Get percents
1218                 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1219                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />");
1220
1221                 // Some percents found?
1222                 if ($per > 0) {
1223                         // Calculate new points
1224                         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />");
1225                         $ref_points = $points * $per / 100;
1226
1227                         // Pay refback here if level > 0 and in ref-mode
1228                         if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1229                                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - BEFORE!<br />");
1230                                 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1231                                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},data={$GLOBALS['cache_array']['add_userid'][$userid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - AFTER!<br />");
1232                         } // END - if
1233
1234                         // Update points...
1235                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`='%s' LIMIT 1",
1236                                 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1237                         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - UPDATE! (".SQL_AFFECTEDROWS().")<br />");
1238
1239                         // No entry updated?
1240                         if (SQL_AFFECTEDROWS() < 1) {
1241                                 // First ref in this level! :-)
1242                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,'%s',%s)",
1243                                         array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1244                                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):data={$data},ref_points={$ref_points},userid={$userid},depth={$GLOBALS['ref_level']},mode={$add_mode} - INSERTED! (".SQL_AFFECTEDROWS().")<br />");
1245                         } // END - if
1246
1247                         // Points updated, maybe I shall send him an email?
1248                         if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
1249                                 // Prepare content
1250                                 $content = array(
1251                                         'percents' => $per,
1252                                         'level'    => bigintval($GLOBALS['ref_level']),
1253                                         'points'   => $ref_points,
1254                                         'refid'    => getUserData('refid')
1255                                 );
1256
1257                                 // Load email template
1258                                 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1259
1260                                 // Send email
1261                                 sendEmail($userid, getMessage('THANX_REFERAL_ONE_SUBJECT'), $message);
1262                         } elseif (($sendNotify === true) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
1263                                 // Prepare content
1264                                 $content = array(
1265                                         'text'   => getMessage('REASON_DIRECT_PAYMENT'),
1266                                         'points' => translateComma($ref_points)
1267                                 );
1268
1269                                 // Load message
1270                                 $message = loadEmailTemplate('add-points', $content, $userid);
1271
1272                                 // And sent it away
1273                                 sendEmail($userid, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1274                                 if (!isGetRequestParameterSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1275                         }
1276
1277                         // Maybe there's another ref?
1278                         if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1279                                 // Then let's credit him here...
1280                                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},ref=".getUserData('refid').",points={$points} - ADVANCE!<br />");
1281                                 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1282                         } // END - if
1283                 } // END - if
1284         } // END - if
1285
1286         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
1287 }
1288
1289 // Updates the referal counter
1290 function updateReferalCounter ($userid) {
1291         // Make it sure referal level zero (member him-/herself) is at least selected
1292         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1293         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}<br />");
1294
1295         // Update counter
1296         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1297                 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1298
1299         // When no entry was updated then we have to create it here
1300         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
1301         if (SQL_AFFECTEDROWS() < 1) {
1302                 // First count!
1303                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1304                         array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1305                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid}<br />");
1306         } // END - if
1307
1308         // Init referal id
1309         $ref = '0';
1310
1311         // Check for his referal
1312         if (fetchUserData($userid)) {
1313                 // Get it
1314                 $ref = getUserData('refid');
1315         } // END - if
1316
1317         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},ref={$ref}<br />");
1318
1319         // When he has a referal...
1320         if (($ref > 0) && ($ref != $userid)) {
1321                 // Move to next referal level and count his counter one up!
1322                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):ref={$ref} - ADVANCE!<br />");
1323                 $GLOBALS['cache_array']['ref_level'][$userid]++;
1324                 updateReferalCounter($ref);
1325         } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1326                 // Remove cache here
1327                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):ref={$ref} - CACHE!<br />");
1328                 rebuildCache('refsystem', 'refsystem');
1329         }
1330
1331         // "Walk" back here
1332         $GLOBALS['cache_array']['ref_level'][$userid]--;
1333
1334         // Handle refback here if extension is installed
1335         if (isExtensionActive('refback')) {
1336                 updateRefbackTable($userid);
1337         } // END - if
1338 }
1339
1340 // Sends out mail to all administrators. This function is no longer obsolete
1341 // because we need it when there is no ext-admins installed
1342 function sendAdminEmails ($subj, $message) {
1343         // Load all admin email addresses
1344         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1345         while ($content = SQL_FETCHARRAY($result)) {
1346                 // Send the email out
1347                 sendEmail($content['email'], $subj, $message);
1348         } // END - if
1349
1350         // Free result
1351         SQL_FREERESULT($result);
1352
1353         // Really simple... ;-)
1354 }
1355
1356 // Get id number from administrator's login name
1357 function getAdminId ($adminLogin) {
1358         // By default no admin is found
1359         $data['id'] = '-1';
1360
1361         // Check cache
1362         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1363                 // Use it if found to save SQL queries
1364                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1365
1366                 // Update cache hits
1367                 incrementStatsEntry('cache_hits');
1368         } elseif (!isExtensionActive('cache')) {
1369                 // Load from database
1370                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1371                         array($adminLogin), __FUNCTION__, __LINE__);
1372
1373                 // Do we have an entry?
1374                 if (SQL_NUMROWS($result) == 1) {
1375                         // Get it
1376                         $data = SQL_FETCHARRAY($result);
1377                 } // END - if
1378
1379                 // Free result
1380                 SQL_FREERESULT($result);
1381         }
1382
1383         // Return the id
1384         return $data['id'];
1385 }
1386
1387 // "Getter" for current admin id
1388 function getCurrentAdminId () {
1389         // Do we have cache?
1390         if (!isset($GLOBALS['current_admin_id'])) {
1391                 // Get the admin login from session
1392                 $adminLogin = getSession('admin_login');
1393
1394                 // "Solve" it into an id
1395                 $adminId = getAdminId($adminLogin);
1396
1397                 // Remember in cache securely
1398                 setCurrentAdminId(bigintval($adminId));
1399         } // END - if
1400
1401         // Return it
1402         return $GLOBALS['current_admin_id'];
1403 }
1404
1405 // Setter for current admin id
1406 function setCurrentAdminId ($currentAdminId) {
1407         // Set it secured
1408         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1409 }
1410
1411 // Get password hash from administrator's login name
1412 function getAdminHash ($adminLogin) {
1413         // By default an invalid hash is returned
1414         $data['password'] = '-1';
1415
1416         if (isAdminHashSet($adminLogin)) {
1417                 // Check cache
1418                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminLogin];
1419
1420                 // Update cache hits
1421                 incrementStatsEntry('cache_hits');
1422         } elseif (!isExtensionActive('cache')) {
1423                 // Load from database
1424                 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1425                         array($adminLogin), __FUNCTION__, __LINE__);
1426
1427                 // Do we have an entry?
1428                 if (SQL_NUMROWS($result) == 1) {
1429                         // Fetch data
1430                         $data = SQL_FETCHARRAY($result);
1431
1432                         // Set cache
1433                         setAdminHash($adminLogin, $data['password']);
1434                 } // END - if
1435
1436                 // Free result
1437                 SQL_FREERESULT($result);
1438         }
1439
1440         // Return password hash
1441         return $data['password'];
1442 }
1443
1444 // "Getter" for admin login
1445 function getAdminLogin ($adminId) {
1446         // By default a non-existent login is returned (other functions react on this!)
1447         $data['login'] = '***';
1448
1449         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1450                 // Get cache
1451                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1452
1453                 // Update cache hits
1454                 incrementStatsEntry('cache_hits');
1455         } elseif (!isExtensionActive('cache')) {
1456                 // Load from database
1457                 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1458                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1459
1460                 // Entry found?
1461                 if (SQL_NUMROWS($result) == 1) {
1462                         // Fetch data
1463                         $data = SQL_FETCHARRAY($result);
1464
1465                         // Set cache
1466                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1467                 } // END - if
1468
1469                 // Free memory
1470                 SQL_FREERESULT($result);
1471         }
1472
1473         // Return the result
1474         return $data['login'];
1475 }
1476
1477 // Get email address of admin id
1478 function getAdminEmail ($adminId) {
1479         // By default an invalid emails is returned
1480         $data['email'] = '***';
1481
1482         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1483                 // Get cache
1484                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1485
1486                 // Update cache hits
1487                 incrementStatsEntry('cache_hits');
1488         } elseif (!isExtensionActive('cache')) {
1489                 // Load from database
1490                 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1491                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1492
1493                 // Entry found?
1494                 if (SQL_NUMROWS($result_admin_id) == 1) {
1495                         // Get data
1496                         $data = SQL_FETCHARRAY($result_admin_id);
1497
1498                         // Set cache
1499                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1500                 } // END - if
1501
1502                 // Free result
1503                 SQL_FREERESULT($result_admin_id);
1504         }
1505
1506         // Return email
1507         return $data['email'];
1508 }
1509
1510 // Get default ACL  of admin id
1511 function getAdminDefaultAcl ($adminId) {
1512         // By default an invalid ACL value is returned
1513         $data['default_acl'] = '***';
1514
1515         // Is sql_patches there and was it found in cache?
1516         if (!isExtensionActive('sql_patches')) {
1517                 // Not found, which is bad, so we need to allow all
1518                 $data['default_acl'] =  'allow';
1519         } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1520                 // Use cache
1521                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1522
1523                 // Update cache hits
1524                 incrementStatsEntry('cache_hits');
1525         } elseif (!isExtensionActive('cache')) {
1526                 // Load from database
1527                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1528                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1529                 if (SQL_NUMROWS($result_admin_id) == 1) {
1530                         // Fetch data
1531                         $data = SQL_FETCHARRAY($result_admin_id);
1532
1533                         // Set cache
1534                         $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1535                 }
1536
1537                 // Free result
1538                 SQL_FREERESULT($result_admin_id);
1539         }
1540
1541         // Return default ACL
1542         return $data['default_acl'];
1543 }
1544
1545 // Generates an option list from various parameters
1546 function generateOptionList ($table, $id, $name, $default='', $special='', $where='', $disabled=array()) {
1547         $ret = '';
1548         if ($table == '/ARRAY/') {
1549                 // Selection from array
1550                 if ((is_array($id)) && (is_array($name)) && (count($id)) == (count($name))) {
1551                         // Both are arrays
1552                         foreach ($id as $idx => $value) {
1553                                 $ret .= '<option value="' . $value . '"';
1554                                 if ($default == $value) {
1555                                         // Selected by default
1556                                         $ret .= ' selected="selected"';
1557                                 } elseif (isset($disabled[$value])) {
1558                                         // Disabled!
1559                                         $ret .= ' disabled="disabled"';
1560                                 }
1561                                 $ret .= '>' . $name[$idx] . '</option>';
1562                         } // END - foreach
1563                 } else {
1564                         // Problem in request
1565                         debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name));
1566                 }
1567         } else {
1568                 // Data from database
1569                 $SPEC = ', `' . $id . '`';
1570                 if (!empty($special)) $SPEC = ', `' . $special . '`';
1571
1572                 // Query the database
1573                 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1574                         array(
1575                                 $id,
1576                                 $name,
1577                                 $table,
1578                                 $name
1579                         ), __FUNCTION__, __LINE__);
1580
1581                 // Do we have rows?
1582                 if (SQL_NUMROWS($result) > 0) {
1583                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1584                         // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1585                         while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1586                                 if (empty($special)) $add = '';
1587                                 $ret .= '<option value="' . $value . '"';
1588                                 if ($default == $value) {
1589                                         // Selected by default
1590                                         $ret .= ' selected="selected"';
1591                                 } elseif (isset($disabled[$value])) {
1592                                         // Disabled!
1593                                         $ret .= ' disabled="disabled"';
1594                                 }
1595                                 if (!empty($add)) $add = ' ('.$add.')';
1596                                 $ret .= '>' . $title . $add . '</option>';
1597                         } // END - while
1598                 } else {
1599                         // No data found
1600                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1601                 }
1602
1603                 // Free memory
1604                 SQL_FREERESULT($result);
1605         }
1606
1607         // Return - hopefully - the requested data
1608         return $ret;
1609 }
1610 // Activate exchange
1611 function FILTER_ACTIVATE_EXCHANGE () {
1612         // Is the extension 'user' there?
1613         if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
1614                 // Silently abort here
1615                 return false;
1616         } // END - if
1617
1618         // Check total amount of users
1619         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1620
1621         if ($totalUsers >= getConfig('activate_xchange')) {
1622                 // Activate System
1623                 setSqlsArray(array(
1624                         "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1625                         "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1626                 ));
1627
1628                 // Run SQLs
1629                 runFilterChain('run_sqls');
1630
1631                 // Update configuration
1632                 updateConfiguration('activate_xchange' ,0);
1633
1634                 // Rebuild cache
1635                 rebuildCache('modules', 'modules');
1636         } // END - if
1637 }
1638
1639 // Deletes a user account with given reason
1640 function deleteUserAccount ($userid, $reason) {
1641         // Init points
1642         $data['points'] = '0';
1643
1644         $result = SQL_QUERY_ESC("SELECT
1645         (SUM(p.points) - d.used_points) AS points
1646 FROM
1647         `{?_MYSQL_PREFIX?}_user_points` AS p
1648 LEFT JOIN
1649         `{?_MYSQL_PREFIX?}_user_data` AS d
1650 ON
1651         p.userid=d.userid
1652 WHERE
1653         p.userid=%s",
1654                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1655
1656         // Do we have an entry?
1657         if (SQL_NUMROWS($result) == 1) {
1658                 // Save his points to add them to the jackpot
1659                 $data = SQL_FETCHARRAY($result);
1660
1661                 // Delete points entries as well
1662                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
1663
1664                 // Update mediadata as well
1665                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1666                         // Update database
1667                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1668                 } // END - if
1669
1670                 // Now, when we have all his points adds them do the jackpot!
1671                 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1672         } // END - if
1673
1674         // Free the result
1675         SQL_FREERESULT($result);
1676
1677         // Delete category selections as well...
1678         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1679                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1680
1681         // Remove from rallye if found
1682         // @TODO Rewrite this to a filter
1683         if (isExtensionActive('rallye')) {
1684                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1685                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1686         } // END - if
1687
1688         // Add reason and translate points
1689         $data['text']   = $reason;
1690         $data['points'] = translateComma($data['points']);
1691
1692         // Now a mail to the user and that's all...
1693         $message = loadEmailTemplate('del-user', $data, $userid);
1694         sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1695
1696         // Ok, delete the account!
1697         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1698 }
1699
1700 // Gets the matching what name from module
1701 function getWhatFromModule ($modCheck) {
1702         // Is the request element set?
1703         if (isGetRequestParameterSet('what')) {
1704                 // Then return this!
1705                 return getRequestParameter('what');
1706         } // END - if
1707
1708         // Default is empty
1709         $what = '';
1710
1711         //* DEBUG: */ print(__LINE__.'!'.$modCheck."!<br />");
1712         switch ($modCheck) {
1713                 case 'admin':
1714                         $what = 'overview';
1715                         break;
1716
1717                 case 'login':
1718                 case 'index':
1719                         // Is ext-sql_patches installed and newer than 0.0.5?
1720                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1721                                 // Use it from config
1722                                 $what = getConfig('index_home');
1723                         } else {
1724                                 // Use default 'welcome'
1725                                 $what = 'welcome';
1726                         }
1727                         break;
1728
1729                 default:
1730                         $what = '';
1731                         break;
1732         } // END - switch
1733
1734         // Return what value
1735         return $what;
1736 }
1737
1738 // Subtract points from database and mediadata cache
1739 function subtractPoints ($subject, $userid, $points) {
1740         // Add points to used points
1741         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1742                 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1743
1744         // Prepare filter data
1745         $filterData = array(
1746                 'subject' => $subject,
1747                 'userid'  => $userid,
1748                 'points'  => $points,
1749                 'mode'    => 'sub'
1750         );
1751
1752         // Insert booking record
1753         runFilterChain('sub_points', $filterData);
1754 }
1755
1756 // "Getter" for total available receivers
1757 function getTotalReceivers ($mode='normal') {
1758         // Query database
1759         $result_all = SQL_QUERY("SELECT
1760         `userid`
1761 FROM
1762         `{?_MYSQL_PREFIX?}_user_data`
1763 WHERE
1764         `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1765         __FUNCTION__, __LINE__);
1766
1767         // Get num rows
1768         $numRows = SQL_NUMROWS($result_all);
1769
1770         // Free result
1771         SQL_FREERESULT($result_all);
1772
1773         // Return value
1774         return $numRows;
1775 }
1776
1777 // Returns HTML code with an option list of all categories
1778 function generateCategoryOptionsList ($mode) {
1779         // Prepare WHERE statement
1780         $whereStatement = " WHERE `visible`='Y'";
1781         if (isAdmin()) $whereStatement = '';
1782
1783         // Initialize array...
1784         $CATS = array(
1785                 'id'   => array(),
1786                 'name' => array(),
1787                 'userids' => array()
1788         );
1789
1790         // Get categories
1791         $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC",
1792                 __FUNCTION__, __LINE__);
1793
1794         // Do we have entries?
1795         if (SQL_NUMROWS($result) > 0) {
1796                 // ... and begin loading stuff
1797                 while ($content = SQL_FETCHARRAY($result)) {
1798                         // Transfer some data
1799                         $CATS['id'][]   = $content['id'];
1800                         $CATS['name'][] = $content['cat'];
1801
1802                         // Check which users are in this category
1803                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1804                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1805
1806                         // Init count
1807                         $userid_cnt = '0';
1808
1809                         // Start adding all
1810                         while ($data = SQL_FETCHARRAY($result_userids)) {
1811                                 // Add user count
1812                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1813                         } // END - while
1814
1815                         // Free memory
1816                         SQL_FREERESULT($result_userids);
1817
1818                         // Add counter
1819                         $CATS['userids'][] = $userid_cnt;
1820                 } // END - while
1821
1822                 // Free memory
1823                 SQL_FREERESULT($result);
1824
1825                 // Generate options
1826                 $OUT = '';
1827                 foreach ($CATS['id'] as $key => $value) {
1828                         if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1829                         $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1830                 } // END - foreach
1831         } else {
1832                 // No cateogries are defined yet
1833                 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1834         }
1835
1836         // Return HTML code
1837         return $OUT;
1838 }
1839
1840 // Add bonus mail to queue
1841 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1842         // Is admin or bonus extension there?
1843         if (!isAdmin()) {
1844                 // Abort here
1845                 return false;
1846         } elseif (!isExtensionActive('bonus')) {
1847                 // Abort here
1848                 return false;
1849         }
1850
1851         // Calculcate target sent
1852         $target = countSelection(explode(';', $receiverList));
1853
1854         // Receiver is zero?
1855         if ($receiver == '0') {
1856                 // Then auto-fix it
1857                 $receiver = $target;
1858         } // END - if
1859
1860         // HTML extension active?
1861         if (isExtensionActive('html_mail')) {
1862                 // No HTML by default
1863                 $HTML = 'N';
1864
1865                 // HTML mode?
1866                 if ($mode == 'html') $HTML = 'Y';
1867
1868                 // Add HTML mail
1869                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1870 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1871 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1872                 array(
1873                         $subject,
1874                         $text,
1875                         $receiverList,
1876                         $points,
1877                         $seconds,
1878                         $url,
1879                         $cat,
1880                         $target,
1881                         bigintval($receiver),
1882                         $HTML
1883                 ), __FUNCTION__, __LINE__);
1884         } else {
1885                 // Add regular mail
1886                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1887 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1888 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1889                 array(
1890                         $subject,
1891                         $text,
1892                         $receiverList,
1893                         $points,
1894                         $seconds,
1895                         $url,
1896                         $cat,
1897                         $target,
1898                         bigintval($receiver),
1899                 ), __FUNCTION__, __LINE__);
1900         }
1901 }
1902
1903 // Generate a receiver list for given category and maximum receivers
1904 function generateReceiverList ($cat, $receiver, $mode = '') {
1905         // Init variables
1906         $CAT_TABS     = '';
1907         $CAT_WHERE    = '';
1908         $receiverList = '';
1909         $result       = false;
1910
1911         // Secure data
1912         $cat      = bigintval($cat);
1913         $receiver = bigintval($receiver);
1914
1915         // Is the receiver zero and mode set?
1916         if (($receiver == '0') && (!empty($mode))) {
1917                 // Auto-fix receiver maximum
1918                 $receiver = getTotalReceivers($mode);
1919         } // END - if
1920
1921         // Category given?
1922         if ($cat > 0) {
1923                 // Select category
1924                 $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1925                 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1926         } // END - if
1927
1928         // Exclude users in holiday?
1929         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1930                 // Add something for the holiday extension
1931                 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1932         } // END - if
1933
1934         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1935                 // Only include HTML receivers
1936                 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1937                         array(
1938                                 $receiver
1939                         ), __FUNCTION__, __LINE__);
1940         } else {
1941                 // Include all
1942                 $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
1943                         array(
1944                                 $receiver
1945                         ), __FUNCTION__, __LINE__);
1946         }
1947
1948         // Entries found?
1949         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1950                 // Load all entries
1951                 while ($content = SQL_FETCHARRAY($result)) {
1952                         // Add receiver when not empty
1953                         if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1954                 } // END - while
1955
1956                 // Free memory
1957                 SQL_FREERESULT($result);
1958
1959                 // Remove trailing semicolon
1960                 $receiverList = substr($receiverList, 0, -1);
1961         } // END - if
1962
1963         // Return list
1964         return $receiverList;
1965 }
1966
1967 // "Getter" for array for user refs and points in given level
1968 function getUserReferalPoints ($userid, $level) {
1969         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1970         // Default is no refs and no nickname
1971         $add = '';
1972         $refs = array();
1973
1974         // Do we have nickname extension installed?
1975         if (isExtensionActive('nickname')) {
1976                 $add = ', ud.nickname';
1977         } // END - if
1978
1979         // Get refs from database
1980         $result = SQL_QUERY_ESC("SELECT
1981         ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
1982 FROM
1983         `{?_MYSQL_PREFIX?}_user_refs` AS ur
1984 LEFT JOIN
1985         `{?_MYSQL_PREFIX?}_user_points` AS up
1986 ON
1987         ur.refid=up.userid AND ur.level=0
1988 LEFT JOIN
1989         `{?_MYSQL_PREFIX?}_user_data` AS ud
1990 ON
1991         ur.refid=ud.userid
1992 WHERE
1993         ur.userid=%s AND ur.level=%s
1994 ORDER BY
1995         ur.refid ASC",
1996                 array(
1997                         bigintval($userid),
1998                         bigintval($level)
1999                 ), __FUNCTION__, __LINE__);
2000
2001         // Are there some entries?
2002         if (SQL_NUMROWS($result) > 0) {
2003                 // Fetch all entries
2004                 while ($row = SQL_FETCHARRAY($result)) {
2005                         // Get total points of this user
2006                         $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2007
2008                         // Get unconfirmed mails
2009                         $row['unconfirmed']  = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2010
2011                         // Init clickrate with zero
2012                         $row['clickrate'] = '0';
2013
2014                         // Is at least one mail received?
2015                         if ($row['emails_received'] > 0) {
2016                                 // Calculate clickrate
2017                                 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2018                         } // END - if
2019
2020                         // Activity is 'active' by default because if autopurge is not installed
2021                         $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2022
2023                         // Is autopurge installed and the user inactive?
2024                         if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online']))  {
2025                                 // Inactive user!
2026                                 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2027                         } // END - if
2028
2029                         // Remove some entries
2030                         unset($row['mails_confirmed']);
2031                         unset($row['emails_received']);
2032                         unset($row['last_online']);
2033
2034                         // Add row
2035                         $refs[$row['id']] = $row;
2036                 } // END - while
2037         } // END - if
2038
2039         // Free result
2040         SQL_FREERESULT($result);
2041
2042         // Return result
2043         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
2044         return $refs;
2045 }
2046
2047 // Recuce the amount of received emails for the receipients for given email
2048 function reduceRecipientReceivedMails ($column, $id, $count) {
2049         // Search for mail in database
2050         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2051                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2052
2053         // Are there entries?
2054         if (SQL_NUMROWS($result) > 0) {
2055                 // Now load all userids for one big query!
2056                 $userids = array();
2057                 while ($data = SQL_FETCHARRAY($result)) {
2058                         // By default we want to reduce and have no mails found
2059                         $num = 0;
2060
2061                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
2062                         // @TODO Rewrite this to a filter
2063                         if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
2064                                 // User email
2065                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
2066                         } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
2067                                 // Bonus mail
2068                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
2069                         }
2070
2071                         // Reduce this users total received emails?
2072                         if ($num === 0) $userids[$data['userid']] = $data['userid'];
2073                 } // END - while
2074
2075                 if (count($userids) > 0) {
2076                         // Now update all user accounts
2077                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2078                                 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
2079                 } else {
2080                         // Nothing deleted
2081                         loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
2082                 }
2083         } // END - if
2084
2085         // Free result
2086         SQL_FREERESULT($result);
2087 }
2088
2089 // Creates a new task
2090 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
2091         // Insert the task data into the database
2092         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())",
2093                 array(
2094                         $adminId,
2095                         $userid,
2096                         $taskType,
2097                         $subject,
2098                         $notes
2099                 ), __FUNCTION__, __LINE__, true, $strip);
2100 }
2101
2102 // Updates last module / online time
2103 // @TODO Fix inconsistency between last_module and getWhat()
2104 function updateLastActivity($userid) {
2105         // Run the update query
2106         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
2107                 array(
2108                         getWhat(),
2109                         detectRemoteAddr(),
2110                         bigintval($userid)
2111                 ), __FUNCTION__, __LINE__);
2112 }
2113
2114 // [EOF]
2115 ?>