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