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