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