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