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