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