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