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