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