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