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