Further fixes for non-working admin login and debug lines commented out
[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                 return $GLOBALS['is_member'];
563         } elseif (getMemberId() == '0') {
564                 // No member
565                 return false;
566         } else {
567                 // Transfer userid=>current
568                 setCurrentUserid(getMemberId());
569         }
570
571         // Init user data array
572         initUserData();
573
574         // Fix "deleted" cookies first
575         fixDeletedCookies(array('userid', 'u_hash'));
576
577         // Are cookies set?
578         if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
579                 // Cookies are set with values, but are they valid?
580                 if (fetchUserData(getMemberId()) === true) {
581                         // Validate password by created the difference of it and the secret key
582                         $valPass = encodeHashForCookie(getUserData('password'));
583
584                         // Transfer last module and online time
585                         $GLOBALS['last_online']['module'] = getUserData('last_module');
586                         $GLOBALS['last_online']['online'] = getUserData('last_online');
587
588                         // So did we now have valid data and an unlocked user?
589                         if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
590                                 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
591                                 $ret = true;
592                         } else {
593                                 // Maybe got locked etc.
594                                 logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status'));
595                                 destroyMemberSession();
596                         }
597                 } else {
598                         // Cookie data is invalid!
599                         destroyMemberSession();
600                 }
601         } else {
602                 // Cookie data is invalid!
603                 destroyMemberSession();
604         }
605
606         // Cache status
607         $GLOBALS['is_member'] = $ret;
608
609         // Return status
610         return $ret;
611 }
612
613 // Fetch user data for given user id
614 function fetchUserData ($userid, $column = 'userid') {
615         // If we should look for userid secure&set it here
616         if (substr($column, -2, 2) == 'id') {
617                 // Secure userid
618                 $userid = bigintval($userid);
619
620                 // Set it here
621                 setCurrentUserId($userid);
622
623                 // Don't look for invalid userids...
624                 if ($userid < 1) {
625                         // Invalid, so abort here
626                         debug_report_bug('User id ' . $userid . ' is invalid.');
627                 } elseif (isUserDataValid()) {
628                         // Use cache, so it is fine
629                         return true;
630                 }
631         } elseif (isUserDataValid()) {
632                 // Use cache, so it is fine
633                 return true;
634         }
635
636
637         // By default none was found
638         $found = false;
639
640         // Extra statements
641         $ADD = '';
642         if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
643
644         // Query for the user
645         $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
646                 array($column, $userid), __FUNCTION__, __LINE__);
647
648         // Do we have a record?
649         if (SQL_NUMROWS($result) == 1) {
650                 // Load data from cookies
651                 $data = SQL_FETCHARRAY($result);
652
653                 // Set the userid for later use
654                 setCurrentUserId($data['userid']);
655                 $GLOBALS['user_data'][getCurrentUserId()] = $data;
656
657                 // Rewrite 'last_failure' if found
658                 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
659                         // Backup the raw one and zero it
660                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
661                         $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0';
662
663                         // Is it not zero?
664                         if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
665                                 // Seperate data/time
666                                 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
667
668                                 // Seperate data and time again
669                                 $array['date'] = explode('-', $array[0]);
670                                 $array['time'] = explode(':', $array[1]);
671
672                                 // Now pass it to mktime()
673                                 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
674                                         $array['time'][0],
675                                         $array['time'][1],
676                                         $array['time'][2],
677                                         $array['date'][1],
678                                         $array['date'][2],
679                                         $array['date'][0]
680                                 );
681                         } // END - if
682                 } // END - if
683
684                 // Found, but valid?
685                 $found = isUserDataValid();
686         } // END - if
687
688         // Free memory
689         SQL_FREERESULT($result);
690
691         // Return result
692         return $found;
693 }
694
695 // This patched function will reduce many SELECT queries for the specified or current admin login
696 function isAdmin ($adminLogin = '') {
697         // Init variables
698         $ret = false;
699         $passCookie = '';
700         $valPass = '';
701         //* DEBUG: */ print(__FUNCTION__.':'.$adminLogin.'<br />');
702
703         // If admin login is not given take current from cookies...
704         if ((empty($adminLogin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
705                 // Get admin login and password from session/cookies
706                 $adminLogin = getSession('admin_login');
707                 $passCookie = getSession('admin_md5');
708         } // END - if
709         //* DEBUG: */ print(__FUNCTION__.':'.$adminLogin.'/'.$passCookie.'<br />');
710
711         // Do we have cache?
712         if (!isset($GLOBALS['is_admin'][$adminLogin])) {
713                 // Init it with failed
714                 $GLOBALS['is_admin'][$adminLogin] = false;
715
716                 // Search in array for entry
717                 if (isset($GLOBALS['admin_hash'])) {
718                         // Use cached string
719                         $valPass = $GLOBALS['admin_hash'];
720                 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminLogin) === true) && (!empty($adminLogin))) {
721                         // Login data is valid or not?
722                         $valPass = encodeHashForCookie(getAdminHash($adminLogin));
723
724                         // Cache it away
725                         $GLOBALS['admin_hash'] = $valPass;
726
727                         // Count cache hits
728                         incrementStatsEntry('cache_hits');
729                 } elseif ((!empty($adminLogin)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminLogin) === false))) {
730                         // Get admin hash and hash it
731                         $valPass = encodeHashForCookie(getAdminHash($adminLogin));
732
733                         // Cache it away
734                         $GLOBALS['admin_hash'] = $valPass;
735                 }
736
737                 if (!empty($valPass)) {
738                         // Check if password is valid
739                         //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'<br />');
740                         $GLOBALS['is_admin'][$adminLogin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
741                 } // END - if
742         } // END - if
743
744         // Return result of comparision
745         return $GLOBALS['is_admin'][$adminLogin];
746 }
747
748 // Generates a list of "max receiveable emails per day"
749 function addMaxReceiveList ($mode, $default = '', $return = false) {
750         $OUT = '';
751         $result = false;
752
753         switch ($mode) {
754                 case 'guest':
755                         // Guests (in the registration form) are not allowed to select 0 mails per day.
756                         $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC",
757                         __FUNCTION__, __LINE__);
758                         break;
759
760                 case 'member':
761                         // Members are allowed to set to zero mails per day (we will change this soon!)
762                         $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC",
763                         __FUNCTION__, __LINE__);
764                         break;
765
766                 default: // Invalid!
767                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
768                         break;
769         }
770
771         // Some entries are found?
772         if (SQL_NUMROWS($result) > 0) {
773                 $OUT = '';
774                 while ($content = SQL_FETCHARRAY($result)) {
775                         $OUT .= '      <option value="' . $content['value'] . '"';
776                         if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
777                         $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
778                         if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
779                         $OUT .= '</option>';
780                 }
781
782                 // Load template
783                 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
784         } else {
785                 // Maybe the admin has to setup some maximum values?
786                 debug_report_bug('Nothing is being done here?');
787         }
788
789         // Free result
790         SQL_FREERESULT($result);
791
792         if ($return === true) {
793                 // Return generated HTML code
794                 return $OUT;
795         } else {
796                 // Output directly (default)
797                 outputHtml($OUT);
798         }
799 }
800
801 // Checks wether the given email address is used.
802 function isEmailTaken ($email) {
803         // Query the database
804         $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",
805                 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
806
807         // Is the email there?
808         $ret = (SQL_NUMROWS($result) == 1);
809
810         // Free the result
811         SQL_FREERESULT($result);
812
813         // Return result
814         return $ret;
815 }
816
817 // Validate the given menu action
818 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
819         // Is the cache entry there and we shall not update?
820         if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
821                 // Count cache hit
822                 incrementStatsEntry('cache_hits');
823
824                 // Then use this cache
825                 return $GLOBALS['action_valid'][$mode][$action][$what];
826         } // END - if
827
828         // By default nothing is valid
829         $ret = false;
830
831         // Look in all menus or only unlocked
832         $add = '';
833         if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
834
835         //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*<br />");
836         if (($mode != 'admin') && ($updateEntry === true)) {
837                 // Update guest or member menu
838                 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
839                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
840         } elseif (($what != 'overview') && (!empty($what))) {
841                 // Other actions
842                 $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",
843                         array($mode, $action, $what), __FUNCTION__, __LINE__, false);
844         } else {
845                 // Admin login overview
846                 $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",
847                         array($mode, $action), __FUNCTION__, __LINE__, false);
848         }
849
850         // Run SQL command
851         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
852
853         // Should we look for affected rows (only update) or found rows?
854         if ($updateEntry === true) {
855                 // Check updated/affected rows
856                 $ret = (SQL_AFFECTEDROWS() == 1);
857         } else {
858                 // Check found rows
859                 $ret = (SQL_NUMROWS($result) == 1);
860         }
861
862         // Free memory
863         SQL_FREERESULT($result);
864
865         // Set cache entry
866         $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
867
868         // Return result
869         return $ret;
870 }
871
872 // Get action value from mode (admin/guest/member) and what-value
873 function getActionFromModuleWhat ($module, $what) {
874         // Init status
875         $data['action'] = '';
876
877         //* DEBUG: */ print(__LINE__.'='.$module.'/'.$what.'/'.getAction()."=<br />");
878         if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
879                 // sql_patches is missing so choose depending on mode
880                 if (isWhatSet()) {
881                         // Use setted what
882                         $what = getWhat();
883                 } elseif ($module == 'admin') {
884                         // Admin area
885                         $what = 'overview';
886                 } else {
887                         // Everywhere else
888                         $what = 'welcome';
889                 }
890         } elseif ((empty($what)) && ($module != 'admin')) {
891                 // Use configured 'home'
892                 $what = getConfig('index_home');
893         } // END - if
894
895         if ($module == 'admin') {
896                 // Action value for admin area
897                 if (isGetRequestParameterSet('action')) {
898                         // Use from request!
899                         return getRequestParameter('action');
900                 } elseif (isActionSet()) {
901                         // Get it directly from URL
902                         return getAction();
903                 } elseif (($what == 'overview') || (!isWhatSet())) {
904                         // Default value for admin area
905                         $data['action'] = 'login';
906                 }
907         } elseif (isActionSet()) {
908                 // Get it directly from URL
909                 return getAction();
910         }
911         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ret=' . $data['action'] . '<br />');
912
913         // Does the module have a menu?
914         if (ifModuleHasMenu($module)) {
915                 // Rewriting modules to menu
916                 $module = mapModuleToTable($module);
917
918                 // Guest and member menu is 'main' as the default
919                 if (empty($data['action'])) $data['action'] = 'main';
920
921                 // Load from database
922                 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
923                         array($module, $what), __FUNCTION__, __LINE__);
924                 if (SQL_NUMROWS($result) == 1) {
925                         // Load action value and pray that this one is the right you want... ;-)
926                         $data = SQL_FETCHARRAY($result);
927                 } // END - if
928
929                 // Free memory
930                 SQL_FREERESULT($result);
931         } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
932                 // No sql_patches installed, but maybe we need to register an admin?
933                 if (isAdminRegistered()) {
934                         // Redirect to admin area
935                         redirectToUrl('admin.php');
936                 } // END - if
937         }
938
939         // Return action value
940         return $data['action'];
941 }
942
943 // Get category name back
944 function getCategory ($cid) {
945         // Default is not found
946         $data['cat'] = getMessage('_CATEGORY_404');
947
948         // Is the category id set?
949         if ($cid == '0') {
950                 // No category
951                 $data['cat'] = getMessage('_CATEGORY_NONE');
952         } elseif ($cid > 0) {
953                 // Lookup the category in database
954                 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
955                         array(bigintval($cid)), __FUNCTION__, __LINE__);
956                 if (SQL_NUMROWS($result) == 1) {
957                         // Category found... :-)
958                         $data = SQL_FETCHARRAY($result);
959                 } // END - if
960
961                 // Free result
962                 SQL_FREERESULT($result);
963         } // END - if
964
965         // Return result
966         return $data['cat'];
967 }
968
969 // Get a string of "mail title" and price back
970 function getPaymentTitlePrice ($pid, $full=false) {
971         // Default is not found
972         $ret = getMessage('_PAYMENT_404');
973
974         // Load payment data
975         $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
976                 array(bigintval($pid)), __FUNCTION__, __LINE__);
977         if (SQL_NUMROWS($result) == 1) {
978                 // Payment type found... :-)
979                 $data = SQL_FETCHARRAY($result);
980
981                 // Only title or also including price?
982                 if ($full === false) {
983                         $ret = $data['mail_title'];
984                 } else {
985                         $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
986                 }
987         }
988
989         // Free result
990         SQL_FREERESULT($result);
991
992         // Return result
993         return $ret;
994 }
995
996 // Get (basicly) the price of given payment id
997 function getPaymentPoints ($pid, $lookFor = 'price') {
998         // Default value...
999         $data[$lookFor] = '-1';
1000
1001         // Search for it in database
1002         $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1003                 array($lookFor, $pid), __FUNCTION__, __LINE__);
1004
1005         // Is the entry there?
1006         if (SQL_NUMROWS($result) == 1) {
1007                 // Payment type found... :-)
1008                 $data = SQL_FETCHARRAY($result);
1009         } // END - if
1010
1011         // Free result
1012         SQL_FREERESULT($result);
1013
1014         // Return value
1015         return $data[$lookFor];
1016 }
1017
1018 // Remove a receiver's id from $receivers and add a link for him to confirm
1019 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1020         // Default is not removed
1021         $ret = 'failed';
1022
1023         // Is the userid valid?
1024         if ($userid > 0) {
1025                 // Remove entry from array
1026                 unset($receivers[$key]);
1027
1028                 // Is there already a line for this user available?
1029                 if ($stats_id > 0) {
1030                         // Only when we got a real stats id continue searching for the entry
1031                         $type = 'NORMAL'; $rowName = 'stats_id';
1032                         if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1033
1034                         // Try to look the entry up
1035                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1036                                 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1037
1038                         // Was it *not* found?
1039                         if (SQL_NUMROWS($result) == '0') {
1040                                 // So we add one!
1041                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1042                                         array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1043                                 $ret = 'done';
1044                         } else {
1045                                 // Already found
1046                                 $ret = 'already';
1047                         }
1048
1049                         // Free memory
1050                         SQL_FREERESULT($result);
1051                 }
1052         }
1053
1054         // Return status for sending routine
1055         return $ret;
1056 }
1057
1058 // Calculate sum (default) or count records of given criteria
1059 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1060         // Init count/sum
1061         $data['res'] = '0';
1062
1063         //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />');
1064         if ((empty($search)) && ($search != '0')) {
1065                 // Count or sum whole table?
1066                 if ($countRows === true) {
1067                         // Count whole table
1068                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1069                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1070                 } else {
1071                         // Sum whole table
1072                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1073                                 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1074                 }
1075         } elseif (($countRows === true) || ($lookFor == 'userid')) {
1076                 // Count rows
1077                 //* DEBUG: */ print("COUNT!<br />");
1078                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1079                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1080         } else {
1081                 // Add all rows
1082                 //* DEBUG: */ print("SUM!<br />");
1083                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1084                         array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1085         }
1086
1087         // Load row
1088         $data = SQL_FETCHARRAY($result);
1089
1090         // Free result
1091         SQL_FREERESULT($result);
1092
1093         // Fix empty values
1094         if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1095                 // Float number
1096                 $data['res'] = '0.00000';
1097         } elseif (''.$data['res'].'' == '') {
1098                 // Fix empty result
1099                 $data['res'] = '0';
1100         }
1101
1102         // Return value
1103         //* DEBUG: */ print 'ret=' . $data['res'] . '<br />';
1104         return $data['res'];
1105 }
1106 // Getter fro ref level percents
1107 function getReferalLevelPercents ($level) {
1108         // Default is zero
1109         $data['percents'] = '0';
1110
1111         // Do we have cache?
1112         if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1113                 // First look for level
1114                 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1115                 if ($key !== false) {
1116                         // Entry found!
1117                         $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1118
1119                         // Count cache hit
1120                         incrementStatsEntry('cache_hits');
1121                 } // END - if
1122         } elseif (!isExtensionActive('cache')) {
1123                 // Get referal data
1124                 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1125                         array(bigintval($level)), __FUNCTION__, __LINE__);
1126
1127                 // Entry found?
1128                 if (SQL_NUMROWS($result_level) == 1) {
1129                         // Get percents
1130                         $data = SQL_FETCHARRAY($result_level);
1131                 } // END - if
1132
1133                 // Free result
1134                 SQL_FREERESULT($result_level);
1135         }
1136
1137         // Return percent
1138         return $data['percents'];
1139 }
1140
1141 /**
1142  *
1143  * Dynamic referal system, can also send mails!
1144  *
1145  * subject     = Subject line, write in lower-case letters and underscore is allowed
1146  * userid         = Referal id wich should receive...
1147  * points      = ... xxx points
1148  * sendNotify  = shall I send the referal an email or not?
1149  * rid         = inc/modules/guest/what-confirm.php need this
1150  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
1151  * add_mode    = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1152  *               for default value will cause no referal will get points ever!!!)
1153  */
1154 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1155         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
1156         // Convert mode to lower-case
1157         $add_mode = strtolower($add_mode);
1158
1159         // When $userid = '0' add points to jackpot
1160         if (($userid == '0') && (isExtensionActive('jackpot'))) {
1161                 // Add points to jackpot
1162                 addPointsToJackpot($points);
1163                 return;
1164         } // END - if
1165
1166         // Prepare data for the filter
1167         $filterData = array(
1168                 'subject'  => $subject,
1169                 'userid'   => $userid,
1170                 'points'   => $points,
1171                 'notify'   => $sendNotify,
1172                 'rid'      => $rid,
1173                 'locked'   => $locked,
1174                 'mode'     => 'add',
1175                 'sub_mode' => $add_mode,
1176         );
1177
1178         // Filter it now
1179         runFilterChain('add_points', $filterData);
1180
1181         // Count up referal depth
1182         if (!isset($GLOBALS['ref_level'])) {
1183                 // Initialialize referal system
1184                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>): Referal system initialized!<br />");
1185                 $GLOBALS['ref_level'] = '0';
1186         } else {
1187                 // Increase referal level
1188                 $GLOBALS['ref_level']++;
1189                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />");
1190         }
1191
1192         // Default is 'normal' points
1193         $data = 'points';
1194
1195         // Which points, locked or normal?
1196         if ($locked === true) $data = 'locked_points';
1197
1198         // Check user account
1199         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points}<br />");
1200         if (fetchUserData($userid)) {
1201                 // This is the user and his ref
1202                 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1203
1204                 // Get percents
1205                 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1206                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />");
1207
1208                 // Some percents found?
1209                 if ($per > 0) {
1210                         // Calculate new points
1211                         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />");
1212                         $ref_points = $points * $per / 100;
1213
1214                         // Pay refback here if level > 0 and in ref-mode
1215                         if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1216                                 //* 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 />");
1217                                 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1218                                 //* 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 />");
1219                         } // END - if
1220
1221                         // Update points...
1222                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`='%s' LIMIT 1",
1223                                 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1224                         //* 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 />");
1225
1226                         // No entry updated?
1227                         if (SQL_AFFECTEDROWS() < 1) {
1228                                 // First ref in this level! :-)
1229                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,'%s',%s)",
1230                                         array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __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} - INSERTED! (".SQL_AFFECTEDROWS().")<br />");
1232                         } // END - if
1233
1234                         // Points updated, maybe I shall send him an email?
1235                         if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
1236                                 // Prepare content
1237                                 $content = array(
1238                                         'percents' => $per,
1239                                         'level'    => bigintval($GLOBALS['ref_level']),
1240                                         'points'   => $ref_points,
1241                                         'refid'    => getUserData('refid')
1242                                 );
1243
1244                                 // Load email template
1245                                 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1246
1247                                 // Send email
1248                                 sendEmail($userid, getMessage('THANX_REFERAL_ONE_SUBJECT'), $message);
1249                         } elseif (($sendNotify === true) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
1250                                 // Prepare content
1251                                 $content = array(
1252                                         'text'   => getMessage('REASON_DIRECT_PAYMENT'),
1253                                         'points' => translateComma($ref_points)
1254                                 );
1255
1256                                 // Load message
1257                                 $message = loadEmailTemplate('add-points', $content, $userid);
1258
1259                                 // And sent it away
1260                                 sendEmail($userid, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1261                                 if (!isGetRequestParameterSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1262                         }
1263
1264                         // Maybe there's another ref?
1265                         if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1266                                 // Then let's credit him here...
1267                                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},ref=".getUserData('refid').",points={$points} - ADVANCE!<br />");
1268                                 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1269                         } // END - if
1270                 } // END - if
1271         } // END - if
1272
1273         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
1274 }
1275
1276 // Updates the referal counter
1277 function updateReferalCounter ($userid) {
1278         // Make it sure referal level zero (member him-/herself) is at least selected
1279         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1280         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}<br />");
1281
1282         // Update counter
1283         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1284                 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1285
1286         // When no entry was updated then we have to create it here
1287         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
1288         if (SQL_AFFECTEDROWS() < 1) {
1289                 // First count!
1290                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1291                         array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1292                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid}<br />");
1293         } // END - if
1294
1295         // Init referal id
1296         $ref = '0';
1297
1298         // Check for his referal
1299         if (fetchUserData($userid)) {
1300                 // Get it
1301                 $ref = getUserData('refid');
1302         } // END - if
1303
1304         //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):userid={$userid},ref={$ref}<br />");
1305
1306         // When he has a referal...
1307         if (($ref > 0) && ($ref != $userid)) {
1308                 // Move to next referal level and count his counter one up!
1309                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):ref={$ref} - ADVANCE!<br />");
1310                 $GLOBALS['cache_array']['ref_level'][$userid]++;
1311                 updateReferalCounter($ref);
1312         } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1313                 // Remove cache here
1314                 //* DEBUG: */ print(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__."</font>):ref={$ref} - CACHE!<br />");
1315                 rebuildCache('refsystem', 'refsystem');
1316         }
1317
1318         // "Walk" back here
1319         $GLOBALS['cache_array']['ref_level'][$userid]--;
1320
1321         // Handle refback here if extension is installed
1322         if (isExtensionActive('refback')) {
1323                 updateRefbackTable($userid);
1324         } // END - if
1325 }
1326
1327 // Sends out mail to all administrators. This function is no longer obsolete
1328 // because we need it when there is no ext-admins installed
1329 function sendAdminEmails ($subj, $message) {
1330         // Load all admin email addresses
1331         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1332         while ($content = SQL_FETCHARRAY($result)) {
1333                 // Send the email out
1334                 sendEmail($content['email'], $subj, $message);
1335         } // END - if
1336
1337         // Free result
1338         SQL_FREERESULT($result);
1339
1340         // Really simple... ;-)
1341 }
1342
1343 // Get id number from administrator's login name
1344 function getAdminId ($adminLogin) {
1345         // By default no admin is found
1346         $data['id'] = '-1';
1347
1348         // Check cache
1349         if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1350                 // Use it if found to save SQL queries
1351                 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1352
1353                 // Update cache hits
1354                 incrementStatsEntry('cache_hits');
1355         } elseif (!isExtensionActive('cache')) {
1356                 // Load from database
1357                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1358                         array($adminLogin), __FUNCTION__, __LINE__);
1359
1360                 // Do we have an entry?
1361                 if (SQL_NUMROWS($result) == 1) {
1362                         // Get it
1363                         $data = SQL_FETCHARRAY($result);
1364                 } // END - if
1365
1366                 // Free result
1367                 SQL_FREERESULT($result);
1368         }
1369
1370         // Return the id
1371         return $data['id'];
1372 }
1373
1374 // "Getter" for current admin id
1375 function getCurrentAdminId () {
1376         // Do we have cache?
1377         if (!isset($GLOBALS['current_admin_id'])) {
1378                 // Get the admin login from session
1379                 $adminLogin = getSession('admin_login');
1380
1381                 // "Solve" it into an id
1382                 $adminId = getAdminId($adminLogin);
1383
1384                 // Remember in cache securely
1385                 setCurrentAdminId(bigintval($adminId));
1386         } // END - if
1387
1388         // Return it
1389         return $GLOBALS['current_admin_id'];
1390 }
1391
1392 // Setter for current admin id
1393 function setCurrentAdminId ($currentAdminId) {
1394         // Set it secured
1395         $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1396 }
1397
1398 // Get password hash from administrator's login name
1399 function getAdminHash ($adminLogin) {
1400         // By default an invalid hash is returned
1401         $data['password'] = '-1';
1402
1403         if (isAdminHashSet($adminLogin)) {
1404                 // Check cache
1405                 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminLogin];
1406
1407                 // Update cache hits
1408                 incrementStatsEntry('cache_hits');
1409         } elseif (!isExtensionActive('cache')) {
1410                 // Load from database
1411                 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1412                         array($adminLogin), __FUNCTION__, __LINE__);
1413
1414                 // Do we have an entry?
1415                 if (SQL_NUMROWS($result) == 1) {
1416                         // Fetch data
1417                         $data = SQL_FETCHARRAY($result);
1418
1419                         // Set cache
1420                         setAdminHash($adminLogin, $data['password']);
1421                 } // END - if
1422
1423                 // Free result
1424                 SQL_FREERESULT($result);
1425         }
1426
1427         // Return password hash
1428         return $data['password'];
1429 }
1430
1431 // "Getter" for admin login
1432 function getAdminLogin ($adminId) {
1433         // By default a non-existent login is returned (other functions react on this!)
1434         $data['login'] = '***';
1435
1436         if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1437                 // Get cache
1438                 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1439
1440                 // Update cache hits
1441                 incrementStatsEntry('cache_hits');
1442         } elseif (!isExtensionActive('cache')) {
1443                 // Load from database
1444                 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1445                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1446
1447                 // Entry found?
1448                 if (SQL_NUMROWS($result) == 1) {
1449                         // Fetch data
1450                         $data = SQL_FETCHARRAY($result);
1451
1452                         // Set cache
1453                         $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1454                 } // END - if
1455
1456                 // Free memory
1457                 SQL_FREERESULT($result);
1458         }
1459
1460         // Return the result
1461         return $data['login'];
1462 }
1463
1464 // Get email address of admin id
1465 function getAdminEmail ($adminId) {
1466         // By default an invalid emails is returned
1467         $data['email'] = '***';
1468
1469         if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1470                 // Get cache
1471                 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1472
1473                 // Update cache hits
1474                 incrementStatsEntry('cache_hits');
1475         } elseif (!isExtensionActive('cache')) {
1476                 // Load from database
1477                 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1478                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1479
1480                 // Entry found?
1481                 if (SQL_NUMROWS($result_admin_id) == 1) {
1482                         // Get data
1483                         $data = SQL_FETCHARRAY($result_admin_id);
1484
1485                         // Set cache
1486                         $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1487                 } // END - if
1488
1489                 // Free result
1490                 SQL_FREERESULT($result_admin_id);
1491         }
1492
1493         // Return email
1494         return $data['email'];
1495 }
1496
1497 // Get default ACL  of admin id
1498 function getAdminDefaultAcl ($adminId) {
1499         // By default an invalid ACL value is returned
1500         $data['default_acl'] = '***';
1501
1502         // Is sql_patches there and was it found in cache?
1503         if (!isExtensionActive('sql_patches')) {
1504                 // Not found, which is bad, so we need to allow all
1505                 $data['default_acl'] =  'allow';
1506         } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1507                 // Use cache
1508                 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1509
1510                 // Update cache hits
1511                 incrementStatsEntry('cache_hits');
1512         } elseif (!isExtensionActive('cache')) {
1513                 // Load from database
1514                 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1515                         array(bigintval($adminId)), __FUNCTION__, __LINE__);
1516                 if (SQL_NUMROWS($result_admin_id) == 1) {
1517                         // Fetch data
1518                         $data = SQL_FETCHARRAY($result_admin_id);
1519
1520                         // Set cache
1521                         $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1522                 }
1523
1524                 // Free result
1525                 SQL_FREERESULT($result_admin_id);
1526         }
1527
1528         // Return default ACL
1529         return $data['default_acl'];
1530 }
1531
1532 // Generates an option list from various parameters
1533 function generateOptionList ($table, $id, $name, $default='', $special='', $where='', $disabled=array()) {
1534         $ret = '';
1535         if ($table == '/ARRAY/') {
1536                 // Selection from array
1537                 if ((is_array($id)) && (is_array($name)) && (count($id)) == (count($name))) {
1538                         // Both are arrays
1539                         foreach ($id as $idx => $value) {
1540                                 $ret .= '<option value="' . $value . '"';
1541                                 if ($default == $value) {
1542                                         // Selected by default
1543                                         $ret .= ' selected="selected"';
1544                                 } elseif (isset($disabled[$value])) {
1545                                         // Disabled!
1546                                         $ret .= ' disabled="disabled"';
1547                                 }
1548                                 $ret .= '>' . $name[$idx] . '</option>';
1549                         } // END - foreach
1550                 } else {
1551                         // Problem in request
1552                         debug_report_bug('Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name));
1553                 }
1554         } else {
1555                 // Data from database
1556                 $SPEC = ', `' . $id . '`';
1557                 if (!empty($special)) $SPEC = ', `' . $special . '`';
1558
1559                 // Query the database
1560                 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1561                         array(
1562                                 $id,
1563                                 $name,
1564                                 $table,
1565                                 $name
1566                         ), __FUNCTION__, __LINE__);
1567
1568                 // Do we have rows?
1569                 if (SQL_NUMROWS($result) > 0) {
1570                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1571                         // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1572                         while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1573                                 if (empty($special)) $add = '';
1574                                 $ret .= '<option value="' . $value . '"';
1575                                 if ($default == $value) {
1576                                         // Selected by default
1577                                         $ret .= ' selected="selected"';
1578                                 } elseif (isset($disabled[$value])) {
1579                                         // Disabled!
1580                                         $ret .= ' disabled="disabled"';
1581                                 }
1582                                 if (!empty($add)) $add = ' ('.$add.')';
1583                                 $ret .= '>' . $title . $add . '</option>';
1584                         } // END - while
1585                 } else {
1586                         // No data found
1587                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1588                 }
1589
1590                 // Free memory
1591                 SQL_FREERESULT($result);
1592         }
1593
1594         // Return - hopefully - the requested data
1595         return $ret;
1596 }
1597 // Activate exchange
1598 function FILTER_ACTIVATE_EXCHANGE () {
1599         // Is the extension 'user' there?
1600         if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
1601                 // Silently abort here
1602                 return false;
1603         } // END - if
1604
1605         // Check total amount of users
1606         $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1607
1608         if ($totalUsers >= getConfig('activate_xchange')) {
1609                 // Activate System
1610                 setSqlsArray(array(
1611                         "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1612                         "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1613                 ));
1614
1615                 // Run SQLs
1616                 runFilterChain('run_sqls');
1617
1618                 // Update configuration
1619                 updateConfiguration('activate_xchange' ,0);
1620
1621                 // Rebuild cache
1622                 rebuildCache('modules', 'modules');
1623         } // END - if
1624 }
1625
1626 // Deletes a user account with given reason
1627 function deleteUserAccount ($userid, $reason) {
1628         // Init points
1629         $data['points'] = '0';
1630
1631         $result = SQL_QUERY_ESC("SELECT
1632         (SUM(p.points) - d.used_points) AS points
1633 FROM
1634         `{?_MYSQL_PREFIX?}_user_points` AS p
1635 LEFT JOIN
1636         `{?_MYSQL_PREFIX?}_user_data` AS d
1637 ON
1638         p.userid=d.userid
1639 WHERE
1640         p.userid=%s",
1641                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1642
1643         // Do we have an entry?
1644         if (SQL_NUMROWS($result) == 1) {
1645                 // Save his points to add them to the jackpot
1646                 $data = SQL_FETCHARRAY($result);
1647
1648                 // Delete points entries as well
1649                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
1650
1651                 // Update mediadata as well
1652                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1653                         // Update database
1654                         updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1655                 } // END - if
1656
1657                 // Now, when we have all his points adds them do the jackpot!
1658                 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1659         } // END - if
1660
1661         // Free the result
1662         SQL_FREERESULT($result);
1663
1664         // Delete category selections as well...
1665         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1666                 array(bigintval($userid)), __FUNCTION__, __LINE__);
1667
1668         // Remove from rallye if found
1669         // @TODO Rewrite this to a filter
1670         if (isExtensionActive('rallye')) {
1671                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1672                         array(bigintval($userid)), __FUNCTION__, __LINE__);
1673         } // END - if
1674
1675         // Add reason and translate points
1676         $data['text']   = $reason;
1677         $data['points'] = translateComma($data['points']);
1678
1679         // Now a mail to the user and that's all...
1680         $message = loadEmailTemplate('del-user', $data, $userid);
1681         sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1682
1683         // Ok, delete the account!
1684         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1685 }
1686
1687 // Gets the matching what name from module
1688 function getWhatFromModule ($modCheck) {
1689         // Is the request element set?
1690         if (isGetRequestParameterSet('what')) {
1691                 // Then return this!
1692                 return getRequestParameter('what');
1693         } // END - if
1694
1695         // Default is empty
1696         $what = '';
1697
1698         //* DEBUG: */ print(__LINE__.'!'.$modCheck."!<br />");
1699         switch ($modCheck) {
1700                 case 'admin':
1701                         $what = 'overview';
1702                         break;
1703
1704                 case 'login':
1705                 case 'index':
1706                         // Is ext-sql_patches installed and newer than 0.0.5?
1707                         if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1708                                 // Use it from config
1709                                 $what = getConfig('index_home');
1710                         } else {
1711                                 // Use default 'welcome'
1712                                 $what = 'welcome';
1713                         }
1714                         break;
1715
1716                 default:
1717                         $what = '';
1718                         break;
1719         } // END - switch
1720
1721         // Return what value
1722         return $what;
1723 }
1724
1725 // Subtract points from database and mediadata cache
1726 function subtractPoints ($subject, $userid, $points) {
1727         // Add points to used points
1728         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1729                 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1730
1731         // Prepare filter data
1732         $filterData = array(
1733                 'subject' => $subject,
1734                 'userid'  => $userid,
1735                 'points'  => $points,
1736                 'mode'    => 'sub'
1737         );
1738
1739         // Insert booking record
1740         runFilterChain('sub_points', $filterData);
1741 }
1742
1743 // "Getter" for total available receivers
1744 function getTotalReceivers ($mode='normal') {
1745         // Query database
1746         $result_all = SQL_QUERY("SELECT
1747         `userid`
1748 FROM
1749         `{?_MYSQL_PREFIX?}_user_data`
1750 WHERE
1751         `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1752         __FUNCTION__, __LINE__);
1753
1754         // Get num rows
1755         $numRows = SQL_NUMROWS($result_all);
1756
1757         // Free result
1758         SQL_FREERESULT($result_all);
1759
1760         // Return value
1761         return $numRows;
1762 }
1763
1764 // Returns HTML code with an option list of all categories
1765 function generateCategoryOptionsList ($mode) {
1766         // Prepare WHERE statement
1767         $whereStatement = " WHERE `visible`='Y'";
1768         if (isAdmin()) $whereStatement = '';
1769
1770         // Initialize array...
1771         $CATS = array(
1772                 'id'   => array(),
1773                 'name' => array(),
1774                 'userids' => array()
1775         );
1776
1777         // Get categories
1778         $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC",
1779                 __FUNCTION__, __LINE__);
1780
1781         // Do we have entries?
1782         if (SQL_NUMROWS($result) > 0) {
1783                 // ... and begin loading stuff
1784                 while ($content = SQL_FETCHARRAY($result)) {
1785                         // Transfer some data
1786                         $CATS['id'][]   = $content['id'];
1787                         $CATS['name'][] = $content['cat'];
1788
1789                         // Check which users are in this category
1790                         $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1791                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1792
1793                         // Init count
1794                         $userid_cnt = '0';
1795
1796                         // Start adding all
1797                         while ($data = SQL_FETCHARRAY($result_userids)) {
1798                                 // Add user count
1799                                 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1800                         } // END - while
1801
1802                         // Free memory
1803                         SQL_FREERESULT($result_userids);
1804
1805                         // Add counter
1806                         $CATS['userids'][] = $userid_cnt;
1807                 } // END - while
1808
1809                 // Free memory
1810                 SQL_FREERESULT($result);
1811
1812                 // Generate options
1813                 $OUT = '';
1814                 foreach ($CATS['id'] as $key => $value) {
1815                         if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1816                         $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1817                 } // END - foreach
1818         } else {
1819                 // No cateogries are defined yet
1820                 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1821         }
1822
1823         // Return HTML code
1824         return $OUT;
1825 }
1826
1827 // Add bonus mail to queue
1828 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1829         // Is admin or bonus extension there?
1830         if (!isAdmin()) {
1831                 // Abort here
1832                 return false;
1833         } elseif (!isExtensionActive('bonus')) {
1834                 // Abort here
1835                 return false;
1836         }
1837
1838         // Calculcate target sent
1839         $target = countSelection(explode(';', $receiverList));
1840
1841         // Receiver is zero?
1842         if ($receiver == '0') {
1843                 // Then auto-fix it
1844                 $receiver = $target;
1845         } // END - if
1846
1847         // HTML extension active?
1848         if (isExtensionActive('html_mail')) {
1849                 // No HTML by default
1850                 $HTML = 'N';
1851
1852                 // HTML mode?
1853                 if ($mode == 'html') $HTML = 'Y';
1854
1855                 // Add HTML mail
1856                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1857 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1858 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1859                 array(
1860                         $subject,
1861                         $text,
1862                         $receiverList,
1863                         $points,
1864                         $seconds,
1865                         $url,
1866                         $cat,
1867                         $target,
1868                         bigintval($receiver),
1869                         $HTML
1870                 ), __FUNCTION__, __LINE__);
1871         } else {
1872                 // Add regular mail
1873                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1874 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1875 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1876                 array(
1877                         $subject,
1878                         $text,
1879                         $receiverList,
1880                         $points,
1881                         $seconds,
1882                         $url,
1883                         $cat,
1884                         $target,
1885                         bigintval($receiver),
1886                 ), __FUNCTION__, __LINE__);
1887         }
1888 }
1889
1890 // Generate a receiver list for given category and maximum receivers
1891 function generateReceiverList ($cat, $receiver, $mode = '') {
1892         // Init variables
1893         $CAT_TABS     = '';
1894         $CAT_WHERE    = '';
1895         $receiverList = '';
1896         $result       = false;
1897
1898         // Secure data
1899         $cat      = bigintval($cat);
1900         $receiver = bigintval($receiver);
1901
1902         // Is the receiver zero and mode set?
1903         if (($receiver == '0') && (!empty($mode))) {
1904                 // Auto-fix receiver maximum
1905                 $receiver = getTotalReceivers($mode);
1906         } // END - if
1907
1908         // Category given?
1909         if ($cat > 0) {
1910                 // Select category
1911                 $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1912                 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1913         } // END - if
1914
1915         // Exclude users in holiday?
1916         if (getExtensionVersion('holiday') >= '0.1.3') {
1917                 // Add something for the holiday extension
1918                 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1919         } // END - if
1920
1921         if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1922                 // Only include HTML receivers
1923                 $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",
1924                         array(
1925                                 $receiver
1926                         ), __FUNCTION__, __LINE__);
1927         } else {
1928                 // Include all
1929                 $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",
1930                         array(
1931                                 $receiver
1932                         ), __FUNCTION__, __LINE__);
1933         }
1934
1935         // Entries found?
1936         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1937                 // Load all entries
1938                 while ($content = SQL_FETCHARRAY($result)) {
1939                         // Add receiver when not empty
1940                         if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
1941                 } // END - while
1942
1943                 // Free memory
1944                 SQL_FREERESULT($result);
1945
1946                 // Remove trailing semicolon
1947                 $receiverList = substr($receiverList, 0, -1);
1948         } // END - if
1949
1950         // Return list
1951         return $receiverList;
1952 }
1953
1954 // Get timestamp for given stats type and data
1955 function getTimestampFromUserStats ($statsType, $statsData, $userid = '0') {
1956         // Default timestamp is zero
1957         $data['inserted'] = '0';
1958
1959         // User id set?
1960         if ((isMemberIdSet()) && ($userid == '0')) {
1961                 $userid = getMemberId();
1962         } // END - if
1963
1964         // Is the extension installed and updated?
1965         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
1966                 // Return zero here
1967                 return $data['inserted'];
1968         } // END - if
1969
1970         // Try to find the entry
1971         $result = SQL_QUERY_ESC("SELECT
1972         UNIX_TIMESTAMP(`inserted`) AS inserted
1973 FROM
1974         `{?_MYSQL_PREFIX?}_user_stats_data`
1975 WHERE
1976         `userid`=%s AND
1977         `stats_type`='%s' AND
1978         `stats_data`='%s'
1979 LIMIT 1",
1980                 array(
1981                         bigintval($userid),
1982                         $statsType,
1983                         $statsData
1984                 ), __FUNCTION__, __LINE__);
1985
1986         // Is the entry there?
1987         if (SQL_NUMROWS($result) == 1) {
1988                 // Get this stamp
1989                 $data = SQL_FETCHARRAY($result);
1990         } // END - if
1991
1992         // Free result
1993         SQL_FREERESULT($result);
1994
1995         // Return stamp
1996         return $data['inserted'];
1997 }
1998
1999 // Inserts user stats
2000 function insertUserStatsRecord ($userid, $statsType, $statsData) {
2001         // Is the extension installed and updated?
2002         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
2003                 // Return zero here
2004                 return false;
2005         } // END - if
2006
2007         // Does it exist?
2008         if ((!getTimestampFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
2009                 // Then insert it!
2010                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2011                         array(bigintval($userid), $statsType, $statsData), __FUNCTION__, __LINE__);
2012         } elseif (is_array($statsData)) {
2013                 // Invalid data!
2014                 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$statsType},data={".gettype($statsData).": Invalid statistics data type!");
2015         }
2016 }
2017
2018 // "Getter" for array for user refs and points in given level
2019 function getUserReferalPoints ($userid, $level) {
2020         //* DEBUG: */ print("----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n");
2021         // Default is no refs and no nickname
2022         $add = '';
2023         $refs = array();
2024
2025         // Do we have nickname extension installed?
2026         if (isExtensionActive('nickname')) {
2027                 $add = ', ud.nickname';
2028         } // END - if
2029
2030         // Get refs from database
2031         $result = SQL_QUERY_ESC("SELECT
2032         ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2033 FROM
2034         `{?_MYSQL_PREFIX?}_user_refs` AS ur
2035 LEFT JOIN
2036         `{?_MYSQL_PREFIX?}_user_points` AS up
2037 ON
2038         ur.refid=up.userid AND ur.level=0
2039 LEFT JOIN
2040         `{?_MYSQL_PREFIX?}_user_data` AS ud
2041 ON
2042         ur.refid=ud.userid
2043 WHERE
2044         ur.userid=%s AND ur.level=%s
2045 ORDER BY
2046         ur.refid ASC",
2047                 array(
2048                         bigintval($userid),
2049                         bigintval($level)
2050                 ), __FUNCTION__, __LINE__);
2051
2052         // Are there some entries?
2053         if (SQL_NUMROWS($result) > 0) {
2054                 // Fetch all entries
2055                 while ($row = SQL_FETCHARRAY($result)) {
2056                         // Get total points of this user
2057                         $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2058
2059                         // Get unconfirmed mails
2060                         $row['unconfirmed']  = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2061
2062                         // Init clickrate with zero
2063                         $row['clickrate'] = '0';
2064
2065                         // Is at least one mail received?
2066                         if ($row['emails_received'] > 0) {
2067                                 // Calculate clickrate
2068                                 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2069                         } // END - if
2070
2071                         // Activity is 'active' by default because if autopurge is not installed
2072                         $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2073
2074                         // Is autopurge installed and the user inactive?
2075                         if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online']))  {
2076                                 // Inactive user!
2077                                 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2078                         } // END - if
2079
2080                         // Remove some entries
2081                         unset($row['mails_confirmed']);
2082                         unset($row['emails_received']);
2083                         unset($row['last_online']);
2084
2085                         // Add row
2086                         $refs[$row['id']] = $row;
2087                 } // END - while
2088         } // END - if
2089
2090         // Free result
2091         SQL_FREERESULT($result);
2092
2093         // Return result
2094         //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
2095         return $refs;
2096 }
2097
2098 // Recuce the amount of received emails for the receipients for given email
2099 function reduceRecipientReceivedMails ($column, $id, $count) {
2100         // Search for mail in database
2101         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2102                 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2103
2104         // Are there entries?
2105         if (SQL_NUMROWS($result) > 0) {
2106                 // Now load all userids for one big query!
2107                 $userids = array();
2108                 while ($data = SQL_FETCHARRAY($result)) {
2109                         // By default we want to reduce and have no mails found
2110                         $num = 0;
2111
2112                         // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
2113                         // @TODO Rewrite this to a filter
2114                         if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
2115                                 // User email
2116                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
2117                         } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
2118                                 // Bonus mail
2119                                 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
2120                         }
2121
2122                         // Reduce this users total received emails?
2123                         if ($num === 0) $userids[$data['userid']] = $data['userid'];
2124                 } // END - while
2125
2126                 if (count($userids) > 0) {
2127                         // Now update all user accounts
2128                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2129                                 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
2130                 } else {
2131                         // Nothing deleted
2132                         loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
2133                 }
2134         } // END - if
2135
2136         // Free result
2137         SQL_FREERESULT($result);
2138 }
2139
2140 // Creates a new task
2141 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
2142         // Insert the task data into the database
2143         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())",
2144                 array(
2145                         $adminId,
2146                         $userid,
2147                         $taskType,
2148                         $subject,
2149                         $notes
2150                 ), __FUNCTION__, __LINE__, true, $strip);
2151 }
2152
2153 // Updates last module / online time
2154 // @TODO Fix inconsistency between last_module and getWhat()
2155 function updateLastActivity($userid) {
2156         // Run the update query
2157         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
2158                 array(
2159                         getWhat(),
2160                         detectRemoteAddr(),
2161                         bigintval($userid)
2162                 ), __FUNCTION__, __LINE__);
2163 }
2164
2165 // [EOF]
2166 ?>