X-Git-Url: https://git.mxchange.org/?p=mailer.git;a=blobdiff_plain;f=inc%2Fmysql-manager.php;h=bc2ccddadf095d4718a0f10feb9815586c4324f9;hp=7c4d4a8960442429842e99e838d0b08ca2914b45;hb=d36d67adb800513d9293a897bef1ee09db6b3583;hpb=c8a83fa31256474eccf50db85187ee6a83d67e26 diff --git a/inc/mysql-manager.php b/inc/mysql-manager.php index 7c4d4a8960..bc2ccddadf 100644 --- a/inc/mysql-manager.php +++ b/inc/mysql-manager.php @@ -79,7 +79,7 @@ function getModuleTitle ($mod) { if (empty($title)) { // No name found $title = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $mod); - if (SQL_NUMROWS($result) == 0) { + if (SQL_NUMROWS($result) == '0') { // Add module to database $dummy = checkModulePermissions($mod); } // END - if @@ -134,10 +134,10 @@ function checkModulePermissions ($mod = '') { // Check for prefix is a extension... $modSplit = explode('_', $mod); $extension = ''; $mod_chk = $mod; - //* DEBUG: */ outputHtml(__LINE__."*".count($modSplit)."*/".$mod."*
"); + //* DEBUG: */ print(__LINE__."*".count($modSplit)."*/".$mod."*
"); if (count($modSplit) == 2) { // Okay, there is a seperator (_) in the name so is the first part a module? - //* DEBUG: */ outputHtml(__LINE__."*".$modSplit[0]."*
"); + //* DEBUG: */ print(__LINE__."*".$modSplit[0]."*
"); if (isExtensionActive($modSplit[0])) { // The prefix is an extension's name, so let's set it $extension = $modSplit[0]; $mod = $modSplit[1]; @@ -253,7 +253,7 @@ function checkModulePermissions ($mod = '') { // Destroy cache here // @TODO Rewrite this to a filter - if (getOutputMode() == '0') rebuildCacheFile('modreg', 'modreg'); + if ((getOutputMode() == '0') || (getOutputMode() == -1)) rebuildCacheFile('modules', 'modules'); // And reload data unset($GLOBALS['module_status'][$mod]); @@ -262,9 +262,9 @@ function checkModulePermissions ($mod = '') { // Module not found we don't add it to the database $ret = '404'; } - } elseif (($ret == 'cache_miss') && (getOutputMode() == 0)) { + } elseif (($ret == 'cache_miss') && (getOutputMode() == '0')) { // Rebuild the cache files - rebuildCacheFile('modreg', 'modreg'); + rebuildCacheFile('modules', 'modules'); } elseif ($found === false) { // Problem with module detected logDebugMessage(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s, output_mode=%s", @@ -348,7 +348,7 @@ function addMenuDescription ($accessLevel, $FQFN, $return = false, $output = tru // Begin the navigation line if ((!isset($GLOBALS['nav_depth'])) && ($return === false)) { - $GLOBALS['nav_depth'] = 0; + $GLOBALS['nav_depth'] = '0'; $prefix = "
{--YOU_ARE_HERE--} Home"; } else { if ($return === false) $GLOBALS['nav_depth']++; @@ -381,9 +381,9 @@ function addMenuDescription ($accessLevel, $FQFN, $return = false, $output = tru $OUT = $prefix . ""); + //* DEBUG: */ print(__LINE__."*".$type.'/'.getWhat()."*
"); if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) { - //* DEBUG: */ outputHtml(__LINE__.'+'.$type."+
"); + //* DEBUG: */ print(__LINE__.'+'.$type."+
"); // Add closing div and br-tag $OUT .= "

\n"; $GLOBALS['nav_depth'] = '0'; @@ -411,7 +411,7 @@ function addMenuDescription ($accessLevel, $FQFN, $return = false, $output = tru // Adds a menu (mode = guest/member/admin/sponsor) to output function addMenu ($mode, $action, $what) { // Init some variables - $main_cnt = 0; + $main_cnt = '0'; $AND = ''; // is the menu action valid? @@ -428,12 +428,12 @@ function addMenu ($mode, $action, $what) { $result_main = SQL_QUERY_ESC("SELECT `title`, `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$AND." ORDER BY `sort` ASC", array($mode), __FUNCTION__, __LINE__); - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.':'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*
"); if (SQL_NUMROWS($result_main) > 0) { // There are menus available, so we simply display them... :) $GLOBALS['rows'] = ''; while ($content = SQL_FETCHARRAY($result_main)) { - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].':'.getWhat()."*
"); // Init variables enableBlockMode(false); $action = $content['action']; @@ -451,7 +451,7 @@ function addMenu ($mode, $action, $what) { // Do we have some entries? if ($totalWhats > 0) { // Init counter - $cnt = 0; + $cnt = '0'; // Load all sub menus while ($content2 = SQL_FETCHARRAY($result_sub)) { @@ -462,7 +462,7 @@ function addMenu ($mode, $action, $what) { $OUT = ''; // Full file name for checking menu - //* DEBUG: */ outputHtml(__LINE__.":!!!!".$content['sub_what']."!!!
"); + //* DEBUG: */ print(__LINE__.":!!!!".$content['sub_what']."!!!
"); $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']); if (isIncludeReadable($inc)) { // Mark currently selected menu - open @@ -517,17 +517,17 @@ function addMenu ($mode, $action, $what) { if (isFileReadable($INC)) { // Load include file if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode); - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*
"); loadInclude($INC); - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.getWhat()."*
"); if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode); } - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*
"); } $main_cnt++; - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.':'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.':'.getWhat()."*
"); if (SQL_NUMROWS($result_main) > $main_cnt) { // Add seperator $GLOBALS['rows'] .= loadTemplate('menu_seperator', true, $mode); @@ -562,7 +562,7 @@ function addMenu ($mode, $action, $what) { ); // Load main template - //* DEBUG: */ outputHtml(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*
"); + //* DEBUG: */ print(__LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*
"); loadTemplate('menu_table', false, $content); } // END - if } @@ -580,54 +580,47 @@ function isMember () { if (isset($GLOBALS['is_member'])) { // Then return it return $GLOBALS['is_member']; - } // END - if + } elseif (getMemberId() == '0') { + // No member + return false; + } else { + // Transfer userid=>current + setCurrentUserid(getMemberId()); + } - // Init global 'status' - $GLOBALS['status'] = false; + // Init global user data array + initUserData(); // Fix "deleted" cookies first fixDeletedCookies(array('userid', 'u_hash')); // Are cookies set? - if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) { + if ((isMemberIdSet()) && (isSessionVariableSet('u_hash'))) { // Cookies are set with values, but are they valid? - $result = SQL_QUERY_ESC("SELECT `password`, `status`, `last_module`, `last_online` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", - array(getUserId()), __FUNCTION__, __LINE__); - if (SQL_NUMROWS($result) == 1) { - // Load data from cookies - list($password, $GLOBALS['status'], $mod, $onl) = SQL_FETCHROW($result); - + if (fetchUserData(getMemberId()) === true) { // Validate password by created the difference of it and the secret key - $valPass = generatePassString($password); + $valPass = generatePassString(getUserData('password')); // Transfer last module and online time - if ((!empty($mod)) && (empty($GLOBALS['last_online']['module']))) { - // @TODO Try to rewrite this to one or more functions - $GLOBALS['last_online']['module'] = $mod; - $GLOBALS['last_online']['online'] = $onl; - } // END - if + $GLOBALS['last_online']['module'] = getUserData('last_module'); + $GLOBALS['last_online']['online'] = getUserData('last_online'); // So did we now have valid data and an unlocked user? - if (($GLOBALS['status'] == 'CONFIRMED') && ($valPass == getSession('u_hash'))) { + if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) { // Account is confirmed and all cookie data is valid so he is definely logged in! :-) $ret = true; } else { // Maybe got locked etc. - //* DEBUG: */ outputHtml(__LINE__."!!!
"); - destroyUserSession(); + logDebugMessage(__FUNCTION__, __LINE__, 'status=' . getUserData('status')); + destroyMemberSession(); } } else { // Cookie data is invalid! - //* DEBUG: */ outputHtml(__LINE__."***
"); - destroyUserSession(); + destroyMemberSession(); } - - // Free memory - SQL_FREERESULT($result); } else { // Cookie data is invalid! - //* DEBUG: */ outputHtml(__LINE__."///
"); - destroyUserSession(); + destroyMemberSession(); } // Cache status @@ -637,63 +630,147 @@ function isMember () { return $ret; } +// Fetch user data for given user id +function fetchUserData ($userid, $column='userid') { + // If we should look for userid secure&set it here + if (substr($column, -2, 2) == 'id') { + // Secure userid + $userid = bigintval($userid); + + // Set it here + setCurrentUserId($userid); + + // Don't look for invalid userids... + if ($userid < 1) { + // Invalid, so abort here + debug_report_bug('User id ' . $userid . ' is invalid.'); + } elseif (isUserDataValid()) { + // Use cache, so it is fine + return true; + } + } elseif (isUserDataValid()) { + // Use cache, so it is fine + return true; + } + + + // By default none was found + $found = false; + + // Query for the user + $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1", + array($column, $userid), __FUNCTION__, __LINE__); + + // Do we have a record? + if (SQL_NUMROWS($result) == 1) { + // Load data from cookies + $data = SQL_FETCHARRAY($result); + + // Set the userid for later use + setCurrentUserId($data['userid']); + $GLOBALS['user_data'][getCurrentUserId()] = $data; + + // Rewrite 'last_failure' if found + if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) { + // Backup the raw one and zero it + $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure']; + $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = '0'; + + // Is it not zero? + if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') { + // Seperate data/time + $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']); + + // Seperate data and time again + $array['date'] = explode('-', $array[0]); + $array['time'] = explode(':', $array[1]); + + // Now pass it to mktime() + $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime( + $array['time'][0], + $array['time'][1], + $array['time'][2], + $array['date'][1], + $array['date'][2], + $array['date'][0] + ); + } // END - if + } // END - if + + // Found, but valid? + $found = isUserDataValid(); + } // END - if + + // Free memory + SQL_FREERESULT($result); + + // Return result + return $found; +} + // This patched function will reduce many SELECT queries for the specified or current admin login function isAdmin ($admin = '') { // Init variables $ret = false; $passCookie = ''; $valPass = ''; - //* DEBUG: */ outputHtml(__LINE__."ADMIN:".$admin."
"); + //* DEBUG: */ print(__FUNCTION__.':'.$admin.'
'); // If admin login is not given take current from cookies... if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) { // Get admin login and password from session/cookies $admin = getSession('admin_login'); $passCookie = getSession('admin_md5'); - } - //* DEBUG: */ outputHtml(__LINE__."ADMIN:".$admin.'/'.$passCookie."
"); + } // END - if + //* DEBUG: */ print(__FUNCTION__.':'.$admin.'/'.$passCookie.'
'); - // Search in array for entry - if (isset($GLOBALS['admin_hash'])) { - // Use cached string - $valPass = $GLOBALS['admin_hash']; - } elseif ((!empty($passCookie)) && (isset($GLOBALS['cache_array']['admins']['password'][$admin])) && (!empty($admin))) { - // Login data is valid or not? - $valPass = generatePassString($GLOBALS['cache_array']['admins']['password'][$admin]); + // Do we have cache? + if (!isset($GLOBALS['is_admin'][$admin])) { + // Init it with failed + $GLOBALS['is_admin'][$admin] = false; + + // Search in array for entry + if (isset($GLOBALS['admin_hash'])) { + // Use cached string + $valPass = $GLOBALS['admin_hash']; + } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) { + // Login data is valid or not? + $valPass = generatePassString(getAdminHash($admin)); + + // Cache it away + $GLOBALS['admin_hash'] = $valPass; + + // Count cache hits + incrementStatsEntry('cache_hits'); + } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) { + // Search for admin + $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1", + array($admin), __FUNCTION__, __LINE__); - // Cache it away - $GLOBALS['admin_hash'] = $valPass; + // Is he admin? + $passDB = ''; + if (SQL_NUMROWS($result) == 1) { + // Admin login was found so let's load password from DB + list($passDB) = SQL_FETCHROW($result); - // Count cache hits - incrementStatsEntry('cache_hits'); - } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (!isset($GLOBALS['cache_array']['admins']['password'][$admin]))) { - // Search for admin - $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1", - array($admin), __FUNCTION__, __LINE__); + // Temporary cache it + setAdminHash($admin, $passDB); - // Is he admin? - $passDB = ''; - if (SQL_NUMROWS($result) == 1) { - // Admin login was found so let's load password from DB - list($passDB) = SQL_FETCHROW($result); + // Generate password hash + $valPass = generatePassString($passDB); + } // END - if - // Temporary cache it - $GLOBALS['cache_array']['admins']['password'][$admin] = $passDB; + // Free memory + SQL_FREERESULT($result); + } - // Generate password hash - $valPass = generatePassString($passDB); + if (!empty($valPass)) { + // Check if password is valid + //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'
'); + $GLOBALS['is_admin'][$admin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache')))); } // END - if - - // Free memory - SQL_FREERESULT($result); - } - - if (!empty($valPass)) { - // Check if password is valid - //* DEBUG: */ outputHtml(__FUNCTION__."*".$valPass.'/'.$passCookie."*
"); - $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == "*FAILED*") && (!isExtensionActive('cache')))); } // END - if // Return result of comparision - return $ret; + return $GLOBALS['is_admin'][$admin]; } // Generates a list of "max receiveable emails per day" @@ -766,9 +843,9 @@ function isEmailTaken ($email) { } // Validate the given menu action -function isMenuActionValid ($mode, $action, $what, $UPDATE=false) { +function isMenuActionValid ($mode, $action, $what, $updateEntry=false) { // Is the cache entry there and we shall not update? - if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($UPDATE === false)) { + if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) { // Count cache hit incrementStatsEntry('cache_hits'); @@ -783,8 +860,8 @@ function isMenuActionValid ($mode, $action, $what, $UPDATE=false) { $add = ''; if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'"; - //* DEBUG: */ outputHtml(__LINE__.':'.$mode.'/'.$action.'/'.$what."*
"); - if (($mode != 'admin') && ($UPDATE === true)) { + //* DEBUG: */ print(__LINE__.':'.$mode.'/'.$action.'/'.$what."*
"); + if (($mode != 'admin') && ($updateEntry === true)) { // Update guest or member menu $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1", array($mode, $action, $what), __FUNCTION__, __LINE__, false); @@ -800,7 +877,9 @@ function isMenuActionValid ($mode, $action, $what, $UPDATE=false) { // Run SQL command $result = SQL_QUERY($sql, __FUNCTION__, __LINE__); - if ($UPDATE === true) { + + // Should we look for affected rows (only update) or found rows? + if ($updateEntry === true) { // Check updated/affected rows $ret = (SQL_AFFECTEDROWS() == 1); } else { @@ -818,24 +897,22 @@ function isMenuActionValid ($mode, $action, $what, $UPDATE=false) { return $ret; } -// +// Send out mails depending on the 'mod/modes' combination +// @TODO Lame description for this function function sendModeMails ($mod, $modes) { // Load hash - $result_main = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1", - array(getUserId()), __FUNCTION__, __LINE__); - if (SQL_NUMROWS($result_main) == 1) { - // Load hash from database - list($hashDB) = SQL_FETCHROW($result_main); - + if (fetchUserData(getMemberId())) { // Extract salt from cookie $salt = substr(getSession('u_hash'), 0, -40); // Now let's compare passwords - $hash = generatePassString($hashDB); + $hash = generatePassString(getUserData('password')); + + // Does the hash match or should we change it? if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) { // Load user's data 0 1 2 3 4 5 6 7 $result = SQL_QUERY_ESC("SELECT gender, surname, family, street_nr, country, zip, city, email FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND password='%s' LIMIT 1", - array(getUserId(), $hashDB), __FUNCTION__, __LINE__); + array(getMemberId(), getUserData('password')), __FUNCTION__, __LINE__); if (SQL_NUMROWS($result) == 1) { // Load the data $content = SQL_FETCHARRAY($result, 0, false); @@ -847,7 +924,7 @@ function sendModeMails ($mod, $modes) { $content['gender'] = translateGender($content['gender']); // Clear/init the content variable - $content['info'] = ''; + $content['message'] = ''; switch ($mod) { case 'mydata': @@ -864,10 +941,10 @@ function sendModeMails ($mod, $modes) { default: logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode)); - $content['message'] = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n"; + $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n"; break; } // END - switch - } // END - if + } // END - foreach if (isExtensionActive('country')) { // Replace code with description @@ -878,7 +955,7 @@ function sendModeMails ($mod, $modes) { $content = merge_array($content, postRequestArray()); // Load template - $message = loadEmailTemplate('member_mydata_notify', $content, getUserId()); + $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId()); if (getConfig('admin_notify') == 'Y') { // The admin needs to be notified about a profile change @@ -925,7 +1002,7 @@ function sendModeMails ($mod, $modes) { if (empty($content)) { if ((!empty($sub_adm)) && (!empty($message_admin))) { // Send admin mail - sendAdminNotification($sub_adm, $message_admin, $content, getUserId()); + sendAdminNotification($sub_adm, $message_admin, $content, getMemberId()); } elseif (getConfig('admin_notify') == 'Y') { // Cannot send mails to admin! $content = getMessage('CANNOT_SEND_ADMIN_MAILS'); @@ -939,19 +1016,12 @@ function sendModeMails ($mod, $modes) { loadTemplate('admin_settings_saved', false, $content); } -// Update module counter -function countModuleHit($mod) { - // Do count all other modules but not accesses on CSS file css.php! - SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1", - array($mod), __FUNCTION__, __LINE__); -} - // Get action value from mode (admin/guest/member) and what-value function getModeAction ($mode, $what) { // Init status $ret = ''; - //* DEBUG: */ outputHtml(__LINE__.'='.$mode.'/'.$what.'/'.getAction()."=
"); + //* DEBUG: */ print(__LINE__.'='.$mode.'/'.$what.'/'.getAction()."=
"); if ((empty($what)) && ($mode != 'admin')) { $what = getConfig('index_home'); } // END - if @@ -972,7 +1042,7 @@ function getModeAction ($mode, $what) { // Get it directly from URL return getAction(); } - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."): ret=".$ret."
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."): ret=".$ret.'
'); // Does the module have a menu? if (ifModuleHasMenu($mode)) { @@ -995,9 +1065,8 @@ function getModeAction ($mode, $what) { } elseif ((!isExtensionInstalled('sql_patches')) && ($mode != 'admin')) { // No sql_patches installed, but maybe we need to register an admin? if (isAdminRegistered()) { - // Redirect - // @TODO Why does this lead into an endless loop but we still need it??? - // @TODO Commented out redirectToUrl('admin.php'); + // Redirect to admin area + redirectToUrl('admin.php'); } // END - if } @@ -1080,7 +1149,7 @@ function getPaymentPoints ($pid, $lookFor = 'price') { return $ret; } -// Remove a receiver's ID from $receivers and add a link for him to confirm +// Remove a receiver's id from $receivers and add a link for him to confirm function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) { // Default is not removed $ret = 'failed'; @@ -1092,7 +1161,7 @@ function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $ // Is there already a line for this user available? if ($stats_id > 0) { - // Only when we got a real stats ID continue searching for the entry + // Only when we got a real stats id continue searching for the entry $type = 'NORMAL'; $rowName = 'stats_id'; if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; } @@ -1101,7 +1170,7 @@ function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $ array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__); // Was it *not* found? - if (SQL_NUMROWS($result) == 0) { + if (SQL_NUMROWS($result) == '0') { // So we add one! SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES ('%s','%s','%s')", array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__); @@ -1122,8 +1191,8 @@ function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $ // Calculate sum (default) or count records of given criteria function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '') { - $ret = 0; - //* DEBUG: */ outputHtml($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'
'); + $ret = '0'; + //* DEBUG: */ print($search.'/'.$tableName.'/'.$lookFor.'/'.$whereStatement.'/'.$add.'
'); if ((empty($search)) && ($search != '0')) { // Count or sum whole table? if ($countRows === true) { @@ -1137,12 +1206,12 @@ function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatemen } } elseif (($countRows === true) || ($lookFor == 'userid')) { // Count rows - //* DEBUG: */ outputHtml("COUNT!
"); + //* DEBUG: */ print("COUNT!
"); $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add, array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__); } else { // Add all rows - //* DEBUG: */ outputHtml("SUM!
"); + //* DEBUG: */ print("SUM!
"); $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s'".$add, array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__); } @@ -1163,27 +1232,28 @@ function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatemen } // Return value + //* DEBUG: */ print 'ret='.$ret.'
'; return $ret; } // Getter fro ref level percents function getReferalLevelPercents ($level) { // Default is zero - $per = 0; + $per = '0'; // Do we have cache? - if ((isset($GLOBALS['cache_array']['ref_depths']['level'])) && (isExtensionActive('cache'))) { + if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) { // First look for level - $key = array_search($level, $GLOBALS['cache_array']['ref_depths']['level']); + $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']); if ($key !== false) { // Entry found! - $per = $GLOBALS['cache_array']['ref_depths']['percents'][$key]; + $per = $GLOBALS['cache_array']['refdepths']['percents'][$key]; // Count cache hit incrementStatsEntry('cache_hits'); - } + } // END - if } elseif (!isExtensionActive('cache')) { // Get referal data - $result_level = SQL_QUERY_ESC("SELECT percents FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE level='%s' LIMIT 1", + $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`='%s' LIMIT 1", array(bigintval($level)), __FUNCTION__, __LINE__); // Entry found? @@ -1205,7 +1275,7 @@ function getReferalLevelPercents ($level) { * Dynamic referal system, can also send mails! * * subject = Subject line, write in lower-case letters and underscore is allowed - * userid = Referal ID wich should receive... + * userid = Referal id wich should receive... * points = ... xxx points * sendNotify = shall I send the referal an email or not? * rid = inc/modules/guest/what-confirm.php need this @@ -1214,11 +1284,11 @@ function getReferalLevelPercents ($level) { * for default value will cause no referal will get points ever!!!) */ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify = false, $rid = '0', $locked = false, $add_mode = 'ref') { - //* DEBUG: */ outputHtml("----------------------- ".__FUNCTION__." - ENTRY ----------------------------------------------- ".__FUNCTION__." - EXIT ------------------------
"); } // Updates the referal counter function updateReferalCounter ($userid) { // Make it sure referal level zero (member him-/herself) is at least selected if (empty($GLOBALS['cache_array']['ref_level'][$userid])) $GLOBALS['cache_array']['ref_level'][$userid] = 1; - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):userid={$userid},level={$GLOBALS['cache_array']['ref_level'][$userid]}
"); // Update counter SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`='%s' LIMIT 1", array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__); // When no entry was updated then we have to create it here - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):updated=".SQL_AFFECTEDROWS()."
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):updated=".SQL_AFFECTEDROWS().'
'); if (SQL_AFFECTEDROWS() < 1) { // First count! SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)", array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__); - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):userid={$userid}
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):userid={$userid}
"); } // END - if - // Check for his referal - $result = SQL_QUERY_ESC("SELECT `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", - array(bigintval($userid)), __FUNCTION__, __LINE__); + // Init referal id + $ref = '0'; - // Load refid - list($ref) = SQL_FETCHROW($result); + // Check for his referal + if (fetchUserData($userid)) { + // Get it + $ref = getUserData('refid'); + } // END - if - // Free memory - SQL_FREERESULT($result); - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):userid={$userid},ref={$ref}
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):userid={$userid},ref={$ref}
"); // When he has a referal... if (($ref > 0) && ($ref != $userid)) { // Move to next referal level and count his counter one up! - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):ref={$ref} - ADVANCE!
"); - $GLOBALS['cache_array']['ref_level'][$userid]++; updateReferalCounter($ref); - } elseif ((($ref == $userid) || ($ref == 0)) && (getExtensionVersion('cache') >= '0.1.2')) { + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):ref={$ref} - ADVANCE!
"); + $GLOBALS['cache_array']['ref_level'][$userid]++; + updateReferalCounter($ref); + } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) { // Remove cache here - //* DEBUG: */ outputHtml(__FUNCTION__."(".__LINE__."):ref={$ref} - CACHE!
"); + //* DEBUG: */ print(__FUNCTION__."(".__LINE__."):ref={$ref} - CACHE!
"); rebuildCacheFile('refsystem', 'refsystem'); } @@ -1406,15 +1471,15 @@ function sendAdminEmails ($subj, $message) { // Really simple... ;-) } -// Get ID number from administrator's login name +// Get id number from administrator's login name function getAdminId ($login) { // By default no admin is found $ret = '-1'; // Check cache - if (isset($GLOBALS['cache_array']['admins']['admin_id'][$login])) { + if (isset($GLOBALS['cache_array']['admin']['admin_id'][$login])) { // Use it if found to save SQL queries - $ret = $GLOBALS['cache_array']['admins']['admin_id'][$login]; + $ret = $GLOBALS['cache_array']['admin']['admin_id'][$login]; // Update cache hits incrementStatsEntry('cache_hits'); @@ -1451,26 +1516,26 @@ function getCurrentAdminId () { } // Get password hash from administrator's login name -function getAdminHash ($adminId) { +function getAdminHash ($admin) { // By default an invalid hash is returned $ret = '-1'; - if (isset($GLOBALS['cache_array']['admins']['password'][$adminId])) { + if (isAdminHashSet($admin)) { // Check cache - $ret = $GLOBALS['cache_array']['admins']['password'][$adminId]; + $ret = $GLOBALS['cache_array']['admin']['password'][$admin]; // Update cache hits incrementStatsEntry('cache_hits'); } elseif (!isExtensionActive('cache')) { // Load from database $result = SQL_QUERY_ESC("SELECT password FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1", - array($adminId), __FUNCTION__, __LINE__); + array($admin), __FUNCTION__, __LINE__); if (SQL_NUMROWS($result) == 1) { // Fetch data list($ret) = SQL_FETCHROW($result); // Set cache - $GLOBALS['cache_array']['admins']['password'][$adminId] = $ret; + setAdminHash($admin, $ret); } // END - if // Free result @@ -1484,9 +1549,9 @@ function getAdminLogin ($adminId) { // By default a non-existent login is returned (other functions react on this!) $ret = '***'; - if (isset($GLOBALS['cache_array']['admins']['login'][$adminId])) { + if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) { // Get cache - $ret = $GLOBALS['cache_array']['admins']['login'][$adminId]; + $ret = $GLOBALS['cache_array']['admin']['login'][$adminId]; // Update cache hits incrementStatsEntry('cache_hits'); @@ -1499,7 +1564,7 @@ function getAdminLogin ($adminId) { list($ret) = SQL_FETCHROW($result); // Set cache - $GLOBALS['cache_array']['admins']['login'][$adminId] = $ret; + $GLOBALS['cache_array']['admin']['login'][$adminId] = $ret; } // END - if // Free memory @@ -1513,9 +1578,9 @@ function getAdminEmail ($adminId) { // By default an invalid emails is returned $ret = '***'; - if (isset($GLOBALS['cache_array']['admins']['email'][$adminId])) { + if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) { // Get cache - $ret = $GLOBALS['cache_array']['admins']['email'][$adminId]; + $ret = $GLOBALS['cache_array']['admin']['email'][$adminId]; // Update cache hits incrementStatsEntry('cache_hits'); @@ -1528,7 +1593,7 @@ function getAdminEmail ($adminId) { list($ret) = SQL_FETCHROW($result_admin_id); // Set cache - $GLOBALS['cache_array']['admins']['email'][$adminId] = $ret; + $GLOBALS['cache_array']['admin']['email'][$adminId] = $ret; } // END - if // Free result @@ -1548,9 +1613,9 @@ function getAdminDefaultAcl ($adminId) { if (!isExtensionActive('sql_patches')) { // Not found, which is bad, so we need to allow all $ret = 'allow'; - } elseif (isset($GLOBALS['cache_array']['admins']['def_acl'][$adminId])) { + } elseif (isset($GLOBALS['cache_array']['admin']['def_acl'][$adminId])) { // Use cache - $ret = $GLOBALS['cache_array']['admins']['def_acl'][$adminId]; + $ret = $GLOBALS['cache_array']['admin']['def_acl'][$adminId]; // Update cache hits incrementStatsEntry('cache_hits'); @@ -1563,7 +1628,7 @@ function getAdminDefaultAcl ($adminId) { list($ret) = SQL_FETCHROW($result_admin_id); // Set cache - $GLOBALS['cache_array']['admins']['def_acl'][$adminId] = $ret; + $GLOBALS['cache_array']['admin']['def_acl'][$adminId] = $ret; } // Free result @@ -1620,7 +1685,7 @@ function generateOptionList ($table, $id, $name, $default='', $special='', $wher // Activate exchange function FILTER_ACTIVATE_EXCHANGE () { // Is the extension 'user' there? - if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == 0)) { + if ((!isExtensionActive('user')) || (getConfig('activate_xchange') == '0')) { // Silently abort here return false; } // END - if @@ -1642,18 +1707,24 @@ function FILTER_ACTIVATE_EXCHANGE () { updateConfiguration('activate_xchange' ,0); // Rebuild cache - rebuildCacheFile('modreg', 'modreg'); + rebuildCacheFile('modules', 'modules'); } // END - if } // Deletes a user account with given reason function deleteUserAccount ($userid, $reason) { - $points = 0; - $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points -FROM `{?_MYSQL_PREFIX?}_user_points` AS p -LEFT JOIN `{?_MYSQL_PREFIX?}_user_data` AS d -ON p.userid=d.userid -WHERE p.userid=%s", array(bigintval($userid)), __FUNCTION__, __LINE__); + $points = '0'; + $result = SQL_QUERY_ESC("SELECT + (SUM(p.points) - d.used_points) AS points +FROM + `{?_MYSQL_PREFIX?}_user_points` AS p +LEFT JOIN + `{?_MYSQL_PREFIX?}_user_data` AS d +ON + p.userid=d.userid +WHERE + p.userid=%s", + array(bigintval($userid)), __FUNCTION__, __LINE__); if (SQL_NUMROWS($result) == 1) { // Save his points to add them to the jackpot list($points) = SQL_FETCHROW($result); @@ -1662,7 +1733,7 @@ WHERE p.userid=%s", array(bigintval($userid)), __FUNCTION__, __LINE__); SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s", array(bigintval($userid)), __FUNCTION__, __LINE__); // Update mediadata as well - if (getExtensionVersion('mediadata') >= '0.0.4') { + if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) { // Update database updateMediadataEntry(array('total_points'), 'sub', $points); } // END - if @@ -1718,7 +1789,7 @@ function getWhatFromModule ($modCheck) { // Default is empty $what = ''; - //* DEBUG: */ outputHtml(__LINE__.'!'.$modCheck."!
"); + //* DEBUG: */ print(__LINE__.'!'.$modCheck."!
"); switch ($modCheck) { case 'admin': $what = 'overview'; @@ -1726,7 +1797,14 @@ function getWhatFromModule ($modCheck) { case 'login': case 'index': - $what = getConfig('index_home'); + // Is ext-sql_patches installed and newer than 0.0.5? + if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) { + // Use it from config + $what = getConfig('index_home'); + } else { + // Use default 'welcome' + $what = 'welcome'; + } break; default: @@ -1791,7 +1869,10 @@ function generateCategoryOptionsList ($mode) { ); // Get categories - $result = SQL_QUERY("SELECT id, cat FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__); + $result = SQL_QUERY("SELECT `id`, `cat` FROM `{?_MYSQL_PREFIX?}_cats`".$whereStatement." ORDER BY `sort` ASC", + __FUNCTION__, __LINE__); + + // Do we have entries? if (SQL_NUMROWS($result) > 0) { // ... and begin loading stuff while ($content = SQL_FETCHARRAY($result)) { @@ -1804,7 +1885,7 @@ function generateCategoryOptionsList ($mode) { array(bigintval($content['id'])), __FUNCTION__, __LINE__); // Start adding all - $userid_cnt = 0; + $userid_cnt = '0'; // @TODO Rewrite this to $content = SQL_FETCHARRAY() while (list($ucat) = SQL_FETCHROW($result_userids)) { $result_ver = SQL_QUERY_ESC("SELECT @@ -1812,7 +1893,9 @@ function generateCategoryOptionsList ($mode) { FROM `{?_MYSQL_PREFIX?}_user_data` WHERE - `userid`=%s AND `status`='CONFIRMED' AND `receive_mails` > 0".runFilterChain('exclude_users', $mode)." + `userid`=%s AND + `status`='CONFIRMED' AND + `receive_mails` > 0".runFilterChain('exclude_users', $mode)." LIMIT 1", array(bigintval($ucat)), __FUNCTION__, __LINE__); @@ -1863,7 +1946,7 @@ function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $target = countSelection(explode(';', $receiverList)); // Receiver is zero? - if ($receiver == 0) { + if ($receiver == '0') { // Then auto-fix it $receiver = $target; } // END - if @@ -1914,7 +1997,7 @@ VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')", // Generate a receiver list for given category and maximum receivers function generateReceiverList ($cat, $receiver, $mode = '') { // Init variables - $CAT_TABS = "%s"; + $CAT_TABS = ''; $CAT_WHERE = ''; $receiverList = ''; $result = false; @@ -1924,7 +2007,7 @@ function generateReceiverList ($cat, $receiver, $mode = '') { $receiver = bigintval($receiver); // Is the receiver zero and mode set? - if (($receiver == 0) && (!empty($mode))) { + if (($receiver == '0') && (!empty($mode))) { // Auto-fix receiver maximum $receiver = getTotalReceivers($mode); } // END - if @@ -1933,7 +2016,7 @@ function generateReceiverList ($cat, $receiver, $mode = '') { if ($cat > 0) { // Select category $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid"; - $CAT_WHERE = " AND c.cat_id=%s"; + $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat); } // END - if // Exclude users in holiday? @@ -1944,12 +2027,16 @@ function generateReceiverList ($cat, $receiver, $mode = '') { if ((isExtensionActive('html_mail')) && ($mode == 'html')) { // Only include HTML receivers - $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.%s %s LIMIT %s", - array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__); + $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", + array( + $receiver + ), __FUNCTION__, __LINE__); } else { // Include all - $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.%s %s LIMIT %s", - array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__); + $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", + array( + $receiver + ), __FUNCTION__, __LINE__); } // Entries found? @@ -1972,13 +2059,13 @@ function generateReceiverList ($cat, $receiver, $mode = '') { } // Get timestamp for given stats type and data -function getTimestampFromUserStats ($type, $data, $userid = 0) { +function getTimestampFromUserStats ($type, $data, $userid = '0') { // Default timestamp is zero - $stamp = 0; + $stamp = '0'; // User id set? - if ((isUserIdSet()) && ($userid == 0)) { - $userid = getUserId(); + if ((isMemberIdSet()) && ($userid == '0')) { + $userid = getMemberId(); } // END - if // Is the extension installed and updated? @@ -2035,7 +2122,7 @@ function insertUserStatsRecord ($userid, $type, $data) { // "Getter" for array for user refs and points in given level function getUserReferalPoints ($userid, $level) { - //* DEBUG: */ outputHtml("----------------------- ".__FUNCTION__." - ENTRY ----------------------------------------------- ".__FUNCTION__." - EXIT ------------------------
"); return $refs; } @@ -2137,10 +2224,22 @@ function reduceRecipientReceivedMails ($column, $id, $count) { } // Creates a new task -function createNewTask ($subject, $notes, $taskType, $userid = 0, $adminId = 0, $strip = true) { +function createNewTask ($subject, $notes, $taskType, $userid = '0', $adminId = '0', $strip = true) { // Insert the task data into the database 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())", - array($adminId, $userid, $taskType, $subject, smartAddSlashes($notes)), __FUNCTION__, __LINE__, true, $strip); + array($adminId, $userid, $taskType, $subject, escapeQuotes($notes)), __FUNCTION__, __LINE__, true, $strip); +} + +// Updates last module / online time +// @TODO Fix inconsistency between last_module and getWhat() +function updateLastActivity($userid) { + // Run the update query + SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1", + array( + getWhat(), + detectRemoteAddr(), + bigintval($userid) + ), __FUNCTION__, __LINE__); } // [EOF]