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