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