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