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