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