]> git.mxchange.org Git - mailer.git/blob - inc/mysql-manager.php
2fdeaa1ad8d9bae3074329f02eb28e5863af8e32
[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         // @TODO Why is this global??? #100
514         global $status;
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         $ret = false;
521
522         // is the cache entry there?
523         if (isset($GLOBALS['cache_array']['is_member'])) {
524                 // Then return it
525                 return $GLOBALS['cache_array']['is_member'];
526         } // END - if
527
528         // Fix "deleted" cookies first
529         fixDeletedCookies(array('userid', 'u_hash'));
530
531         // Are cookies set?
532         if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) {
533                 // Cookies are set with values, but are they valid?
534                 $result = SQL_QUERY_ESC("SELECT password, status, last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
535                 array(getUserId()), __FUNCTION__, __LINE__);
536                 if (SQL_NUMROWS($result) == 1) {
537                         // Load data from cookies
538                         list($password, $status, $mod, $onl) = SQL_FETCHROW($result);
539
540                         // Validate password by created the difference of it and the secret key
541                         $valPass = generatePassString($password);
542
543                         // Transfer last module and online time
544                         if ((!empty($mod)) && (empty($GLOBALS['last']['module']))) {
545                                 $GLOBALS['last']['module'] = $mod;
546                                 $GLOBALS['last']['online'] = $onl;
547                         } // END - if
548
549                         // So did we now have valid data and an unlocked user?
550                         //* DEBUG: */ echo $valPass."<br />".getSession('u_hash')."<br />";
551                         if (($status == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
552                                 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
553                                 $ret = true;
554                         } else {
555                                 // Maybe got locked etc.
556                                 //* DEBUG: */ echo __LINE__."!!!<br />";
557                                 destroyUserSession();
558                         }
559                 } else {
560                         // Cookie data is invalid!
561                         //* DEBUG: */ echo __LINE__."***<br />";
562                         destroyUserSession();
563                 }
564
565                 // Free memory
566                 SQL_FREERESULT($result);
567         } else {
568                 // Cookie data is invalid!
569                 //* DEBUG: */ echo __LINE__."///<br />";
570                 destroyUserSession();
571         }
572
573         // Cache status
574         $GLOBALS['cache_array']['is_member'] = $ret;
575
576         // Return status
577         return $ret;
578 }
579
580 // This patched function will reduce many SELECT queries for the specified or current admin login
581 function IS_ADMIN ($admin = '') {
582         // Init variables
583         $ret = false; $passCookie = ''; $valPass = '';
584         //* DEBUG: */ echo __LINE__."ADMIN:".$admin."<br />";
585
586         // If admin login is not given take current from cookies...
587         if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
588                 // Get admin login and password from session/cookies
589                 $admin = getSession('admin_login');
590                 $passCookie = getSession('admin_md5');
591         }
592         //* DEBUG: */ echo __LINE__."ADMIN:".$admin.'/'.$passCookie."<br />";
593
594         // Search in array for entry
595         if (isset($GLOBALS['cache_array']['admin_hash'])) {
596                 // Use cached string
597                 $valPass = $GLOBALS['cache_array']['admin_hash'];
598         } elseif ((!empty($passCookie)) && (isset($GLOBALS['cache_array']['admins']['password'][$admin])) && (!empty($admin))) {
599                 // Login data is valid or not?
600                 $valPass = generatePassString($GLOBALS['cache_array']['admins']['password'][$admin]);
601
602                 // Cache it away
603                 $GLOBALS['cache_array']['admin_hash'] = $valPass;
604
605                 // Count cache hits
606                 incrementConfigEntry('cache_hits');
607         } elseif ((!empty($admin)) && ((!EXT_IS_ACTIVE('cache'))) || (!isset($GLOBALS['cache_array']['admins']['password'][$admin]))) {
608                 // Search for admin
609                 $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
610                 array($admin), __FUNCTION__, __LINE__);
611
612                 // Is he admin?
613                 $passDB = '';
614                 if (SQL_NUMROWS($result) == 1) {
615                         // Admin login was found so let's load password from DB
616                         list($passDB) = SQL_FETCHROW($result);
617
618                         // Temporary cache it
619                         $GLOBALS['cache_array']['admins']['password'][$admin] = $passDB;
620
621                         // Generate password hash
622                         $valPass = generatePassString($passDB);
623                 } // END - if
624
625                 // Free memory
626                 SQL_FREERESULT($result);
627         }
628
629         if (!empty($valPass)) {
630                 // Check if password is valid
631                 //* DEBUG: */ print __FUNCTION__."*".$valPass.'/'.$passCookie."*<br />\n";
632                 $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE('cache'))));
633         } // END - if
634
635         // Return result of comparision
636         //* DEBUG: */ if (!$ret) echo __LINE__."OK!<br />";
637         return $ret;
638 }
639
640 // Generates a list of "max receiveable emails per day"
641 function addMaxReceiveList ($mode, $default = '', $return = false) {
642         $OUT = '';
643         $result = false;
644
645         switch ($mode) {
646                 case 'guest':
647                         // Guests (in the registration form) are not allowed to select 0 mails per day.
648                         $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` WHERE value > 0 ORDER BY value",
649                         __FUNCTION__, __LINE__);
650                         break;
651
652                 case 'member':
653                         // Members are allowed to set to zero mails per day (we will change this soon!)
654                         $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` ORDER BY value",
655                         __FUNCTION__, __LINE__);
656                         break;
657
658                 default: // Invalid!
659                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
660                         break;
661         }
662
663         // Some entries are found?
664         if (SQL_NUMROWS($result) > 0) {
665                 $OUT = '';
666                 while ($content = SQL_FETCHARRAY($result)) {
667                         $OUT .= "      <option value=\"".$content['value']."\"";
668                         if (REQUEST_POST('max_mails') == $content['value']) $OUT .= ' selected="selected"';
669                         $OUT .= ">".$content['value']." {--PER_DAY--}";
670                         if (!empty($content['comment'])) $OUT .= " (".$content['comment'].')';
671                         $OUT .= "</option>\n";
672                 }
673                 define('__MAX_RECEIVE_OPTIONS', $OUT);
674
675                 // Load template
676                 $OUT = LOAD_TEMPLATE($mode . '_receive_table', true);
677         } else {
678                 // Maybe the admin has to setup some maximum values?
679                 debug_report_bug('Nothing is being done here?');
680         }
681
682         // Free result
683         SQL_FREERESULT($result);
684
685         if ($return === true) {
686                 // Return generated HTML code
687                 return $OUT;
688         } else {
689                 // Output directly (default)
690                 OUTPUT_HTML($OUT);
691         }
692 }
693
694 // Checks wether the given email address is used.
695 function isEmailTaken ($email) {
696         // Query the database
697         $result = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE email LIKE '{PER}%s{PER}' LIMIT 1",
698         array($email), __FUNCTION__, __LINE__);
699
700         // Is the email there?
701         $ret = (SQL_NUMROWS($result) == 1);
702
703         // Free the result
704         SQL_FREERESULT($result);
705
706         // Return result
707         return $ret;
708 }
709
710 // Validate the given menu action
711 function isMenuActionValid ($mode, $act, $wht, $UPDATE=false) {
712         // Is the cache entry there and we shall not update?
713         if ((isset($GLOBALS['cache_array']['action_valid'][$mode][$act][$wht])) && ($UPDATE === false)) {
714                 // Count cache hit
715                 incrementConfigEntry('cache_hits');
716
717                 // Then use this cache
718                 return $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht];
719         } // END - if
720
721         // By default nothing is valid
722         $ret = false;
723
724         // Look in all menus or only unlocked
725         $add = '';
726         if ((!IS_ADMIN()) && ($mode != 'admin')) $add = " AND `locked`='N'";
727
728         //* DEBUG: */ echo __LINE__.':'.$mode.'/'.$act.'/'.$wht."*<br />\n";
729         if (($mode != 'admin') && ($UPDATE === true)) {
730                 // Update guest or member menu
731                 $sql = SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
732                 array($mode, $act, $wht), __FUNCTION__, __LINE__, false);
733         } elseif (($wht != "overview") && (!empty($wht))) {
734                 // Other actions
735                 $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",
736                 array($mode, $act, $wht), __FUNCTION__, __LINE__, false);
737         } else {
738                 // Admin login overview
739                 $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",
740                 array($mode, $act), __FUNCTION__, __LINE__, false);
741         }
742
743         // Run SQL command
744         $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
745         if ($UPDATE === true) {
746                 // Check updated/affected rows
747                 $ret = (SQL_AFFECTEDROWS() == 1);
748         } else {
749                 // Check found rows
750                 $ret = (SQL_NUMROWS($result) == 1);
751         }
752
753         // Free memory
754         SQL_FREERESULT($result);
755
756         // Set cache entry
757         $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht] = $ret;
758
759         // Return result
760         return $ret;
761 }
762
763 //
764 function sendModeMails ($mod, $modes) {
765         global $DATA;
766
767         // Load hash
768         $result_main = SQL_QUERY_ESC("SELECT password FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
769         array(getUserId()), __FUNCTION__, __LINE__);
770         if (SQL_NUMROWS($result_main) == 1) {
771                 // Load hash from database
772                 list($hashDB) = SQL_FETCHROW($result_main);
773
774                 // Extract salt from cookie
775                 $salt = substr(getSession('u_hash'), 0, -40);
776
777                 // Now let's compare passwords
778                 $hash = generatePassString($hashDB);
779                 if (($hash == getSession('u_hash')) || (REQUEST_POST('pass1') == REQUEST_POST('pass2'))) {
780                         // Load user's data
781                         $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",
782                         array(getUserId(), $hashDB), __FUNCTION__, __LINE__);
783                         if (SQL_NUMROWS($result) == 1) {
784                                 // Load the data
785                                 $DATA = SQL_FETCHROW($result);
786
787                                 // Free result
788                                 SQL_FREERESULT($result);
789
790                                 // Translate gender
791                                 $DATA[0] = translateGender($DATA[0]);
792
793                                 // Clear/init the content variable
794                                 $content = '';
795                                 $DATA['info'] = '';
796
797                                 switch ($mod)
798                                 {
799                                         case 'mydata':
800                                                 foreach ($modes as $mode) {
801                                                         switch ($mode)
802                                                         {
803                                                                 case 'normal': break; // Do not add any special lines
804
805                                                                 case 'email': // Email was changed!
806                                                                         $content = getMessage('MEMBER_CHANGED_EMAIL').": ".REQUEST_POST('old_addy')."\n";
807                                                                         break;
808
809                                                                 case 'pass': // Password was changed
810                                                                         $content = getMessage('MEMBER_CHANGED_PASS')."\n";
811                                                                         break;
812
813                                                                 default:
814                                                                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
815                                                                         $content = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n";
816                                                                         break;
817                                                         } // END - switch
818                                                 } // END - if
819
820                                                 if (EXT_IS_ACTIVE('country')) {
821                                                         // Replace code with description
822                                                         $DATA[4] = COUNTRY_GENERATE_INFO(REQUEST_POST('country_code'));
823                                                 } // END - if
824
825                                                 // Merge content with data from POST
826                                                 $content = merge_array($content, REQUEST_POST_ARRAY());
827
828                                                 // Load template
829                                                 $msg = LOAD_EMAIL_TEMPLATE('member_mydata_notify', $content, getUserId());
830
831                                                 if (getConfig('admin_notify') == 'Y') {
832                                                         // The admin needs to be notified about a profile change
833                                                         $msg_admin = 'admin_mydata_notify';
834                                                         $sub_adm   = getMessage('ADMIN_CHANGED_DATA');
835                                                 } else {
836                                                         // No mail to admin
837                                                         $msg_admin = '';
838                                                         $sub_adm   = '';
839                                                 }
840
841                                                 // Set subject lines
842                                                 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
843
844                                                 // Output success message
845                                                 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
846                                                 break;
847
848                                         default: // Unsupported module!
849                                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
850                                                 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
851                                                 break;
852                                 } // END - switch
853                         } else {
854                                 // Could not load profile data
855                                 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
856                         }
857                 } else {
858                         // Passwords mismatch
859                         $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
860                 }
861         } else {
862                 // Could not load profile
863                 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
864         }
865
866         // Send email to user if required
867         if ((!empty($sub_mem)) && (!empty($msg))) {
868                 // Send member mail
869                 sendEmail($DATA[7], $sub_mem, $msg);
870         } // END - if
871
872         // Send only if no other error has occured
873         if (empty($content)) {
874                 if ((!empty($sub_adm)) && (!empty($msg_admin))) {
875                         // Send admin mail
876                         sendAdminNotification($sub_adm, $msg_admin, $content, getUserId());
877                 } elseif (getConfig('admin_notify') == 'Y') {
878                         // Cannot send mails to admin!
879                         $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
880                 } else {
881                         // No mail to admin
882                         $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
883                 }
884         } // END - if
885
886         // Load template
887         LOAD_TEMPLATE('admin_settings_saved', false, $content);
888 }
889
890 // Update module counter
891 function countModuleHit($mod) {
892         if ($mod != "css") {
893                 // Do count all other modules but not accesses on CSS file css.php!
894                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET clicks=clicks+1 WHERE `module`='%s' LIMIT 1",
895                 array($mod), __FUNCTION__, __LINE__);
896         } // END - if
897 }
898
899 // Get action value from mode (admin/guest/member) and what-value
900 function getModeAction ($mode, &$wht) {
901         // Init status
902         $ret = '';
903
904         //* DEBUG: */ echo __LINE__.'='.$mode.'/'.$wht.'/'.$GLOBALS['action']."=<br />";
905         if ((empty($wht)) && ($mode != 'admin')) {
906                 $wht = "welcome";
907                 if (getConfig('index_home') != '') $wht = getConfig('index_home');
908         } // END - if
909
910         if ($mode == 'admin') {
911                 // Action value for admin area
912                 if (REQUEST_ISSET_GET('action')) {
913                         // Use from request!
914                         return REQUEST_GET('action');
915                 } elseif (!empty($GLOBALS['action'])) {
916                         // Get it directly from URL
917                         return $GLOBALS['action'];
918                 } elseif (($wht == "overview") || (empty($GLOBALS['what']))) {
919                         // Default value for admin area
920                         $ret = "login";
921                 }
922         } elseif (!empty($GLOBALS['action'])) {
923                 // Get it directly from URL
924                 return $GLOBALS['action'];
925         }
926         //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret."<br />\n";
927
928         // Does the module have a menu?
929         if (MODULE_HAS_MENU($mode)) {
930                 // Rewriting modules to menu
931                 switch ($mode) {
932                         case 'index': $mode = 'guest';  break;
933                         case "login": $mode = 'member'; break;
934                 } // END - switch
935
936                 // Guest and member menu is "main" as the default
937                 if (empty($ret)) $ret = "main";
938
939                 // Load from database
940                 $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `what`='%s' LIMIT 1",
941                 array($mode, $wht), __FUNCTION__, __LINE__);
942                 if (SQL_NUMROWS($result) == 1) {
943                         // Load action value and pray that this one is the right you want... ;-)
944                         list($ret) = SQL_FETCHROW($result);
945                 } // END - if
946
947                 // Free memory
948                 SQL_FREERESULT($result);
949         } elseif ((GET_EXT_VERSION('sql_patches') == '') && ($mode != 'admin')) {
950                 // No sql_patches installed, but maybe we need to register an admin?
951                 if (isAdminRegistered()) {
952                         // Redirect
953                         // @TODO Why does this lead into an endless loop but we still need it???
954                         // @TODO Commented out redirectToUrl('admin.php');
955                 } // END - if
956         }
957
958         // Return action value
959         return $ret;
960 }
961
962 // Get category name back
963 function getCategory ($cid) {
964         // Default is not found
965         $ret = getMessage('_CATEGORY_404');
966
967         // Is the category id set?
968         if ($cid == '0') {
969                 // No category
970                 $ret = getMessage('_CATEGORY_NONE');
971         } elseif ($cid > 0) {
972                 // Lookup the category in database
973                 $result = SQL_QUERY_ESC("SELECT cat FROM `{!_MYSQL_PREFIX!}_cats` WHERE `id`=%s LIMIT 1",
974                 array(bigintval($cid)), __FUNCTION__, __LINE__);
975                 if (SQL_NUMROWS($result) == 1) {
976                         // Category found... :-)
977                         list($ret) = SQL_FETCHROW($result);
978                 } // END - if
979
980                 // Free result
981                 SQL_FREERESULT($result);
982         } // END - if
983
984         // Return result
985         return $ret;
986 }
987
988 // Get a string of "mail title" and price back
989 function getPaymentTitlePrice ($pid, $full=false) {
990         // Default is not found
991         $ret = getMessage('_PAYMENT_404');
992
993         // Load payment data
994         $result = SQL_QUERY_ESC("SELECT mail_title, price FROM `{!_MYSQL_PREFIX!}_payments` WHERE `id`=%s LIMIT 1",
995         array(bigintval($pid)), __FUNCTION__, __LINE__);
996         if (SQL_NUMROWS($result) == 1) {
997                 // Payment type found... :-)
998                 if (!$full) {
999                         // Return only title
1000                         list($ret) = SQL_FETCHROW($result);
1001                 } else {
1002                         // Return title and price
1003                         list($t, $p) = SQL_FETCHROW($result);
1004                         $ret = $t.' / '.translateComma($p).' {!POINTS!}';
1005                 }
1006         }
1007
1008         // Free result
1009         SQL_FREERESULT($result);
1010
1011         // Return result
1012         return $ret;
1013 }
1014
1015 // Get (basicly) the price of given payment id
1016 function getPaymentPoints ($pid, $lookFor = 'price') {
1017         // Default value...
1018         $ret = '-1';
1019
1020         // Search for it in database
1021         $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_payments` WHERE `id`=%s LIMIT 1",
1022         array($lookFor, $pid), __FUNCTION__, __LINE__);
1023
1024         // Is the entry there?
1025         if (SQL_NUMROWS($result) == 1) {
1026                 // Payment type found... :-)
1027                 list($ret) = SQL_FETCHROW($result);
1028         } // END - if
1029
1030         // Free result
1031         SQL_FREERESULT($result);
1032
1033         // Return value
1034         return $ret;
1035 }
1036
1037 // Remove a receiver's ID from $receivers and add a link for him to confirm
1038 function removeReceiver (&$receivers, $key, $uid, $pool_id, $stats_id='', $bonus=false) {
1039         // Default is not removed
1040         $ret = 'failed';
1041
1042         // Is the userid valid?
1043         if ($uid > 0) {
1044                 // Remove entry from array
1045                 unset($receivers[$key]);
1046
1047                 // Is there already a line for this user available?
1048                 if ($stats_id > 0) {
1049                         // Only when we got a real stats ID continue searching for the entry
1050                         $type = 'NORMAL'; $rowName = 'stats_id';
1051                         if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1052
1053                         // Try to look the entry up
1054                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1055                         array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
1056
1057                         // Was it *not* found?
1058                         if (SQL_NUMROWS($result) == 0) {
1059                                 // So we add one!
1060                                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_links` (%s, userid, link_type) VALUES ('%s','%s','%s')",
1061                                 array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
1062                                 $ret = 'done';
1063                         } else {
1064                                 // Already found
1065                                 $ret = 'already';
1066                         }
1067
1068                         // Free memory
1069                         SQL_FREERESULT($result);
1070                 }
1071         }
1072
1073         // Return status for sending routine
1074         return $ret;
1075 }
1076
1077 // Calculate sum (default) or count records of given criteria
1078 function GET_TOTAL_DATA ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1079         $ret = 0;
1080         //* DEBUG: */ echo $search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'<br />\n';
1081         if ((empty($search)) && ($search != '0')) {
1082                 // Count or sum whole table?
1083                 if ($countRows === true) {
1084                         // Count whole table
1085                         $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
1086                         array($lookFor, $tableName), __FUNCTION__, __LINE__);
1087                 } else {
1088                         // Sum whole table
1089                         $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
1090                         array($lookFor, $tableName), __FUNCTION__, __LINE__);
1091                 }
1092         } elseif (($countRows === true) || ($lookFor == 'userid')) {
1093                 // Count rows
1094                 //* DEBUG: */ echo "COUNT!<br />\n";
1095                 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
1096                 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1097         } else {
1098                 // Add all rows
1099                 //* DEBUG: */ echo "SUM!<br />\n";
1100                 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
1101                 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1102         }
1103
1104         // Load row
1105         list($ret) = SQL_FETCHROW($result);
1106
1107         // Free result
1108         SQL_FREERESULT($result);
1109
1110         // Fix empty values
1111         if ((empty($ret)) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1112                 // Float number
1113                 $ret = '0.00000';
1114         } elseif (''.$ret.'' == '') {
1115                 // Fix empty result
1116                 $ret = '0';
1117         }
1118
1119         // Return value
1120         return $ret;
1121 }
1122 // Getter fro ref level percents
1123 function getReferalLevelPercents ($level) {
1124         // Default is zero
1125         $per = 0;
1126
1127         // Do we have cache?
1128         if ((isset($GLOBALS['cache_array']['ref_depths']['level'])) && (EXT_IS_ACTIVE('cache'))) {
1129                 // First look for level
1130                 $key = array_search($level, $GLOBALS['cache_array']['ref_depths']['level']);
1131                 if ($key !== false) {
1132                         // Entry found!
1133                         $per = $GLOBALS['cache_array']['ref_depths']['percents'][$key];
1134
1135                         // Count cache hit
1136                         incrementConfigEntry('cache_hits');
1137                 }
1138         } elseif (!EXT_IS_ACTIVE('cache')) {
1139                 // Get referal data
1140                 $result_lvl = SQL_QUERY_ESC("SELECT percents FROM `{!_MYSQL_PREFIX!}_refdepths` WHERE level='%s' LIMIT 1",
1141                 array(bigintval($level)), __FUNCTION__, __LINE__);
1142
1143                 // Entry found?
1144                 if (SQL_NUMROWS($result_lvl) == 1) {
1145                         // Get percents
1146                         list($per) = SQL_FETCHROW($result_lvl);
1147                 } // END - if
1148
1149                 // Free result
1150                 SQL_FREERESULT($result_lvl);
1151         }
1152
1153         // Return percent
1154         return $per;
1155 }
1156
1157 /**
1158  *
1159  * Dynamic referal system, can also send mails!
1160  *
1161  * subject     = Subject line, write in lower-case letters and underscore is allowed
1162  * uid         = Referal ID wich should receive...
1163  * points      = ... xxx points
1164  * send_notify = shall I send the referal an email or not?
1165  * rid         = inc/modules/guest/what-confirm.php need this (DEPRECATED???)
1166  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
1167  * add_mode    = Add points only to $uid or also refs? (WARNING! Changing 'ref' to 'direct'
1168  *               for default value will cause no referal will get points ever!!!)
1169  */
1170 function ADD_POINTS_REFSYSTEM ($subject, $uid, $points, $send_notify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1171         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
1172         global $DATA;
1173
1174         // Convert mode to lower-case
1175         $add_mode = strtolower($add_mode);
1176
1177         // When $uid = 0 add points to jackpot
1178         if ($uid == '0') {
1179                 // Add points to jackpot
1180                 ADD_JACKPOT($points);
1181                 return;
1182         } // END - if
1183
1184         // Add booking record if extension is installed
1185         if (EXT_IS_ACTIVE('booking')) {
1186                 // Add record
1187                 ADD_BOOKING_RECORD($subject, $uid, $points, 'add');
1188         } // END - if
1189
1190         // Count up referal depth
1191         if (!isset($GLOBALS['ref_level'])) {
1192                 // Initialialize referal system
1193                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />\n";
1194                 $GLOBALS['ref_level'] = 0;
1195         } else {
1196                 // Increase referal level
1197                 $GLOBALS['ref_level']++;
1198                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />\n";
1199         }
1200
1201         // Default is 'normal' points
1202         $data = 'points';
1203
1204         // Which points, locked or normal?
1205         if ($locked) $data = 'locked_points';
1206
1207         // Check user account
1208         $result_user = SQL_QUERY_ESC("SELECT refid, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
1209         array(bigintval($uid)), __FUNCTION__, __LINE__);
1210
1211         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},numRows=".SQL_NUMROWS($result_user).",points={$points}<br />\n";
1212         if (SQL_NUMROWS($result_user) == 1) {
1213                 // This is the user and his ref
1214                 list($ref, $email) = SQL_FETCHROW($result_user);
1215                 $GLOBALS['cache_array']['add_uid'][$ref] = $uid;
1216
1217                 // Get percents
1218                 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1219                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />\n";
1220
1221                 // Some percents found?
1222                 if ($per > 0) {
1223                         // Calculate new points
1224                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />\n";
1225                         $ref_points = $points * $per / 100;
1226
1227                         // Pay refback here if level > 0 and in ref-mode
1228                         if ((EXT_IS_ACTIVE('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_uid'][$uid]))) {
1229                                 //* 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";
1230                                 $ref_points = ADD_REFBACK_POINTS($GLOBALS['cache_array']['add_uid'][$uid], $uid, $points, $ref_points);
1231                                 //* 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";
1232                         } // END - if
1233
1234                         // Update points...
1235                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_points` SET %s=%s+%s WHERE userid=%s AND ref_depth='%s' LIMIT 1",
1236                         array($data, $data, $ref_points, bigintval($uid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1237                         //* 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";
1238
1239                         // No entry updated?
1240                         if (SQL_AFFECTEDROWS() < 1) {
1241                                 // First ref in this level! :-)
1242                                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_points` (userid,ref_depth,%s) VALUES (%s,'%s',%s)",
1243                                 array($data, bigintval($uid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1244                                 //* 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";
1245                         } // END - if
1246
1247                         // Update mediadata as well
1248                         if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1249                                 // Update database
1250                                 MEDIA_UPDATE_ENTRY(array('total_points'), 'add', $ref_points);
1251                         } // END - if
1252
1253                         // Points updated, maybe I shall send him an email?
1254                         if (($send_notify) && ($ref > 0) && (!$locked)) {
1255                                 // Prepare content
1256                                 $content = array(
1257                                         'percent' => $per,
1258                                         'level'   => bigintval($GLOBALS['ref_level']),
1259                                         'points'  => $ref_points,
1260                                         'refid'   => bigintval($ref)
1261                                 );
1262
1263                                 // Load email template
1264                                 $msg = LOAD_EMAIL_TEMPLATE('confirm-referal', $content, bigintval($uid));
1265
1266                                 sendEmail($email, THANX_REFERRAL_ONE, $msg);
1267                         } elseif (($send_notify) && ($ref == 0) && (!$locked) && ($add_mode == 'direct') && (!defined('__POINTS_VALUE'))) {
1268                                 // Direct payment shall be notified about
1269                                 define('__POINTS_VALUE', $ref_points);
1270
1271                                 // Prepare content
1272                                 $content = array(
1273                                         'text'   => getMessage('REASON_DIRECT_PAYMENT'),
1274                                         'points' => translateComma($ref_points)
1275                                 );
1276
1277                                 // Load message
1278                                 $msg = LOAD_EMAIL_TEMPLATE('add-points', $content, $uid);
1279
1280                                 // And sent it away
1281                                 sendEmail($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $msg);
1282                                 if (!REQUEST_ISSET_GET(('mid'))) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1283                         }
1284
1285                         // Maybe there's another ref?
1286                         if (($ref > 0) && ($points > 0) && ($ref != $uid) && ($add_mode == 'ref')) {
1287                                 // Then let's credit him here...
1288                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref},points={$points} - ADVANCE!<br />\n";
1289                                 ADD_POINTS_REFSYSTEM(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), $ref, $points, $send_notify, $ref, $locked);
1290                         } // END - if
1291                 } // END - if
1292         } // END - if
1293
1294         // Free result
1295         SQL_FREERESULT($result_user);
1296         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
1297 }
1298
1299 // Wrapper function for ADD_POINTS_REFSYSTEM()
1300 function ADD_POINTS_REFSYSTEM_DIRECT ($subject, $uid, $points) {
1301         return ADD_POINTS_REFSYSTEM($subject, $uid, $points, false, 0, false, 'direct');
1302 }
1303
1304 // Updates the referal counter
1305 function updateReferalCounter ($uid) {
1306         // Make it sure referal level zero (member him-/herself) is at least selected
1307         if (empty($GLOBALS['cache_array']['ref_level'][$uid])) $GLOBALS['cache_array']['ref_level'][$uid] = 1;
1308         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['ref_level'][$uid]}<br />\n";
1309
1310         // Update counter
1311         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_refsystem` SET counter=counter+1 WHERE userid=%s AND level='%s' LIMIT 1",
1312         array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
1313
1314         // When no entry was updated then we have to create it here
1315         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS()."<br />\n";
1316         if (SQL_AFFECTEDROWS() < 1) {
1317                 // First count!
1318                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_refsystem` (userid, level, counter) VALUES (%s,%s,1)",
1319                 array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
1320                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid}<br />\n";
1321         } // END - if
1322
1323         // Check for his referal
1324         $result = SQL_QUERY_ESC("SELECT refid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
1325         array(bigintval($uid)), __FUNCTION__, __LINE__);
1326
1327         // Load refid
1328         list($ref) = SQL_FETCHROW($result);
1329
1330         // Free memory
1331         SQL_FREERESULT($result);
1332         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref}<br />\n";
1333
1334         // When he has a referal...
1335         if (($ref > 0) && ($ref != $uid)) {
1336                 // Move to next referal level and count his counter one up!
1337                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />\n";
1338                 $GLOBALS['cache_array']['ref_level'][$uid]++; updateReferalCounter($ref);
1339         } elseif ((($ref == $uid) || ($ref == 0)) && (GET_EXT_VERSION('cache') >= '0.1.2')) {
1340                 // Remove cache here
1341                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />\n";
1342                 rebuildCacheFiles('refsystem', 'refsystem');
1343         }
1344
1345         // "Walk" back here
1346         $GLOBALS['cache_array']['ref_level'][$uid]--;
1347
1348         // Handle refback here if extension is installed
1349         if (EXT_IS_ACTIVE('refback')) {
1350                 updateRefbackTable($uid);
1351         } // END - if
1352 }
1353
1354 // Sends out mail to all administrators. This function is no longer obsolete
1355 // because we need it when there is no ext-admins installed
1356 function SEND_ADMIN_EMAILS ($subj, $msg) {
1357         // Load all admin email addresses
1358         $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1359         while ($content = SQL_FETCHARRAY($result)) {
1360                 // Send the email out
1361                 sendEmail($content['email'], $subj, $msg);
1362         } // END - if
1363
1364         // Free result
1365         SQL_FREERESULT($result);
1366
1367         // Really simple... ;-)
1368 }
1369
1370 // Get ID number from administrator's login name
1371 function GET_ADMIN_ID ($login) {
1372         // By default no admin is found
1373         $ret = '-1';
1374
1375         // Check cache
1376         if (isset($GLOBALS['cache_array']['admins']['aid'][$login])) {
1377                 // Use it if found to save SQL queries
1378                 $ret = $GLOBALS['cache_array']['admins']['aid'][$login];
1379
1380                 // Update cache hits
1381                 incrementConfigEntry('cache_hits');
1382         } elseif (!EXT_IS_ACTIVE('cache')) {
1383                 // Load from database
1384                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1385                 array($login), __FUNCTION__, __LINE__);
1386                 if (SQL_NUMROWS($result) == 1) {
1387                         list($ret) = SQL_FETCHROW($result);
1388                 } // END - if
1389
1390                 // Free result
1391                 SQL_FREERESULT($result);
1392         }
1393         return $ret;
1394 }
1395
1396 // "Getter" for current admin id
1397 function getCurrentAdminId () {
1398         // Get the admin login from session
1399         $adminLogin = getSession('admin_login');
1400
1401         // "Solve" it into an id
1402         $adminId = GET_ADMIN_ID($adminLogin);
1403
1404         // Secure and return it
1405         return bigintval($adminId);
1406 }
1407
1408 // Get password hash from administrator's login name
1409 function GET_ADMIN_HASH ($aid) {
1410         // By default an invalid hash is returned
1411         $ret = '-1';
1412
1413         if (isset($GLOBALS['cache_array']['admins']['password'][$aid])) {
1414                 // Check cache
1415                 $ret = $GLOBALS['cache_array']['admins']['password'][$aid];
1416
1417                 // Update cache hits
1418                 incrementConfigEntry('cache_hits');
1419         } elseif (!EXT_IS_ACTIVE('cache')) {
1420                 // Load from database
1421                 $result = SQL_QUERY_ESC("SELECT password FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1422                 array($aid), __FUNCTION__, __LINE__);
1423                 if (SQL_NUMROWS($result) == 1) {
1424                         // Fetch data
1425                         list($ret) = SQL_FETCHROW($result);
1426
1427                         // Set cache
1428                         $GLOBALS['cache_array']['admins']['password'][$aid] = $ret;
1429                 } // END - if
1430
1431                 // Free result
1432                 SQL_FREERESULT($result);
1433         }
1434         return $ret;
1435 }
1436
1437 // "Getter" for admin login
1438 function getAdminLogin ($aid) {
1439         // By default a non-existent login is returned (other functions react on this!)
1440         $ret = '***';
1441
1442         if (isset($GLOBALS['cache_array']['admins']['login'][$aid])) {
1443                 // Get cache
1444                 $ret = $GLOBALS['cache_array']['admins']['login'][$aid];
1445
1446                 // Update cache hits
1447                 incrementConfigEntry('cache_hits');
1448         } elseif (!EXT_IS_ACTIVE('cache')) {
1449                 // Load from database
1450                 $result = SQL_QUERY_ESC("SELECT login FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1451                 array(bigintval($aid)), __FUNCTION__, __LINE__);
1452                 if (SQL_NUMROWS($result) == 1) {
1453                         // Fetch data
1454                         list($ret) = SQL_FETCHROW($result);
1455
1456                         // Set cache
1457                         $GLOBALS['cache_array']['admins']['login'][$aid] = $ret;
1458                 } // END - if
1459
1460                 // Free memory
1461                 SQL_FREERESULT($result);
1462         }
1463         return $ret;
1464 }
1465
1466 // Get email address of admin id
1467 function getAdminEmail ($aid) {
1468         // By default an invalid emails is returned
1469         $ret = '***';
1470
1471         if (isset($GLOBALS['cache_array']['admins']['email'][$aid])) {
1472                 // Get cache
1473                 $ret = $GLOBALS['cache_array']['admins']['email'][$aid];
1474
1475                 // Update cache hits
1476                 incrementConfigEntry('cache_hits');
1477         } elseif (!EXT_IS_ACTIVE('cache')) {
1478                 // Load from database
1479                 $result_aid = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1480                 array(bigintval($aid)), __FUNCTION__, __LINE__);
1481                 if (SQL_NUMROWS($result_aid) == 1) {
1482                         // Get data
1483                         list($ret) = SQL_FETCHROW($result_aid);
1484
1485                         // Set cache
1486                         $GLOBALS['cache_array']['admins']['email'][$aid] = $ret;
1487                 } // END - if
1488
1489                 // Free result
1490                 SQL_FREERESULT($result_aid);
1491         }
1492
1493         // Return email
1494         return $ret;
1495 }
1496
1497 // Get default ACL  of admin id
1498 function getAdminDefaultAcl ($aid) {
1499         // By default an invalid ACL value is returned
1500         $ret = '***';
1501
1502         // Is sql_patches there and was it found in cache?
1503         if (!EXT_IS_ACTIVE('sql_patches')) {
1504                 // Not found, which is bad, so we need to allow all
1505                 $ret =  'allow';
1506         } elseif (isset($GLOBALS['cache_array']['admins']['def_acl'][$aid])) {
1507                 // Use cache
1508                 $ret = $GLOBALS['cache_array']['admins']['def_acl'][$aid];
1509
1510                 // Update cache hits
1511                 incrementConfigEntry('cache_hits');
1512         } elseif (!EXT_IS_ACTIVE('cache')) {
1513                 // Load from database
1514                 $result_aid = SQL_QUERY_ESC("SELECT default_acl FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
1515                 array(bigintval($aid)), __FUNCTION__, __LINE__);
1516                 if (SQL_NUMROWS($result_aid) == 1) {
1517                         // Fetch data
1518                         list($ret) = SQL_FETCHROW($result_aid);
1519
1520                         // Set cache
1521                         $GLOBALS['cache_array']['admins']['def_acl'][$aid] = $ret;
1522                 }
1523
1524                 // Free result
1525                 SQL_FREERESULT($result_aid);
1526         }
1527
1528         // Return email
1529         return $ret;
1530 }
1531
1532 // Generates an option list from various parameters
1533 function generateOptionList ($table, $id, $name, $default='', $special='', $where='') {
1534         $ret = '';
1535         if ($table == '/ARRAY/') {
1536                 // Selection from array
1537                 if (is_array($id) && is_array($name) && count($id) == count($name)) {
1538                         // Both are arrays
1539                         foreach ($id as $idx => $value) {
1540                                 $ret .= '<option value="' . $value . '"';
1541                                 if ($default == $value) $ret .= ' selected="selected"';
1542                                 $ret .= '>' . $name[$idx] . '</option>';
1543                         } // END - foreach
1544                 } // END - if
1545         } else {
1546                 // Data from database
1547                 $SPEC = ', '.$id;
1548                 if (!empty($special)) $SPEC = ', ' . $special;
1549                 $ORDER = $name.$SPEC;
1550                 if ($table == 'country') $ORDER = $special;
1551                 $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM `{!_MYSQL_PREFIX!}_%s` ".$where." ORDER BY %s",
1552                 array($id, $ORDER, $table, $name), __FUNCTION__, __LINE__);
1553                 if (SQL_NUMROWS($result) > 0) {
1554                         // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1555                         // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1556                         while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1557                                 if (empty($special)) $add = '';
1558                                 $ret .= '<option value="' . $value . '"';
1559                                 if ($default == $value) $ret .= ' selected="selected"';
1560                                 if (!empty($add)) $add = ' ('.$add.')';
1561                                 $ret .= '>' . $title . $add . '</option>';
1562                         } // END - while
1563
1564                         // Free memory
1565                         SQL_FREERESULT($result);
1566                 } else {
1567                         // No data found
1568                         $ret = '<option value="x">{--SELECT_NONE--}</option>';
1569                 }
1570         }
1571
1572         // Return - hopefully - the requested data
1573         return $ret;
1574 }
1575 // Activate exchange
1576 function activateExchange () {
1577         // Is the extension 'user' there?
1578         if (!EXT_IS_ACTIVE('user')) {
1579                 // Silently abort here
1580                 return false;
1581         } // END - if
1582
1583         // Check total amount of users
1584         $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1585
1586         if ($totalUsers >= getConfig('activate_xchange')) {
1587                 // Activate System
1588                 SET_SQLS(array(
1589                         "UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1590                         "UPDATE `{!_MYSQL_PREFIX!}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1591                         "UPDATE `{!_MYSQL_PREFIX!}_config` SET `activate_xchange`=0 WHERE `config`=0 LIMIT 1"
1592                         ));
1593
1594                         // Run SQLs
1595                         runFilterChain('run_sqls');
1596
1597                         // Rebuild caches
1598                         // @TODO Rewrite this to a filter
1599                         rebuildCacheFiles('config', 'config');
1600                         rebuildCacheFiles('modreg', 'modreg');
1601         } // END - if
1602 }
1603
1604 // Deletes a user account with given reason
1605 function deleteUserAccount ($uid, $reason) {
1606         $points = 0;
1607         $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points
1608 FROM `{!_MYSQL_PREFIX!}_user_points` AS p
1609 LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
1610 ON p.userid=d.userid
1611 WHERE p.userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
1612         if (SQL_NUMROWS($result) == 1) {
1613                 // Save his points to add them to the jackpot
1614                 list($points) = SQL_FETCHROW($result);
1615
1616                 // Delete points entries as well
1617                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_points` WHERE userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
1618
1619                 // Update mediadata as well
1620                 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1621                         // Update database
1622                         MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
1623                 } // END - if
1624
1625                 // Now, when we have all his points adds them do the jackpot!
1626                 ADD_JACKPOT($points);
1627         } // END - if
1628
1629         // Free the result
1630         SQL_FREERESULT($result);
1631
1632         // Delete category selections as well...
1633         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE userid=%s",
1634         array(bigintval($uid)), __FUNCTION__, __LINE__);
1635
1636         // Remove from rallye if found
1637         if (EXT_IS_ACTIVE('rallye')) {
1638                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_rallye_users` WHERE userid=%s",
1639                 array(bigintval($uid)), __FUNCTION__, __LINE__);
1640         } // END - if
1641
1642         // Now a mail to the user and that's all...
1643         $msg = LOAD_EMAIL_TEMPLATE('del-user', array('text' => $reason), $uid);
1644         sendEmail($uid, getMessage('ADMIN_DEL_ACCOUNT'), $msg);
1645
1646         // Ok, delete the account!
1647         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($uid)), __FUNCTION__, __LINE__);
1648 }
1649
1650 // Generates meta description for given module and 'what' value
1651 function generateMetaDescriptionCode ($mod, $wht) {
1652         // Exclude admin and member's area
1653         if (($mod != 'admin') && ($mod != 'login')) {
1654                 // Construct dynamic description
1655                 $DESCR = '{!MAIN_TITLE!} '.trim(getConfig('title_middle')) . ' ' . ADD_DESCR('guest', 'what-'.$wht, true);
1656
1657                 // Output it directly
1658                 OUTPUT_HTML('<meta name="description" content="' . $DESCR . '" />');
1659         } // END - if
1660
1661         // Remove depth
1662         unset($GLOBALS['ref_level']);
1663 }
1664
1665 // Adds points to the jackpot
1666 function ADD_JACKPOT ($points) {
1667         $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
1668         if (SQL_NUMROWS($result) == 0) {
1669                 // Create line
1670                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok','%s')", array($points), __FUNCTION__, __LINE__);
1671         } else {
1672                 // Free memory
1673                 SQL_FREERESULT($result);
1674
1675                 // Update points
1676                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points+%s WHERE ok='ok' LIMIT 1",
1677                 array($points), __FUNCTION__, __LINE__);
1678         }
1679 }
1680
1681 // Subtracts points from the jackpot
1682 function SUB_JACKPOT ($points) {
1683         // First failed
1684         $ret = '-1';
1685
1686         // Get current points
1687         $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
1688         if (SQL_NUMROWS($result) == 0) {
1689                 // Create line
1690                 SQL_QUERY("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok', 0.00000)", __FUNCTION__, __LINE__);
1691         } else {
1692                 // Read points
1693                 list($jackpot) = SQL_FETCHROW($result);
1694                 if ($jackpot >= $points) {
1695                         // Update points when there are enougth points in jackpot
1696                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points-%s WHERE ok='ok' LIMIT 1",
1697                         array($points), __FUNCTION__, __LINE__);
1698                         $ret = $jackpot - $points;
1699                 } // END - if
1700         }
1701
1702         // Free memory
1703         SQL_FREERESULT($result);
1704 }
1705
1706 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
1707 function IS_DEMO () {
1708         return ((EXT_IS_ACTIVE('demo')) && (getSession('admin_login') == 'demo'));
1709 }
1710
1711 // Gets the matching what name from module
1712 function getWhatFromModule ($modCheck) {
1713         // Is the request element set?
1714         if (REQUEST_ISSET_GET('what')) {
1715                 // Then return this!
1716                 return REQUEST_GET('what');
1717         } // END - if
1718
1719         $wht = '';
1720         //* DEBUG: */ echo __LINE__.'!'.$modCheck."!<br />\n";
1721         switch ($modCheck)
1722         {
1723                 case 'admin':
1724                         $wht = 'overview';
1725                         break;
1726
1727                 case 'login':
1728                 case 'index':
1729                         $wht = 'welcome';
1730                         if (($modCheck == 'index') && (getConfig('index_home') != '')) $wht = getConfig('index_home');
1731                         break;
1732
1733                 default:
1734                         $wht = '';
1735                         break;
1736         }
1737
1738         // Return what value
1739         return $wht;
1740 }
1741
1742 // Subtract points from database and mediadata cache
1743 function SUB_POINTS ($subject, $uid, $points) {
1744         // Add points to used points
1745         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `used_points`=`used_points`+%s WHERE userid=%s LIMIT 1",
1746         array($points, bigintval($uid)), __FUNCTION__, __LINE__);
1747
1748         // Insert booking record
1749         if (EXT_IS_ACTIVE('booking')) {
1750                 // Add record
1751                 ADD_BOOKING_RECORD($subject, $uid, $points, 'sub');
1752         } // END - if
1753
1754         // Update mediadata as well
1755         if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
1756                 // Update database
1757                 MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
1758         } // END - if
1759 }
1760
1761 // Update config entries
1762 function updateConfiguration ($entries, $values, $updateMode='') {
1763         // Do not update config in CSS mode
1764         if (($GLOBALS['output_mode'] == '1') || ($GLOBALS['output_mode'] == -1)) {
1765                 return;
1766         } // END - if
1767
1768         // Do we have multiple entries?
1769         if (is_array($entries)) {
1770                 // Walk through all
1771                 $all = '';
1772                 foreach ($entries as $idx => $entry) {
1773                         // Update mode set?
1774                         if (!empty($updateMode)) {
1775                                 // Update entry
1776                                 // @TODO Find a way for updating $_CONFIG here
1777                                 $all .= sprintf("%s=%s%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
1778                         } else {
1779                                 // Check if string or number
1780                                 if (($values[$idx] + 0) === $values[$idx]) {
1781                                         // Number detected
1782                                         $all .= sprintf("%s=%s,", $entry, (float)$values[$idx]);
1783                                 } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
1784                                         // Function UNIX_TIMESTAMP() detected
1785                                         $all .= sprintf("%s=%s,", $entry, $values[$idx]);
1786                                 } else {
1787                                         // String detected
1788                                         $all .= sprintf("%s='%s',", $entry, SQL_ESCAPE($values[$idx]));
1789                                 }
1790                         }
1791
1792                         // Set it in config as well
1793                         setConfigEntry($entry, $values[$idx]);
1794                 } // END - foreach
1795
1796                 // Remove last comma
1797                 $entries = substr($all, 0, -1);
1798         } elseif (!empty($updateMode)) {
1799                 // Update mode set
1800                 // @TODO Find a way for updating $_CONFIG here
1801                 $entries .= sprintf("=%s%s%s", $entries, $updateMode, (float)$values);
1802         } else {
1803                 // Set it in config first
1804                 setConfigEntry($entries, $values);
1805
1806                 // Regular entry to update
1807                 $entries .= sprintf("='%s'", SQL_ESCAPE($values));
1808         }
1809
1810         // Run database update
1811         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "entries={$entries}");
1812         SQL_QUERY("UPDATE `{!_MYSQL_PREFIX!}_config` SET ".$entries." WHERE config=0 LIMIT 1", __FUNCTION__, __LINE__);
1813
1814         // Get affected rows
1815         $affectedRows = SQL_AFFECTEDROWS();
1816         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):entries={$entries},affectedRows={$affectedRows}<br />\n";
1817
1818         // Rebuild cache
1819         rebuildCacheFiles('config', 'config');
1820 }
1821
1822 // Prepares an SQL statement part for HTML mail and/or holiday depency
1823 // @TODO Can this be rewritten to a filter?
1824 function PREPARE_SQL_HTML_HOLIDAY ($mode) {
1825         // Exclude no users by default
1826         $MORE = '';
1827
1828         // HTML mail?
1829         if ($mode == 'html') $MORE = " AND `html`='Y'";
1830         if (GET_EXT_VERSION('holiday') >= '0.1.3') {
1831                 // Add something for the holiday extension
1832                 $MORE .= " AND `holiday_active`='N'";
1833         } // END - if
1834
1835         // Return result
1836         return $MORE;
1837 }
1838
1839 // "Getter" for total available receivers
1840 function getTotalReceivers ($mode='normal') {
1841         // Query database
1842         $result_all = SQL_QUERY("SELECT userid
1843 FROM `{!_MYSQL_PREFIX!}_user_data`
1844 WHERE `status`='CONFIRMED' AND receive_mails > 0 ".PREPARE_SQL_HTML_HOLIDAY($mode),
1845         __FUNCTION__, __LINE__);
1846
1847         // Get num rows
1848         $numRows = SQL_NUMROWS($result_all);
1849
1850         // Free result
1851         SQL_FREERESULT($result_all);
1852
1853         // Return value
1854         return $numRows;
1855 }
1856
1857 // Returns HTML code with an "<option> list" of all categories
1858 function generateCategoryOptionsList ($mode) {
1859         // Prepare WHERE statement
1860         $whereStatement = " WHERE `visible`='Y'";
1861         if (IS_ADMIN()) $whereStatement = '';
1862
1863         // Initialize array...
1864         $CATS = array(
1865                 'id'   => array(),
1866                 'name' => array(),
1867                 'uids' => array()
1868         );
1869
1870         // Get categories
1871         $result = SQL_QUERY("SELECT id, cat FROM `{!_MYSQL_PREFIX!}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__);
1872         if (SQL_NUMROWS($result) > 0) {
1873                 // ... and begin loading stuff
1874                 while ($content = SQL_FETCHARRAY($result)) {
1875                         // Transfer some data
1876                         $CATS['id'][]   = $content['id'];
1877                         $CATS['name'][] = $content['cat'];
1878
1879                         // Check which users are in this category
1880                         $result_uids = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE cat_id=%s",
1881                         array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1882
1883                         // Start adding all
1884                         $uid_cnt = 0;
1885                         // @TODO Rewrite this to $content = SQL_FETCHARRAY()
1886                         while (list($ucat) = SQL_FETCHROW($result_uids)) {
1887                                 $result_ver = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data`
1888 WHERE userid=%s AND `status`='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML_HOLIDAY($mode)." LIMIT 1",
1889                                 array(bigintval($ucat)), __FUNCTION__, __LINE__);
1890
1891                                 // Add user count
1892                                 $uid_cnt += SQL_NUMROWS($result_ver);
1893
1894                                 // Free memory
1895                                 SQL_FREERESULT($result_ver);
1896                         } // END - while
1897
1898                         // Free memory
1899                         SQL_FREERESULT($result_uids);
1900
1901                         // Add counter
1902                         $CATS['uids'][] = $uid_cnt;
1903                 } // END - while
1904
1905                 // Free memory
1906                 SQL_FREERESULT($result);
1907
1908                 // Generate options
1909                 $OUT = '';
1910                 foreach ($CATS['id'] as $key => $value) {
1911                         if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1912                         $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['uids'][$key] . ' {--USER_IN_CAT--})</option>';
1913                 } // END - foreach
1914         } else {
1915                 // No cateogries are defined yet
1916                 $OUT = '<option class="member_failed">{!MEMBER_NO_CATS!}</option>';
1917         }
1918
1919         // Return HTML code
1920         return $OUT;
1921 }
1922
1923 // Add bonus mail to queue
1924 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1925         // Is admin or bonus extension there?
1926         if (!IS_ADMIN()) {
1927                 // Abort here
1928                 return false;
1929         } elseif (!EXT_IS_ACTIVE('bonus')) {
1930                 // Abort here
1931                 return false;
1932         }
1933
1934         // Calculcate target sent
1935         $target = countSelection(explode(';', $receiverList));
1936
1937         // Receiver is zero?
1938         if ($receiver == 0) {
1939                 // Then auto-fix it
1940                 $receiver = $target;
1941         } // END - if
1942
1943         // HTML extension active?
1944         if (EXT_IS_ACTIVE('html_mail')) {
1945                 // No HTML by default
1946                 $HTML = 'N';
1947
1948                 // HTML mode?
1949                 if ($mode == 'html') $HTML = 'Y';
1950
1951                 // Add HTML mail
1952                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
1953 (subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent, html_msg)
1954 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1955                 array(
1956                 $subject,
1957                 $text,
1958                 $receiverList,
1959                 $points,
1960                 $seconds,
1961                 $url,
1962                 $cat,
1963                 $target,
1964                 bigintval($receiver),
1965                 $HTML
1966                 ), __FUNCTION__, __LINE__);
1967         } else {
1968                 // Add regular mail
1969                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
1970 (subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent)
1971 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1972                 array(
1973                 $subject,
1974                 $text,
1975                 $receiverList,
1976                 $points,
1977                 $seconds,
1978                 $url,
1979                 $cat,
1980                 $target,
1981                 bigintval($receiver),
1982                 ), __FUNCTION__, __LINE__);
1983         }
1984 }
1985
1986 // Generate a receiver list for given category and maximum receivers
1987 function generateReceiverList ($cat, $receiver, $mode = '') {
1988         // Init variables
1989         $CAT_TABS     = "%s";
1990         $CAT_WHERE    = '';
1991         $receiverList = '';
1992         $result       = false;
1993
1994         // Secure data
1995         $cat      = bigintval($cat);
1996         $receiver = bigintval($receiver);
1997
1998         // Is the receiver zero and mode set?
1999         if (($receiver == 0) && (!empty($mode))) {
2000                 // Auto-fix receiver maximum
2001                 $receiver = getTotalReceivers($mode);
2002         } // END - if
2003
2004         // Category given?
2005         if ($cat > 0) {
2006                 // Select category
2007                 $CAT_TABS  = "LEFT JOIN `{!_MYSQL_PREFIX!}_user_cats` AS c ON d.userid=c.userid";
2008                 $CAT_WHERE = " AND c.cat_id=%s";
2009         } // END - if
2010
2011         // Exclude users in holiday?
2012         if (GET_EXT_VERSION('holiday') >= '0.1.3') {
2013                 // Add something for the holiday extension
2014                 $CAT_WHERE .= " AND d.`holiday_active`='N'";
2015         } // END - if
2016
2017         if ((EXT_IS_ACTIVE('html_mail')) && ($mode == 'html')) {
2018                 // Only include HTML receivers
2019                 $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",
2020                 array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
2021         } else {
2022                 // Include all
2023                 $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",
2024                 array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
2025         }
2026
2027         // Entries found?
2028         if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
2029                 // Load all entries
2030                 while ($content = SQL_FETCHARRAY($result)) {
2031                         // Add receiver when not empty
2032                         if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
2033                 } // END - while
2034
2035                 // Free memory
2036                 SQL_FREERESULT($result);
2037
2038                 // Remove trailing semicolon
2039                 $receiverList = substr($receiverList, 0, -1);
2040         } // END - if
2041
2042         // Return list
2043         return $receiverList;
2044 }
2045
2046 // Get timestamp for given stats type and data
2047 function getTimestampFromUserStats ($type, $data, $uid = 0) {
2048         // Default timestamp is zero
2049         $stamp = 0;
2050
2051         // User id set?
2052         if ((isUserIdSet()) && ($uid == 0)) {
2053                 $uid = getUserId();
2054         } // END - if
2055
2056         // Is the extension installed and updated?
2057         if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
2058                 // Return zero here
2059                 return $stamp;
2060         } // END - if
2061
2062         // Try to find the entry
2063         $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`inserted`) AS `stamp`
2064 FROM `{!_MYSQL_PREFIX!}_user_stats_data`
2065 WHERE userid=%s AND stats_type='%s' AND stats_data='%s'
2066 LIMIT 1",
2067         array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
2068
2069         // Is the entry there?
2070         if (SQL_NUMROWS($result) == 1) {
2071                 // Get this stamp
2072                 list($stamp) = SQL_FETCHROW($result);
2073         } // END - if
2074
2075         // Free result
2076         SQL_FREERESULT($result);
2077
2078         // Return stamp
2079         return $stamp;
2080 }
2081
2082 // Inserts user stats
2083 function insertUserStatsRecord ($uid, $type, $data) {
2084         // Is the extension installed and updated?
2085         if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
2086                 // Return zero here
2087                 return false;
2088         } // END - if
2089
2090         // Does it exist?
2091         if ((!getTimestampFromUserStats($type, $data, $uid)) && (!is_array($data))) {
2092                 // Then insert it!
2093                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
2094                 array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
2095         } elseif (is_array($data)) {
2096                 // Invalid data!
2097                 DEBUG_LOG(__FUNCTION__, __LINE__, " uid={$uid},type={$type},data={".gettype($data).": Invalid statistics data type!");
2098         }
2099 }
2100
2101 // "Getter" for array for user refs and points in given level
2102 function getUserReferalPoints ($uid, $level) {
2103         //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
2104         // Default is no refs and no nickname
2105         $add = '';
2106         $refs = array();
2107
2108         // Do we have nickname extension installed?
2109         if (EXT_IS_ACTIVE('nickname')) {
2110                 $add = ', ud.nickname';
2111         } // END - if
2112
2113         // Get refs from database
2114         $result = SQL_QUERY_ESC("SELECT ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2115 FROM `{!_MYSQL_PREFIX!}_user_refs` AS ur
2116 LEFT JOIN `{!_MYSQL_PREFIX!}_user_points` AS up
2117 ON ur.refid=up.userid AND ur.level=0
2118 LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS ud
2119 ON ur.refid=ud.userid
2120 WHERE ur.userid=%s AND ur.level=%s
2121 ORDER BY ur.refid ASC",
2122         array(bigintval($uid), bigintval($level)), __FUNCTION__, __LINE__);
2123
2124         // Are there some entries?
2125         if (SQL_NUMROWS($result) > 0) {
2126                 // Fetch all entries
2127                 while ($row = SQL_FETCHARRAY($result)) {
2128                         // Get total points of this user
2129                         $row['points'] = GET_TOTAL_DATA($row['refid'], 'user_points', 'points') - GET_TOTAL_DATA($row['refid'], 'user_data', 'used_points');
2130
2131                         // Get unconfirmed mails
2132                         $row['unconfirmed']  = GET_TOTAL_DATA($row['refid'], 'user_links', 'id', 'userid', true);
2133
2134                         // Init clickrate with zero
2135                         $row['clickrate'] = 0;
2136
2137                         // Is at least one mail received?
2138                         if ($row['emails_received'] > 0) {
2139                                 // Calculate clickrate
2140                                 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2141                         } // END - if
2142
2143                         // Activity is 'active' by default because if autopurge is not installed
2144                         $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2145
2146                         // Is autopurge installed and the user inactive?
2147                         if ((EXT_IS_ACTIVE('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online']))  {
2148                                 // Inactive user!
2149                                 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2150                         } // END - if
2151
2152                         // Remove some entries
2153                         unset($row['mails_confirmed']);
2154                         unset($row['emails_received']);
2155                         unset($row['last_online']);
2156
2157                         // Add row
2158                         $refs[$row['id']] = $row;
2159                 } // END - while
2160         } // END - if
2161
2162         // Free result
2163         SQL_FREERESULT($result);
2164
2165         // Return result
2166         //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
2167         return $refs;
2168 }
2169
2170 // Recuce the amount of received emails for the receipients for given email
2171 function reduceRecipientReceivedMails ($column, $id, $count) {
2172         // Search for mail in database
2173         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{!_MYSQL_PREFIX!}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2174         array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2175
2176         // Are there entries?
2177         if (SQL_NUMROWS($result) > 0) {
2178                 // Now load all userids for one big query!
2179                 // @TODO This can be somehow rewritten
2180                 $UIDs = array();
2181                 while (list($uid) = SQL_FETCHROW($result)) {
2182                         $UIDs[$uid] = $uid;
2183                 } // END - while
2184
2185                 // Now update all user accounts
2186                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2187                 array(implode(',', $UIDs), count($UIDs)), __FUNCTION__, __LINE__);
2188         } // END - if
2189
2190         // Free result
2191         SQL_FREERESULT($result);
2192 }
2193
2194 // Init SQLs array
2195 function INIT_SQLS () {
2196         SET_SQLS(array());
2197 }
2198
2199 // Checks wether the sqls array is initialized
2200 function IS_SQLS_INITIALIZED () {
2201         return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
2202 }
2203
2204 // Setter for SQLs array
2205 function SET_SQLS ($SQLs) {
2206         $GLOBALS['sqls'] = (array) $SQLs;
2207 }
2208
2209 // Remover for SQLs array
2210 function UNSET_SQLS () {
2211         unset($GLOBALS['sqls']);
2212 }
2213
2214 // Getter for SQLs array
2215 function GET_SQLS () {
2216         return $GLOBALS['sqls'];
2217 }
2218
2219 // Add an SQL to the list
2220 function ADD_SQL ($sql) {
2221         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("sql=%s, count=%d", $sql, COUNT_SQLS()));
2222         $GLOBALS['sqls'][] = (string) $sql;
2223 }
2224
2225 // Setter for SQLs key
2226 function SET_SQL_KEY ($key, $value) {
2227         $GLOBALS['sqls'][$key] = (string) $value;
2228 }
2229
2230 // Merge SQLs together
2231 function MERGE_SQLS ($SQLs) {
2232         SET_SQLS(merge_array(GET_SQLS(), $SQLs));
2233 }
2234
2235 // Counter for SQLs array
2236 function COUNT_SQLS () {
2237         // Default is false
2238         $count = false;
2239
2240         // Is the array there?
2241         if (IS_SQLS_INITIALIZED()) {
2242                 // Then count it
2243                 $count = count($GLOBALS['sqls']);
2244                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
2245         } // END - if
2246
2247         // Return it
2248         return $count;
2249 }
2250
2251 // Checks wether the SQLs array is filled
2252 function IS_SQLS_VALID () {
2253         return (
2254         (IS_SQLS_INITIALIZED()) &&
2255         (COUNT_SQLS() > 0)
2256         );
2257 }
2258
2259 // [EOF]
2260 ?>