query masking rewritten in more SQLs, several cleanups and fix on beg link
[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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
36 {
37         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
38         require($INC);
39 }
40
41 //
42 function ADD_MODULE_TITLE($mod)
43 {
44         global $MODULES, $CONFIG;
45         $name = ""; $result = false;
46         // Load title
47         if (!mxchange_installing)
48         {
49                 if ((GET_EXT_VERSION("cache") >= "0.1.2") && (is_array($MODULES['module'])) && (isset($MODULES['module'][$mod])))
50                 {
51                         // Load from cache
52                         $name = $MODULES['title'][$mod];
53
54                         // Update cache hits
55                         $CONFIG['cache_hits']++;
56                 }
57                  else
58                 {
59                         // Load from database
60                         $result = SQL_QUERY_ESC("SELECT title FROM "._MYSQL_PREFIX."_mod_reg WHERE module='%s' LIMIT 1", array($mod), __FILE__, __LINE__);
61                         list($name) = SQL_FETCHROW($result);
62                         SQL_FREERESULT($result);
63                 }
64         }
65
66         // Trim name
67         $name = trim($name);
68
69         // Still no luck or empty title?
70         if (empty($name))
71         {
72                 // No name found
73                 $name = LANG_UNKNOWN_MODULE." (".$mod.")";
74                 if (SQL_NUMROWS($result) == 0)
75                 {
76                         // Add module to database
77                         $dummy = CHECK_MODULE($mod);
78                 }
79         }
80         return $name;
81 }
82 //
83 function CHECK_MODULE($mod)
84 {
85         // We need them now here...
86         global $MODULES, $CONFIG, $CACHE;
87
88         // Filter module name (names with low chars and underlines are fine!)
89         $mod = preg_replace("/[^a-z_]/", "", $mod);
90
91         // Check for prefix is a extension...
92         $MOD_SPLIT = explode("_", $mod);
93         $extension = ""; $mod_chk = $mod;
94         //* DEBUG: */ echo __LINE__."*".count($MOD_SPLIT)."*/".$mod."*<BR>";
95         if (count($MOD_SPLIT) == 2)
96         {
97                 // Okay, there is a seperator (_) in the name so is the first part a module?
98                 //* DEBUG: */ echo __LINE__."*".$MOD_SPLIT[0]."*<BR>";
99                 if (EXT_IS_ACTIVE($MOD_SPLIT[0]))
100                 {
101                         // The prefix is an extension's name, so let's set it
102                         $extension = $MOD_SPLIT[0]; $mod = $MOD_SPLIT[1];
103                 }
104         }
105
106         // Major error in module registry is the default
107         $ret = "major";
108
109         // Check if script is installed if not return a "done" to prevent some errors
110         if ((!mxchange_installed) || (mxchange_installing) || (!admin_registered)) return "done";
111
112         // Check if cache is latest version
113         $locked = 'Y'; $hidden = 'N'; $admin = 'N'; $mem = 'N'; $found = false;
114         if ((GET_EXT_VERSION("cache") >= "0.1.2") && (is_array($MODULES['module'])))
115         {
116                 // Is the module cached?
117                 if (isset($MODULES['locked'][$mod_chk])) {
118                         // Check cache
119                         $locked = $MODULES['locked'][$mod_chk];
120                         $hidden = $MODULES['hidden'][$mod_chk];
121                         $admin  = $MODULES['admin_only'][$mod_chk];
122                         $mem    = $MODULES['mem_only'][$mod_chk];
123
124                         // Update cache hits
125                         $CONFIG['cache_hits']++;
126                         $found = true;
127                 } else {
128                         // No, then we have to update it!
129                         $ret = "cache_miss";
130                 }
131         }
132          else
133         {
134                 // Check for module in database
135                 $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__);
136                 if (SQL_NUMROWS($result) == 1)
137                 {
138                         // Read data
139                         list($locked, $hidden, $admin, $mem) = SQL_FETCHROW($result);
140                         SQL_FREERESULT($result);
141                         $found = true;
142                 }
143         }
144
145         // Check returned values against current access permissions
146         //
147         //  Admin access            ----- Guest access -----           --- Guest   or   member? ---
148         if ((IS_ADMIN()) || (($locked == 'N') && ($admin == 'N') && (($mem == 'N') || (IS_LOGGED_IN()))))
149         {
150                 // If you are admin you are welcome for everything!
151                 $ret = "done";
152         }
153          elseif ($locked == 'Y')
154         {
155                 // Module is locked
156                 $ret = "locked";
157         }
158          elseif (($mem == 'Y') && (!IS_LOGGED_IN()))
159         {
160                 // You have to login first!
161                 $ret = "mem_only";
162         }
163          elseif (($admin == 'Y') && (!IS_ADMIN()))
164         {
165                 // Only the Admin is allowed to enter this module!
166                 $ret = "admin_only";
167         }
168
169         // Still no luck or not found?
170         if (($ret == "major") || ($ret == "cache_miss") || (!$found))
171         {
172                 //         ----- Legacy module -----                      ---- Module in base folder  ----           --- Module with extension's name ---
173                 if ((file_exists(PATH."inc/modules/".$mod.".php")) || (file_exists(PATH.$mod.".php")) || (file_exists(PATH.$extension."/".$mod.".php")))
174                 {
175                         // Data is missing so we add it
176                         if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
177                                 // Since 0.3.6 we have a has_menu column, this took me a half hour
178                                 // to find a loop here... *sigh*
179                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_mod_reg
180 (module, locked, hidden, mem_only, admin_only, has_menu) VALUES
181 ('%s', 'Y', 'N', 'N', 'N', 'N')", array($mod_chk), __FILE__, __LINE__);
182                         } else {
183                                 // Wrong/missing sql_patches!
184                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_mod_reg
185 (module, locked, hidden, mem_only, admin_only) VALUES
186 ('%s', 'Y', 'N', 'N', 'N')", array($mod_chk), __FILE__, __LINE__);
187                         }
188
189                         // Everthing is fine?
190                         if (SQL_AFFECTEDROWS() == 0) {
191                                 // Something bad happend!
192                                 return "major";
193                         }
194
195                         // Destroy cache here
196                         if (GET_EXT_VERSION("cache") >= "0.1.2")
197                         {
198                                 if ($CACHE->cache_file("mod_reg", true)) $CACHE->cache_destroy();
199                                 unset($MODULES);
200                         }
201
202                         // And reload data
203                         $ret = CHECK_MODULE($mod_chk);
204                 }
205                  else
206                 {
207                         // Module not found we don't add it to the database
208                         $ret = "404";
209                 }
210         }
211
212         // Return the value
213         return $ret;
214 }
215 //
216 function ADD_DESCR($ACC_LVL, $file, $return = false, $output = true)
217 {
218         global $DEPTH, $CONFIG;
219         $LINK_ADD = ""; $OUT = ""; $AND = "";
220         // First we have to do some analysis...
221         if (ereg("action-", $file))
222         {
223                 // This is an action file!
224                 $type = "action";
225                 $search = substr($file, 7);
226                 switch ($ACC_LVL)
227                 {
228                 case "admin":
229                         $MOD_CHECK = "admin";
230                         break;
231
232                 case "sponsor":
233                 case "guest":
234                 case "member":
235                         $MOD_CHECK = $GLOBALS['module'];
236                         break;
237                 }
238                 $AND = " AND what=''";
239         }
240          elseif (ereg("what-", $file))
241         {
242                 // This is an admin what file!
243                 $type = "what";
244                 $search = substr($file, 5);
245                 $AND = "";
246                 switch ($ACC_LVL)
247                 {
248                 case "admin":
249                         $MOD_CHECK = "admin";
250                         break;
251
252                 case "guest":
253                 case "member":
254                         $MOD_CHECK = $GLOBALS['module'];
255                         if (!IS_ADMIN())
256                         {
257                                 $AND = " AND visible='Y' AND locked='N'";
258                         }
259                         break;
260                 }
261                 $DUMMY = substr($search, 0, -4);
262                 $AND .= " AND action='".GET_ACTION($ACC_LVL, $DUMMY)."'";
263         }
264          elseif (($ACC_LVL == "sponsor") || ($ACC_LVL == "engine"))
265         {
266                 // Sponsor / engine menu
267                 $type = "what";
268                 $search = $file;
269                 $MOD_CHECK = $GLOBALS['module'];
270                 $AND = "";
271         }
272          else
273         {
274                 // Other
275                 $type = "menu";
276                 $search = $file;
277                 $MOD_CHECK = $GLOBALS['module'];
278                 $AND = "";
279         }
280         if ((!isset($DEPTH)) && (!$return))
281         {
282                 $DEPTH = "0";
283                 $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>";
284         }
285          else
286         {
287                 if (!$return) $DEPTH++;
288                 $prefix = "";
289         }
290         $prefix .= "&nbsp;-&gt;&nbsp;";
291         if (ereg(".php", $search))
292         {
293                 $search = substr($search, 0, strpos($search, ".php"));
294         }
295         $result = SQL_QUERY_ESC("SELECT title FROM "._MYSQL_PREFIX."_%s_menu WHERE %s='%s' ".$AND." LIMIT 1",
296          array($ACC_LVL, $type, $search), __FILE__, __LINE__);
297         if (SQL_NUMROWS($result) == 1)
298         {
299                 list($ret) = SQL_FETCHROW($result);
300                 SQL_FREERESULT($result);
301                 if ($return)
302                 {
303                         // Return title
304                         return $ret;
305                 }
306                  elseif (((GET_EXT_VERSION("sql_patches") >= "0.2.3") && ($CONFIG['youre_here'] == 'Y')) || ((IS_ADMIN()) && ($MOD_CHECK == "admin")))
307                 {
308                         // Output HTML code
309                         $OUT = $prefix."<STRONG><A class=\"you_are_here\" href=\"".URL."/modules.php?module=".$MOD_CHECK."&amp;".$type."=".$search.$LINK_ADD."\">".$ret."</A></STRONG>\n";
310                         //* DEBUG: */ echo __LINE__."*".$type."/".$GLOBALS['what']."*<br />\n";
311                         if (($type == "what") || (($type == "action") && (!isset($_GET['what'])) && ($GLOBALS['what'] != "welcome"))) {
312                                 //* DEBUG: */ echo __LINE__."+".$type."+<br />\n";
313                                 $OUT .= "</DIV><BR>\n";
314                         }
315                 }
316         }
317
318         // Return or output HTML code?
319         if ($output)
320         {
321                 // Output HTML code here
322                 OUTPUT_HTML($OUT);
323         }
324          else
325         {
326                 // Return HTML code
327                 return $OUT;
328         }
329 }
330 //
331 function ADD_MENU($MODE, $act, $wht)
332 {
333         global $CONFIG;
334         if (!VALIDATE_MENU_ACTION($MODE, $act, $wht, true)) return CODE_MENU_NOT_VALID;
335         $main_cnt = 0; $AND = ""; $main_action = ""; $sub_what = "";
336         if (!IS_ADMIN())
337         {
338                 $AND = "AND visible='Y' AND locked='N'";
339         }
340         // Load SQL data and add the menu to the output stream...
341         $result_main = SQL_QUERY_ESC("SELECT title, action FROM "._MYSQL_PREFIX."_%s_menu WHERE what='' ".$AND." ORDER BY sort",
342          array($MODE), __FILE__, __LINE__);
343         //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
344         if (SQL_NUMROWS($result_main) > 0)
345         {
346                 OUTPUT_HTML("<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"".$MODE."_menu\">");
347                 // There are menus available, so we simply display them... :)
348                 while (list($main_title, $main_action) = SQL_FETCHROW($result_main))
349                 {
350                         //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
351                         // Load menu header template
352                         $BLOCK_MODE = false; $act = $main_action;
353                         LOAD_TEMPLATE($MODE."_menu_title", false, $main_title);
354
355                         $result_sub = SQL_QUERY_ESC("SELECT title, what FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s' AND what != '' ".$AND." ORDER BY sort",
356                          array($MODE, $main_action), __FILE__, __LINE__);
357                         $ctl = SQL_NUMROWS($result_sub);
358                         if ($ctl > 0)
359                         {
360                                 $cnt=0;
361                                 while (list($sub_title, $sub_what) = SQL_FETCHROW($result_sub))
362                                 {
363                                         $content = "";
364
365                                         // Full file name for checking menu
366                                         //* DEBUG: */ echo __LINE__.":!!!!".$sub_what."!!!<br />\n";
367                                         $test_inc = sprintf("%sinc/modules/%s/what-%s.php", PATH, $MODE, $sub_what);
368                                         $test = (file_exists($test_inc) && is_readable($test_inc));
369                                         if ($test)
370                                         {
371                                                 if ((!empty($wht)) && (($wht == $sub_what)))
372                                                 {
373                                                         $content = "<STRONG>";
374                                                 }
375
376                                                 // Navigation link
377                                                 $content .= "<A name=\"menu\" class=\"menu_blur\" href=\"".URL."/modules.php?module=".$GLOBALS['module']."&amp;what=".$sub_what.ADD_URL_DATA("")."\"";
378
379                                                 if (frameset_active)
380                                                 {
381                                                         // We need to add a JavaScript here to reload both frames!
382                                                 }
383                                                  else
384                                                 {
385                                                         // Add the default target _self
386                                                         $content .= " target=\"_self\"";
387                                                 }
388                                                 $content .= ">";
389                                         }
390                                          else
391                                         {
392                                                 $content .= "<I>";
393                                         }
394
395                                         // Menu title
396                                         $content .= $CONFIG['middot'].$sub_title;
397
398                                         if ($test)
399                                         {
400                                                 $content .= "</A>";
401                                         }
402                                          else
403                                         {
404                                                 $content .= "</I>";
405                                         }
406
407                                         if ((!empty($wht)) && (($wht == $sub_what)))
408                                         {
409                                                 $content .= "</STRONG>";
410                                         }
411                                         $wht = $sub_what; $cnt++;
412                                         if ($cnt < $ctl)
413                                         {
414                                                 LOAD_TEMPLATE($MODE."_menu_row", false, $content);
415                                         }
416                                          else
417                                         {
418                                                 LOAD_TEMPLATE($MODE."_menu_bottom", false, $content);
419                                         }
420                                 }
421                         }
422                          else
423                         {
424                                 // This is a menu block... ;-)
425                                 $BLOCK_MODE = true;
426                                 $INC_BLOCK = sprintf(PATH."inc/modules/%s/action-%s.php", $MODE, $main_action);
427                                 if ((file_exists($INC_BLOCK)) && (is_readable($INC_BLOCK)))
428                                 {
429                                         // Load include file
430                                         if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("<TR>
431   <TD class=\"".$MODE."_menu_whats\">");
432                                         //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
433                                         include ($INC_BLOCK);
434                                         //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
435                                         if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("  </TD>
436 </TR>");
437                                 }
438                                 //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
439                         }
440                         $main_cnt++;
441                         //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
442                         if (SQL_NUMROWS($result_main) > $main_cnt)      OUTPUT_HTML("<TR><TD class=\"".$MODE."_menu_seperator\"></TD></TR>");
443                 }
444
445                 // Free memory
446                 SQL_FREERESULT($result_main);
447
448                 // Close table
449                 //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
450                 OUTPUT_HTML("</TABLE>");
451         }
452 }
453 // This patched function will reduce many SELECT queries for the specified or current admin login
454 function IS_ADMIN($admin="")
455 {
456         global $_COOKIE, $ADMINS, $CONFIG;
457         $ret = false; $passCookie = ""; $valPass = "";
458         //* DEBUG: */ echo __LINE__."ADMIN:".$admin."<BR>";
459
460         // If admin login is not given take current from cookies...
461         if ((empty($admin)) && (!empty($_COOKIE['admin_login'])) && (!empty($_COOKIE['admin_md5'])))
462         {
463                 $admin = SQL_ESCAPE($_COOKIE['admin_login']); $passCookie = $_COOKIE['admin_md5'];
464         }
465         //* DEBUG: */ echo __LINE__."ADMIN:".$admin."/".$passCookie."<BR>";
466
467         // Search in array for entry
468         if ((!empty($passCookie)) && (isset($ADMINS['password'][$admin])) && (!empty($admin)))
469         {
470                 // Count cache hits
471                 $CONFIG['cache_hits']++;
472
473                 // Login data is valid or not?
474                 $valPass = generatePassString($ADMINS['password'][$admin]);
475         }
476          elseif (!empty($admin))
477         {
478                 // Search for admin
479                 $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
480                  array($admin), __FILE__, __LINE__);
481
482                 // Is he admin?
483                 $passDB = "";
484                 if (SQL_NUMROWS($result) == 1)
485                 {
486                         // Admin login was found so let's load password from DB
487                         list($passDB) = SQL_FETCHROW($result);
488                         $valPass = generatePassString($passDB);
489                 }
490
491                 // Free memory
492                 SQL_FREERESULT($result);
493         }
494
495         if (!empty($valPass))
496         {
497                 // Check if password is valid
498                 //* DEBUG: */ echo __LINE__."*".$valPass."/".$passCookie)."*<br>";
499                 $ret = (($valPass == $passCookie) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE("cache"))));
500         }
501
502         // Return result of comparision
503         //* DEBUG: */ if (!$ret) echo __LINE__."OK!<br>";
504         return $ret;
505 }
506 //
507 function ADD_MAX_RECEIVE_LIST($MODE, $default="", $return=false)
508 {
509         global $_POST;
510         $OUT = "";
511         switch ($MODE)
512         {
513         case "guest":
514                 // Guests (in the registration form) are not allowed to select 0 mails per day.
515                 $result = SQL_QUERY("SELECT value, comment FROM "._MYSQL_PREFIX."_max_receive WHERE value > 0 ORDER BY value", __FILE__, __LINE__);
516                 if (SQL_NUMROWS($result) > 0)
517                 {
518                         $OUT = "";
519                         while (list($value, $comment) = SQL_FETCHROW($result))
520                         {
521                                 $OUT .= "      <OPTION value=\"".$value."\"";
522                                 if ($_POST['max_mails'] == $value) $OUT .= " selected=\"selected\"";
523                                 $OUT .= ">".$value." ".PER_DAY;
524                                 if (!empty($comment)) $OUT .= " (".$comment.")";
525                                 $OUT .= "</OPTION>\n";
526                         }
527                         define('__MAX_RECEIVE_OPTIONS', $OUT);
528
529                         // Free memory
530                         SQL_FREERESULT($result);
531                         $OUT = LOAD_TEMPLATE("guest_receive_table", true);
532                 }
533                  else
534                 {
535                         // Maybe the admin has to setup some maximum values?
536                 }
537                 break;
538
539         case "member":
540                 // Members are allowed to set to zero mails per day (we will change this soon!)
541                 $result = SQL_QUERY("SELECT value, comment FROM "._MYSQL_PREFIX."_max_receive ORDER BY value", __FILE__, __LINE__);
542                 if (SQL_NUMROWS($result) > 0)
543                 {
544                         $OUT = "";
545                         while (list($value, $comment) = SQL_FETCHROW($result))
546                         {
547                                 $OUT .= "      <OPTION value=\"".$value."\"";
548                                 if ($default == $value) $OUT .= " selected=\"selected\"";
549                                 $OUT .= ">".$value." ".PER_DAY;
550                                 if (!empty($comment)) $OUT .= " (".$comment.")";
551                                 $OUT .= "</OPTION>\n";
552                         }
553                         define('__MAX_RECEIVE_OPTIONS', $OUT);
554                         SQL_FREERESULT($result);
555                         $OUT = LOAD_TEMPLATE("member_receive_table", true);
556                 }
557                  else
558                 {
559                         // Maybe the admin has to setup some maximum values?
560                         $OUT = LOAD_TEMPLATE("admin_settings_saved", true, NO_MAX_VALUES);
561                 }
562                 break;
563         }
564         if ($return)
565         {
566                 // Return generated HTML code
567                 return $OUT;
568         }
569          else
570         {
571                 // Output directly (default)
572                 OUTPUT_HTML($OUT);
573         }
574 }
575 //
576 function SEARCH_EMAIL_USERTAB($email)
577 {
578         $ret = false;
579         $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_user_data WHERE email LIKE '{PER}%s{PER}' LIMIT 1", array($email), __FILE__, __LINE__);
580         if (SQL_NUMROWS($result) == 1) $ret = true;
581         SQL_FREERESULT($result);
582         return $ret;
583 }
584 //
585 function WHAT_IS_VALID($act, $wht, $type="guest")
586 {
587         if (IS_ADMIN())
588         {
589                 // Everything is valid to the admin :-)
590                 return true;
591         }
592          else
593         {
594                 $ret = false;
595                 $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__);
596                 // Is "what" valid?
597                 if (SQL_NUMROWS($result) == 1) $ret = true;
598                 SQL_FREERESULT($result);
599                 return $ret;
600         }
601 }
602 //
603 function IS_LOGGED_IN()
604 {
605         global $_COOKIE, $status, $LAST;
606         if (!is_array($LAST)) $LAST = array();
607         $ret = false;
608
609         // Fix "deleted" cookies first
610         FIX_DELETED_COOKIES(array('userid', 'u_hash', 'lifetime'));
611
612         // Are cookies set?
613         if ((!empty($GLOBALS['userid'])) && (!empty($_COOKIE['u_hash'])) && (!empty($_COOKIE['lifetime'])) && (defined('COOKIE_PATH')))
614         {
615                 // Cookies are set with values, but are they valid?
616                 $result = SQL_QUERY_ESC("SELECT password, status, last_module, last_online FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
617                  array($GLOBALS['userid']), __FILE__, __LINE__);
618                 if (SQL_NUMROWS($result) == 1)
619                 {
620                         // Load data from cookies
621                         list($password, $status, $mod, $onl) = SQL_FETCHROW($result);
622
623                         // Validate password by created the difference of it and the secret key
624                         $valPass = generatePassString($password);
625
626                         // Transfer last module and online time
627                         if ((!empty($mod)) && (empty($LAST['module']))) { $LAST['module'] = $mod; $LAST['online'] = $onl; }
628
629                         // So did we now have valid data and an unlocked user?
630                         //* DEBUG: */ echo $valPass."<br>".$_COOKIE['u_hash']."<br>";
631                         if (($status == "CONFIRMED") && ($valPass == $_COOKIE['u_hash']))
632                         {
633                                 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
634                                 $ret = true;
635                         }
636                          else
637                         {
638                                 // Maybe got locked etc.
639                                 //* DEBUG: */ echo __LINE__."!!!<br>";
640                                 @setcookie("userid", "", time() - 3600, COOKIE_PATH);
641                                 @setcookie("u_hash", "", time() - 3600, COOKIE_PATH);
642                                 @setcookie("lifetime", "0", time() - 3600, COOKIE_PATH);
643
644                                 // Remove array elements to prevent errors
645                                 unset($GLOBALS['userid']);
646                                 unset($_COOKIE['u_hash']);
647                                 unset($_COOKIE['lifetime']);
648                         }
649                 }
650                  else
651                 {
652                         // Cookie data is invalid!
653                         //* DEBUG: */ echo __LINE__."***<br>";
654                         @setcookie("userid", "", time() - 3600, COOKIE_PATH);
655                         @setcookie("u_hash", "", time() - 3600, COOKIE_PATH);
656                         @setcookie("lifetime", "0", time() - 3600, COOKIE_PATH);
657
658                         // Remove array elements to prevent errors
659                         unset($GLOBALS['userid']);
660                         unset($_COOKIE['u_hash']);
661                         unset($_COOKIE['lifetime']);
662                 }
663
664                 // Free memory
665                 SQL_FREERESULT($result);
666         }
667          else
668         {
669                 // Cookie data is invalid!
670                 //* DEBUG: */ echo __LINE__."///<br>";
671                 @setcookie("userid", "", time() - 3600, COOKIE_PATH);
672                 @setcookie("u_hash", "", time() - 3600, COOKIE_PATH);
673                 @setcookie("lifetime", "0", time() - 3600, COOKIE_PATH);
674
675                 // Remove array elements to prevent errors
676                 unset($GLOBALS['userid']);
677                 unset($_COOKIE['u_hash']);
678                 unset($_COOKIE['lifetime']);
679         }
680         return $ret;
681 }
682 //
683 function UPDATE_LOGIN_DATA ($UPDATE=true) {
684         global $LAST;
685         if (!is_array($LAST)) $LAST = array();
686
687         // Are the required cookies set?
688         if ((!isset($GLOBALS['userid'])) || (!isset($_COOKIE['u_hash'])) || (!isset($_COOKIE['lifetime']))) {
689                 // Nope, then return here to caller function
690                 return false;
691         } else {
692                 // Secure user ID
693                 $GLOBALS['userid'] = bigintval($_COOKIE['userid']);
694         }
695
696         // Extract last online time (life) and how long is auto-login valid (time)
697         $newl = time() + bigintval($_COOKIE['lifetime']);
698
699         // Recheck if logged in
700         if (!IS_LOGGED_IN()) return false;
701
702         // Load last module and last online time
703         $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array($GLOBALS['userid']), __FILE__, __LINE__);
704         if (SQL_NUMROWS($result) == 1) {
705                 // Load last module and online time
706                 list($mod, $onl) = SQL_FETCHROW($result);
707                 SQL_FREERESULT($result);
708
709                 // Maybe first login time?
710                 if (empty($mod)) $mod = "login";
711
712                 if (@setcookie("userid", $GLOBALS['userid'], $newl, COOKIE_PATH) && @setcookie("u_hash", SQL_ESCAPE($_COOKIE['u_hash']), $newl, COOKIE_PATH) && @setcookie("lifetime", bigintval($_COOKIE['lifetime']), $newl, COOKIE_PATH)) {
713                         // This will be displayed on welcome page! :-)
714                         if (empty($LAST['module'])) {
715                                 $LAST['module'] = $mod; $LAST['online'] = $onl;
716                         }
717                         if (empty($GLOBALS['what'])) {
718                                 $GLOBALS['what'] = "welcome";
719                         }
720
721                         // Update last module / online time
722                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET last_module='%s', last_online=UNIX_TIMESTAMP() WHERE userid=%d LIMIT 1",
723                          array($GLOBALS['what'], $GLOBALS['userid']), __FILE__, __LINE__);
724                 }
725         }
726          else
727         {
728                 // Destroy session, we cannot update!
729                 @setcookie("userid", "", time() - 3600, COOKIE_PATH);
730                 @setcookie("u_hash", "", time() - 3600, COOKIE_PATH);
731                 @setcookie("lifetime", "0", time() - 3600, COOKIE_PATH);
732         }
733 }
734 //
735 function VALIDATE_MENU_ACTION ($MODE, $act, $wht, $UPDATE=false)
736 {
737         global $link;
738         $ret = false;
739         $ADD = "";
740         if ((!IS_ADMIN()) && ($MODE != "admin")) $ADD = " AND locked='N'";
741         //* DEBUG: */ echo __LINE__.":".$MODE."/".$act."/".$wht."*<br />\n";
742         if (($MODE != "admin") && ($UPDATE))
743         {
744                 // Update guest or member menu
745                 $SQL = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_%s_menu SET counter=counter+1 WHERE action='%s' AND what='%s'".$ADD." LIMIT 1",
746                  array($MODE, $act, $wht), __FILE__, __LINE__, false);
747         }
748          elseif ($wht != "overview")
749         {
750                 // Other actions
751                 $SQL = SQL_QUERY_ESC("SELECT id, what FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s'".$ADD." ORDER BY action DESC LIMIT 1",
752                  array($MODE, $act), __FILE__, __LINE__, false);
753         }
754          else
755         {
756                 // Admin login overview
757                 $SQL = SQL_QUERY_ESC("SELECT id, what FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s' AND what=''".$ADD." ORDER BY action DESC LIMIT 1",
758                  array($MODE, $act), __FILE__, __LINE__, false);
759         }
760
761         // Run SQL command
762         $result = SQL_QUERY($SQL, __FILE__, __LINE__);
763         if ($UPDATE)
764         {
765                 if (SQL_AFFECTEDROWS($link, __FILE__, __LINE__) == 1) $ret = true;
766                 //* DEBUG: */ debug_print_backtrace();
767         }
768          else
769         {
770                 if (SQL_NUMROWS($result) == 1) {
771                         list($id, $wht2) = SQL_FETCHROW($result);
772                         //* DEBUG: */ echo __LINE__."+".$SQL."+<br />\n";
773                         //* DEBUG: */ echo __LINE__."*".$id."/".$wht."/".$wht2."*<br />\n";
774                         $ret = true;
775                 }
776         }
777
778         // Free memory
779         SQL_FREERESULT($result);
780         //* DEBUG: */ var_dump($ret);
781         return $ret;
782 }
783 //
784 function GET_MOD_DESCR($MODE, $wht)
785 {
786         if (empty($wht)) $wht = "welcome";
787         $ret = "??? (".$wht.")";
788         $result = SQL_QUERY_ESC("SELECT title FROM "._MYSQL_PREFIX."_%s_menu WHERE what='%s' LIMIT 1", array($MODE, $wht), __FILE__, __LINE__);
789         if (SQL_NUMROWS($result) == 1)
790         {
791                 list($ret) = SQL_FETCHROW($result);
792                 SQL_FREERESULT($result);
793         }
794         return $ret;
795 }
796 //
797 function SEND_MODE_MAILS($mod, $modes)
798 {
799         global $_COOKIE, $_POST, $CONFIG, $DATA;
800         // Load hash
801         $result_main = SQL_QUERY("SELECT password FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND status='CONFIRMED' LIMIT 1",
802          array($GLOBALS['userid']), __FILE__, __LINE__);
803         if (SQL_NUMROWS($result_main) == 1)
804         {
805                 // Load hash and extract salt
806                 list($hash) = SQL_FETCHROW($result_main);
807                 $salt = substr($hash, 0, -40);
808
809                 // Now let's compare passwords
810                 $hash = generateHash($_POST['pass1'], $salt);
811                 if (($hash == $_COOKIE['u_hash']) || ($_POST['pass1'] == $_POST['pass2']))
812                 {
813                         // Load user's data
814                         $result = SQL_QUERY_ESC("SELECT sex, surname, family, street_nr, country, zip, city, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND password='%s' LIMIT 1",
815                          array($GLOBALS['userid'], $hash), __FILE__, __LINE__);
816                         if (SQL_NUMROWS($result) == 1)
817                         {
818                                 $DATA = SQL_FETCHROW($result);
819                                 SQL_FREERESULT($result);
820                                 $DATA[0] = TRANSLATE_SEX($DATA[0]);
821                                 switch ($mod)
822                                 {
823                                 case "mydata":
824                                         foreach ($modes as $mode)
825                                         {
826                                                 switch ($mode)
827                                                 {
828                                                 case "normal": break; // Do not add any special lines
829
830                                                 case "email": // Email was changed!
831                                                         $content = MEMBER_CHANGED_EMAIL.": ".$_POST['old_addy']."\n";
832                                                         break;
833
834                                                 case "pass": // Password was changed
835                                                         $content = MEMBER_CHANGED_PASS."\n";
836                                                         break;
837
838                                                 default:
839                                                         $content = MEMBER_UNKNOWN_MODE.": ".$mode."\n\n";
840                                                         break;
841                                                 }
842                                         }
843
844                                         if (EXT_IS_ACTIVE("country"))
845                                         {
846                                                 // Replace code with description
847                                                 $DATA[4] = COUNTRY_GENERATE_INFO($_POST['country_code']);
848                                         }
849
850                                         // Load template
851                                         $msg = LOAD_EMAIL_TEMPLATE("member_mydata_notify", $content, $GLOBALS['userid']);
852
853                                         if ($CONFIG['admin_notify'] == 'Y')
854                                         {
855                                                 // The admin needs to be notified about a profile change
856                                                 $msg_admin = "admin_mydata_notify";
857                                                 $sub_adm = ADMIN_CHANGED_DATA;
858                                         }
859                                          else
860                                         {
861                                                 // No mail to admin
862                                                 $msg_admin = "";
863                                                 $sub_adm = "";
864                                         }
865
866                                         // Set subject lines
867                                         $sub_mem = MEMBER_CHANGED_DATA;
868
869                                         // Output success message
870                                         $content = "<STRONG><SPAN class=\"member_done\">".MYDATA_MAIL_SENT."</SPAN></STRONG>";
871                                         break;
872
873                                 default:
874                                         $content = "<STRONG><SPAN class=\"member_failed\">".UNKNOWN_MODULE."</SPAN></STRONG>";
875                                         break;
876                                 }
877                         }
878                          else
879                         {
880                                 // Could not load profile data
881                                 $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_CANNOT_LOAD_PROFILE."</SPAN></STRONG>";
882                         }
883                 }
884                  else
885                 {
886                         // Passwords mismatch
887                         $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_PASSWORD_ERROR."</SPAN></STRONG>";
888                 }
889         }
890          else
891         {
892                 // Could not load profile
893                 $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_CANNOT_LOAD_PROFILE."</SPAN></STRONG>";
894         }
895         if ((!empty($sub_mem)) && (!empty($msg)))
896         {
897                 // Send member mail
898                 SEND_EMAIL($DATA[7], $sub_mem, $msg);
899         }
900         if ((!empty($sub_adm)) && (!empty($msg_admin)))
901         {
902                 // Send admin mail
903                 if (GET_EXT_VERSION("admins") >= "0.4.1")
904                 {
905                         SEND_ADMIN_EMAILS_PRO($sub_adm, $msg_admin, $content, $GLOBALS['userid']);
906                 }
907                  else
908                 {
909                         SEND_ADMIN_EMAILS($sub_adm, LOAD_EMAIL_TEMPLATE($msg_admin, $content, $GLOBALS['userid']));
910                 }
911         }
912          elseif ($CONFIG['admin_notify'] == 'Y')
913         {
914                 // Cannot send mails to admin!
915                 $content = CANNOT_SEND_ADMIN_MAILS;
916         }
917          else
918         {
919                 // No mail to admin
920                 $content = "<STRONG><SPAN class=\"member_done\">".MYDATA_MAIL_SENT."</SPAN></STRONG>";
921         }
922
923         // Load template
924         LOAD_TEMPLATE("admin_settings_saved", false, $content);
925 }
926 // Update module counter
927 function COUNT_MODULE($mod)
928 {
929         if ($mod != "css")
930         {
931                 // Do count all other modules but not accesses on CSS file css.php!
932                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_mod_reg SET clicks=clicks+1 WHERE module='%s' LIMIT 1",
933                  array($mod), __FILE__, __LINE__);
934         }
935 }
936 // Get action value from mode (admin/guest/member) and what-value
937 function GET_ACTION ($MODE, &$wht)
938 {
939         global $ret; $ret = "";
940         //* DEBUG: */ echo __LINE__."=".$MODE."/".$wht."/".$GLOBALS['action']."=<br>";
941         if ((empty($wht)) && ($MODE != "admin"))
942         {
943                 $wht = "welcome";
944         }
945         if ($MODE == "admin")
946         {
947                 // Action value for admin area
948                 if (!empty($GLOBALS['action']))
949                 {
950                         // Get it directly from URL
951                         return $GLOBALS['action'];
952                 }
953                  elseif (($wht == "overview") || (empty($GLOBALS['what'])))
954                 {
955                         // Default value for admin area
956                         $ret = "login";
957                 }
958         }
959          elseif (!empty($GLOBALS['action']))
960         {
961                 // Fix welcome value
962                 if (empty($wht)) $wht = "welcome";
963                 return $GLOBALS['action'];
964         }
965          else
966         {
967                 // Everything else will be touched after checking the module has a menu assigned
968         }
969         //* DEBUG: */ echo __LINE__."*".$ret."*<br />\n";
970
971         if (MODULE_HAS_MENU($MODE))
972         {
973                 // Rewriting modules to menu
974                 switch ($MODE)
975                 {
976                         case "index": $MODE = "guest";  break;
977                         case "login": $MODE = "member"; break;
978                                 break;
979                 }
980
981                 // Guest and member menu is "main" as the default
982                 if (empty($ret)) $ret = "main";
983
984                 // Load from database
985                 $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_%s_menu WHERE what='%s' LIMIT 1",
986                  array($MODE, $wht), __FILE__, __LINE__);
987                 if (SQL_NUMROWS($result) == 1)
988                 {
989                         // Load action value and pray that this one is the right you want... ;-)
990                         list($ret) = SQL_FETCHROW($result);
991                 }
992
993                 // Free memory
994                 SQL_FREERESULT($result);
995         }
996
997         // Return action value
998         return $ret;
999 }
1000 //
1001 function GET_CATEGORY ($cid)
1002 {
1003         $ret = _CATEGORY_404;
1004         $result = SQL_QUERY_ESC("SELECT cat FROM "._MYSQL_PREFIX."_cats WHERE id=%d LIMIT 1", array($cid), __FILE__, __LINE__);
1005         if (SQL_NUMROWS($result) == 1)
1006         {
1007                 // Category found... :-)
1008                 list($ret) = SQL_FETCHROW($result);
1009                 SQL_FREERESULT($result);
1010         }
1011         return $ret;
1012 }
1013 //
1014 function GET_PAYMENT ($pid, $full=false)
1015 {
1016         $ret = _PAYMENT_404;
1017         $result = SQL_QUERY_ESC("SELECT mail_title, price FROM "._MYSQL_PREFIX."_payments WHERE id=%d LIMIT 1", array($pid), __FILE__, __LINE__);
1018         if (SQL_NUMROWS($result) == 1)
1019         {
1020                 // Payment type found... :-)
1021                 if (!$full)
1022                 {
1023                         // Return only title
1024                         list($ret) = SQL_FETCHROW($result);
1025                         SQL_FREERESULT($result);
1026                 }
1027                  else
1028                 {
1029                         // Return title and price
1030                         list($t, $p) = SQL_FETCHROW($result);
1031                         $ret = $t." / ".TRANSLATE_COMMA($p)." ".POINTS;
1032                 }
1033         }
1034         return $ret;
1035 }
1036 //
1037 function GET_PAY_POINTS($pid, $DATA="price")
1038 {
1039         $ret = "-1";
1040         $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_payments WHERE id=%d LIMIT 1", array($DATA, $pid), __FILE__, __LINE__);
1041         if (SQL_NUMROWS($result) == 1)
1042         {
1043                 // Payment type found... :-)
1044                 list($ret) = SQL_FETCHROW($result);
1045                 SQL_FREERESULT($result);
1046         }
1047         return $ret;
1048 }
1049 // Remove a receiver's ID from $ARRAY and add a link for him to confirm
1050 function REMOVE_RECEIVER(&$ARRAY, $key, $uid, $pool_id, $stats_id="", $bonus=false)
1051 {
1052         $ret = "failed";
1053         if ($uid > 0)
1054         {
1055                 // Remove entry from array
1056                 unset($ARRAY[$key]);
1057
1058                 // Is there already a line for this user available?
1059                 if ($stats_id > 0)
1060                 {
1061                         // Only when we got a real stats ID continue searching for the entry
1062                         $type = "NORMAL"; $ROW = "stats_id";
1063                         if ($bonus) { $type = "BONUS"; $ROW = "bonus_id"; }
1064                         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_user_links WHERE %s='%s' AND userid=%d AND link_type='%s' LIMIT 1",
1065                          array($ROW, $stats_id, bigintval($uid), $type), __FILE__, __LINE__);
1066                         if (SQL_NUMROWS($result) == 0)
1067                         {
1068                                 // No, so we add one!
1069                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_user_links (%s, userid, link_type) VALUES ('%s', '%s', '%s')",
1070                                  array($ROW, $stats_id, bigintval($uid), $type), __FILE__, __LINE__);
1071                                 $ret = "done";
1072                         }
1073                          else
1074                         {
1075                                 // Already found
1076                                 $ret = "already";
1077                         }
1078
1079                         // Free memory
1080                         SQL_FREERESULT($result);
1081                 }
1082         }
1083         // Return status for sending routine
1084         return $ret;
1085 }
1086 //
1087 function GET_TOTAL_DATA($search, $TABLE, $DATA, $WHERE="userid", $ONLY_ROWS=false)
1088 {
1089         $ret = "0";
1090         if ($ONLY_ROWS)
1091         {
1092                 // Count rows
1093                 $result = SQL_QUERY_ESC("SELECT COUNT(%s) FROM "._MYSQL_PREFIX."_%s WHERE %s='%s'",
1094                  array($DATA, $TABLE, $WHERE, $search), __FILE__, __LINE__);
1095         }
1096          else
1097         {
1098                 // Add all rows
1099                 $result = SQL_QUERY_ESC("SELECT SUM(%s) FROM "._MYSQL_PREFIX."_%s WHERE %s='%s'",
1100                  array($DATA, $TABLE, $WHERE, $search), __FILE__, __LINE__);
1101         }
1102         // Load row
1103         list($ret) = SQL_FETCHROW($result);
1104         //* DEBUG: */ echo __LINE__."*".$DATA."/".$search."/".$TABLE."/".$ret."*<br />\n";
1105         SQL_FREERESULT($result);
1106         if (empty($ret)) {
1107                 if (($DATA == "counter") || ($DATA == "id")) {
1108                         $ret = "0";
1109                 } else {
1110                         $ret = "0.00000";
1111                 }
1112         }
1113         return $ret;
1114 }
1115 /**
1116  *
1117  * Dynamic referral system, can also send mails!
1118  *
1119  * uid         = Referral ID wich should receive...
1120  * points      = ... xxx points
1121  * send_notify = shall I send the referral an email or not?
1122  * refid       = inc/modules/guest/what-confirm.php need this
1123  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
1124  * add_mode    = Add points only to $uid or also refs? (WARNING! Changing "ref" to "direct"
1125  *               will cause no referral will get points ever!!!)
1126  */
1127 function ADD_POINTS_REFSYSTEM($uid, $points, $send_notify=false, $rid="0", $locked=false, $add_mode="ref")
1128 {
1129         global $DEPTH, $_GET, $CONFIG, $DATA, $link;
1130
1131         // When $uid = 0 add points to jackpot
1132         if ($uid == "0")
1133         {
1134                 // Add points to jackpot
1135                 ADD_JACKPOT($points);
1136                 return;
1137         }
1138
1139         // Count up referral depth
1140         if (empty($DEPTH))
1141         {
1142                 // Initialialize referral system
1143                 $DEPTH = "0";
1144         }
1145          else
1146         {
1147                 // Increase referral level
1148                 $DEPTH++;
1149         }
1150
1151         // Which points, locked or normal?
1152         $data = "points"; if ($locked) $data = "locked_points";
1153
1154         $result_user = SQL_QUERY_ESC("SELECT refid, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND status='CONFIRMED' LIMIT 1",
1155          array(bigintval($uid)), __FILE__, __LINE__);
1156         if (SQL_NUMROWS($result_user) == 1)
1157         {
1158                 // This is the user and his ref
1159                 list ($ref, $email) = SQL_FETCHROW($result_user);
1160                 SQL_FREERESULT($result_user);
1161                 $result = SQL_QUERY_ESC("SELECT percents FROM "._MYSQL_PREFIX."_refdepths WHERE level='%s' LIMIT 1",
1162                  array(bigintval($DEPTH)), __FILE__, __LINE__);
1163                 if (SQL_NUMROWS($result) == 1)
1164                 {
1165                         list($per) = SQL_FETCHROW($result);
1166                         SQL_FREERESULT($result);
1167                         $P = $points * $per / 100;
1168
1169                         // Update points...
1170                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_points SET %s=%s+%s WHERE userid=%d AND ref_depth=%d LIMIT 1",
1171                          array($data, $data, $P, bigintval($uid), bigintval($DEPTH)), __FILE__, __LINE__);
1172                         if (SQL_AFFECTEDROWS($link, __FILE__, __LINE__) == 0)
1173                         {
1174                                 // First ref in this level! :-)
1175                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_user_points (userid, ref_depth, %s) VALUES (%d, %d, %s)",
1176                                  array($data, bigintval($uid), bigintval($DEPTH), $P), __FILE__, __LINE__);
1177                         }
1178
1179                         // Update mediadata as well
1180                         if (GET_EXT_VERSION("mediadata") >= "0.0.4")
1181                         {
1182                                 // Update database
1183                                 MEDIA_UPDATE_ENTRY(array("total_points"), "add", $P);
1184                         }
1185
1186                         // Points updated, maybe I shall send him an email?
1187                         if (($send_notify) && ($ref > 0) && (!$locked))
1188                         {
1189                                 //              0                1      2              3
1190                                 $DATA = array($per, bigintval($DEPTH), $P, bigintval($ref));
1191                                 $msg = LOAD_EMAIL_TEMPLATE("confirm-referral", "", bigintval($uid));
1192
1193                                 SEND_EMAIL($email, THANX_REFERRAL_ONE, $msg);
1194                         }
1195
1196                         // Maybe there's another ref?
1197                         if (($ref > 0) && ($points > 0) && ($ref != $uid) && ($add_mode == "ref"))
1198                         {
1199                                 // Then let's credit him here...
1200                                 ADD_POINTS_REFSYSTEM($ref, $points, $send_notify, $ref, $locked);
1201                         }
1202                 }
1203         }
1204 }
1205 //
1206 function UPDATE_REF_COUNTER($uid)
1207 {
1208         global $REF_LVL, $link, $CACHE;
1209         // Make it sure referral level zero (member him-/herself) is at least selected
1210         if (empty($REF_LVL)) $REF_LVL = "0";
1211
1212         // Update counter
1213         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_refsystem SET counter=counter+1 WHERE userid=%d AND level='%s' LIMIT 1",
1214          array(bigintval($uid), $REF_LVL), __FILE__, __LINE__);
1215
1216         // When no entry was updated then we have to create it here
1217         if (SQL_AFFECTEDROWS($link) == 0)
1218         {
1219                 // First count!
1220                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_refsystem (userid, level, counter) VALUES ('%s', '%s', '1')",
1221                  array(bigintval($uid), $REF_LVL), __FILE__, __LINE__);
1222         }
1223
1224         // Check for his referral
1225         $result = SQL_QUERY_ESC("SELECT refid FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
1226          array(bigintval($uid)), __FILE__, __LINE__);
1227         list($ref) = SQL_FETCHROW($result);
1228
1229         // Free memory
1230         SQL_FREERESULT($result);
1231
1232         // When he has a referral...
1233         if (($ref > 0) && ($ref != $uid))
1234         {
1235                 // Move to next referral level and count his counter one up!
1236                 $REF_LVL++; UPDATE_REF_COUNTER($ref);
1237         }
1238          elseif ((($ref == $uid) || ($ref == 0)) && (GET_EXT_VERSION("cache") >= "0.1.2"))
1239         {
1240                 // Remove cache here
1241                 if ($CACHE->cache_file("refsystem", true)) $CACHE->cache_destroy();
1242         }
1243 }
1244 //
1245 function UPDATE_ONLINE_LIST($SID, $mod, $act, $wht)
1246 {
1247         global $_COOKIE, $_SERVER, $link, $_GET, $CONFIG;
1248         // Do not update online list when extension is deactivated
1249         if (!EXT_IS_ACTIVE("online", true)) return;
1250
1251         // Initialize variables
1252         $uid = "0"; $rid = "0"; $MEM = 'N'; $ADMIN = 'N';
1253         if (!empty($GLOBALS['userid']))
1254         {
1255                 // Update member status only when userid is valid
1256                 if (($GLOBALS['userid'] > 0) && (IS_LOGGED_IN()))
1257                 {
1258                         // Is valid user
1259                         $uid = $GLOBALS['userid'];
1260                         $MEM = 'Y';
1261                 }
1262         }
1263         if (IS_ADMIN())
1264         {
1265                 // Is administrator
1266                 $ADMIN = 'Y';
1267         }
1268         if (!empty($_COOKIE['refid']))
1269         {
1270                 // Check cookie
1271                 if ($_COOKIE['refid'] > 0) $rid = $GLOBALS['refid'];
1272         }
1273
1274         // Now Read data
1275         $result = SQL_QUERY_ESC("SELECT timestamp FROM "._MYSQL_PREFIX."_online
1276 WHERE sid='%s' LIMIT 1",
1277  array($SID), __FILE__, __LINE__);
1278
1279         if (SQL_NUMROWS($result) == 1)
1280         {
1281                 SQL_FREERESULT($result);
1282                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_online SET
1283 module='%s',
1284 action='%s',
1285 what='%s',
1286 userid=%d,
1287 refid=%d,
1288 is_member='%s',
1289 is_admin='%s',
1290 timestamp=UNIX_TIMESTAMP()
1291 WHERE sid='%s' LIMIT 1",
1292  array(
1293         $mod,
1294         $act,
1295         $wht,
1296         bigintval($uid),
1297         bigintval($rid),
1298         $MEM,
1299         $ADMIN,
1300         $SID
1301 ), __FILE__, __LINE__);
1302         }
1303          else
1304         {
1305                 // No entry does exists so we simply add it!
1306                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_online (module, action, what, userid, refid, is_member, is_admin, timestamp, sid, ip) VALUES ('%s', '%s', '%s', %d, %d, '%s', '%s', UNIX_TIMESTAMP(), '%s', '%s')",
1307                  array($mod, $act, $wht, bigintval($uid), bigintval($rid), $MEM, $ADMIN, $SID, getenv('REMOTE_ADDR')), __FILE__, __LINE__);
1308         }
1309
1310         // Purge old entries
1311         $TIMEOUT = time() - $CONFIG['online_timeout'];
1312         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_online WHERE timestamp <= %d",
1313          array($TIMEOUT), __FILE__, __LINE__);
1314 }
1315 // OBSULETE: Sends out mail to all administrators
1316 function SEND_ADMIN_EMAILS($subj, $msg)
1317 {
1318         $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1319         while (list($email) = SQL_FETCHROW($result))
1320         {
1321                 SEND_EMAIL($email, $subj, $msg);
1322         }
1323         // Really simple... ;-)
1324         SQL_FREERESULT($result);
1325 }
1326 // Get ID number from administrator's login name
1327 function GET_ADMIN_ID($login)
1328 {
1329         global $ADMINS;
1330         $ret = "-1";
1331         if (!empty($ADMINS['aid'][$login]))
1332         {
1333                 // Check cache
1334                 $ret = $ADMINS['aid'][$login];
1335                 if (empty($ret)) $ret = "-1";
1336         }
1337          else
1338         {
1339                 // Load from database
1340                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
1341                  array($login), __FILE__, __LINE__);
1342                 if (SQL_NUMROWS($result) == 1)
1343                 {
1344                         list($ret) = SQL_FETCHROW($result);
1345                         SQL_FREERESULT($result);
1346                 }
1347         }
1348         return $ret;
1349 }
1350 //
1351 // Get password hash from administrator's login name
1352 function GET_ADMIN_HASH($login)
1353 {
1354         global $ADMINS;
1355         $ret = "-1";
1356         if (!empty($ADMINS['password'][$login]))
1357         {
1358                 // Check cache
1359                 $ret = $ADMINS['password'][$login];
1360                 if (empty($ret)) $ret = "-1";
1361         }
1362          else
1363         {
1364                 // Load from database
1365                 $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
1366                  array($login), __FILE__, __LINE__);
1367                 if (SQL_NUMROWS($result) == 1)
1368                 {
1369                         list($ret) = SQL_FETCHROW($result);
1370                         SQL_FREERESULT($result);
1371                 }
1372         }
1373         return $ret;
1374 }
1375 //
1376 function GET_ADMIN_LOGIN($aid)
1377 {
1378         global $ADMINS;
1379         $ret = "***";
1380         if (!empty($ADMINS['login']['aid']))
1381         {
1382                 // Check cache
1383                 if (!empty($ADMINS['login'][$aid]))     $ret = $ADMINS['login'][$aid];
1384                 if (empty($ret)) $ret = "***";
1385         }
1386          else
1387         {
1388                 // Load from database
1389                 $result = SQL_QUERY_ESC("SELECT login FROM "._MYSQL_PREFIX."_admins WHERE id=%d LIMIT 1",
1390                  array(bigintval($aid)), __FILE__, __LINE__);
1391                 if (SQL_NUMROWS($result) == 1)
1392                 {
1393                         // Fetch data
1394                         list($ret) = SQL_FETCHROW($result);
1395                 }
1396
1397                 // Free memory
1398                 SQL_FREERESULT($result);
1399         }
1400         return $ret;
1401 }
1402 //
1403 function ADD_OPTION_LINES($table, $id, $name, $default="",$special="",$where="")
1404 {
1405         $ret = "";
1406         if ($table == "/ARRAY/")
1407         {
1408                 // Selection from array
1409                 if (is_array($id) && is_array($name) && sizeof($id) == sizeof($name))
1410                 {
1411                         // Both are arrays
1412                         foreach ($id as $idx=>$value)
1413                         {
1414                                 $ret .= "<OPTION value=\"".$value."\"";
1415                                 if ($default == $value) $ret .= " selected checked";
1416                                 $ret .= ">".$name[$idx]."</OPTION>\n";
1417                         }
1418                 }
1419         }
1420          else
1421         {
1422                 // Data from database
1423                 $SPEC = ", ".$id;
1424                 if (!empty($special)) $SPEC = ", ".$special;
1425                 $ORDER = $name.$SPEC;
1426                 if ($table == "country") $ORDER = $special;
1427                 $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM "._MYSQL_PREFIX."_%s ".$where." ORDER BY %s",
1428                  array($id, $ORDER, $table, $name), __FILE__, __LINE__);
1429                 if (SQL_NUMROWS($result) > 0)
1430                 {
1431                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1432                         while (list($value, $title, $add) = SQL_FETCHROW($result))
1433                         {
1434                                 if (empty($special)) $add = "";
1435                                 $ret .= "<OPTION value=\"".$value."\"";
1436                                 if ($default == $value) $ret .= " selected checked";
1437                                 if (!empty($add)) $add = " (".$add.")";
1438                                 $ret .= ">".$title.$add."</OPTION>\n";
1439                         }
1440
1441                         // Free memory
1442                         SQL_FREERESULT($result);
1443                 }
1444                  else
1445                 {
1446                         // No data found
1447                         $ret = "<OPTION value=\"x\">".SELECT_NONE."</OPTION>\n";
1448                 }
1449         }
1450         // Return - hopefully - the requested data
1451         return $ret;
1452 }
1453 // Aiut
1454 function activateExchange() {
1455         global $CONFIG;
1456         $result = SQL_QUERY("SELECT userid FROM "._MYSQL_PREFIX."_user_data WHERE status='CONFIRMED' AND max_mails > 0", __FILE__, __LINE__);
1457         if (SQL_NUMROWS($result) >= $CONFIG['activate_xchange'])
1458         {
1459                 // Free memory
1460                 SQL_FREERESULT($result);
1461
1462                 // Activate System
1463                 $SQLs = array(
1464                         "UPDATE "._MYSQL_PREFIX."_mod_reg SET locked='N', hidden='N', mem_only='Y' WHERE module='order' LIMIT 1",
1465                         "UPDATE "._MYSQL_PREFIX."_member_menu SET visible='Y', locked='N' WHERE what='order' OR what='unconfirmed' LIMIT 2",
1466                         "UPDATE "._MYSQL_PREFIX."_config SET activate_xchange='0' WHERE config='0' LIMIT 1"
1467                 );
1468
1469                 // Run SQLs
1470                 foreach ($SQLs as $sql)
1471                 {
1472                         $result = SQL_QUERY($sql, __FILE__, __LINE__);
1473                 }
1474
1475                 // Destroy cache
1476         }
1477 }
1478 //
1479 function DELETE_USER_ACCOUNT($uid, $reason)
1480 {
1481         $POINTS = 0;
1482         $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points
1483 FROM "._MYSQL_PREFIX."_user_points AS p
1484 LEFT JOIN "._MYSQL_PREFIX."_user_data AS d
1485 ON p.userid=d.userid
1486 WHERE p.userid=%d", array(bigintval($uid)), __FILE__, __LINE__);
1487         if (SQL_NUMROWS($result) == 1)
1488         {
1489                 // Save his points to add them to the jackpot
1490                 list($POINTS) = SQL_FETCHROW($result);
1491                 SQL_FREERESULT($result);
1492
1493                 // Delete points entries as well
1494                 $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_points WHERE userid=%d", array(bigintval($uid)), __FILE__, __LINE__);
1495
1496                 // Update mediadata as well
1497                 if (GET_EXT_VERSION("mediadata") >= "0.0.4")
1498                 {
1499                         // Update database
1500                         MEDIA_UPDATE_ENTRY(array("total_points"), "sub", $POINTS);
1501                 }
1502
1503                 // Now, when we have all his points adds them do the jackpot!
1504                 ADD_JACKPOT($POINTS);
1505         }
1506
1507         // Delete category selections as well...
1508         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_cats WHERE userid=%d",
1509          array(bigintval($uid)), __FILE__, __LINE__);
1510
1511         // Remove from rallye if found
1512         if (EXT_IS_ACTIVE("rallye"))
1513         {
1514                 $result = SQL_QUERY("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_users WHERE userid=%d",
1515                  array(bigintval($uid)), __FILE__, __LINE__);
1516         }
1517
1518         // Now a mail to the user and that's all...
1519         $msg = LOAD_EMAIL_TEMPLATE("del-user", stripslashes($reason), $uid);
1520         SEND_EMAIL($uid, ADMIN_DEL_ACCOUNT, $msg);
1521
1522         // Ok, delete the account!
1523         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array(bigintval($uid)), __FILE__, __LINE__);
1524 }
1525 //
1526 function META_DESCRIPTION($mod, $wht)
1527 {
1528         global $CONFIG, $DEPTH;
1529         if (($mod != "admin") && ($mod != "login"))
1530         {
1531                 // Exclude admin and member's area
1532                 $DESCR = MAIN_TITLE." ".trim($CONFIG['title_middle'])." ".ADD_DESCR("guest", "what-".$wht, true);
1533                 unset($DEPTH);
1534                 OUTPUT_HTML("<META name=\"description\" content=\"".$DESCR."\">\n");
1535         }
1536 }
1537 //
1538 function ADD_JACKPOT($points)
1539 {
1540         $result = SQL_QUERY("SELECT points FROM "._MYSQL_PREFIX."_jackpot WHERE ok='ok' LIMIT 1", __FILE__, __LINE__);
1541         if (SQL_NUMROWS($result) == 0)
1542         {
1543                 // Create line
1544                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_jackpot (ok, points) VALUES ('ok', '%s')", array($points), __FILE__, __LINE__);
1545         }
1546          else
1547         {
1548                 // Free memory
1549                 SQL_FREERESULT($result);
1550
1551                 // Update points
1552                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_jackpot SET points=points+%s WHERE ok='ok' LIMIT 1",
1553                  array($points), __FILE__, __LINE__);
1554         }
1555 }
1556 //
1557 function SUB_JACKPOT($points)
1558 {
1559         // First failed
1560         $ret = "-1";
1561
1562         // Get current points
1563         $result = SQL_QUERY("SELECT points FROM "._MYSQL_PREFIX."_jackpot WHERE ok='ok' LIMIT 1", __FILE__, __LINE__);
1564         if (SQL_NUMROWS($result) == 0)
1565         {
1566                 // Create line
1567                 $result = SQL_QUERY("INSERT INTO "._MYSQL_PREFIX."_jackpot (ok, points) VALUES ('ok', 0.00000)", __FILE__, __LINE__);
1568         }
1569          else
1570         {
1571                 // Free memory
1572                 SQL_FREERESULT($result);
1573
1574                 // Read points
1575                 list($jackpot) = SQL_FETCHROW($result);
1576                 if ($jackpot >= $points)
1577                 {
1578                         // Update points when there are enougth points in jackpot
1579                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_jackpot SET points=points-%s WHERE ok='ok' LIMIT 1",
1580                                 array($points), __FILE__, __LINE__);
1581                         $ret = $jackpot - $points;
1582                 }
1583         }
1584 }
1585 //
1586 function IS_DEMO()
1587 {
1588         global $_COOKIE;
1589         return ((EXT_IS_ACTIVE("demo")) && ($_COOKIE['admin_login'] == "demo"));
1590 }
1591 //
1592 function LOAD_CONFIG($no="0")
1593 {
1594         global $CFG_CACHE, $CONFIG;
1595         $CFG_DUMMY = false;
1596         // Check for cache extension, cache-array and if the requested configuration is in cache
1597         if ((is_array($CFG_CACHE)) && (isset($CFG_CACHE['config'][$no])))
1598         {
1599                 // Load config from cache
1600                 $CFG_DUMMY = array();
1601                 foreach ($CFG_CACHE as $element=>$cfgs)
1602                 {
1603                         $CFG_DUMMY[$element] = $cfgs[$no];
1604                 }
1605
1606                 // Count cache hits
1607                 $CONFIG['cache_hits']++;
1608         }
1609          else
1610         {
1611                 // Load config from DB
1612                 $result_config = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_config WHERE config='%d' LIMIT 1",
1613                  array(bigintval($no)), __FILE__, __LINE__);
1614                 $CFG_DUMMY = SQL_FETCHARRAY($result_config);
1615                 SQL_FREERESULT($result_config);
1616         }
1617
1618         // Return config array
1619         return $CFG_DUMMY;
1620 }
1621 // Gets the matching what name from module
1622 function GET_WHAT($MOD_CHECK)
1623 {
1624         $wht = "";
1625         //* DEBUG: */ echo __LINE__."!".$MOD_CHECK."!<br />\n";
1626         switch ($MOD_CHECK)
1627         {
1628         case "admin":
1629                 $wht = "overview";
1630                 break;
1631
1632         case "login":
1633         case "index":
1634                 $wht = "welcome";
1635                 break;
1636
1637         default:
1638                 $wht = "";
1639                 break;
1640         }
1641
1642         // Return what value
1643         return $wht;
1644 }
1645 //
1646 function MODULE_HAS_MENU($mod)
1647 {
1648         global $EXTENSIONS, $MODULES, $CONFIG;
1649
1650         // All is false by default
1651         $ret = false;
1652         if (GET_EXT_VERSION("cache") >= "0.1.2")
1653         {
1654                 if (isset($MODULES['has_menu'][$mod]))
1655                 {
1656                         // Check module cache and count hit
1657                         if ($MODULES['has_menu'][$mod] == 'Y') $ret = true;
1658                         $CONFIG['cache_hits']++;
1659                 }
1660                  elseif (isset($EXTENSIONS['ext_menu'][$mod]))
1661                 {
1662                         // Check cache and count hit
1663                         if ($EXTENSIONS['ext_menu'][$mod] == 'Y') $ret = true;
1664                         $CONFIG['cache_hits']++;
1665                 }
1666         }
1667         if ((GET_EXT_VERSION("sql_patches") >= "0.3.6") && ($ret === false))
1668         {
1669                 // Check database for entry
1670                 $result = SQL_QUERY_ESC("SELECT has_menu FROM "._MYSQL_PREFIX."_mod_reg WHERE module='%s' LIMIT 1",
1671                  array($mod), __FILE__, __LINE__);
1672                 if (SQL_NUMROWS($result) == 1)
1673                 {
1674                         list($has_menu) = SQL_FETCHROW($result);
1675                         if ($has_menu == 'Y') $ret = true;
1676                 }
1677
1678                 // Free memory
1679                 SQL_FREERESULT($result);
1680         } elseif (GET_EXT_VERSION("sql_patches") == "") {
1681                 // No sql_patches installed, so maybe in admin area?
1682                 if ((IS_ADMIN()) && ($mod == "admin")) return true; // Then there is a menu!
1683         }
1684
1685         // Return status
1686         return $ret;
1687 }
1688 //
1689 ?>