$value) { $cgi[$key] = $value; } foreach ($_GET as $key => $value) { $cgi[$key] = $value; } // Two connections - one auto-commits, the other does not. // Mysqli2 is explicitly cut at the end of the file. $mysqli = new mysqli($conf["path"], $conf["sites_database_login"], $conf["sites_database_password"], $conf["sites_database_name"]); $mysqli2 = new mysqli($conf["path"], $conf["sites_database_login"], $conf["sites_database_password"], $conf["sites_database_name"]); $mysqli2->autocommit(FALSE); if (isset($_SESSION['SGWOriginLoggedIn2'])) { include "i_r0_lib.php"; include "i_r1_lib.php"; include "i_r2_lib.php"; include "i_r3_lib.php"; include "i_r4_lib.php"; } if (isset($_SESSION['SGWOriginLoggedIn'])) { $sN = $_SERVER['SCRIPT_NAME']; if (($sN == $conf["path"].'/index.php') || ($sN == $conf["path"].'/register.php') || ($sN == $conf["path"].'/activate.php') || ($sN == $conf["path"].'/forgotpass.php')) { header("Location: base.php"); exit; } } //-------------------------------------------- FUNCTIONS ------------------------------ function pin($var) { echo $var; } function micro_time() { return round(1000 * microtime(TRUE)); } function timePassed($time) { $currentTime = time(); return $currentTime - $time; } function timeAgo($time) { $timeAgo = timePassed($time); if ($timeAgo > 60 * 60 * 24 * 7) { return date("M jS Y", $time); } elseif ($timeAgo > 60 * 60 * 24) { return floor($timeAgo / (60 * 60 * 24))." day".(floor($timeAgo / (60 * 60 * 24)) == 1 ? "" : "s")." ago"; } elseif ($timeAgo > 60 * 60) { return floor($timeAgo / (60 * 60))." hour".(floor($timeAgo / (60 * 60)) == 1 ? "" : "s")." ago"; } elseif ($timeAgo > 60) { return floor($timeAgo / (60))." minute".(floor($timeAgo / (60)) == 1 ? "" : "s")." ago"; } else { return $timeAgo." second".($timeAgo == 1 ? "" : "s")." ago"; } } function updateActivityLog($Activity, $FromID, $ToID = 0, $Amount = 0) { global $mysqli, $browser, $ip_of_user_on; $now = microtime(); $activity_log = array("Activity" => $Activity, "FromID" => $FromID, "ToID" => $ToID, "Amount" => $Amount); $query = " INSERT INTO `Log__Activity` ( `IP`, `Activity`, `FromID`, `ToID`, `Amount`, `Time`, `referer`, `browser`) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? ) "; $stmt = $mysqli->prepare($query); $stmt->bind_param("ssiiisss", $ip_of_user_on, $activity_log["Activity"], $activity_log["FromID"], $activity_log["ToID"], $activity_log["Amount"], $now, $_SERVER["HTTP_REFERER"], $browser); $result = $stmt->execute(); return $result; } function alert($msg) { echo ""; } //----------------------------Arrays--------------------------------------------------- function array_sort($array, $on, $order = SORT_ASC) { $new_array = array(); $sortable_array = array(); if (count($array) > 0) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k => $v) { $new_array[$k] = $array[$k]; } } return $new_array; } //----------------------------Arrays: END---------------------------------------------- //----------------------------Strings-------------------------------------------------- function stripText($info, $tagsAllowed = "
") { $info = strip_tags($info, $tagsAllowed); $info = str_replace(chr(13), "
", $info); $info = str_replace(chr(12), "    ", $info); $info = str_replace(array("\\r\\n", "\\r", "\\n"), "
", $info); $info = str_replace("'", "'", $info); $info = str_replace('"', """, $info); $info = stripslashes($info); return $info; } //----------------------------Strings: END--------------------------------------------- //----------------------------Validations---------------------------------------------- function heavy_sanitize($string) { return preg_replace("[^[:space:]a-zA-Z0-9*_.-]", "", $string); } function number_sanitize($string) { $string = substr($string, 0, 15); return preg_replace("[^0-9]", "", $string); } function numberCheck($input) { $input = substr($input, 0, 11); //if (eregi("^[0-9]*$",$input)) {//old if (preg_match("^\-?[0-9]+\.?[0-9]*$", $input)) { return TRUE; } return FALSE; } function az_sanitize($string) { return preg_replace("[^0-9a-zA-Z]", "", $string); } function very_lite_sanitize($input_text) { $bad_chars = array("&", "script", "?", "@", "java", "=", ",", "+", "-", "*", "^", "'", "frame", "load", "click", "oilfight", "atlanteanwars", "hellwars",); $replace_chars = array(" and ", "_", "_", "_", "_", "_", "_", "", "", "", "", "_", "", "", "", "stargatewars", "atlanteanwar", "stargatewars"); $text_return = str_replace($bad_chars, $replace_chars, $input_text); $text_return = strip_tags($text_return, '
'); $text_return = nl2br($text_return); return $text_return; } function lite_sanitize($input_text) { $bad_chars = array("&", "script", "/", "?", "@", "http", "java", "=", ",", "+", "-", "*", "^", ".", "'", "frame", "oilfight", "atlanteanwars", "hellwars"); $replace_chars = array(" and ", "_", "_", "_", "_", "_", "_", "_", "_", "", "", "", "", "", "_", "", "stargatewars", "atlanteanwars", "stargatewars"); $text_return = str_replace($bad_chars, $replace_chars, $input_text); $text_return = strip_tags($text_return, '
'); $text_return = nl2br($text_return); return $text_return; } function sanitize($input_text) { //$bad_chars = array("$","'","{","}","#","@","%","*","=","/","\","html","<",">","php","~","update","set","where","ID","userName","&","delete"); $bad_chars = array("java", "Java", "JAVA", "&", "select", "delete", "insert", "where", "userName", "SELECT", "DELETE", "INSERT", "WHERE", "USERNAME", "html", "fuck", "fuk", "shit", "bastard", "cunt", "whore", "nigger", "niger", "dick", "penis", "slut", "asshole", "asswipe", "oilfight", "atlanteanwars", "hellwars"); //$replace_chars = array("money"," ","-","-","-","-","-","-","-","-","-","webcode"," less than "," greater than ","code","-","change","sets","whereabouts","I.D.","User Name"," and ", "eliminate"); $replace_chars = array("code", "code", "code", " and ", "choose", "eliminate", "add into", "whereabouts", "user name", "choose", "eliminate", "add into", "whereabouts", "user name", "web code", "****", "****", "****", "******", "****", "*****", "******", "*****", "****", "*****", "****", "*******", "*******", "stargatewars", "atlanteanwar", "stargatewars"); //$text=str_ireplace($bad_chars,$replace_chars,$text1); $text_return = str_replace($bad_chars, $replace_chars, $input_text); $text_return = strip_tags($text_return, '
'); $text_return = nl2br($text_return); return $text_return; } function checkwords($input) { if (preg_match("admin|root|java|script|\&|select|delete|insert|where.*=.*|userName|html|fuck|fuk|shit|bastard|cunt|whore|nigger|niger|dick|penis|slut|asshole|asswipe|cock|tit|twat|bitch", $input)) { return TRUE; } return FALSE; } function checkwordsSpecial($input) { if (preg_match("admin|root|java|script|select|delete|insert|where.*=.*|userName|fuck|fuk|shit|bastard|cunt|whore|nigger|niger|dick|penis|slut|asshole|asswipe|cock|tit|twat|bitch", $input)) { return TRUE; } return FALSE; } function isAlpha($var) { if (preg_match("^[a-zA-Z]*$", $var)) { return TRUE; } return FALSE; } function isAlphaNum($var) { if (preg_match("^[a-zA-Z0-9]*$", $var)) { return TRUE; } return FALSE; } function isNum($input) { //check to see if input is a number $input = substr($input, 0, 11); //if (eregi("^[0-9]*$",$input)) {//old if (preg_match("^\-?[0-9]+\.?[0-9]*$", $input)) { return TRUE; } return FALSE; } function isValid($type, $var) { $valid = FALSE; switch ($type) { case "csv": if (preg_match("^([a-zA-Z0-9 ,\.\*]*)$", $var)) { $valid = TRUE; } break; case "IP": if (preg_match('^([0-9]{1,3}\.){3}[0-9]{1,3}$', $var)) { $valid = TRUE; } break; case "URL": if (preg_match("^(https?://)([a-zA-Z0-9\.\-\_]+)(\.)([a-zA-Z0-9\-\_]+)(\.)([a-zA-Z0-9]{2,4})(/*)([a-zA-Z0-9\/\=\?\.]*)$", $var)) { $valid = TRUE; } break; case "SSN": if (preg_match("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$", $var)) { $valid = TRUE; } break; case "CC": if (preg_match("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$", $var)) { $valid = TRUE; } break; case "ISBN": if (preg_match("^[0-9]{9}[[0-9]|X|x]$", $var)) { $valid = TRUE; } break; case "Date": if (preg_match("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$", $var)) { $valid = TRUE; } break; case "Zip": if (preg_match("^[0-9]{5}(-[0-9]{4})?$", $var)) { $valid = TRUE; } break; case "Phone": if (preg_match("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$", $var)) { $valid = TRUE; } break; case "HexColor": if (preg_match('^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$', $var)) { $valid = TRUE; } break; case "User": if (preg_match("^[a-zA-Z0-9_]{3,16}$", $var)) { $valid = TRUE; } break; case "Email": if (preg_match("^([A-Za-z0-9\.|-|_]+)([@])([A-Za-z0-9\.|-|_]+)(\.)([A-Za-z]{2,4})$", $var)) { $valid = TRUE; } break; } //switch(type) return $valid; } //----------------------------Validations: END----------------------------------------- //----------------------------Game Variables------------------------------------------- //----------------------------Game Variables: GET-------------------------------------- function getOnlineUsersCount() { global $conf, $mysqli; $array = array(); $time = time() - $conf["minutes_per_turn"] * 60; $stmt = $mysqli->prepare(" SELECT COUNT(*) AS `count` FROM `User__Details` WHERE `lastTurnTime` > ? AND `active` IN (1, 3) "); $stmt->bind_param("i", $time); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } if ($result->num_rows == 0) { $array["count"] = 0; } return $array["count"]; } function getNextTurn() { global $conf; $info = getCommonInfo(); $lastTurnTime = $info["lastTurnTime"]; $thisTime = time(); $dif = $thisTime - $lastTurnTime; $nextTurnMin = $dif / 60; $nextTurn = round($nextTurnMin); $nextTurn = $conf["minutes_per_turn"] - $nextTurn; if ($nextTurn < 0) $nextTurn = 0; return $nextTurn; } function getCommonInfo() { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT * FROM `Mercenaries` "); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } return $array; } //----------------------------Game Variables: SET-------------------------------------- function updateMercenary($str) { global $mysqli; $str = " UPDATE Mercenaries SET $str WHERE 1 "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "function updateMercenary failed - q1: ".$str); } //----------------------------Game Variables: END-------------------------------------- //----------------------------User__Details---------------------------------------------- //----------------------------User__Details: GET----------------------------------------- //----------------------------User__Details: GET: USER----------------------------------- function getUserDetailsByName($name) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `User__Details` WHERE `userName` = ? "); $stmt->bind_param('s', $name); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $row["untrained"] = floor($row["untrained"]); $array = $row; $i++; } return $array; } function getUserDetailsByEmail($email) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `User__Details` WHERE `e_mail` = ? "); $stmt->bind_param('s', $email); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $row["untrained"] = floor($row["untrained"]); $array = $row; $i++; } return $array; } function getAllUserDetailsByEmail($email) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `User__Details` WHERE `e_mail` = ? "); $stmt->bind_param('s', $email); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $row["untrained"] = floor($row["untrained"]); $array[$i] = $row; $i++; } return $array; } function getUserDetails($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `User__Details` WHERE `ID` = ? "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $row["untrained"] = floor($row["untrained"]); $array = $row; $i++; } return $array; } function getUserRanks($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `User__Details` WHERE `ID` = ? "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $row["untrained"] = floor($row["untrained"]); $array = $row; $i++; } //Marked for deletion if ($result->num_rows == 0) { $array["strikeActionRank"] = "unranked"; $array["defenceActionRank"] = "unranked"; $array["covertActionRank"] = "unranked"; $array["antiCovertActionRank"] = "unranked"; $array["totalActionRank"] = "unranked"; return $array; } else { if (!$array["strikeActionRank"]) { $array["strikeActionRank"] = 'unranked'; } if (!$array["defenceActionRank"]) { $array["defenceActionRank"] = 'unranked'; } if (!$array["covertActionRank"]) { $array["covertActionRank"] = 'unranked'; } if (!$array["antiCovertActionRank"]) { $array["antiCovertActionRank"] = 'unranked'; } if (!$array["totalActionRank"]) { $array["totalActionRank"] = 'unranked'; } return $array; } } //----------------------------User__Details: GET: USER: END------------------------------ //----------------------------User__Details: GET: VALUES--------------------------------- function checkRaces($leadRace, $followRace) { global $conf; return $conf["alliance"][$leadRace][$followRace]; } function getTotalFightingForce($user) { $count = 0; $count += $user["attackers"]; $count += $user["defenders"]; $count += $user["untrained"]; $count += $user["spies"]; $count += $user["assassins"]; return $count; } //----------------------------User__Details: GET: VALUES: END---------------------------- //----------------------------User__Details: GET: ACTION--------------------------------- function getStrikeAction($user_id) { global $conf; $user = getUserDetails($user_id); $num = 0; $trainedCount = $user["attackers"]; $trainedMultiplier = $conf["trained_weaps_multiplier"]; //now cycle to get each variable count of weapon $attackWeapons = getAttackWeaponsDesc($user_id); // $weapCount = $conf["num_att_weaps"]; for ($i = 0; $i < count($attackWeapons); $i++) { $weapCount = $attackWeapons[$i]["weaponCount"]; $weapStrength = $attackWeapons[$i]["weaponStrength"]; if ($trainedCount >= $weapCount) { $num += ($weapCount * $weapStrength * $trainedMultiplier); $trainedCount -= $weapCount; $weapCount = 0; } else { $num += ($trainedCount * $weapStrength * $trainedMultiplier); $weapCount -= $trainedCount; $trainedCount = 0; } $totalCount = $trainedCount; if ($totalCount == 0) { if (!$num) { $num = 0; } break; } } if ($conf["race"][$user["race"]]["bonus_attack"]) { $num += floor(($num * $conf["race"][$user["race"]]["bonus_attack"]) / 100); } return $num; } function explainStrikeAction($user_id) { global $conf; echo "
Explain action calculation
"; $user = getUserDetails($user_id); $num = 0; $trainedCount = $user["attackers"]; echo "Initial trained units: " . number_format($trainedCount) . "
"; $trainedMultiplier = $conf["trained_weaps_multiplier"]; //now cycle to get each variable count of weapon $attackWeapons = getAttackWeaponsDesc($user_id); // $weapCount = $conf["num_att_weaps"]; for ($i = 0; $i < count($attackWeapons); $i++) { echo "Weapon contribution for weapon id " . $attackWeapons[$i]["weaponID"] . " " . $attackWeapons[$i]["isAttack"] . "
"; $weapCount = $attackWeapons[$i]["weaponCount"]; echo "Weapon count: " . number_format($weapCount) . "
"; $weapStrength = $attackWeapons[$i]["weaponStrength"]; echo "Weapon strength: " . number_format($weapStrength) . "
"; if ($trainedCount >= $weapCount) { echo "Trained Units remaining: " . number_format($trainedCount - $weapCount) . "
"; $num += ($weapCount * $weapStrength * $trainedMultiplier); echo "Power contribution: " . number_format($weapCount * $weapStrength * $trainedMultiplier) . "
"; $trainedCount -= $weapCount; } else { echo "Weapons remaining: " . number_format($weapCount - $trainedCount) . "
"; $num += ($trainedCount * $weapStrength * $trainedMultiplier); echo "Power contribution: " . number_format($trainedCount * $weapStrength * $trainedMultiplier) . "
"; $trainedCount = 0; } $totalCount = $trainedCount; if ($totalCount == 0) { if (!$num) { $num = 0; } break; } echo "
"; } if ($conf["race"][$user["race"]]["bonus_attack"]) { $num += floor(($num * $conf["race"][$user["race"]]["bonus_attack"]) / 100); } echo "
Total power: " . number_format($num) . "
"; // return $num; } function getDefenceAction($user_id) { global $conf; $user = getUserDetails($user_id); $num = 0; $trainedCount = $user["defenders"]; $trainedMultiplier = $conf["trained_weaps_multiplier"]; //now cycle to get each variable count of weapon $defenceWeapons = getDefenceWeaponsDesc($user_id); // $weapCount = $conf["num_att_weaps"]; for ($i = 0; $i < count($defenceWeapons); $i++) { $weapCount = $defenceWeapons[$i]["weaponCount"]; $weapStrength = $defenceWeapons[$i]["weaponStrength"]; if ($trainedCount >= $weapCount) { $num += ($weapCount * $weapStrength * $trainedMultiplier); $trainedCount -= $weapCount; $weapCount = 0; } else { $num += ($trainedCount * $weapStrength * $trainedMultiplier); $weapCount -= $trainedCount; $trainedCount = 0; } $totalCount = $trainedCount; if ($totalCount == 0) { if (!$num) { $num = 0; } break; } } if ($conf["race"][$user["race"]]["bonus_defend"]) { $num += floor(($num * $conf["race"][$user["race"]]["bonus_defend"]) / 100); } return $num; } function getCovertAction($user_id) { global $conf; $user = getUserDetails($user_id); $num_min = $user["currentSpySkill"]; if (!$user["spies"]) { return $num_min; } $num = $user["spies"] * pow(2, ($user["currentSpySkill"]) / 4); if ($conf["race"][$user["race"]]["bonus_spy"]) { $num += (($num * $conf["race"][$user["race"]]["bonus_spy"]) / 100); } $num = ($num / 10) + $user["spies"]; $num = round($num); return $num; } function getCovertAction_away($user_id, $spy_number) { global $conf; $user = getUserDetails($user_id); $num = $spy_number * pow(2, ($user["currentSpySkill"]) / 4); if ($conf["race"][$user["race"]]["bonus_spy"]) { $num += (($num * $conf["race"][$user["race"]]["bonus_spy"]) / 100); } $num = ($num / 10) + $spy_number; $num = round($num); return $num; } function getAntiCovertAction($user_id) { global $conf; $user = getUserDetails($user_id); $num_min = $user["currentAntiSpySkill"]; if ($num_min == 0) { $num_min = 1; } if (!$user["assassins"]) { return $num_min; } $num = $user["assassins"] * pow(2, ($user["currentAntiSpySkill"]) / 4); if ($conf["race"][$user["race"]]["bonus_anti_spy"]) { $num += (($num * $conf["race"][$user["race"]]["bonus_anti_spy"]) / 100); } $num = ($num / 10) + $user["assassins"]; $num = round($num); return $num; } //----------------------------User__Details: GET: ACTION: END---------------------------- //----------------------------User__Details: SET----------------------------------------- function updateActions($user) { global $mysqli; $user_ID = $user["ID"]; $att_val = getStrikeAction($user_ID); $def_val = getDefenceAction($user_ID); $spy_val = getCovertAction($user_ID); $spk_val = getAntiCovertAction($user_ID); $total_val = $att_val + $def_val + $spy_val + $spk_val; $stmt = $mysqli->prepare(" UPDATE `User__Details` SET `strikeAction` = ?, `defenceAction` = ?, `covertAction` = ?, `antiCovertAction` = ?, `totalAction` = ? WHERE `ID` = ? "); $stmt->bind_param('sssssi', $att_val, $def_val, $spy_val, $spk_val, $total_val, $user_ID); $stmt->execute(); // return $result; } function turnUpdate() { global $mysqli; $stmt = $mysqli->prepare(" SELECT `ID` FROM `User__Details` WHERE `active` IN (1, 3) ORDER BY `totalActionRank` ASC "); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $user_ID = $row["ID"]; $att_val = getStrikeAction($user_ID); $def_val = getDefenceAction($user_ID); $spy_val = getCovertAction($user_ID); $spk_val = getAntiCovertAction($user_ID); $total_val = $att_val + $def_val + $spy_val + $spk_val; $stmt = $mysqli->prepare(" UPDATE `User__Details` SET `strikeAction` = ?, `defenceAction` = ?, `covertAction` = ?, `antiCovertAction` = ?, `totalAction` = ? WHERE `ID` = ? "); $stmt->bind_param('sssssi', $att_val, $def_val, $spy_val, $spk_val, $total_val, $user_ID); $stmt->execute(); } } function updateIncome($user) { global $conf; // $user2 = getUserDetails($user["ID"]);//retrieves user variables from database $income_troopsU = $user["untrained"];//retrieves number of untraind soldiers $income_troopsD = $user["defenders"];//retrieves number of defence soldiers $income_troopsO = $user["attackers"];//retrieves number of offence soldiers $income = $conf["gold_from_soldier"] * $income_troopsU;//base income from Untrained $income += floor(($conf["gold_from_defence"] * $income_troopsD) - (($conf["gold_from_defence"] * $income_troopsD)));//increases income by defence (reduced by defence rate) $income += floor(($conf["gold_from_offence"] * $income_troopsO) - (($conf["gold_from_offence"] * $income_troopsO)));//increases income by offence (reduced by offence rate) if ($conf["race"][$user["race"]]["bonus_income"]) {//adds a bonus to income if race has a bonus $income += floor(($income * $conf["race"][$user["race"]]["bonus_income"]) / 100); } updateUser($user["ID"], " turnIncome=$income ");//updates player's turnIncome } function updateUnitProduction($user) { global $conf, $mysqli; $percentof_dailyrecruit_per_turn = 1 / (24 * (60 / $conf["minutes_per_turn"])); $user2 = getUserDetails($user["ID"]); $unitProduction = $user2["currentUnitProduction"] * $percentof_dailyrecruit_per_turn; $stmt = $mysqli->prepare("UPDATE `User__Details` SET `turnUnitProduction` = ? WHERE `ID` = ? "); // Bind "$user_id" to parameter. $stmt->bind_param('ii', $unitProduction, $user["ID"]); if ($stmt === FALSE) { return NULL; } $stmt->execute(); // Execute the prepared query. return NULL; } function updateUser($user_id, $str) { global $mysqli; $result = $mysqli->query(" UPDATE User__Details SET $str WHERE ID = {$user_id} "); if ($result == FALSE) { sendMessage_admin(99, "", "function updateUser failed - q1: ".$str); } } function updateLastLogin($user_id) { global $mysqli; $stmt = $mysqli->prepare(" UPDATE `User__Details` SET `lastLoginTime` = UNIX_TIMESTAMP(NOW()) WHERE `ID` = ? "); // Bind "$user_id" to parameter. $stmt->bind_param('i', $user_id); if ($stmt === FALSE) { return NULL; } $stmt->execute(); // Execute the prepared query. return NULL; } function setLastSeen($id, $date) { updateUser($id, " lastTurnTime = '$date' "); } //----------------------------User__Details: SET: END------------------------------------ //----------------------------User__Details: END----------------------------------------- //----------------------------weapons---------------------------------------------------- //----------------------------weapons: GET----------------------------------------------- function getAttackWeapons($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `weaponID`, `weaponCount`, `weaponStrength`, `weaponStrengthMax` FROM `Weapon` WHERE `userID` = ? AND `isAttack` = 1 ORDER BY `weaponID` ASC "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAttackWeaponsDesc($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `weaponID`, `weaponCount`, `weaponStrength`, `weaponStrengthMax` FROM `Weapon` WHERE `userID` = ? AND `isAttack` = 1 ORDER BY `weaponID` DESC "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getDefenceWeapons($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `weaponID`, `weaponCount`, `weaponStrength`, `weaponStrengthMax` FROM `Weapon` WHERE `userID` = ? AND `isAttack` = 0 ORDER BY `weaponID` ASC "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getDefenceWeaponsDesc($user_id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `weaponID`, `weaponCount`, `weaponStrength`, `weaponStrengthMax` FROM `Weapon` WHERE `userID` = ? AND `isAttack` = 0 ORDER BY `weaponID` DESC "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function weaponCostFormula($i) { $info = getCommonInfo(); $mod = 1 + round($info["weeks"] / 52, 3); $num = $mod * pow((6 * $i + 100), 1.6) + 1000; $num = round($num / 500); return $num * 500; } function trainCostFormula($i, $user) { $info = getCommonInfo(); if ($user["race"] == 3) { $mod_race_att = 0.9; } else { $mod_race_att = 1; } if ($user["race"] == 1) { $mod_race_def = 0.9; } else { $mod_race_def = 1; } $mod_time = 1 + round($info["weeks"] / 104, 3); $num = $mod_time * pow((6 * $i + 100), 1.6) + 1000; $num = $mod_race_att * $num; $num = $mod_race_def * $num; $num = round($num / 500); return $num * 500; } function getWeaponCost($user, $weapon = "0", $attdef = "att") { global $conf; $cost = 1; if ($attdef == "att") { $cost = weaponCostFormula($conf["race"][$user["race"]]["weapon"][$weapon]["strength"]); if ($conf["race"][$user["race"]]["bonus_attack"]) { $cost = $cost - ($cost * ($conf["race"][$user["race"]]["bonus_attack"] / 100)); } } elseif ($attdef == "def") { $cost = weaponCostFormula($conf["race"][$user["race"]]["defenceweapon"][$weapon]["strength"]); if ($conf["race"][$user["race"]]["bonus_defend"]) { $cost = $cost - ($cost * ($conf["race"][$user["race"]]["bonus_defend"] / 100)); } } $cost = 100 * round($cost / 100); return $cost; } function getWeaponRepair($user, $weapon = "0", $attdef = "att") { global $conf; $cost = getWeaponCost($user, $weapon, $attdef); if ($attdef == "att") { $cost = round((($cost - 1500) / $conf["race"][$user["race"]]["weapon"][$weapon]["strength"] + 40) * ($conf["att_repair"])); } elseif ($attdef == "def") { $cost = round((($cost - 1500) / $conf["race"][$user["race"]]["defenceweapon"][$weapon]["strength"] + 40) * ($conf["def_repair"])); } //return $cost*9/10; return $cost; } function getMaxWeaponLevel() { global $mysqli; $stmt = $mysqli->prepare(" SELECT `maxWeaponLevel` FROM `Mercenaries` WHERE `open` = 1 "); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($maxWeaponLevel); $stmt->fetch(); } else { $maxWeaponLevel = 0; } return $maxWeaponLevel; } function getAKilled($count) { return floor($count * .03); } function getDKilled($count) { return round($count * .02); } function getWeaponStrA($user, $wA, $turns, $strRatio) { global $conf; $weapons = array(); for ($i = 0; $i < count($wA); $i++) { $weapons["ID"] .= $wA[$i]["weaponID"].";"; $weapons["start"] .= $wA[$i]["weaponStrength"].";"; $allWeaponStrength = $conf["race"][$user["race"]]["weapon"][$wA[$i]["weaponID"]]["strength"]; $weaponDamage = round(rand($allWeaponStrength / 200 * $turns, ($allWeaponStrength / 50 * $turns < 0) ? $allWeaponStrength / 50 * $turns : 1)); if ($weaponDamage > 50) { $weaponDamage = round(rand(4, 9) * $turns); } if ($strRatio < 0.4) { $strRatio = 0.4; //lower limit of damage reduction } if ($strRatio > 0.9) { $newWeaponStrength = $wA[$i]["weaponStrength"] - $weaponDamage; } else { $newWeaponStrength = $wA[$i]["weaponStrength"] - (round($weaponDamage * ($strRatio + 0.1))); //provides between 50% and 0% damage reduction } if ($newWeaponStrength <= 0) { $newWeaponStrength = 0; delWeapon($wA[$i]["ID"]); } else { setWeapon($wA[$i]["ID"], $newWeaponStrength); } $weapons["end"] .= $newWeaponStrength.";"; $weapons["count"] .= $wA[$i]["weaponCount"].";"; $weapons["damage"] += ($weaponDamage * $wA[$i]["weaponCount"]); } if ($weapons["ID"]) $weapons["ID"] = substr($weapons["ID"], 0, strlen($weapons["ID"]) - 1); if ($weapons["start"]) $weapons["start"] = substr($weapons["start"], 0, strlen($weapons["start"]) - 1); if ($weapons["end"]) $weapons["end"] = substr($weapons["end"], 0, strlen($weapons["end"]) - 1); if ($weapons["count"]) $weapons["count"] = substr($weapons["count"], 0, strlen($weapons["count"]) - 1); return $weapons; } function getWeaponStrD($user, $wA, $turns) { global $conf; $weapons = array(); for ($i = 0; $i < count($wA); $i++) { $weapons["ID"] .= $wA[$i]["weaponID"].";"; $weapons["start"] .= $wA[$i]["weaponStrength"].";"; $allWeaponStrength = $conf["race"][$user["race"]]["weapon"][$wA[$i]["weaponID"]]["strength"]; $weaponDamage = round(rand($allWeaponStrength / 200 * $turns, ($allWeaponStrength / 50 * $turns < 0) ? $allWeaponStrength / 50 * $turns : 1) / 2); if ($weaponDamage > 50) { $weaponDamage = round(rand(4, 9) * $turns); } $weaponDamage = ($weaponDamage > ($allWeaponStrength / 20)) ? ($allWeaponStrength / 20) : $weaponDamage; $newWeaponStrength = $wA[$i]["weaponStrength"] - $weaponDamage; if ($newWeaponStrength <= 0) { $newWeaponStrength = 0; delWeapon($wA[$i]["ID"]); } else { setWeapon($wA[$i]["ID"], $newWeaponStrength); } $weapons["end"] .= $newWeaponStrength.";"; $weapons["count"] .= $wA[$i]["weaponCount"].";"; $weapons["damage"] += ($weaponDamage * $wA[$i]["weaponCount"]); } if ($weapons["ID"]) $weapons["ID"] = substr($weapons["ID"], 0, strlen($weapons["ID"]) - 1); if ($weapons["start"]) $weapons["start"] = substr($weapons["start"], 0, strlen($weapons["start"]) - 1); if ($weapons["end"]) $weapons["end"] = substr($weapons["end"], 0, strlen($weapons["end"]) - 1); if ($weapons["count"]) $weapons["count"] = substr($weapons["count"], 0, strlen($weapons["count"]) - 1); return $weapons; } function getWeaponStrD_noDamage($wA) { $weapons = array(); for ($i = 0; $i < count($wA); $i++) { $weapons["ID"] .= $wA[$i]["weaponID"].";"; $weapons["start"] .= $wA[$i]["weaponStrength"].";"; $weaponDamage = 0; $newWeaponStrength = $wA[$i]["weaponStrength"] - $weaponDamage; $weapons["end"] .= $newWeaponStrength.";"; $weapons["count"] .= $wA[$i]["weaponCount"].";"; $weapons["damage"] += ($weaponDamage * $wA[$i]["weaponCount"]); } if ($weapons["ID"]) $weapons["ID"] = substr($weapons["ID"], 0, strlen($weapons["ID"]) - 1); if ($weapons["start"]) $weapons["start"] = substr($weapons["start"], 0, strlen($weapons["start"]) - 1); if ($weapons["end"]) $weapons["end"] = substr($weapons["end"], 0, strlen($weapons["end"]) - 1); if ($weapons["count"]) $weapons["count"] = substr($weapons["count"], 0, strlen($weapons["count"]) - 1); return $weapons; } function setWeapon($id, $strength) { global $mysqli; $stmt = $mysqli->prepare(" UPDATE `Weapon` SET `weaponStrength` = ? WHERE `ID` = ? "); $stmt->bind_param('ii', $strength, $id); $stmt->execute(); } function reduceWeapon($id, $amount) { global $mysqli; $str = " UPDATE Weapon set weaponCount=weaponCount-'$amount' WHERE ID='$id' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "function reduceWeapon failed - q: ".$str); } function delWeapon($id) { global $mysqli; $str = " DELETE FROM `Weapon` WHERE ID='$id' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "function delWeapon failed - q: ".$str); } //----------------------------weapons: END--------------------------------------------- //----------------------------Battlefield---------------------------------------------- //----------------------------Battlefield: Get----------------------------------------- function getActivePlayersCount() { global $mysqli; $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `User__Details` WHERE `active` IN (1, 3, 4) "); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($count); $stmt->fetch(); } else { $count = 0; } return $count; } function getActivePlayers($page) { global $conf, $mysqli; $start = $conf["users_per_page"] * ($page - 1); $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `userName`, `raceName`, `gold`, `active` FROM `User__Details` WHERE `active` IN (1, 3) ORDER BY `totalActionRank` ASC LIMIT ?, ? "); $stmt->bind_param('ii', $start, $conf["users_per_page"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAllActivePlayers() { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `userName`, `raceName`, `gold`, `active` FROM `User__Details` WHERE `active` IN (1, 3) ORDER BY `totalActionRank` ASC "); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAllRegisteredPlayers() { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT `ID`, `userName`, `raceName`, `gold`, `active` FROM `User__Details` WHERE `active` NOT IN (2, 9) ORDER BY `ID` ASC "); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } //----------------------------Battlefield: Set----------------------------------------- //----------------------------Messages------------------------------------------------- //----------------------------Messages: Get-------------------------------------------- function getMessagesCount($userID) { global $mysqli; $stmt = $mysqli->prepare(" SELECT COUNT(*) FROM Messages WHERE userID='$userID' AND delUserID <> 1 "); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($count); $stmt->fetch(); } else { $count = 0; } return $count; } function getNewMessagesCount($user_id) { global $mysqli; $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `Messages` WHERE `userID`= ? AND `delUserID` <> 1 AND `is_read` = 0"); // Bind "$user_id" to parameter. $stmt->bind_param('i', $user_id); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($new); $stmt->fetch(); } else { $new = 0; } return $new; } function getNewMessagesSinceCount($user_id, $time) { global $mysqli; $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `Messages` WHERE `userID`= ? AND `delUserID` <> 1 AND `is_read` = 0 AND `timeSent` > ? "); // Bind "$user_id" to parameter. $stmt->bind_param('ii', $user_id, $time); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($new); $stmt->fetch(); } else { $new = 0; } return $new; } /* * Get active chats (array of IDs, time of last message) * Retrieve all messages * Mark as read when loaded into view */ function getActiveChatIDs($user_id) { global $mysqli; $array = array(); $i = 0; $j = 0; $active = array(); $stmt = $mysqli->prepare(" SELECT `userID` FROM ( SELECT DISTINCT(`userID`) AS `userID` FROM `Messages` WHERE ? IN(`fromID`, `userID`) UNION SELECT DISTINCT(`fromID`) AS `userID` FROM `Messages` WHERE ? IN(`fromID`, `userID`) ) AS `DistinctIDs` WHERE 1 "); $stmt->bind_param('ii', $user_id, $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { if ($row["userID"] != $user_id) { $active[$j] = $row["userID"]; $j++; } } for ($k = 0; $k < count($active); $k++) { $stmt = $mysqli->prepare(" SELECT `fromID`, `userID`, `text`, `timeSent`, `is_read` FROM `Messages` WHERE ? IN(`fromID`, `userID`) AND ? IN(`fromID`, `userID`) ORDER BY `timeSent` DESC LIMIT 0,1 "); $stmt->bind_param("ii", $active[$k], $user_id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } } $array = array_sort($array, 'timeSent', SORT_DESC); $array = array_values($array); return $array; } function getAllChatsBetweenIDs($user_id, $other_id, $count = 100) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT `ID`, `fromID`, `userID`, `text`, `timeSent`, `is_read` FROM `Messages` WHERE ? IN(`fromID`, `userID`) AND ? IN(`fromID`, `userID`) ORDER BY `timeSent` DESC LIMIT 0, ?"); $stmt->bind_param('iii', $user_id, $other_id, $count); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getUnreadFromIDCount($user_id, $fromID) { global $mysqli; $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `Messages` WHERE ( ? IN(`userID`) AND ? IN(`fromID`) ) AND `delUserID` <> 1 AND `is_read` = 0"); // Bind "$user_id" to parameter. $stmt->bind_param('ii', $user_id, $fromID); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($new); $stmt->fetch(); } else { $new = 0; } if ($new > 9) { $new = 10; } return $new; } //----------------------------Messages: Set-------------------------------------------- function setRead($message_ID) { global $mysqli; $stmt = $mysqli->prepare(" UPDATE `Messages` SET `is_read` = 1 WHERE `ID` = ? "); /* Bind our params */ $stmt->bind_param('i', $message_ID); /* Execute the prepared Statement */ $stmt->execute(); $stmt->close(); } //----------------------------Messages: Send------------------------------------------- function sendMessage($id, $toid, $subject, $text) { global $mysqli; $text = urlencode($text); $subject = urlencode($subject); $text = sanitize($text); $subject = sanitize($subject); $date = time(); if ($toid and $id) { updateUser($toid, " messages = messages + 1 "); updateUser($id, " mailCount = mailCount + 1 "); $str = " INSERT INTO Messages (fromID, userID, subject, text, timeSent ) VALUES ('$id', '$toid', '$subject', '$text', '$date') "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "sendMessage failed - q: ".$str); } } function sendMessage_Special($id, $toid, $subject, $text) { global $mysqli; $text = urlencode($text); $subject = urlencode($subject); $text = sanitize($text); $subject = sanitize($subject); $date = time(); updateUser($toid, " messages = messages + 1 "); $str = " INSERT INTO Messages (fromID, userID, subject, text, timeSent, delFromID ) VALUES ('$id', '$toid', '$subject', '$text', '$date', 1) "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "sendMessage_Special failed - q: ".$str); } function sendMessage_admin($toid, $subject, $text) { global $mysqli; $text = urlencode($text); $subject = urlencode($subject); $text = sanitize($text); $subject = sanitize($subject); $date = time(); if ($toid) { updateUser($toid, " messages = messages + 1 "); //updateUser($id," mailCount=mailCount+1 "); //Removed to allow admin to still mail. $str = " INSERT INTO Messages (fromID, userID, subject, text, timeSent ) VALUES ('99', '$toid', '$subject', '$text', '$date') "; $mysqli->query($str); } } function sendMessage_tutorial($toid, $subject, $text) { global $mysqli; $text = urlencode($text); $subject = urlencode($subject); $text = sanitize($text); $subject = sanitize($subject); $date = time(); if ($toid) { updateUser($toid, " messages = messages + 1 "); //updateUser($id," mailCount=mailCount+1 "); //Removed to allow admin to still mail. $str = " INSERT INTO Messages (fromID, userID, subject, text, timeSent ) VALUES ('77', '$toid', '$subject', '$text', '$date') "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "sendMessage_tutorial failed - q: ".$str); } } //----------------------------Messages: END-------------------------------------------- //----------------------------Conversions---------------------------------------------- function numecho($str) { if ($str == "unranked") { echo $str; } elseif ($str == "None") { echo $str; } elseif ($str == "No") { echo $str; } else { //echo $str; echo number_format($str); } } function vDate($time) { $timenowraw = time(); $timedate = date("M d, Y", $time); $timetime = date("H:i", $time); $timedatetime = date("M d,", $time)." ".$timetime; $cyear = date('Y', $timenowraw); $dyear = date('Y', $time); $cdate = date("M d, Y", $timenowraw); $ddate = date("M d, Y", $time); if ($cyear != $dyear) { $showtime = $timedate; } elseif ($cdate == $ddate) { $showtime = $timetime; } else { $showtime = $timedatetime; } return $showtime; } function vDateMicro($time) { $time = substr($time, 0, 10); $timenowraw = time(); $timedate = date("M d, Y", $time); $timetime = date("H:i", $time); $timedatetime = date("M d,", $time)." ".$timetime; $cyear = date('Y', $timenowraw); $dyear = date('Y', $time); $cdate = date("M d, Y", $timenowraw); $ddate = date("M d, Y", $time); if ($cyear != $dyear) { $showtime = $timedate; } elseif ($cdate == $ddate) { $showtime = $timetime; } else { $showtime = $timedatetime; } return $showtime; } function genRandomPas() { $pas = rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9); return $pas; } //----------------------------Conversions: END----------------------------------------- //----------------------------Security------------------------------------------------- function addIP($ip, $userID, $forUserID = '99') { global $mysqli; //this is used for signups $time = time(); $str = " INSERT INTO IPs (ip, userID, time, forUserID) VALUES ('$ip', '$userID', '$time', '$forUserID') "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function addIP_clickcheck($ip, $userID, $forUserID, $referer) { global $mysqli; //this is used for daily click sold bonus $time = time(); $referer2 = addslashes($referer); $str = " INSERT INTO IPs (ip, userID, time, forUserID, referer) VALUES ('$ip', '$userID', '$time', '$forUserID', '$referer2') "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function isIPandUser($ip, $id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `IPs` WHERE `ip` = ? AND `userID` = ? "); $stmt->bind_param('ii', $ip, $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function isIPNewerThen($ip, $time) { global $mysqli; $time = time() - $time; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `IPs` WHERE `ip` = ? AND `time` > ? "); $stmt->bind_param('ii', $ip, $time); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function isIPForUserNewerThen($ip, $time, $forUserID) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `IPs` WHERE `ip` = ? AND `time` > ? AND `forUserID` = ? "); $stmt->bind_param('iii', $ip, $time, $forUserID); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getIP($id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `IPs` WHERE `userID` = ? "); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getUserIPs($id) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `IPs` WHERE `userID` = ? ORDER BY `time` DESC "); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function deleteIP($id) { global $mysqli; $str = " DELETE FROM IPs WHERE userID='$id' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function deleteIPByIP($ip) { global $mysqli; $str = " DELETE FROM IPs WHERE ip='$ip' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function deleteIPforUserByIP($ip, $forUserID) { global $mysqli; $str = " DELETE FROM IPs WHERE ip='$ip' AND forUserID='$forUserID' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function deleteIPByID($id) { global $mysqli; $str = " DELETE FROM IPs WHERE ID='$id' "; $result = $mysqli->query($str); if ($result == FALSE) sendMessage_admin(99, "", "weeks update failed - q: ".$str); } function logIP($id) { global $conf; $ip = $_SERVER['REMOTE_ADDR']; if (!isIPandUser($ip, $id)) { $IPs = getUserIPs($id); if (count($IPs) >= $conf["ips_to_hold_per_user"]) { //print_r ($IPs); //echo $IPs[count($IPs)-1]->ID; //echo "##".count($IPs); deleteIPByID($IPs[count($IPs) - 1]->ID); } addIP($ip, $id); } } //------------------------------Security: END------------------------------------------ //------------------------------Attack------------------------------------------------- function getAttack($id) { global $mysqli; // $start = ($page - 1) * $conf['users_per_page']; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `ID` = ? "); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAttackByAttackerCount($user_id) { global $mysqli; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `userID` = ? "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows < 1) { $return = 0; } else { $return = $result->num_rows; } return $return; } function getAttackByAttacker($user_id, $page = 1) { global $conf, $mysqli; $start = ($page - 1) * $conf['users_per_page']; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `userID` = ? ORDER BY `time` DESC LIMIT ?, ? "); $stmt->bind_param('iii', $user_id, $start, $conf["users_per_page"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAttackByDefenderCount($user_id) { global $mysqli; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `toUserID` = ? "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows < 1) { $return = 0; } else { $return = $result->num_rows; } return $return; } function getAttackByDefender($user_id, $page = 1) { global $conf, $mysqli; $start = ($page - 1) * $conf['users_per_page']; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `toUserID` = ? ORDER BY `time` DESC LIMIT ?, ? "); $stmt->bind_param('iii', $user_id, $start, $conf["users_per_page"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAttackByParticipants($attacker, $defender) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT * FROM `Log__Attack` WHERE `userID` = ? AND `toUserID` = ? ORDER BY `time` DESC LIMIT 0,3 "); $stmt->bind_param('ii', $attacker, $defender); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getAttackByUser1User2AndTime($User1, $User2, $time, $fields = "*") { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare("SELECT ? FROM `Log__Attack` WHERE `userID` = ? AND `toUserID` = ? AND `time` = ? "); $stmt->bind_param('siii', $fields, $User1, $User2, $time); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getNewAttacksCount($user_id, $time) { global $mysqli; $stmt = $mysqli->prepare("SELECT COUNT(*) FROM `Log__Attack` WHERE `toUserID`= ? AND time > ?"); // Bind "$user_id" to parameter. $stmt->bind_param('ii', $user_id, $time); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($new); $stmt->fetch(); } else { $new = 0; } return $new; } function getNewAttacksLost($user_id, $time) { global $mysqli; $stmt = $mysqli->prepare("SELECT SUM(gold_stolen) FROM `Log__Attack` WHERE `toUserID`= ? AND time > ? "); // Bind "$user_id" to parameter. $stmt->bind_param('ii', $user_id, $time); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($new); $stmt->fetch(); } else { $new = 0; } return $new; } //----------------------------Attack: SET---------------------------------------------- function addAttack($attacker, $defender, $time, $mission, $gold_stolen, $gold_available, $attack_strength_attack, $attack_strength_defence, $attack_strength_covert, $attack_strength_assassin, $defence_strength_attack, $defence_strength_defence, $defence_strength_covert, $defence_strength_assassin, $attack_attackers, $attack_defenders, $attack_spies, $attack_assassins, $attack_untrained, $defence_attackers, $defence_defenders, $defence_spies, $defence_assassins, $defence_untrained, $attack_dead_attackers, $attack_dead_defenders, $attack_dead_spies, $attack_dead_assassins, $attack_dead_untrained, $defence_dead_attackers, $defence_dead_defenders, $defence_dead_spies, $defence_dead_assassins, $defence_dead_untrained, $attack_weapons = "", $attack_weapons_start = "", $attack_weapons_end = "", $attack_weapons_count = "", $defence_weapons = "", $defence_weapons_start = "", $defence_weapons_end = "", $defence_weapons_count = "", $attack_race = 0, $attack_race_name = "", $defence_race = 0, $defence_race_name = "", $notes = "") { global $mysqli; $log = array("attacker" => $attacker, "defender" => $defender, "time" => $time, "mission" => $mission, "gold_stolen" => $gold_stolen, "gold_available" => $gold_available, "attack_strength_attack" => $attack_strength_attack, "attack_strength_defence" => $attack_strength_defence, "attack_strength_covert" => $attack_strength_covert, "attack_strength_assassin" => $attack_strength_assassin, "defence_strength_attack" => $defence_strength_attack, "defence_strength_defence" => $defence_strength_defence, "defence_strength_covert" => $defence_strength_covert, "defence_strength_assassin" => $defence_strength_assassin, "attack_attackers" => $attack_attackers, "attack_defenders" => $attack_defenders, "attack_spies" => $attack_spies, "attack_assassins" => $attack_assassins, "attack_untrained" => $attack_untrained, "defence_attackers" => $defence_attackers, "defence_defenders" => $defence_defenders, "defence_spies" => $defence_spies, "defence_assassins" => $defence_assassins, "defence_untrained" => $defence_untrained, "attack_dead_attackers" => $attack_dead_attackers, "attack_dead_defenders" => $attack_dead_defenders, "attack_dead_spies" => $attack_dead_spies, "attack_dead_assassins" => $attack_dead_assassins, "attack_dead_untrained" => $attack_dead_untrained, "defence_dead_attackers" => $defence_dead_attackers, "defence_dead_defenders" => $defence_dead_defenders, "defence_dead_spies" => $defence_dead_spies, "defence_dead_assassins" => $defence_dead_assassins, "defence_dead_untrained" => $defence_dead_untrained, "attack_weapons" => $attack_weapons, "attack_weapons_start" => $attack_weapons_start, "attack_weapons_end" => $attack_weapons_end, "attack_weapons_count" => $attack_weapons_count, "defence_weapons" => $defence_weapons, "defence_weapons_start" => $defence_weapons_start, "defence_weapons_end" => $defence_weapons_end, "defence_weapons_count" => $defence_weapons_count, "attack_race" => $attack_race, "attack_race_name" => $attack_race_name, "defence_race" => $defence_race, "defence_race_name" => $defence_race_name, "notes" => $notes); $query = " INSERT INTO `Log__Attack`(`userID`, `toUserID`, `time`, `mission`, `gold_stolen`, `gold_available`, `attack_strength_attack`, `attack_strength_defence`, `attack_strength_covert`, `attack_strength_assassin`, `defence_strength_attack`, `defence_strength_defence`, `defence_strength_covert`, `defence_strength_assassin`, `attack_attackers`, `attack_defenders`, `attack_spies`, `attack_assassins`, `attack_untrained`, `defence_attackers`, `defence_defenders`, `defence_spies`, `defence_assassins`, `defence_untrained`, `attack_dead_attackers`, `attack_dead_defenders`, `attack_dead_spies`, `attack_dead_assassins`, `attack_dead_untrained`, `defence_dead_attackers`, `defence_dead_defenders`, `defence_dead_spies`, `defence_dead_assassins`, `defence_dead_untrained`, `attack_weapons`, `attack_weapons_start`, `attack_weapons_end`, `attack_weapons_count`, `defence_weapons`, `defence_weapons_start`, `defence_weapons_end`, `defence_weapons_count`, `attack_race`, `attack_race_name`, `defence_race`, `defence_race_name`, `notes`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) "; $stmt = $mysqli->prepare($query); if (FALSE === $stmt) { // and since all the following operations need a valid/ready statement object // it doesn't make sense to go on // you might want to use a more sophisticated mechanism than die() // but's it's only an example return 0; // return ('prepare() failed: '.htmlspecialchars($mysqli->error)); } $rc = $stmt->bind_param("iiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiissssssssisiss", $log["attacker"], $log["defender"], $log["time"], $log["mission"], $log["gold_stolen"], $log["gold_available"], $log["attack_strength_attack"], $log["attack_strength_defence"], $log["attack_strength_covert"], $log["attack_strength_assassin"], $log["defence_strength_attack"], $log["defence_strength_defence"], $log["defence_strength_covert"], $log["defence_strength_assassin"], $log["attack_attackers"], $log["attack_defenders"], $log["attack_spies"], $log["attack_assassins"], $log["attack_untrained"], $log["defence_attackers"], $log["defence_defenders"], $log["defence_spies"], $log["defence_assassins"], $log["defence_untrained"], $log["attack_dead_attackers"], $log["attack_dead_defenders"], $log["attack_dead_spies"], $log["attack_dead_assassins"], $log["attack_dead_untrained"], $log["defence_dead_attackers"], $log["defence_dead_defenders"], $log["defence_dead_spies"], $log["defence_dead_assassins"], $log["defence_dead_untrained"], $log["attack_weapons"], $log["attack_weapons_start"], $log["attack_weapons_end"], $log["attack_weapons_count"], $log["defence_weapons"], $log["defence_weapons_start"], $log["defence_weapons_end"], $log["defence_weapons_count"], $log["attack_race"], $log["attack_race_name"], $log["defence_race"], $log["defence_race_name"], $log["notes"]); // bind_param() can fail because the number of parameter doesn't match the placeholders in the statement // or there's a type conflict(?), or .... if (FALSE === $rc) { // again execute() is useless if you can't bind the parameters. Bail out somehow. return 0; // return ('bind_param() failed: '.htmlspecialchars($stmt->error)); } $rc = $stmt->execute(); // execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable // 2006 "server gone away" is always an option if (FALSE === $rc) { return 0; // return ('execute() failed: '.htmlspecialchars($stmt->error)); } // $stmt->execute(); return $mysqli->insert_id; } //----------------------------Attack: END---------------------------------------------- //----------------------------Spy------------------------------------------------------ //----------------------------Spy: GET------------------------------------------------- function getSpy($id) { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT * FROM `Log__Spy` WHERE `ID` = ? "); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } return $array; } function getSpyBySpyerCount($user_id) { global $mysqli; $stmt = $mysqli->prepare(" SELECT * FROM `Log__Spy` WHERE `userID` = ? "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows < 1) { $return = 0; } else { $return = $result->num_rows; } return $return; } function getSpyBySpyer($user_id, $page = 1) { global $conf, $mysqli; $start = ($page - 1) * $conf['users_per_page']; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Log__Spy` WHERE `userID` = ? ORDER BY `time` DESC LIMIT ?, ? "); $stmt->bind_param('iii', $user_id, $start, $conf["users_per_page"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getSpyByDefenderCount($user_id) { global $mysqli; $stmt = $mysqli->prepare(" SELECT * FROM `Log__Spy` WHERE `toUserID` = ? AND `isDiscovered` = 1 "); $stmt->bind_param('i', $user_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows < 1) { $return = 0; } else { $return = $result->num_rows; } return $return; } function getSpyByDefender($user_id, $page = 1) { global $conf, $mysqli; $start = ($page - 1) * $conf['users_per_page']; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM Log__Spy WHERE toUserID = ? AND (isDiscovered = 1 or mission = 'sabotage' or mission = 'assassinate') ORDER BY time DESC LIMIT ?, ? "); $stmt->bind_param('iii', $user_id, $start, $conf["users_per_page"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getSpyByUser1User2AndTime($user1, $user2, $time) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Log__Spy` WHERE `userID` = ? AND `toUserID` = ? AND `time` = ? "); $stmt->bind_param('iii', $user1, $user2, $time); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getUserWeaponCount($user) { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT COUNT(*) AS count FROM Weapon WHERE userID = ? "); $stmt->bind_param('i', $user["ID"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } $result = $array["count"]; return $result; } function getUserAllWeapon($user) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Weapon` WHERE `userID` = ? ORDER BY `weaponStrength` DESC "); $stmt->bind_param('i', $user["ID"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getUserAllWeaponWeakFirst($user) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Weapon` WHERE `userID` = ? ORDER BY `weaponStrength`, `isAttack` "); $stmt->bind_param('i', $user["ID"]); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array[$i] = $row; $i++; } return $array; } function getLastAttackTime($id) { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT `Log__Attack`.`time` AS `time`, `User__Details`.`defConRate` * .2 AS `limits` FROM `Log__Attack`, `User__Details` WHERE `Log__Attack`.`toUserID` = ? AND `User__Details`.`ID` = `Log__Attack`.`toUserID` ORDER BY `Log__Attack`.`ID` DESC LIMIT 1 "); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } return $array; } //----------------------------Spy: SET------------------------------------------------- function addSpy($id, $toid, $spiesSent, $mission, $spyStrength, $spyDefStrength, $isDiscovered, $isSuccess, $attackers, $defenders, $spies, $assassins, $untrained, $total, $covertSkill, $covertAntiSkill, $strikeAction, $defenceAction, $covertAction, $antiCovertAction, $attackTurns, $unitProduction, $race, $weapons, $types, $typesTrue, $quantities, $strengths, $allStrengths, $spiesDeadAtt, $spiesDeadDef, $spiesAssassinated, $notes) { global $mysqli; $spy_log = array("userID" => $id, "toUserID" => $toid, "time" => time(), "spiesSent" => $spiesSent, "mission" => $mission, "spyStrength" => $spyStrength, "spyDefStrength" => $spyDefStrength, "isDiscovered" => $isDiscovered, "isSuccess" => $isSuccess, "attackers" => $attackers, "defenders" => $defenders, "spies" => $spies, "assassins" => $assassins, "untrained" => $untrained, "total" => $total, "covertSkill" => $covertSkill, "covertAntiSkill" => $covertAntiSkill, "strikeAction" => $strikeAction, "defenceAction" => $defenceAction, "covertAction" => $covertAction, "antiCovertAction" => $antiCovertAction, "attackTurns" => $attackTurns, "unitProduction" => $unitProduction, "race" => $race, "weapons" => $weapons, "types" => $types, "typesTrue" => $typesTrue, "quantities" => $quantities, "strengths" => $strengths, "allStrengths" => $allStrengths, "spiesDeadAtt" => $spiesDeadAtt, "spiesDeadDef" => $spiesDeadDef, "spiesAssassinated" => $spiesAssassinated, "notes" => $notes); $query = " INSERT INTO `Log__Spy` ( `userID`, `toUserID`, `time`, `spiesSent`, `mission`, `spyStrength`, `spyDefStrength`, `isDiscovered`, `isSuccess`, `attackers`, `defenders`, `spies`, `assassins`, `untrained`, `total`, `covertSkill`, `covertAntiSkill`, `strikeAction`, `defenceAction`, `covertAction`, `antiCovertAction`, `attackTurns`, `unitProduction`, `race`, `weapons`, `types`, `typesTrue`, `quantities`, `strengths`, `allStrengths`, `spiesDeadAtt`, `spiesDeadDef`, `spiesAssassinated`, `notes` ) "."VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) "; $stmt = $mysqli->prepare($query); $stmt->bind_param("iiiisiiiisssssssssssssssssssssssss", $spy_log["userID"], $spy_log["toUserID"], $spy_log["time"], $spy_log["spiesSent"], $spy_log["mission"], $spy_log["spyStrength"], $spy_log["spyDefStrength"], $spy_log["isDiscovered"], $spy_log["isSuccess"], $spy_log["attackers"], $spy_log["defenders"], $spy_log["spies"], $spy_log["assassins"], $spy_log["untrained"], $spy_log["total"], $spy_log["covertSkill"], $spy_log["covertAntiSkill"], $spy_log["strikeAction"], $spy_log["defenceAction"], $spy_log["covertAction"], $spy_log["antiCovertAction"], $spy_log["attackTurns"], $spy_log["unitProduction"], $spy_log["race"], $spy_log["weapons"], $spy_log["types"], $spy_log["typesTrue"], $spy_log["quantities"], $spy_log["strengths"], $spy_log["allStrengths"], $spy_log["spiesDeadAtt"], $spy_log["spiesDeadDef"], $spy_log["spiesAssassinated"], $spy_log["notes"]); $stmt->execute(); return $mysqli->insert_id; } function spiedValue($value, $difPerc) { $value = (rand(($difPerc - 100), $difPerc) > 0) ? $value : "???"; return $value; } //----------------------------Spy: END------------------------------------------------- //-----------------------------Unsorted functions-------------------------------------- // Alert mechanism // // Input: // type - string (info, success, warning, danger) // title - string (plain) // text - string (html) // // Set session variable to relay information privately // Call 'showAlert' to render dismissible alert box // // Order of functions: // - setSession // - setXxxErr // - showAlert function setSession($name, $key, $val) { $_SESSION[$name][$key] = $val; } function setLoginErr($type, $title, $text) { setSession("LoginErr", "type", $type); setSession("LoginErr", "title", $title); setSession("LoginErr", "text", $text); } function setArmoryErr($type, $title, $text) { setSession("ArmoryErr", "type", $type); setSession("ArmoryErr", "title", $title); setSession("ArmoryErr", "text", $text); } function setTrainErr($type, $title, $text) { setSession("TrainErr", "type", $type); setSession("TrainErr", "title", $title); setSession("TrainErr", "text", $text); } function setMissionErr($type, $title, $text) { setSession("MissionErr", "type", $type); setSession("MissionErr", "title", $title); setSession("MissionErr", "text", $text); } function setResetErr($type, $title, $text) { setSession("ResetErr", "type", $type); setSession("ResetErr", "title", $title); setSession("ResetErr", "text", $text); } function showAlert($type, $title, $text, $permanent = FALSE) { $state = "alert-dismissible"; if ($permanent == TRUE) { $state = ""; } $dismissible = << HTML; if ($permanent == TRUE) { $dismissible = ""; } $padding = "style='padding-left: 4rem'"; if ($permanent == TRUE) { $padding = ""; } $alert = <<

{$title}

{$dismissible}

{$text}

HTML; echo $alert; } // Login system - new mechanism function login($usname, $password) { global $mysqli, $ip_of_user_on; // Using prepared statements means that SQL injection is not possible. (JdM: .. or at least 'harder to do') if ($stmt = $mysqli->prepare("SELECT ID, userName, hash, race FROM User__Details WHERE userName = ? LIMIT 1")) { $stmt->bind_param('s', $usname); // Bind "$email" to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); // get variables from result. $stmt->bind_result($user_id, $username, $db_password, $race); $stmt->fetch(); if ($stmt->num_rows == 1) { // If the user exists we check if the account is locked // from too many login attempts if (checkbrute($user_id) == TRUE) { // Account is locked // Send an email to user saying their account is locked return FALSE; } else { // Check if the password in the database matches // the password the user submitted. We are using // the password_verify function to avoid timing attacks. if ($password == $db_password) { // Password is correct! // Get the user-agent string of the user. $user_browser = $_SERVER['HTTP_USER_AGENT']; // XSS protection as we might print this value $user_id = preg_replace("/[^0-9]+/", "", $user_id); $_SESSION['SGWOriginLoggedIn'] = $user_id; // XSS protection as we might print this value $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); $_SESSION['username'] = $username; $_SESSION['login_string'] = hash('sha512', $db_password.$user_browser); // Login successful. $_SESSION['SGWOriginLoggedIn2'] = $race; updateUser($user_id, " lastLoginTime = UNIX_TIMESTAMP(NOW()), session = '".$_SESSION["login_string"]."' "); // check if player has military records - if not, create // echo "We made it here!

Welcome " . $_SESSION["username"] ." (OID:". $_SESSION["SGWOriginLoggedIn"] . ")"; exit; return TRUE; } else { // Password is not correct // We record this attempt in the database $now = time(); $mysqli->query("INSERT INTO LoginAttempts (IP, enteredName, enteredPass, userID, time) VALUES ('$ip_of_user_on', '$usname', '$password', '$user_id', '$now')"); return FALSE; } } } else { // No user exists. return FALSE; } } else { return FALSE; } } function checkbrute($user_id) { global $mysqli; // Get timestamp of current time $now = time(); // All login attempts are counted from the past 2 hours. $valid_attempts = $now - (2 * 60 * 60); if ($stmt = $mysqli->prepare("SELECT time FROM LoginAttempts WHERE userID = ? AND time > '$valid_attempts'")) { $stmt->bind_param('i', $user_id); // Execute the prepared query. $stmt->execute(); $stmt->store_result(); // If there have been more than 5 failed logins if ($stmt->num_rows > 5) { return TRUE; } else { return FALSE; } } return FALSE; // something must have gone wrong } function login_check() { global $mysqli; // Check if all session variables are set if (isset($_SESSION['SGWOriginLoggedIn'], $_SESSION['username'], $_SESSION['login_string'])) { $user_id = $_SESSION['SGWOriginLoggedIn']; $login_string = $_SESSION['login_string']; // $username = $_SESSION['username']; // Get the user-agent string of the user. $user_browser = $_SERVER['HTTP_USER_AGENT']; if ($stmt = $mysqli->prepare("SELECT `hash` FROM `User__Details` WHERE `ID` = ? LIMIT 1")) { // Bind "$user_id" to parameter. $stmt->bind_param('i', $user_id); $stmt->execute(); // Execute the prepared query. $stmt->store_result(); if ($stmt->num_rows == 1) { // If the user exists get variables from result. $stmt->bind_result($password); $stmt->fetch(); $login_check = hash('sha512', $password.$user_browser); if (hash_equals($login_check, $login_string)) { // Logged In!!!! return TRUE; } else { // Not logged in return FALSE; } } else { // Not logged in return FALSE; } } else { // Not logged in return FALSE; } } else { // Not logged in return FALSE; } } function active($page, $check) { if ($page == $check) { echo " class='active' "; } else { // echo "'".$page."'-'".$check."'"; echo ""; } } function userlink($user_id, $button = TRUE) { global $conf; $user = getUserDetails($user_id); if ($button == FALSE) { if ($user_id == 99) { $link = <<System HTML; } elseif ($user_id == 77) { $link = <<Tutorial HTML; } elseif (in_array($user_id, $conf["administrators"])) { $link = <<{$user["userName"]} HTML; } elseif (in_array($user["active"], array(1, 3, 4, 5, 6))) { $link = <<{$user["userName"]} HTML; } elseif ($user == NULL) { $link = <<no such user HTML; } else { $link = <<{$user["userName"]} HTML; } } else { if ($user_id == 99) { $link = <<System HTML; } elseif ($user_id == 77) { $link = <<Tutorial HTML; } elseif (in_array($user["active"], array(1, 3, 4, 5, 6))) { $link = << HTML; } elseif ($user == NULL) { $link = <<no such user HTML; } else { $link = <<{$user["userName"]} HTML; } } return $link; } function mission_type($type) { if ($type == "recon") { return "Reconnaissance"; } elseif ($type == "sabotage" or $type == "Sabotage") { return "Sabotage"; } elseif ($type == "assassination" or $type == "Assassination" or $type == "Assassinate") { return "Assassination"; } elseif ($type == "attack") { return "Attack"; } else { return "undefined"; } } function can_see($user_id, $spies, $target_id, $req = 0.2) { $spy_attack_power = getCovertAction_away($user_id, $spies); $spy_defend_power = getCovertAction($target_id); if ($user_id == $target_id) { return TRUE; } elseif (($spy_attack_power * $req) > $spy_defend_power) { return TRUE; } else { return FALSE; } } function test_can_see($user_id, $spies, $target_id, $req = 0.2) { $spy_attack_power = getCovertAction_away($user_id, $spies); $spy_defend_power = getCovertAction($target_id); if (($spy_attack_power * $req) > $spy_defend_power) { return "userid: ".$user_id." - spies: ".$spies." - target_id: ".$target_id." - req: ".$req." - spy_attack_power: ".$spy_attack_power." - spy_defend_power: ".$spy_defend_power; } else { return FALSE; } } function real_user($user_id) { $user = getUserDetails($user_id); if (in_array($user["active"], array(1, 3, 4, 5, 6))) { return TRUE; } else { return FALSE; } } function checkIfExists_Records($ID) { global $mysqli; if ($stmt = $mysqli->prepare(" SELECT * FROM `Records__User` WHERE `userID` = ? UNION SELECT * FROM `Records__User_temp` WHERE `userID` = ? ")) { $stmt->bind_param('ii', $ID, $ID); // Execute the prepared query. $stmt->execute(); $stmt->store_result(); // If there have been more than 5 failed logins if ($stmt->num_rows == 2) { return TRUE; } else { return FALSE; } } return FALSE; // something must have gone wrong } function createRecords($ID) { global $mysqli; $result = ""; if ($stmt = $mysqli->prepare(" INSERT INTO `Records__User` (`userID`, `started`) VALUES ( ? , UNiX_TIMESTAMP(NOW()) ) ")) { $stmt->bind_param('i', $ID); // Execute the prepared query. if ($stmt->execute() == TRUE) { $result = "record created || "; } if ($stmt = $mysqli->prepare(" INSERT INTO `Records__User_temp` (`userID`, `started`) VALUES ( ? , UNiX_TIMESTAMP(NOW()) ) ")) { $stmt->bind_param('i', $ID); // Execute the prepared query. if ($stmt->execute() == TRUE) { $result .= "temp record created"; } // If there have been more than 5 failed logins if (strlen($result) > 1) { updateActivityLog("records", $ID, 0, $result); return TRUE; } else { return FALSE; } } } return FALSE; // something must have gone wrong } function getRecords($ID) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Records__User` WHERE `userID` = ? "); $stmt->bind_param('i', $ID); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; $i++; } return $array; } function getRecords_temp($ID) { global $mysqli; $array = array(); $i = 0; $stmt = $mysqli->prepare(" SELECT * FROM `Records__User_temp` WHERE `userID` = ? ORDER BY `started` DESC LIMIT 0, 1 "); $stmt->bind_param('i', $ID); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; $i++; } return $array; } function getExperience($ID) { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT points_total AS XP FROM Records__User WHERE userID = ? "); $stmt->bind_param('i', $ID); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } return $array; } function getExperience_temp($ID) { global $mysqli; $array = array(); $stmt = $mysqli->prepare(" SELECT points_total AS XP FROM Records__User_temp WHERE userID = ? ORDER BY started DESC LIMIT 0, 1 "); $stmt->bind_param('i', $ID); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { $array = $row; } return $array; } function updateTable($table, $userID, $update) { $result = array(); foreach ($update as $key => $value) { // $arr[3] will be updated with each value from $arr... $rc = updateColumn($table, $userID, $key, $value); $result[] = (strlen($rc) !== 0) ? $rc : ""; } return $result; } function updateColumn($table, $userID, $key, $value) { global $conf, $mysqli2; // make sure to have the right 'ID' field name $fieldID = "userID"; if ($table == "User__Details") { $fieldID = "ID"; } $query = " UPDATE ".$table." SET ".$key." = ".$value." WHERE ".$fieldID." = ? "; // echo $query . "
"; if ($value) { $stmt = $mysqli2->prepare($query); if (FALSE === $stmt) { // and since all the following operations need a valid/ready statement object // it doesn't make sense to go on // you might want to use a more sophisticated mechanism than die() // but's it's only an example if ($conf["isDevSite"] == 1) { return ('prepare() failed: '.htmlspecialchars($mysqli2->error)); } else return 0; } $rc = $stmt->bind_param("i", $userID); if (FALSE === $rc) { // bind_param() can fail because the number of parameter doesn't match the placeholders in the statement // or there's a type conflict(?), or .... // again execute() is useless if you can't bind the parameters. Bail out somehow. if ($conf["isDevSite"] == 1) { return ('bind_param() failed: '.htmlspecialchars($stmt->error)); } else return 0; } $rc = $stmt->execute(); if (FALSE === $rc) { // execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable // 2006 "server gone away" is always an option if ($conf["isDevSite"] == 1) { return ('execute() failed: '.htmlspecialchars($stmt->error)); } else return 0; } } return NULL; } function updateRecords($update) { global $mysqli2; $userID = $update["attacker"]; $toUserID = $update["defender"]; $updateA = array("updated" => time(), "gold_stolen" => " gold_stolen + ".$update["gold"], "lost_attackers" => "lost_attackers + ".$update["attackers"], "killed_defenders" => "killed_defenders + ".$update["defenders"], "killed_spies" => "killed_spies + ".$update["spies"], "lost_assassins" => "lost_assassins + ".$update["assassins"], "attack_weapons_power_lost" => "attack_weapons_power_lost + ".$update["attack_weapons"], "defence_weapons_power_destroyed" => "defence_weapons_power_destroyed + ".$update["defence_weapons"], "outgoing_attack" => "outgoing_attack + 1"); $updateD = array("updated" => time(), "gold_lost" => " gold_lost + ".$update["gold"], "killed_attackers" => "killed_attackers + ".$update["attackers"], "lost_defenders" => "lost_defenders + ".$update["defenders"], "lost_spies" => "lost_spies + ".$update["spies"], "killed_assassins" => "killed_assassins + ".$update["assassins"], "attack_weapons_power_destroyed" => "attack_weapons_power_destroyed + ".$update["attack_weapons"], "defence_weapons_power_lost" => "defence_weapons_power_lost + ".$update["defence_weapons"], "incoming_attack" => "incoming_attack + 1"); updateTable("Records__User", $userID, $updateA); updateTable("Records__User_temp", $userID, $updateA); updateTable("Records__User", $toUserID, $updateD); updateTable("Records__User_temp", $toUserID, $updateD); $mysqli2->commit(); $mysqli2->close(); } function resetRecords($ID) { global $mysqli, $mysqli2; $result = ""; $reset = array("reset" => time()); updateTable("Records__User_temp", $ID, $reset); $mysqli2->commit(); $mysqli2->close(); if ($stmt = $mysqli->prepare(" INSERT INTO `Records__User_temp` (`userID`, `started`, `reset`) VALUES ( ? , UNiX_TIMESTAMP(NOW()) , UNiX_TIMESTAMP(NOW()) ) ")) { $stmt->bind_param('i', $ID); // Execute the prepared query. if ($stmt->execute() == TRUE) { $result = "temp record reset"; } // If there have been more than 5 failed logins if (strlen($result) > 1) { updateActivityLog("records", $ID, 0, $result); return TRUE; } else { return FALSE; } } else { return FALSE; } } function setLastActive($ID) { updateColumn( "User__Details", $ID, "lastActiveTime", time() ); } function getLastActive($ID) { $info = array(); $time = getUserDetails($ID)["lastActiveTime"]; $info["messages"]["unread"] = getNewMessagesCount($ID); $info["messages"]["new_since"] = getNewMessagesSinceCount($ID, $time); $info["attacks"]["new_since"] = getNewAttacksCount($ID, ($time*1000)); if ($info["attacks"]["new_since"] > 0 ) $info["attacks"]["gold_lost"] = getNewAttacksLost($ID, ($time*1000)); return $info; } include "i_shuffle.php";


Development