2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/26/2003 *
4 * =================== Last change: 11/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : mysql-manager.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All MySQL-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle MySQL-Relevanten Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // "Getter" for module title
46 function getModuleTitle ($module) {
51 // Is the script installed?
53 // Check if cache is valid
54 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($module, $GLOBALS['cache_array']['modules']['module']))) {
56 $data['title'] = $GLOBALS['cache_array']['modules']['title'][$module];
59 incrementStatsEntry('cache_hits');
60 } elseif (!isExtensionActive('cache')) {
62 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
63 array($module), __FUNCTION__, __LINE__);
65 // Is the entry there?
66 if (SQL_NUMROWS($result)) {
67 // Get the title from database
68 $data = SQL_FETCHARRAY($result);
72 SQL_FREERESULT($result);
77 $data['title'] = trim($data['title']);
79 // Still no luck or empty title?
80 if (empty($data['title'])) {
82 $data['title'] = getMaskedMessage('UNKNOWN_MODULE_DETECTED', $module);
83 if ((is_resource($result)) && (SQL_HASZERONUMS($result))) {
84 // Add module to database
85 $dummy = checkModulePermissions($module);
90 return $data['title'];
93 // "Getter" for module description
94 // @TODO Can we cache this?
95 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
98 $what = getConfig('index_home');
101 // Default is not found
102 $data['title'] = '??? (' . $what . ')';
105 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
110 ), __FUNCTION__, __LINE__);
112 // Is there an entry?
113 if (SQL_NUMROWS($result) == 1) {
115 $data = SQL_FETCHARRAY($result);
119 SQL_FREERESULT($result);
122 return $data['title'];
125 // Check validity of a given module name (no file extension)
126 function checkModulePermissions ($module = '') {
127 // Is it empty (default), then take the current one
128 if (empty($module)) $module = getModule();
131 if (isset($GLOBALS['module_status'][$module])) {
133 return $GLOBALS['module_status'][$module];
136 // Filter module name (names with low chars and underlines are fine!)
137 $module = preg_replace('/[^a-z_]/', '', $module);
139 // Check for prefix is a extension...
140 $modSplit = explode('_', $module);
141 $extension = ''; $module_chk = $module;
142 //* DEBUG: */ debugOutput(__LINE__.'*'.count($modSplit).'/'.$module.'*');
143 if (count($modSplit) == 2) {
144 // Okay, there is a seperator (_) in the name so is the first part a module?
145 //* DEBUG: */ debugOutput(__LINE__.'*'.$modSplit[0].'*');
146 if (isExtensionActive($modSplit[0])) {
147 // The prefix is an extension's name, so let's set it
148 $extension = $modSplit[0]; $module = $modSplit[1];
152 // Major error in module registry is the default
155 // Check if script is installed if not return a 'done' to prevent some errors
156 if ((isInstallationPhase()) || (!isAdminRegistered())) {
157 // Not installed or no admin registered or in installation phase
169 // By default nothing is found
172 // Check if cache is latest version
173 if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
174 // Is the cache there?
175 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using cache.');
176 if (isset($GLOBALS['cache_array']['modules']['locked'][$module_chk])) {
178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache found.');
179 $data['locked'] = $GLOBALS['cache_array']['modules']['locked'][$module_chk];
180 $data['hidden'] = $GLOBALS['cache_array']['modules']['hidden'][$module_chk];
181 $data['admin_only'] = $GLOBALS['cache_array']['modules']['admin_only'][$module_chk];
182 $data['mem_only'] = $GLOBALS['cache_array']['modules']['mem_only'][$module_chk];
185 incrementStatsEntry('cache_hits');
188 // No, then we have to update it!
191 } elseif (!isExtensionActive('cache')) {
192 // Check for module in database
193 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using database.');
194 $result = SQL_QUERY_ESC("SELECT `locked`, `hidden`, `admin_only`, `mem_only` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
195 array($module_chk), __FUNCTION__, __LINE__);
196 if (SQL_NUMROWS($result) == 1) {
198 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Entry found.');
199 $data = SQL_FETCHARRAY($result);
201 } elseif (isDebugModeEnabled()) {
202 // Debug message only in debug-mode...
203 logDebugMessage(__FUNCTION__, __LINE__, 'Module ' . $module_chk . ' not found!');
207 SQL_FREERESULT($result);
209 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
211 // Is the module found?
212 if ($found === true) {
213 // Check returned values against current access permissions
215 // Admin access ----- Guest access ----- --- Guest or member? ---
216 if ((isAdmin()) || (($data['locked'] != 'Y') && ($data['admin_only'] != 'Y') && (($data['mem_only'] != 'Y') || (isMember())))) {
217 // If you are admin you are welcome for everything!
219 } elseif ($data['locked'] == 'Y') {
222 } elseif (($data['mem_only'] == 'Y') && (!isMember())) {
223 // You have to login first!
225 } elseif (($data['admin_only'] == 'Y') && (!isAdmin())) {
226 // Only the Admin is allowed to enter this module!
229 // @TODO Nothing helped???
230 logDebugMessage(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
239 // Still no luck or not found?
240 if (($found === false) && (!isExtensionActive('cache')) && ($ret != 'done')) {
241 // ----- Legacy module ----- ---- Module in base folder ---- --- Module with extension's name ---
242 if ((isIncludeReadable(sprintf("inc/modules/%s.php", $module))) || (isIncludeReadable(sprintf("%s.php", $module))) || (isIncludeReadable(sprintf("%s/%s.php", $extension, $module)))) {
243 // Data is missing so we add it
244 if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
245 // Since 0.3.6 we have a has_menu column, this took me a half hour
246 // to find a loop here... *sigh*
247 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
248 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
249 ('%s','Y','N','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
251 // Wrong/missing sql_patches!
252 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_mod_reg`
253 (`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
254 ('%s','Y','N','N','N')", array($module_chk), __FUNCTION__, __LINE__);
257 // Everthing is fine?
258 if (SQL_AFFECTEDROWS() < 1) {
259 // Something bad happend!
263 // Destroy cache here
264 // @TODO Rewrite this to a filter
265 if ((getOutputMode() == '0') || (getOutputMode() == -1)) rebuildCache('modules', 'modules');
268 unset($GLOBALS['module_status'][$module]);
269 $ret = checkModulePermissions($module_chk);
271 // Module not found we don't add it to the database
274 } elseif (($ret == 'cache_miss') && (getOutputMode() == '0')) {
275 // Rebuild the cache files
276 rebuildCache('modules', 'modules');
277 } elseif ($found === false) {
278 // Problem with module detected
279 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s",
291 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret);
292 $GLOBALS['module_status'][$module] = $ret;
296 // Add menu description pending on given file name (without path!)
297 function addMenuDescription ($accessLevel, $FQFN, $return = false) {
298 // Use only filename of the FQFN...
299 $file = basename($FQFN);
307 // First we have to do some analysis...
308 if (substr($file, 0, 7) == 'action-') {
309 // This is an action file!
311 $search = substr($file, 7);
313 // Get access level from it
314 $modCheck = getModuleFromFileName($file, $accessLevel);
317 $ADD = " AND (`what`='' OR `what` IS NULL)";
318 } elseif (substr($file, 0, 5) == 'what-') {
319 // This is a 'what file'!
321 $search = substr($file, 5);
322 $ADD = " AND `visible`='Y' AND `locked`='N'";
324 // Get access level from it
325 $modCheck = getModuleFromFileName($file, $accessLevel);
327 // Do we have admin? Then display all
328 if (isAdmin()) $ADD = '';
330 $dummy = substr($search, 0, -4);
331 $ADD .= " AND `action`='".getActionFromModuleWhat($accessLevel, $dummy)."'";
332 } elseif (($accessLevel == 'sponsor') || ($accessLevel == 'engine')) {
333 // Sponsor / engine menu
336 $modCheck = getModule();
342 $modCheck = getModule();
346 // Begin the navigation line
347 if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) {
349 $GLOBALS['nav_depth'] = '0';
351 // Run the pre-filter chain
352 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
355 $prefix = $ret['content'];
357 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $LINK_ADD . '%}">Home</a></strong>';
358 } elseif ($return === false) {
360 $GLOBALS['nav_depth']++;
363 $prefix .= ' -> ';
365 // We need to remove .php and the end
366 if (substr($search, -4, 4) == '.php') {
368 $search = substr($search, 0, -4);
371 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
373 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $LINK_ADD . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
375 // Can we close the you-are-here navigation?
376 //* DEBUG: */ debugOutput(__LINE__.'*'.$type.'/'.getWhat().'*');
377 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
378 //* DEBUG: */ debugOutput(__LINE__.'+'.$type.'+');
379 // Add closing div and br-tag
381 $GLOBALS['nav_depth'] = '0';
383 // Run the post-filter chain
384 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ''));
386 // Add additional content
387 $OUT .= $ret['content'];
391 // Return or output HTML code?
392 if ($return === true) {
396 // Output HTML code here
401 // Adds a menu (mode = guest/member/admin/sponsor) to output
402 function addMenu ($mode, $action, $what) {
403 // Init some variables
407 // is the menu action valid?
408 if (!isMenuActionValid($mode, $action, $what, true)) {
409 return getCode('MENU_NOT_VALID');
412 // Non-admin shall not see all menus
414 $ADD = " AND `visible`='Y' AND `locked`='N'";
417 // Load SQL data and add the menu to the output stream...
418 $result_main = SQL_QUERY_ESC("SELECT
419 `title`, `what`, `action`, `visible`, `locked`
421 `{?_MYSQL_PREFIX?}_%s_menu`
423 (`what`='' OR `what` IS NULL)
427 array($mode), __FUNCTION__, __LINE__);
429 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
430 if (SQL_NUMROWS($result_main) > 0) {
431 // There are menus available, so we simply display them... :)
432 $GLOBALS['rows'] = '';
433 while ($content = SQL_FETCHARRAY($result_main)) {
434 //* DEBUG: */ debugOutput(__LINE__ . '/' . $main_cnt . '/' . $content['action'] . ':' . getWhat() . '*');
435 // Disable the block-mode
436 enableBlockMode(false);
438 // Load menu header template
439 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
442 $result_sub = SQL_QUERY_ESC("SELECT
443 `title` AS `sub_title`,
444 `what` AS `sub_what`,
445 `visible` AS `sub_visible`,
446 `locked` AS `sub_locked`
448 `{?_MYSQL_PREFIX?}_%s_menu`
456 array($mode, $content['action']), __FUNCTION__, __LINE__);
458 // Do we have some entries?
459 if (SQL_NUMROWS($result_sub) > 0) {
463 // Load all sub menus
464 while ($content2 = SQL_FETCHARRAY($result_sub)) {
465 // Merge both arrays in one
466 $content = merge_array($content, $content2);
471 // Full file name for checking menu
472 //* DEBUG: */ debugOutput(__LINE__ . ':!!!!' . $content['sub_what'] . '!!!');
473 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
474 if (isIncludeReadable($inc)) {
475 // Mark currently selected menu - open
476 if ((!empty($what)) && (($what == $content['sub_what']))) {
481 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
484 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
488 $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
490 if (isIncludeReadable($inc)) {
493 // Mark currently selected menu - close
494 if ((!empty($what)) && (($what == $content['sub_what']))) {
498 // Not found! - close
508 'what' => $content['sub_what'],
509 'visible' => $content['sub_visible'],
510 'locked' => $content['locked'],
513 // Add regular menu row or bottom row?
514 if ($cnt < SQL_NUMROWS($result_sub)) {
515 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
517 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
521 // This is a menu block... ;-)
525 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
526 if (isFileReadable($INC)) {
528 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
529 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
531 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat().'*');
532 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
534 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
538 SQL_FREERESULT($result_sub);
543 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.':'.getWhat().'*');
544 if (SQL_NUMROWS($result_main) > $main_cnt) {
546 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
548 // Should we display adverts in this menu?
549 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
550 // Display advert template
551 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
553 // Add seperator again
554 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
560 SQL_FREERESULT($result_main);
562 // Should we display adverts in this menu?
563 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
564 // Add seperator again
565 $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode);
567 // Display advert template
568 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
573 'rows' => $GLOBALS['rows'],
577 // Load main template
578 //* DEBUG: */ debugOutput(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat().'*');
579 loadTemplate('menu_table', false, $content);
583 // Checks wether the current user is a member
584 function isMember () {
585 // By default no member
588 // Fix missing 'last_online' array, damn stupid code :(((
589 // @TODO Try to rewrite this to one or more functions
590 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
592 // is the cache entry there?
593 if (isset($GLOBALS['is_member'])) {
595 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS['is_member']) . ')');
596 return $GLOBALS['is_member'];
597 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
599 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
602 // Get it secured from session
603 setMemberId(getSession('userid'));
604 setCurrentUserId(getMemberId());
605 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . getSession('userid') . ' used from cookie/session.');
608 // Init user data array
611 // Fix "deleted" cookies first
612 fixDeletedCookies(array('userid', 'u_hash'));
615 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) {
616 // Cookies are set with values, but are they valid?
617 if (fetchUserData(getMemberId()) === true) {
618 // Validate password by created the difference of it and the secret key
619 $valPass = encodeHashForCookie(getUserData('password'));
621 // Transfer last module and online time
622 $GLOBALS['last_online']['module'] = getUserData('last_module');
623 $GLOBALS['last_online']['online'] = getUserData('last_online');
625 // So did we now have valid data and an unlocked user?
626 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
627 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
630 // Maybe got locked etc.
631 //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status') . ',' . $valPass . '(' . strlen($valPass) . ')/' . getSession('u_hash') . '(' . strlen(getSession('u_hash')) . ')/' . getUserData('password') . '(' . strlen(getUserData('password')) . ')');
632 destroyMemberSession();
635 // Cookie data is invalid!
636 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data invalid or user not found.');
637 destroyMemberSession();
640 // Cookie data is invalid!
641 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cookie data not complete.');
642 destroyMemberSession();
646 $GLOBALS['is_member'] = $ret;
649 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
653 // Fetch user data for given user id
654 function fetchUserData ($userid, $column = 'userid') {
655 // If we should look for userid secure&set it here
656 if (substr($column, -2, 2) == 'id') {
658 $userid = bigintval($userid);
661 setCurrentUserId($userid);
663 // Don't look for invalid userids...
665 // Invalid, so abort here
666 debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
667 } elseif (isUserDataValid()) {
668 // Use cache, so it is fine
671 } elseif (isUserDataValid()) {
672 // Use cache, so it is fine
677 // By default none was found
682 if (isExtensionInstalledAndNewer('user', '0.3.5')) $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
684 // Query for the user
685 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
686 array($column, $userid), __FUNCTION__, __LINE__);
688 // Do we have a record?
689 if (SQL_NUMROWS($result) == 1) {
690 // Load data from cookies
691 $data = SQL_FETCHARRAY($result);
693 // Set the userid for later use
694 setCurrentUserId($data['userid']);
695 $GLOBALS['user_data'][getCurrentUserId()] = $data;
697 // Rewrite 'last_failure' if found
698 if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
699 // Backup the raw one and zero it
700 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
701 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0';
704 if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
705 // Seperate data/time
706 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
708 // Seperate data and time again
709 $array['date'] = explode('-', $array[0]);
710 $array['time'] = explode(':', $array[1]);
712 // Now pass it to mktime()
713 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
725 $found = isUserDataValid();
729 SQL_FREERESULT($result);
735 // This patched function will reduce many SELECT queries for the specified or current admin login
736 function isAdmin ($adminLogin = '') {
737 // No admin in installation phase!
738 if ((isInstallationPhase()) || (!isAdminRegistered())) {
746 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminLogin);
748 // If admin login is not given take current from cookies...
749 if ((empty($adminLogin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
750 // Get admin login and password from session/cookies
751 $adminLogin = getSession('admin_login');
752 $passCookie = getSession('admin_md5');
754 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminLogin.'/'.$passCookie);
757 if (!isset($GLOBALS['is_admin'][$adminLogin])) {
758 // Init it with failed
759 $GLOBALS['is_admin'][$adminLogin] = false;
761 // Search in array for entry
762 if (isset($GLOBALS['admin_hash'])) {
764 $valPass = $GLOBALS['admin_hash'];
765 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminLogin) === true) && (!empty($adminLogin))) {
766 // Login data is valid or not?
767 $valPass = encodeHashForCookie(getAdminHash($adminLogin));
770 $GLOBALS['admin_hash'] = $valPass;
773 incrementStatsEntry('cache_hits');
774 } elseif ((!empty($adminLogin)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminLogin) === false))) {
775 // Get admin hash and hash it
776 $valPass = encodeHashForCookie(getAdminHash($adminLogin));
779 $GLOBALS['admin_hash'] = $valPass;
782 if (!empty($valPass)) {
783 // Check if password is valid
784 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
785 $GLOBALS['is_admin'][$adminLogin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
789 // Return result of comparision
790 return $GLOBALS['is_admin'][$adminLogin];
793 // Generates a list of "max receiveable emails per day"
794 function addMaxReceiveList ($mode, $default = '', $return = false) {
800 // Guests (in the registration form) are not allowed to select 0 mails per day.
801 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC",
802 __FUNCTION__, __LINE__);
806 // Members are allowed to set to zero mails per day (we will change this soon!)
807 $result = SQL_QUERY("SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC",
808 __FUNCTION__, __LINE__);
812 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
816 // Some entries are found?
817 if (SQL_NUMROWS($result) > 0) {
819 while ($content = SQL_FETCHARRAY($result)) {
820 $OUT .= ' <option value="' . $content['value'] . '"';
821 if (postRequestParameter('max_mails') == $content['value']) $OUT .= ' selected="selected"';
822 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
823 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
828 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
830 // Maybe the admin has to setup some maximum values?
831 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
835 SQL_FREERESULT($result);
837 if ($return === true) {
838 // Return generated HTML code
841 // Output directly (default)
846 // Checks wether the given email address is used.
847 function isEmailTaken ($email) {
848 // Query the database
849 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' OR `email` LIKE '%%%s%%' LIMIT 1",
850 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
852 // Is the email there?
853 $ret = (SQL_NUMROWS($result) == 1);
856 SQL_FREERESULT($result);
862 // Validate the given menu action
863 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
864 // Is the cache entry there and we shall not update?
865 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
867 incrementStatsEntry('cache_hits');
869 // Then use this cache
870 return $GLOBALS['action_valid'][$mode][$action][$what];
873 // By default nothing is valid
876 // Look in all menus or only unlocked
878 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
880 //* DEBUG: */ debugOutput(__LINE__.':'.$mode.'/'.$action.'/'.$what.'*');
881 if (($mode != 'admin') && ($updateEntry === true)) {
882 // Update guest or member menu
883 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
888 ), __FUNCTION__, __LINE__, false);
889 } elseif (($what != 'overview') && (!empty($what))) {
891 $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",
896 ), __FUNCTION__, __LINE__, false);
898 // Admin login overview
899 $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",
903 ), __FUNCTION__, __LINE__, false);
907 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
909 // Should we look for affected rows (only update) or found rows?
910 if ($updateEntry === true) {
911 // Check updated/affected rows
912 $ret = (SQL_AFFECTEDROWS() == 1);
915 $ret = (SQL_NUMROWS($result) == 1);
919 SQL_FREERESULT($result);
922 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
928 // Get action value from mode (admin/guest/member) and what-value
929 function getActionFromModuleWhat ($module, $what) {
931 $data['action'] = '';
933 //* DEBUG: */ debugOutput(__LINE__.'='.$module.'/'.$what.'/'.getAction().'=');
934 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
935 // sql_patches is missing so choose depending on mode
939 } elseif ($module == 'admin') {
946 } elseif ((empty($what)) && ($module != 'admin')) {
947 // Use configured 'home'
948 $what = getConfig('index_home');
951 if ($module == 'admin') {
952 // Action value for admin area
953 if (isGetRequestParameterSet('action')) {
955 return getRequestParameter('action');
956 } elseif (isActionSet()) {
957 // Get it directly from URL
959 } elseif (($what == 'overview') || (!isWhatSet())) {
960 // Default value for admin area
961 $data['action'] = 'login';
963 } elseif (isActionSet()) {
964 // Get it directly from URL
967 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ret=' . $data['action']);
969 // Does the module have a menu?
970 if (ifModuleHasMenu($module)) {
971 // Rewriting modules to menu
972 $module = mapModuleToTable($module);
974 // Guest and member menu is 'main' as the default
975 if (empty($data['action'])) $data['action'] = 'main';
977 // Load from database
978 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
979 array($module, $what), __FUNCTION__, __LINE__);
980 if (SQL_NUMROWS($result) == 1) {
981 // Load action value and pray that this one is the right you want... ;-)
982 $data = SQL_FETCHARRAY($result);
986 SQL_FREERESULT($result);
987 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
988 // No sql_patches installed, but maybe we need to register an admin?
989 if (isAdminRegistered()) {
990 // Redirect to admin area
991 redirectToUrl('admin.php');
995 // Return action value
996 return $data['action'];
999 // Get category name back
1000 function getCategory ($cid) {
1001 // Default is not found
1002 $data['cat'] = getMessage('_CATEGORY_404');
1004 // Is the category id set?
1007 $data['cat'] = getMessage('_CATEGORY_NONE');
1008 } elseif ($cid > 0) {
1009 // Lookup the category in database
1010 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
1011 array(bigintval($cid)), __FUNCTION__, __LINE__);
1012 if (SQL_NUMROWS($result) == 1) {
1013 // Category found... :-)
1014 $data = SQL_FETCHARRAY($result);
1018 SQL_FREERESULT($result);
1022 return $data['cat'];
1025 // Get a string of "mail title" and price back
1026 function getPaymentTitlePrice ($pid, $full=false) {
1027 // Default is not found
1028 $ret = getMessage('_PAYMENT_404');
1030 // Load payment data
1031 $result = SQL_QUERY_ESC("SELECT `mail_title`, `price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1032 array(bigintval($pid)), __FUNCTION__, __LINE__);
1033 if (SQL_NUMROWS($result) == 1) {
1034 // Payment type found... :-)
1035 $data = SQL_FETCHARRAY($result);
1037 // Only title or also including price?
1038 if ($full === false) {
1039 $ret = $data['mail_title'];
1041 $ret = $data['mail_title'] . ' / ' . translateComma($data['price']) . ' {?POINTS?}';
1046 SQL_FREERESULT($result);
1052 // Get (basicly) the price of given payment id
1053 function getPaymentPoints ($pid, $lookFor = 'price') {
1055 $data[$lookFor] = '-1';
1057 // Search for it in database
1058 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
1059 array($lookFor, $pid), __FUNCTION__, __LINE__);
1061 // Is the entry there?
1062 if (SQL_NUMROWS($result) == 1) {
1063 // Payment type found... :-)
1064 $data = SQL_FETCHARRAY($result);
1068 SQL_FREERESULT($result);
1071 return $data[$lookFor];
1074 // Remove a receiver's id from $receivers and add a link for him to confirm
1075 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
1076 // Default is not removed
1079 // Is the userid valid?
1081 // Remove entry from array
1082 unset($receivers[$key]);
1084 // Is there already a line for this user available?
1085 if ($stats_id > 0) {
1086 // Only when we got a real stats id continue searching for the entry
1087 $type = 'NORMAL'; $rowName = 'stats_id';
1088 if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
1090 // Try to look the entry up
1091 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
1092 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1094 // Was it *not* found?
1095 if (SQL_HASZERONUMS($result)) {
1097 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')",
1098 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
1106 SQL_FREERESULT($result);
1110 // Return status for sending routine
1114 // Calculate sum (default) or count records of given criteria
1115 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') {
1119 //* DEBUG: */ debugOutput($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add);
1120 if ((empty($search)) && ($search != '0')) {
1121 // Count or sum whole table?
1122 if ($countRows === true) {
1123 // Count whole table
1124 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1125 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1128 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s`".$add,
1129 array($lookFor, $tableName), __FUNCTION__, __LINE__);
1131 } elseif (($countRows === true) || ($lookFor == 'userid')) {
1133 //* DEBUG: */ debugOutput('COUNT!');
1134 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1135 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1138 //* DEBUG: */ debugOutput('SUM!');
1139 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS res FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add,
1140 array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
1144 $data = SQL_FETCHARRAY($result);
1147 SQL_FREERESULT($result);
1150 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1152 $data['res'] = '0.00000';
1153 } elseif (''.$data['res'].'' == '') {
1159 //* DEBUG: */ debugOutput('ret=' . $data['res']);
1160 return $data['res'];
1162 // Getter fro ref level percents
1163 function getReferalLevelPercents ($level) {
1165 $data['percents'] = '0';
1167 // Do we have cache?
1168 if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
1169 // First look for level
1170 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
1171 if ($key !== false) {
1173 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
1176 incrementStatsEntry('cache_hits');
1178 } elseif (!isExtensionActive('cache')) {
1180 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1",
1181 array(bigintval($level)), __FUNCTION__, __LINE__);
1184 if (SQL_NUMROWS($result_level) == 1) {
1186 $data = SQL_FETCHARRAY($result_level);
1190 SQL_FREERESULT($result_level);
1194 return $data['percents'];
1199 * Dynamic referal system, can also send mails!
1201 * subject = Subject line, write in lower-case letters and underscore is allowed
1202 * userid = Referal id wich should receive...
1203 * points = ... xxx points
1204 * sendNotify = shall I send the referal an email or not?
1205 * rid = inc/modules/guest/what-confirm.php need this
1206 * locked = Shall I pay it to normal (false) or locked (true) points ammount?
1207 * add_mode = Add points only to $userid or also refs? (WARNING! Changing 'ref' to 'direct'
1208 * for default value will cause no referal will get points ever!!!)
1210 function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
1211 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">' . __FUNCTION__ . ' - ENTRY</font> ------------------------<ul><li>');
1212 // Convert mode to lower-case
1213 $add_mode = strtolower($add_mode);
1215 // When $userid = '0' add points to jackpot
1216 if (($userid == '0') && (isExtensionActive('jackpot'))) {
1217 // Add points to jackpot
1218 addPointsToJackpot($points);
1222 // Prepare data for the filter
1223 $filterData = array(
1224 'subject' => $subject,
1225 'userid' => $userid,
1226 'points' => $points,
1227 'notify' => $sendNotify,
1229 'locked' => $locked,
1231 'sub_mode' => $add_mode,
1235 runFilterChain('add_points', $filterData);
1237 // Count up referal depth
1238 if (!isset($GLOBALS['ref_level'])) {
1239 // Initialialize referal system
1240 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal system initialized!');
1241 $GLOBALS['ref_level'] = '0';
1243 // Increase referal level
1244 $GLOBALS['ref_level']++;
1245 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): Referal level increased. DEPTH='.$GLOBALS['ref_level']);
1248 // Default is 'normal' points
1251 // Which points, locked or normal?
1252 if ($locked === true) $data = 'locked_points';
1254 // Check user account
1255 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points);
1256 if (fetchUserData($userid)) {
1257 // This is the user and his ref
1258 $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
1261 $per = getReferalLevelPercents($GLOBALS['ref_level']);
1262 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',depth='.$GLOBALS['ref_level'].',per='.$per.',mode='.$add_mode);
1264 // Some percents found?
1266 // Calculate new points
1267 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',points='.$points.',per='.$per.',depth='.$GLOBALS['ref_level']);
1268 $ref_points = $points * $per / 100;
1270 // Pay refback here if level > 0 and in ref-mode
1271 if ((isExtensionActive('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == 'ref') && (isset($GLOBALS['cache_array']['add_userid'][$userid]))) {
1272 //* 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!');
1273 $ref_points = addRefbackPoints($GLOBALS['cache_array']['add_userid'][$userid], $userid, $points, $ref_points);
1274 //* 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!');
1278 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
1279 array($data, $data, $ref_points, bigintval($userid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
1280 //* 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().')');
1282 // No entry updated?
1283 if (SQL_AFFECTEDROWS() < 1) {
1284 // First ref in this level! :-)
1285 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s,%s,%s)",
1286 array($data, bigintval($userid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
1287 //* 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().')');
1290 // Points updated, maybe I shall send him an email?
1291 if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
1295 'level' => bigintval($GLOBALS['ref_level']),
1296 'points' => $ref_points,
1297 'refid' => getUserData('refid')
1300 // Load email template
1301 $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
1304 sendEmail($userid, getMessage('THANX_REFERAL_ONE_SUBJECT'), $message);
1305 } elseif (($sendNotify === true) && (getUserData('refid') == '0') && ($locked === false) && ($add_mode == 'direct')) {
1308 'text' => getMessage('REASON_DIRECT_PAYMENT'),
1309 'points' => $ref_points
1313 $message = loadEmailTemplate('add-points', $content, $userid);
1316 sendEmail($userid, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
1317 if (!isGetRequestParameterSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
1320 // Maybe there's another ref?
1321 if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
1322 // Then let's credit him here...
1323 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.getUserData('refid').',points='.$points.' - ADVANCE!');
1324 addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
1329 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
1332 // Updates the referal counter
1333 function updateReferalCounter ($userid) {
1334 // Make it sure referal level zero (member him-/herself) is at least selected
1335 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1;
1336 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',level='.$GLOBALS['cache_array']['ref_level'][$userid]);
1339 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1",
1340 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1342 // When no entry was updated then we have to create it here
1343 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):updated=' . SQL_AFFECTEDROWS());
1344 if (SQL_AFFECTEDROWS() < 1) {
1346 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
1347 array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
1348 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid);
1354 // Check for his referal
1355 if (fetchUserData($userid)) {
1357 $ref = getUserData('refid');
1360 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):userid='.$userid.',ref='.$ref);
1362 // When he has a referal...
1363 if (($ref > 0) && ($ref != $userid)) {
1364 // Move to next referal level and count his counter one up!
1365 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - ADVANCE!');
1366 $GLOBALS['cache_array']['ref_level'][$userid]++;
1367 updateReferalCounter($ref);
1368 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
1369 // Remove cache here
1370 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>):ref='.$ref.' - CACHE!');
1371 rebuildCache('refsystem', 'refsystem');
1375 $GLOBALS['cache_array']['ref_level'][$userid]--;
1377 // Handle refback here if extension is installed
1378 if (isExtensionActive('refback')) {
1379 updateRefbackTable($userid);
1383 // Sends out mail to all administrators. This function is no longer obsolete
1384 // because we need it when there is no ext-admins installed
1385 function sendAdminEmails ($subj, $message) {
1386 // Load all admin email addresses
1387 $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
1388 while ($content = SQL_FETCHARRAY($result)) {
1389 // Send the email out
1390 sendEmail($content['email'], $subj, $message);
1394 SQL_FREERESULT($result);
1396 // Really simple... ;-)
1399 // Get id number from administrator's login name
1400 function getAdminId ($adminLogin) {
1401 // By default no admin is found
1405 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1406 // Use it if found to save SQL queries
1407 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1409 // Update cache hits
1410 incrementStatsEntry('cache_hits');
1411 } elseif (!isExtensionActive('cache')) {
1412 // Load from database
1413 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1414 array($adminLogin), __FUNCTION__, __LINE__);
1416 // Do we have an entry?
1417 if (SQL_NUMROWS($result) == 1) {
1419 $data = SQL_FETCHARRAY($result);
1423 SQL_FREERESULT($result);
1430 // "Getter" for current admin id
1431 function getCurrentAdminId () {
1432 // Do we have cache?
1433 if (!isset($GLOBALS['current_admin_id'])) {
1434 // Get the admin login from session
1435 $adminLogin = getSession('admin_login');
1437 // "Solve" it into an id
1438 $adminId = getAdminId($adminLogin);
1440 // Remember in cache securely
1441 setCurrentAdminId(bigintval($adminId));
1445 return $GLOBALS['current_admin_id'];
1448 // Setter for current admin id
1449 function setCurrentAdminId ($currentAdminId) {
1451 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1454 // Get password hash from administrator's login name
1455 function getAdminHash ($adminLogin) {
1456 // By default an invalid hash is returned
1457 $data['password'] = '-1';
1459 if (isAdminHashSet($adminLogin)) {
1461 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminLogin];
1463 // Update cache hits
1464 incrementStatsEntry('cache_hits');
1465 } elseif (!isExtensionActive('cache')) {
1466 // Load from database
1467 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1468 array($adminLogin), __FUNCTION__, __LINE__);
1470 // Do we have an entry?
1471 if (SQL_NUMROWS($result) == 1) {
1473 $data = SQL_FETCHARRAY($result);
1476 setAdminHash($adminLogin, $data['password']);
1480 SQL_FREERESULT($result);
1483 // Return password hash
1484 return $data['password'];
1487 // "Getter" for admin login
1488 function getAdminLogin ($adminId) {
1489 // By default a non-existent login is returned (other functions react on this!)
1490 $data['login'] = '***';
1492 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1494 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1496 // Update cache hits
1497 incrementStatsEntry('cache_hits');
1498 } elseif (!isExtensionActive('cache')) {
1499 // Load from database
1500 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1501 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1504 if (SQL_NUMROWS($result) == 1) {
1506 $data = SQL_FETCHARRAY($result);
1509 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1513 SQL_FREERESULT($result);
1516 // Return the result
1517 return $data['login'];
1520 // Get email address of admin id
1521 function getAdminEmail ($adminId) {
1522 // By default an invalid emails is returned
1523 $data['email'] = '***';
1525 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1527 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1529 // Update cache hits
1530 incrementStatsEntry('cache_hits');
1531 } elseif (!isExtensionActive('cache')) {
1532 // Load from database
1533 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1534 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1537 if (SQL_NUMROWS($result_admin_id) == 1) {
1539 $data = SQL_FETCHARRAY($result_admin_id);
1542 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1546 SQL_FREERESULT($result_admin_id);
1550 return $data['email'];
1553 // Get default ACL of admin id
1554 function getAdminDefaultAcl ($adminId) {
1555 // By default an invalid ACL value is returned
1556 $data['default_acl'] = '***';
1558 // Is sql_patches there and was it found in cache?
1559 if (!isExtensionActive('sql_patches')) {
1560 // Not found, which is bad, so we need to allow all
1561 $data['default_acl'] = 'allow';
1562 } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) {
1564 $data['default_acl'] = $GLOBALS['cache_array']['admin']['def_acl'][$adminId];
1566 // Update cache hits
1567 incrementStatsEntry('cache_hits');
1568 } elseif (!isExtensionActive('cache')) {
1569 // Load from database
1570 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1571 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1572 if (SQL_NUMROWS($result_admin_id) == 1) {
1574 $data = SQL_FETCHARRAY($result_admin_id);
1577 $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $data['default_acl'];
1581 SQL_FREERESULT($result_admin_id);
1584 // Return default ACL
1585 return $data['default_acl'];
1588 // Generates an option list from various parameters
1589 function generateOptionList ($table, $id, $name, $default='', $special='', $where='', $disabled=array()) {
1591 if ($table == '/ARRAY/') {
1592 // Selection from array
1593 if ((is_array($id)) && (is_array($name)) && (count($id)) == (count($name))) {
1595 foreach ($id as $idx => $value) {
1596 $ret .= '<option value="' . $value . '"';
1597 if ($default == $value) {
1598 // Selected by default
1599 $ret .= ' selected="selected"';
1600 } elseif (isset($disabled[$value])) {
1602 $ret .= ' disabled="disabled"';
1604 $ret .= '>' . $name[$idx] . '</option>';
1607 // Problem in request
1608 debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name));
1611 // Data from database
1612 $SPEC = ', `' . $id . '`';
1613 if (!empty($special)) $SPEC = ', `' . $special . '`';
1615 // Query the database
1616 $result = SQL_QUERY_ESC("SELECT `%s`, `%s`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$where." ORDER BY `%s` ASC",
1622 ), __FUNCTION__, __LINE__);
1625 if (SQL_NUMROWS($result) > 0) {
1626 // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
1627 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
1628 while (list($value, $title, $add) = SQL_FETCHROW($result)) {
1629 if (empty($special)) $add = '';
1630 $ret .= '<option value="' . $value . '"';
1631 if ($default == $value) {
1632 // Selected by default
1633 $ret .= ' selected="selected"';
1634 } elseif (isset($disabled[$value])) {
1636 $ret .= ' disabled="disabled"';
1638 if (!empty($add)) $add = ' ('.$add.')';
1639 $ret .= '>' . $title . $add . '</option>';
1643 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1647 SQL_FREERESULT($result);
1650 // Return - hopefully - the requested data
1653 // Activate exchange
1654 function FILTER_ACTIVATE_EXCHANGE () {
1655 // Is the extension 'user' there?
1656 if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) {
1657 // Silently abort here
1661 // Check total amount of users
1662 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
1664 if ($totalUsers >= getConfig('activate_xchange')) {
1667 "UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1",
1668 "UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
1672 runFilterChain('run_sqls');
1674 // Update configuration
1675 updateConfiguration('activate_xchange' ,0);
1678 rebuildCache('modules', 'modules');
1682 // Deletes a user account with given reason
1683 function deleteUserAccount ($userid, $reason) {
1685 $data['points'] = '0';
1687 $result = SQL_QUERY_ESC("SELECT
1688 (SUM(p.points) - d.used_points) AS points
1690 `{?_MYSQL_PREFIX?}_user_points` AS p
1692 `{?_MYSQL_PREFIX?}_user_data` AS d
1698 array(bigintval($userid)), __FUNCTION__, __LINE__);
1700 // Do we have an entry?
1701 if (SQL_NUMROWS($result) == 1) {
1702 // Save his points to add them to the jackpot
1703 $data = SQL_FETCHARRAY($result);
1705 // Delete points entries as well
1706 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1707 array(bigintval($userid)), __FUNCTION__, __LINE__);
1709 // Update mediadata as well
1710 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1712 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1715 // Now, when we have all his points adds them do the jackpot!
1716 if (isExtensionActive('jackpot')) addPointsToJackpot($data['points']);
1720 SQL_FREERESULT($result);
1722 // Delete category selections as well...
1723 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1724 array(bigintval($userid)), __FUNCTION__, __LINE__);
1726 // Remove from rallye if found
1727 // @TODO Rewrite this to a filter
1728 if (isExtensionActive('rallye')) {
1729 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1730 array(bigintval($userid)), __FUNCTION__, __LINE__);
1733 // Add reason and translate points
1734 $data['text'] = $reason;
1735 $data['points'] = translateComma($data['points']);
1737 // Now a mail to the user and that's all...
1738 $message = loadEmailTemplate('del-user', $data, $userid);
1739 sendEmail($userid, getMessage('ADMIN_DEL_ACCOUNT'), $message);
1741 // Ok, delete the account!
1742 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1745 // Gets the matching what name from module
1746 function getWhatFromModule ($modCheck) {
1747 // Is the request element set?
1748 if (isGetRequestParameterSet('what')) {
1749 // Then return this!
1750 return getRequestParameter('what');
1756 //* DEBUG: */ debugOutput(__LINE__.'!'.$modCheck.'!');
1757 switch ($modCheck) {
1764 // Is ext-sql_patches installed and newer than 0.0.5?
1765 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1766 // Use it from config
1767 $what = getConfig('index_home');
1769 // Use default 'welcome'
1779 // Return what value
1783 // Subtract points from database and mediadata cache
1784 function subtractPoints ($subject, $userid, $points) {
1785 // Add points to used points
1786 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
1787 array($points, bigintval($userid)), __FUNCTION__, __LINE__);
1789 // Prepare filter data
1790 $filterData = array(
1791 'subject' => $subject,
1792 'userid' => $userid,
1793 'points' => $points,
1797 // Insert booking record
1798 runFilterChain('sub_points', $filterData);
1801 // "Getter" for total available receivers
1802 function getTotalReceivers ($mode='normal') {
1804 $result_all = SQL_QUERY("SELECT
1807 `{?_MYSQL_PREFIX?}_user_data`
1809 `status`='CONFIRMED' AND `receive_mails` > 0 ".runFilterChain('exclude_users', $mode),
1810 __FUNCTION__, __LINE__);
1813 $numRows = SQL_NUMROWS($result_all);
1816 SQL_FREERESULT($result_all);
1822 // Returns HTML code with an option list of all categories
1823 function generateCategoryOptionsList ($mode) {
1824 // Prepare WHERE statement
1825 $whereStatement = " WHERE `visible`='Y'";
1826 if (isAdmin()) $whereStatement = '';
1828 // Initialize array...
1832 'userids' => array()
1836 $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC",
1837 __FUNCTION__, __LINE__);
1839 // Do we have entries?
1840 if (SQL_NUMROWS($result) > 0) {
1841 // ... and begin loading stuff
1842 while ($content = SQL_FETCHARRAY($result)) {
1843 // Transfer some data
1844 $CATS['id'][] = $content['id'];
1845 $CATS['name'][] = $content['cat'];
1847 // Check which users are in this category
1848 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1849 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1855 while ($data = SQL_FETCHARRAY($result_userids)) {
1857 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1861 SQL_FREERESULT($result_userids);
1864 $CATS['userids'][] = $userid_cnt;
1868 SQL_FREERESULT($result);
1872 foreach ($CATS['id'] as $key => $value) {
1873 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1874 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1877 // No cateogries are defined yet
1878 $OUT = '<option class="member_failed">{--MEMBER_NO_CATS--}</option>';
1885 // Add bonus mail to queue
1886 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
1887 // Is admin or bonus extension there?
1891 } elseif (!isExtensionActive('bonus')) {
1896 // Calculcate target sent
1897 $target = countSelection(explode(';', $receiverList));
1899 // Receiver is zero?
1900 if ($receiver == '0') {
1902 $receiver = $target;
1905 // HTML extension active?
1906 if (isExtensionActive('html_mail')) {
1907 // No HTML by default
1911 if ($mode == 'html') $HTML = 'Y';
1914 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1915 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`, `html_msg`)
1916 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
1926 bigintval($receiver),
1928 ), __FUNCTION__, __LINE__);
1931 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1932 (`subject`, `text`, `receivers`, `points`, `time`, `data_type`, `timestamp`, `url`, `cat_id`, `target_send`, `mails_sent`)
1933 VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
1943 bigintval($receiver),
1944 ), __FUNCTION__, __LINE__);
1948 // Generate a receiver list for given category and maximum receivers
1949 function generateReceiverList ($cat, $receiver, $mode = '') {
1957 $cat = bigintval($cat);
1958 $receiver = bigintval($receiver);
1960 // Is the receiver zero and mode set?
1961 if (($receiver == '0') && (!empty($mode))) {
1962 // Auto-fix receiver maximum
1963 $receiver = getTotalReceivers($mode);
1969 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
1970 $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
1973 // Exclude users in holiday?
1974 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1975 // Add something for the holiday extension
1976 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1979 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1980 // Only include HTML receivers
1981 $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",
1984 ), __FUNCTION__, __LINE__);
1987 $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",
1990 ), __FUNCTION__, __LINE__);
1994 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1996 while ($content = SQL_FETCHARRAY($result)) {
1997 // Add receiver when not empty
1998 if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
2002 SQL_FREERESULT($result);
2004 // Remove trailing semicolon
2005 $receiverList = substr($receiverList, 0, -1);
2009 return $receiverList;
2012 // "Getter" for array for user refs and points in given level
2013 function getUserReferalPoints ($userid, $level) {
2014 //* DEBUG: */ debugOutput('----------------------- <font color="#00aa00">'.__FUNCTION__.' - ENTRY</font> ------------------------<ul><li>');
2015 // Default is no refs and no nickname
2019 // Do we have nickname extension installed?
2020 if (isExtensionActive('nickname')) {
2021 $add = ', ud.nickname';
2024 // Get refs from database
2025 $result = SQL_QUERY_ESC("SELECT
2026 ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
2028 `{?_MYSQL_PREFIX?}_user_refs` AS ur
2030 `{?_MYSQL_PREFIX?}_user_points` AS up
2032 ur.refid=up.userid AND ur.level=0
2034 `{?_MYSQL_PREFIX?}_user_data` AS ud
2038 ur.userid=%s AND ur.level=%s
2044 ), __FUNCTION__, __LINE__);
2046 // Are there some entries?
2047 if (SQL_NUMROWS($result) > 0) {
2048 // Fetch all entries
2049 while ($row = SQL_FETCHARRAY($result)) {
2050 // Get total points of this user
2051 $row['points'] = countSumTotalData($row['refid'], 'user_points', 'points') - countSumTotalData($row['refid'], 'user_data', 'used_points');
2053 // Get unconfirmed mails
2054 $row['unconfirmed'] = countSumTotalData($row['refid'], 'user_links', 'id', 'userid', true);
2056 // Init clickrate with zero
2057 $row['clickrate'] = '0';
2059 // Is at least one mail received?
2060 if ($row['emails_received'] > 0) {
2061 // Calculate clickrate
2062 $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
2065 // Activity is 'active' by default because if autopurge is not installed
2066 $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
2068 // Is autopurge installed and the user inactive?
2069 if ((isExtensionActive('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online'])) {
2071 $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
2074 // Remove some entries
2075 unset($row['mails_confirmed']);
2076 unset($row['emails_received']);
2077 unset($row['last_online']);
2080 $refs[$row['id']] = $row;
2085 SQL_FREERESULT($result);
2088 //* DEBUG: */ debugOutput('</li></ul>----------------------- <font color="#aa0000">'.__FUNCTION__.' - EXIT</font> ------------------------<br />');
2092 // Recuce the amount of received emails for the receipients for given email
2093 function reduceRecipientReceivedMails ($column, $id, $count) {
2094 // Search for mail in database
2095 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
2096 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
2098 // Are there entries?
2099 if (SQL_NUMROWS($result) > 0) {
2100 // Now load all userids for one big query!
2102 while ($data = SQL_FETCHARRAY($result)) {
2103 // By default we want to reduce and have no mails found
2106 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
2107 // @TODO Rewrite this to a filter
2108 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
2110 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
2111 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
2113 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
2116 // Reduce this users total received emails?
2117 if ($num === 0) $userids[$data['userid']] = $data['userid'];
2120 if (count($userids) > 0) {
2121 // Now update all user accounts
2122 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
2123 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
2126 loadTemplate('admin_settings_saved', false, getMaskedMessage('ADMIN_MAIL_NOTHING_DELETED', $id));
2131 SQL_FREERESULT($result);
2134 // Creates a new task
2135 function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) {
2136 // Insert the task data into the database
2137 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())",
2144 ), __FUNCTION__, __LINE__, true, $strip);
2147 // Updates last module / online time
2148 // @TODO Fix inconsistency between last_module and getWhat()
2149 function updateLastActivity($userid) {
2150 // Run the update query
2151 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
2156 ), __FUNCTION__, __LINE__);