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