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