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