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