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