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