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