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