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