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