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