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