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