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