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