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