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