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