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