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