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