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