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