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