From dab768f662e27d2b8b5ed9f41d311bd04c4a6199 Mon Sep 17 00:00:00 2001 From: Martin Ambrus Date: Wed, 15 Nov 2017 16:01:00 +0100 Subject: [PATCH] refactor: 1st round of database values caching --- GameEngine/Account.php | 24 +- GameEngine/Alliance.php | 39 +- GameEngine/Automation.php | 107 ++- GameEngine/Battle.php | 1171 +++++++++++++++--------------- GameEngine/Database.php | 909 ++++++++++++++++++----- GameEngine/Database/db_MYSQL.php | 0 GameEngine/Market.php | 48 +- GameEngine/Message.php | 362 ++++----- GameEngine/Profile.php | 25 +- GameEngine/Session.php | 10 +- GameEngine/Village.php | 3 +- 11 files changed, 1675 insertions(+), 1023 deletions(-) delete mode 100755 GameEngine/Database/db_MYSQL.php diff --git a/GameEngine/Account.php b/GameEngine/Account.php index af1a144d..b2cc1e9d 100755 --- a/GameEngine/Account.php +++ b/GameEngine/Account.php @@ -135,8 +135,13 @@ class Account { if($uid) { setcookie("COOKUSR",$_POST['name'],time()+COOKIE_EXPIRE,COOKIE_PATH); setcookie("COOKEMAIL",$_POST['email'],time()+COOKIE_EXPIRE,COOKIE_PATH); - $database->updateUserField($uid,"act","",1); - $database->updateUserField($uid,"invited",$_POST['invited'],1); + $database->updateUserField( + $uid, + ["act", "invited"], + ["", $_POST['invited']], + 1 + ); + $this->generateBase($_POST['kid'],$uid,$_POST['name']); header("Location: login.php"); exit; @@ -177,7 +182,7 @@ class Account { private function Unreg() { global $database; - $q = "SELECT password, username FROM ".TB_PREFIX."activate where id = '".$database->escape((int) $_POST['id'])."'"; + $q = "SELECT password, username FROM ".TB_PREFIX."activate where id = ".(int) $_POST['id']; $result = mysqli_query($GLOBALS['link'],$q); $dbarray = mysqli_fetch_array($result); if(password_verify($_POST['pw'], $dbarray['password'])) { @@ -207,12 +212,14 @@ class Account { $form->addError("pw",LOGIN_PW_ERROR); } - if($database->getUserField($_POST['user'],"act",1) != "") { + $userData = $database->getUserArray($_POST['user'], 0); + + if($userData["act"] != "") { $form->addError("activate",$_POST['user']); } // Vacation mode by Shadow - if($database->getUserField($_POST['user'],"vac_mode",1) == 1 && $database->getUserField($_POST['user'],"vac_time",1) > time()) { + if($userData["vac_mode"] == 1 && $userData["vac_time"] > time()) { $form->addError("vacation","Vacation mode is still enabled"); } @@ -224,14 +231,13 @@ class Account { header("Location: login.php"); exit; } else { - $userid = $database->getUserArray($_POST['user'], 0); // Vacation mode by Shadow - $database->removevacationmode($userid['id']); + $database->removevacationmode($userData['id']); // Vacation mode by Shadow if($database->login($_POST['user'],$_POST['pw'])){ - $database->UpdateOnline("login" ,$_POST['user'],time(),$userid['id']); + $database->UpdateOnline("login" ,$_POST['user'],time(),$userData['id']); }else if($database->sitterLogin($_POST['user'],$_POST['pw'])){ - $database->UpdateOnline("sitter" ,$_POST['user'],time(),$userid['id']); + $database->UpdateOnline("sitter" ,$_POST['user'],time(),$userData['id']); } setcookie("COOKUSR",$_POST['user'],time()+COOKIE_EXPIRE,COOKIE_PATH); $session->login($_POST['user']); diff --git a/GameEngine/Alliance.php b/GameEngine/Alliance.php index edb84c91..2a5ad53b 100755 --- a/GameEngine/Alliance.php +++ b/GameEngine/Alliance.php @@ -380,26 +380,27 @@ class Alliance { *****************************************/ private function kickAlliUser($post) { global $database, $session, $form; - if($session->access != BANNED){ - $UserData = $database->getUserArray($post['a_user'], 1); - if($this->userPermArray['opt2'] == 0) { - $form->addError("perm", NO_PERMISSION); - } else if($UserData['id'] != $session->uid){ - $database->updateUserField($post['a_user'], 'alliance', 0, 1); - $database->deleteAlliPermissions($post['a_user']); - $database->deleteAlliance($session->alliance); - // log the notice - $database->insertAlliNotice($session->alliance, '' . addslashes($post['a_user']) . ' has quit the alliance.'); - if($session->alliance && $database->isAllianceOwner($UserData['id']) == $session->alliance){ - $newowner = $database->getAllMember2($session->alliance); - $newleader = $newowner['id']; - $q = "UPDATE " . TB_PREFIX . "alidata set leader = ".(int) $newleader." where id = ".(int) $session->alliance.""; - $database->query($q); - $database->updateAlliPermissions($newleader, 1, 1, 1, 1, 1, 1, 1, 1, 1); - Automation::updateMax($newleader); + + if ($session->access != BANNED) { + $UserData = $database->getUserArray($post['a_user'], 1); + if($this->userPermArray['opt2'] == 0) { + $form->addError("perm", NO_PERMISSION); + } else if($UserData['id'] != $session->uid){ + $database->updateUserField($post['a_user'], 'alliance', 0, 1); + $database->deleteAlliPermissions($post['a_user']); + $database->deleteAlliance($session->alliance); + // log the notice + $database->insertAlliNotice($session->alliance, '' . addslashes($post['a_user']) . ' has quit the alliance.'); + if($session->alliance && $database->isAllianceOwner($UserData['id']) == $session->alliance){ + $newowner = $database->getAllMember2($session->alliance); + $newleader = $newowner['id']; + $q = "UPDATE " . TB_PREFIX . "alidata set leader = ".(int) $newleader." where id = ".(int) $session->alliance.""; + $database->query($q); + $database->updateAlliPermissions($newleader, 1, 1, 1, 1, 1, 1, 1, 1, 1); + Automation::updateMax($newleader); + } } - } - }else{ + } else { header("Location: banned.php"); exit; } diff --git a/GameEngine/Automation.php b/GameEngine/Automation.php index 49119998..6f720b0e 100755 --- a/GameEngine/Automation.php +++ b/GameEngine/Automation.php @@ -244,7 +244,6 @@ class Automation { //create new file to check filetime //not every click regenerate but 1 minute or after - $ourFileHandle = fopen($autoprefix."GameEngine/Prevention/loyalty.txt", 'w'); fclose($ourFileHandle); global $database; @@ -1283,7 +1282,7 @@ class Automation { $database->addMovement(4,0,$data['to'],$attackid,microtime(true),microtime(true)+(180/EVASION_SPEED)); $newgold = $gold-2; $newmaxevasion = $maxevasion-1; - $database->updateUserFields($DefenderID, ["gold", "maxevasion"], [$newgold, $newmaxevasion], 1); + $database->updateUserField($DefenderID, ["gold", "maxevasion"], [$newgold, $newmaxevasion], 1); } } //get defence units @@ -2363,9 +2362,11 @@ class Automation { } } - $exp1 = $database->getVillageField($from['wref'],'exp1'); - $exp2 = $database->getVillageField($from['wref'],'exp2'); - $exp3 = $database->getVillageField($from['wref'],'exp3'); + $expArray = $database->getVillageFields($from['wref'], 'exp1, exp2, exp3'); + $exp1 = $expArray['exp1']; + $exp2 = $expArray['exp2']; + $exp3 = $expArray['exp3']; + if($exp1 == 0){ $villexp = 0; } @@ -2381,18 +2382,24 @@ class Automation { $mode = CP; $cp_mode = $GLOBALS['cp'.$mode]; $need_cps = $cp_mode[count($varray1)+1]; - $user_cps = $database->getUserField($from['owner'],"cp",0); - //see if last village, or village head + + if (!isset($cachedUserData[$from['owner']])) { + $cachedUserData[$from['owner']] = $database->getUserArray($from['owner'], 1); + } + + $user_cps = $cachedUserData[$from['owner']]['cp']; + + //check for last village or capital if($user_cps >= $need_cps){ if(count($varray)!='1' AND $to['capital']!='1' AND $villexp < $canconquer){ if($to['owner']!=3 OR $to['name']!='WW Buildingplan'){ - //if there is no Palace/Residence - for ($i=18; $i<39; $i++){ - if ($database->getFieldLevel($data['to'],"".$i."t")==25 or $database->getFieldLevel($data['to'],"".$i."t")==26){ - $nochiefing='1'; - $info_chief = "".$chief_pic.",The Palace/Residence isn\'t destroyed!"; - } + // check for standing Palace or Residence + if ($database->getFieldLevelInVillage($data['to'], '25, 26')) { + $nochiefing = 1; + $info_chief = "".$chief_pic.",The Palace/Residence isn\'t destroyed!"; } + + // we can conquer this village if(!isset($nochiefing)){ //$info_chief = "".$chief_pic.",You don't have enought CP to chief a village."; if($this->getTypeLevel(35,$data['from']) == 0){ @@ -2408,31 +2415,46 @@ class Automation { $rand+=rand(5,15); } } - //loyalty is more than 0 - if(($toF['loyalty']-$rand)>0){ + + // loyalty is more than 0 + if (($toF['loyalty']-$rand) > 0) { $info_chief = "".$chief_pic.",The loyalty was lowered from ".floor($toF['loyalty'])." to ".floor($toF['loyalty']-$rand)."."; $database->setVillageField($data['to'],'loyalty',($toF['loyalty']-$rand)); } else if (!$village_destroyed) { - //you took over the village + // you took over the village $villname = addslashes($database->getVillageField($data['to'],"name")); $artifact = $database->getOwnArtefactInfo($data['to']); + $info_chief = "".$chief_pic.",Inhabitants of ".$villname." village decided to join your empire."; + if ($artifact['vref'] == $data['to']){ - $database->claimArtefact($data['to'],$data['to'],$database->getVillageField($data['from'],"owner")); + if (!isset($villageOwners[$data['from']])) { + $villageOwners[$data['from']] = $database->getVillageField($data['from'],"owner"); + } + $database->claimArtefact($data['to'], $data['to'], $villageOwners[$data['from']]); } - $database->setVillageField($data['to'],'loyalty',0); - $database->setVillageField($data['to'],'owner',$database->getVillageField($data['from'],"owner")); + + + $database->setVillageFields( + $data['to'], + ['loyalty', 'owner'], + [0, $villageOwners[$data['from']]] + ); + //delete upgrades in armory and blacksmith - $q = "DELETE FROM ".TB_PREFIX."abdata WHERE vref = ".(int) $data['to'].""; + $q = "DELETE FROM ".TB_PREFIX."abdata WHERE vref = ".(int) $data['to']; $database->query($q); $database->addABTech($data['to']); + //delete researches in academy - $q = "DELETE FROM ".TB_PREFIX."tdata WHERE vref = ".(int) $data['to'].""; + $q = "DELETE FROM ".TB_PREFIX."tdata WHERE vref = ".(int) $data['to']; $database->query($q); $database->addTech($data['to']); + //delete reinforcement - $q = "DELETE FROM ".TB_PREFIX."enforcement WHERE `from` = ".(int) $data['to'].""; + $q = "DELETE FROM ".TB_PREFIX."enforcement WHERE `from` = ".(int) $data['to']; $database->query($q); + //no units can stay in the village itself $units2reset = []; for ($u = 1; $u <= 50; $u++) { @@ -2443,36 +2465,50 @@ class Automation { $units2reset[] = 'hero = 0'; $q = "UPDATE ".TB_PREFIX."units SET ".implode(',', $units2reset)." WHERE vref = ".(int) $data['to']; $database->query($q); + // check buildings + $newLevels_fieldNames = []; + $newLevels_fieldValues = []; + $pop1 = $database->getVillageField($data['from'],"pop"); $pop2 = $database->getVillageField($data['to'],"pop"); if($pop1 > $pop2){ $buildlevel = $database->getResourceLevel($data['to']); + for ($i=1; $i<=39; $i++){ if($buildlevel['f'.$i]!=0){ if($buildlevel['f'.$i."t"]!=35 && $buildlevel['f'.$i."t"]!=36 && $buildlevel['f'.$i."t"]!=41){ $leveldown = $buildlevel['f'.$i]-1; - $database->setVillageLevel($data['to'],"f".$i,$leveldown); + $newLevels_fieldNames[] = "f".$i; + $newLevels_fieldValues[] = $leveldown; }else{ - $database->setVillageLevel($data['to'],"f".$i,0); - $database->setVillageLevel($data['to'],"f".$i."t",0); + $newLevels_fieldNames[] = "f".$i; + $newLevels_fieldValues[] = 0; + + $newLevels_fieldNames[] = "f".$i."t"; + $newLevels_fieldValues[] = 0; } } } - if($buildlevel['f99']!=0){ + + if ($buildlevel['f99']!=0) { $leveldown = $buildlevel['f99']-1; - $database->setVillageLevel($data['to'],"f99",$leveldown); + $newLevels_fieldNames[] = "f99"; + $newLevels_fieldValues[] = $leveldown; } } + //destroy wall - $database->setVillageLevel($data['to'],"f40",0); - $database->setVillageLevel($data['to'],"f40t",0); - $database->clearExpansionSlot($data['to']); + $newLevels_fieldNames[] = "f40"; + $newLevels_fieldValues[] = 0; + $newLevels_fieldNames[] = "f40t"; + $newLevels_fieldValues[] = 0; - $exp1 = $database->getVillageField($data['from'],'exp1'); - $exp2 = $database->getVillageField($data['from'],'exp2'); - $exp3 = $database->getVillageField($data['from'],'exp3'); + $expArray = $database->getVillageFields($data['from'], 'exp1, exp2, exp3'); + $exp1 = $expArray['exp1']; + $exp2 = $expArray['exp2']; + $exp3 = $expArray['exp3']; if($exp1 == 0){ $exp = 'exp1'; @@ -2486,11 +2522,16 @@ class Automation { $exp = 'exp3'; $value = $data['to']; } + $database->setVillageField($data['from'],$exp,$value); + //remove oasis related to village $units->returnTroops($data['to'],1); $chiefing_village = 1; + // update data in the database + $database->clearExpansionSlot($data['to']); + $database->setVillageLevel($data['to'], $newLevels_fieldNames, $newLevels_fieldValues); } } } else { diff --git a/GameEngine/Battle.php b/GameEngine/Battle.php index e62eaecd..378c0b5d 100755 --- a/GameEngine/Battle.php +++ b/GameEngine/Battle.php @@ -93,29 +93,30 @@ class Battle { } } private function getBattleHero($uid) { - global $database; - $heroarray = $database->getHero($uid); + global $database; + $heroarray = $database->getHero($uid); - if (!count($heroarray)) { - return array('heroid'=> 0, 'unit'=>'','atk'=>0,'di'=>0,'dc'=>0,'ob'=>0,'db'=>0,'health'=>0); - } + if (!count($heroarray)) { + return array('heroid'=> 0, 'unit'=>'','atk'=>0,'di'=>0,'dc'=>0,'ob'=>0,'db'=>0,'health'=>0); + } - $herodata = $GLOBALS["h".$heroarray[0]['unit']]; - if(!isset($heroarray['health'])) $heroarray['health']=0; - $h_atk = $herodata['atk'] + ($heroarray[0]['attack'] * $herodata['atkp']); - $h_di = $herodata['di'] + 5 * floor($heroarray[0]['defence'] * $herodata['dip'] / 5); - $h_dc = $herodata['dc'] + 5 * floor($heroarray[0]['defence'] * $herodata['dcp'] / 5); - $h_ob = 1 + 0.010 * ($heroarray[0]['attackbonus']/5); - $h_db = 1 + 0.010 * ($heroarray[0]['defencebonus']/5); - return array('heroid'=>(int) $heroarray[0]['heroid'],'unit'=>$heroarray[0]['unit'],'atk'=>$h_atk,'di'=>$h_di,'dc'=>$h_dc,'ob'=>$h_ob,'db'=>$h_db,'health'=>$heroarray['health']); + $herodata = $GLOBALS["h".$heroarray[0]['unit']]; + if(!isset($heroarray['health'])) $heroarray['health']=0; + $h_atk = $herodata['atk'] + ($heroarray[0]['attack'] * $herodata['atkp']); + $h_di = $herodata['di'] + 5 * floor($heroarray[0]['defence'] * $herodata['dip'] / 5); + $h_dc = $herodata['dc'] + 5 * floor($heroarray[0]['defence'] * $herodata['dcp'] / 5); + $h_ob = 1 + 0.010 * ($heroarray[0]['attackbonus']/5); + $h_db = 1 + 0.010 * ($heroarray[0]['defencebonus']/5); + + return array('heroid'=>(int) $heroarray[0]['heroid'],'unit'=>$heroarray[0]['unit'],'atk'=>$h_atk,'di'=>$h_di,'dc'=>$h_dc,'ob'=>$h_ob,'db'=>$h_db,'health'=>$heroarray['health']); } private function getBattleHeroSim($attbonus) { - global $database; - $h_atk =0; - $h_ob = 1 + 0.010 * $attbonus; - - return array('unit'=>16,'atk'=>$h_atk,'ob'=>$h_ob); + global $database; + $h_atk =0; + $h_ob = 1 + 0.010 * $attbonus; + + return array('unit'=>16,'atk'=>$h_atk,'ob'=>$h_ob); } private function simulate($post) { @@ -192,9 +193,9 @@ class Battle { public function getTypeLevel($tid,$vid) { global $village,$database; - $keyholder = array(); - $resourcearray = $database->getResourceLevel($vid); + $keyholder = array(); + $resourcearray = $database->getResourceLevel($vid); foreach(array_keys($resourcearray,$tid) as $key) { if(strpos($key,'t')) { @@ -202,6 +203,7 @@ class Battle { array_push($keyholder, $key); } } + $element = count($keyholder); if($element >= 2) { if($tid <= 4) { @@ -237,604 +239,605 @@ class Battle { } } - //1 raid 0 normal - function calculateBattle($Attacker,$Defender,$def_wall,$att_tribe,$def_tribe,$residence,$attpop,$defpop,$type,$def_ab,$att_ab1,$att_ab2,$att_ab3,$att_ab4,$att_ab5,$att_ab6,$att_ab7,$att_ab8,$tblevel,$stonemason,$walllevel,$offhero,$hero_strenght,$deffhero,$AttackerID,$DefenderID,$AttackerWref,$DefenderWref,$conqureby, $defReinforcements = null, $villageOwners = array(), $userdataCache = array()) { - global $bid34,$bid35,$database; - - // Define the array, with the units - $calvary = array(4,5,6,15,16,23,24,25,26,45,46); - $catapult = array(8,18,28,48); - $rams = array(7,17,27,47); - $catp = $ram = 0; - // Array to return the result of the calculation back - $result = array(); - $involve = 0; - $winner = false; - // at 0 all partial results - $cap = $ap = $dp = $cdp = $rap = $rdp = 0; + //1 raid 0 normal + function calculateBattle($Attacker,$Defender,$def_wall,$att_tribe,$def_tribe,$residence,$attpop,$defpop,$type,$def_ab,$att_ab1,$att_ab2,$att_ab3,$att_ab4,$att_ab5,$att_ab6,$att_ab7,$att_ab8,$tblevel,$stonemason,$walllevel,$offhero,$hero_strenght,$deffhero,$AttackerID,$DefenderID,$AttackerWref,$DefenderWref,$conqureby, $defReinforcements = null, $villageOwners = array(), $userdataCache = array()) { + global $bid34,$bid35,$database; - $att_artefact = count($database->getOwnUniqueArtefactInfo2($AttackerID,3,3,0)); - $att_artefact1 = count($database->getOwnUniqueArtefactInfo2($AttackerWref,3,1,1)); - $att_artefact2 = count($database->getOwnUniqueArtefactInfo2($AttackerID,3,2,0)); - if($att_artefact > 0){ - $attacker_artefact = 10; - }else if($att_artefact1 > 0){ - $attacker_artefact = 5; - }else if($att_artefact2 > 0){ - $attacker_artefact = 3; - }else{ - $attacker_artefact = 1; - } - $def_artefact = count($database->getOwnUniqueArtefactInfo2($DefenderID,3,3,0)); - $def_artefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,3,1,1)); - $def_artefact2 = count($database->getOwnUniqueArtefactInfo2($DefenderID,3,2,0)); - if($def_artefact > 0){ - $defender_artefact = 10; - }else if($att_artefact1 > 0){ - $defender_artefact = 5; - }else if($def_artefact2 > 0){ - $defender_artefact = 3; - }else{ - $defender_artefact = 1; - } - if(isset($Attacker['uhero']) && $Attacker['uhero'] != 0){ - $atkhero = $this->getBattleHero($AttackerID); - } - if(isset($Defender['hero']) && $Defender['hero'] != 0){ - $defenderhero = $this->getBattleHero($DefenderID); - } - //own defender units - if ($type==1) { - $datadefScout=$this->getDataDefScout($Defender,$def_ab,$defender_artefact,$AttackerWref,$AttackerID); - $dp+=$datadefScout['dp']; - $cdp+=$datadefScout['cdp']; - $involve=$datadefScout['involve']; - if ($datadefScout['detect']==1) $detected = 1; - }else{ - $datadef=$this->getDataDef($Defender,$def_ab); - $dp+=$datadef['dp']; - $cdp+=$datadef['cdp']; - $involve=$datadef['involve']; - if(isset($Defender['hero']) && $Defender['hero'] != 0){ - $units['Def_unit']['hero'] = $Defender['hero']; - $cdp += $defenderhero['dc']; - $dp += $defenderhero['di']; - $dp *= $defenderhero['db']; - $cdp *= $defenderhero['db']; - } - } - $DefendersAll = (!is_null($defReinforcements) ? $database->getEnforceVillage($DefenderWref,0) : $defReinforcements); + // Define the array, with the units + $calvary = array(4,5,6,15,16,23,24,25,26,45,46); + $catapult = array(8,18,28,48); + $rams = array(7,17,27,47); + $catp = $ram = 0; + // Array to return the result of the calculation back + $result = array(); + $involve = 0; + $winner = false; + // at 0 all partial results + $cap = $ap = $dp = $cdp = $rap = $rdp = 0; - if (!isset($villageOwners[$DefenderWref])) { - $villageOwners[ $DefenderWref ] = $database->getVillageField( $DefenderWref, "owner" ); + $att_artefact = count($database->getOwnUniqueArtefactInfo2($AttackerID,3,3,0)); + $att_artefact1 = count($database->getOwnUniqueArtefactInfo2($AttackerWref,3,1,1)); + $att_artefact2 = count($database->getOwnUniqueArtefactInfo2($AttackerID,3,2,0)); + if($att_artefact > 0){ + $attacker_artefact = 10; + }else if($att_artefact1 > 0){ + $attacker_artefact = 5; + }else if($att_artefact2 > 0){ + $attacker_artefact = 3; + }else{ + $attacker_artefact = 1; + } + $def_artefact = count($database->getOwnUniqueArtefactInfo2($DefenderID,3,3,0)); + $def_artefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,3,1,1)); + $def_artefact2 = count($database->getOwnUniqueArtefactInfo2($DefenderID,3,2,0)); + if($def_artefact > 0){ + $defender_artefact = 10; + }else if($att_artefact1 > 0){ + $defender_artefact = 5; + }else if($def_artefact2 > 0){ + $defender_artefact = 3; + }else{ + $defender_artefact = 1; + } + if(isset($Attacker['uhero']) && $Attacker['uhero'] != 0){ + $atkhero = $this->getBattleHero($AttackerID); + } + if(isset($Defender['hero']) && $Defender['hero'] != 0){ + $defenderhero = $this->getBattleHero($DefenderID); + } + //own defender units + if ($type==1) { + $datadefScout=$this->getDataDefScout($Defender,$def_ab,$defender_artefact,$AttackerWref,$AttackerID); + $dp+=$datadefScout['dp']; + $cdp+=$datadefScout['cdp']; + $involve=$datadefScout['involve']; + if ($datadefScout['detect']==1) $detected = 1; + }else{ + $datadef=$this->getDataDef($Defender,$def_ab); + $dp+=$datadef['dp']; + $cdp+=$datadef['cdp']; + $involve=$datadef['involve']; + if(isset($Defender['hero']) && $Defender['hero'] != 0){ + $units['Def_unit']['hero'] = $Defender['hero']; + $cdp += $defenderhero['dc']; + $dp += $defenderhero['di']; + $dp *= $defenderhero['db']; + $cdp *= $defenderhero['db']; } + } + $DefendersAll = (!is_null($defReinforcements) ? $database->getEnforceVillage($DefenderWref,0) : $defReinforcements); - if(!empty($DefendersAll) && $DefenderWref>0){ - foreach($DefendersAll as $defenders) { - for ($i=1;$i<=50;$i++) {$def_ab[$i]=0;} - $fromvillage = $defenders['from']; + if (!isset($villageOwners[$DefenderWref])) { + $villageOwners[ $DefenderWref ] = $database->getVillageField( $DefenderWref, "owner" ); + } - if (!isset($villageOwners[$fromvillage])) { - $villageOwners[$fromvillage] = $database->getVillageField($fromvillage,"owner"); - $userdataCache[$fromvillage] = $database->getUserArray($villageOwners[$fromvillage], 1); - } + if(!empty($DefendersAll) && $DefenderWref>0){ + foreach($DefendersAll as $defenders) { + for ($i=1;$i<=50;$i++) {$def_ab[$i]=0;} + $fromvillage = $defenders['from']; - $enforcetribe = $userdataCache[$fromvillage]["tribe"]; - $ud=($enforcetribe-1)*10; - if($defenders['from']>0) { //don't check nature tribe - $armory = $database->getABTech($defenders['from']); // Armory level every village enforcement - $def_ab[$ud+1] = $armory['a1']; - $def_ab[$ud+2] = $armory['a2']; - $def_ab[$ud+3] = $armory['a3']; - $def_ab[$ud+4] = $armory['a4']; - $def_ab[$ud+5] = $armory['a5']; - $def_ab[$ud+6] = $armory['a6']; - $def_ab[$ud+7] = $armory['a7']; - $def_ab[$ud+8] = $armory['a8']; - } - if ($type==1) { - $datadefScout=$this->getDataDefScout($defenders,$def_ab,$defender_artefact,$AttackerWref,$AttackerID); - $dp+=$datadefScout['dp']; - $cdp+=$datadefScout['cdp']; - $involve=$datadefScout['involve']; - if ($datadefScout['detect']==1) $detected = 1; - }else{ - $datadef=$this->getDataDef($defenders,$def_ab); - $dp+=$datadef['dp']; - $cdp+=$datadef['cdp']; - $involve=$datadef['involve']; - } - $reinfowner = $villageOwners[$fromvillage]; - $defhero = $this->getBattleHero($reinfowner); - //calculate def hero from enforcement - if($defenders['hero'] != 0){ - //$cdp += $defhero['dc']; - //$dp += $defhero['di']; - $dp *= $defhero['db']; - $cdp *= $defhero['db']; - } + if (!isset($villageOwners[$fromvillage])) { + $villageOwners[$fromvillage] = $database->getVillageField($fromvillage,"owner"); + $userdataCache[$fromvillage] = $database->getUserArray($villageOwners[$fromvillage], 1); + } + + $enforcetribe = $userdataCache[$fromvillage]["tribe"]; + $ud=($enforcetribe-1)*10; + if($defenders['from']>0) { //don't check nature tribe + $armory = $database->getABTech($defenders['from']); // Armory level every village enforcement + $def_ab[$ud+1] = $armory['a1']; + $def_ab[$ud+2] = $armory['a2']; + $def_ab[$ud+3] = $armory['a3']; + $def_ab[$ud+4] = $armory['a4']; + $def_ab[$ud+5] = $armory['a5']; + $def_ab[$ud+6] = $armory['a6']; + $def_ab[$ud+7] = $armory['a7']; + $def_ab[$ud+8] = $armory['a8']; + } + if ($type==1) { + $datadefScout=$this->getDataDefScout($defenders,$def_ab,$defender_artefact,$AttackerWref,$AttackerID); + $dp+=$datadefScout['dp']; + $cdp+=$datadefScout['cdp']; + $involve=$datadefScout['involve']; + if ($datadefScout['detect']==1) $detected = 1; + }else{ + $datadef=$this->getDataDef($defenders,$def_ab); + $dp+=$datadef['dp']; + $cdp+=$datadef['cdp']; + $involve=$datadef['involve']; + } + $reinfowner = $villageOwners[$fromvillage]; + $defhero = $this->getBattleHero($reinfowner); + //calculate def hero from enforcement + if($defenders['hero'] != 0){ + //$cdp += $defhero['dc']; + //$dp += $defhero['di']; + $dp *= $defhero['db']; + $cdp *= $defhero['db']; } } - // Calculate the total number of points Attacker - $start = ($att_tribe-1)*10+1; - $end = ($att_tribe*10); - if($att_tribe == 3){ - $abcount = 3; - }else{ - $abcount = 4; - } - - if($type == 1) {//scout + } + // Calculate the total number of points Attacker + $start = ($att_tribe-1)*10+1; + $end = ($att_tribe*10); + if($att_tribe == 3){ + $abcount = 3; + }else{ + $abcount = 4; + } - for($i=$start;$i<=$end;$i++) { - global ${'u'.$i}; - $j = $i-$start+1; - if($Attacker['u'.$i]>0 && ($i == 4 || $i == 14 || $i == 23 || $i == 44)){ - if(${'att_ab'.$abcount} > 0) { - $ap += (35 + (35 + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.00697, ${'att_ab'.$abcount}) - 1)) * $Attacker['u'.$i];// ^ ($Attacker['u'.$i]/100); - }else{ - $ap += $Attacker['u'.$i]*35; - } - } - $involve += $Attacker['u'.$i]; - $units['Att_unit'][$i] = $Attacker['u'.$i]; - - } - $att_foolartefact = $database->getFoolArtefactInfo(3,$AttackerWref,$AttackerID); - if(count($att_foolartefact) > 0){ - foreach($att_foolartefact as $arte){ - if($arte['bad_effect'] == 1){ - $ap *= $arte['effect2']; - }else{ - $ap /= $arte['effect2']; - $ap = round($ap); - } - } - } - - }else{ //type=3 normal 4=raid - $abcount = 1; - for($i=$start;$i<=$end;$i++) { - global ${'u'.$i}; - $j = $i-$start+1; - if($abcount <= 8 && ${'att_ab'.$abcount} > 0) { - if(in_array($i,$calvary)) { - $cap += (int) (${'u'.$i}['atk'] + (${'u'.$i}['atk'] + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.007, ${'att_ab'.$abcount}) - 1)) * (int) $Attacker['u'.$i]; - }else{ - $ap += (int) (${'u'.$i}['atk'] + (${'u'.$i}['atk'] + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.007, ${'att_ab'.$abcount}) - 1)) * (int) $Attacker['u'.$i]; - } - }else{ - if(in_array($i,$calvary)) { - $cap += (int) $Attacker['u'.$i]*${'u'.$i}['atk']; - }else{ - $ap += (int) $Attacker['u'.$i]*${'u'.$i}['atk']; - } - } - $abcount +=1; - // Points catapult the attacker - if(in_array($i,$catapult)) { - $catp += (int) $Attacker['u'.$i]; - } - // Points of the Rams attacker - if(in_array($i,$rams)){ - $ram += (int) $Attacker['u'.$i]; - } - $involve += (int) $Attacker['u'.$i]; - $units['Att_unit'][$i] = (int) $Attacker['u'.$i]; - } - if (isset($Attacker['uhero']) && $Attacker['uhero'] != 0){ - $units['Att_unit']['hero'] = $Attacker['uhero']; - $ap *= $atkhero['ob']; - $cap *= $atkhero['ob']; - $ap += $atkhero['atk']; - } - - if ($offhero!=0 || $hero_strenght!=0) { - $atkhero=$this->getBattleHeroSim($offhero); - $ap *= $atkhero['ob']; - $cap *= $atkhero['ob']; - $ap += $hero_strenght; - } - if ($deffhero!=0) { - $dfdhero=$this->getBattleHeroSim($deffhero); - $dp *= $dfdhero['ob']; - $cdp *= $dfdhero['ob']; - } - } - // Formula for calculating the bonus defensive wall and Residence + if($type == 1) {//scout - if($def_wall > 0) { - // Set the factor calculation for the "wall" as the type of the civilization - // Factor = 1030 Wall Roman - // Factor = 1020 Wall Teuton - // Factor = 1025 Wall Goul - $factor = ($def_tribe == 1)? 1.030 : (($def_tribe == 2)? 1.020 : 1.025); - // Defense infantry = Infantry * Wall (%) - // Defense calvary calvary = * Wall (%) - if ($dp>0 || $cdp >0) { - if($type==1) { - $dp *= pow($factor,$def_wall); - $dp1 = 10 * pow($factor,$def_wall) * $def_wall; - $dp +=$dp1; - }else{ - $dp *= pow($factor,$def_wall); - $cdp *= pow($factor,$def_wall); - - // Calculation of the Basic defense bonus "Residence" - $dp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); - $cdp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); - } - } else { - $dp = 10 * pow($factor,$def_wall) * $def_wall; - // Defense calvary calvary = * Wall (%) - $cdp = 10 * pow($factor,$def_wall) * $def_wall; - if($type!=1) { - // Calculation of the Basic defense bonus "Residence" - $dp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); - $cdp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); - }else $cdp=0; - } - }elseif($type!=1) { - // Calculation of the Basic defense bonus "Residence" - $dp += (2*(pow($residence,2))); - $cdp += (2*(pow($residence,2))); - } + for($i=$start;$i<=$end;$i++) { + global ${'u'.$i}; + $j = $i-$start+1; + if($Attacker['u'.$i]>0 && ($i == 4 || $i == 14 || $i == 23 || $i == 44)){ + if(${'att_ab'.$abcount} > 0) { + $ap += (35 + (35 + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.00697, ${'att_ab'.$abcount}) - 1)) * $Attacker['u'.$i];// ^ ($Attacker['u'.$i]/100); + }else{ + $ap += $Attacker['u'.$i]*35; + } + } + $involve += $Attacker['u'.$i]; + $units['Att_unit'][$i] = $Attacker['u'.$i]; - // Formula for calculating points attackers (Infantry & Cavalry) - - if($AttackerWref != 0){ - $rap = ($ap+$cap)+(($ap+$cap)/100*(isset($bid35[$this->getTypeLevel(35,$AttackerWref)]) ? $bid35[$this->getTypeLevel(35,$AttackerWref)]['attri'] : 0)); - }else{ - $rap = $ap+$cap; - } - - // Formula for calculating Defensive Points - - if ($rap==0) - $rdp = ($dp) + ($cdp) + 10; - else - $rdp = ($dp * ($ap/$rap)) + ($cdp * ($cap/$rap)) + 10; - - - // The Winner is....: - $result['Attack_points'] = $rap; - $result['Defend_points'] = $rdp; - $winner = ($rap > $rdp); - - // Formula for calculating the Moral - if($attpop > $defpop) { - if ($rap < $rdp) { - $moralbonus = min(1.5, pow($attpop / $defpop, (0.2*($rap/$rdp)))); - }else{ - if($defpop==0){ - $moralbonus = min(1.5, pow($attpop, 0.2)); - }else{ - $moralbonus = min(1.5, pow($attpop / $defpop, 0.2)); - } - } - }else{ - $moralbonus = 1.0; - } + } + $att_foolartefact = $database->getFoolArtefactInfo(3,$AttackerWref,$AttackerID); + if(count($att_foolartefact) > 0){ + foreach($att_foolartefact as $arte){ + if($arte['bad_effect'] == 1){ + $ap *= $arte['effect2']; + }else{ + $ap /= $arte['effect2']; + $ap = round($ap); + } + } + } - if($involve >= 1000) { - $Mfactor = round(2*(1.8592-pow($involve,0.015)),4); - }else{ - $Mfactor = 1.5; - } - if ($Mfactor < 1.25778){$Mfactor=1.25778;}elseif ($Mfactor > 1.5){$Mfactor=1.5;} - // Formula for calculating lost drives - // $type = 1 scout, 2? - // $type = 3 Normal, 4 Raid - if($type == 1){ - $holder = pow((($rdp*$moralbonus)/$rap),$Mfactor); - if($holder>1) $holder=1; - if ($rdp>$rap) $holder=1; - - // Attacker - $result[1] = $holder; - if ($att_tribe==5) $result[1] = 0; //Birds of Prey cannot die when scout - - // Defender - $result[2] = 0; - }else if($type == 2){ + }else{ //type=3 normal 4=raid + $abcount = 1; + for($i=$start;$i<=$end;$i++) { + global ${'u'.$i}; + $j = $i-$start+1; + if($abcount <= 8 && ${'att_ab'.$abcount} > 0) { + if(in_array($i,$calvary)) { + $cap += (int) (${'u'.$i}['atk'] + (${'u'.$i}['atk'] + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.007, ${'att_ab'.$abcount}) - 1)) * (int) $Attacker['u'.$i]; + }else{ + $ap += (int) (${'u'.$i}['atk'] + (${'u'.$i}['atk'] + 300 * ${'u'.$i}['pop'] / 7) * (pow(1.007, ${'att_ab'.$abcount}) - 1)) * (int) $Attacker['u'.$i]; + } + }else{ + if(in_array($i,$calvary)) { + $cap += (int) $Attacker['u'.$i]*${'u'.$i}['atk']; + }else{ + $ap += (int) $Attacker['u'.$i]*${'u'.$i}['atk']; + } + } + $abcount +=1; + // Points catapult the attacker + if(in_array($i,$catapult)) { + $catp += (int) $Attacker['u'.$i]; + } + // Points of the Rams attacker + if(in_array($i,$rams)){ + $ram += (int) $Attacker['u'.$i]; + } + $involve += (int) $Attacker['u'.$i]; + $units['Att_unit'][$i] = (int) $Attacker['u'.$i]; + } + if (isset($Attacker['uhero']) && $Attacker['uhero'] != 0){ + $units['Att_unit']['hero'] = $Attacker['uhero']; + $ap *= $atkhero['ob']; + $cap *= $atkhero['ob']; + $ap += $atkhero['atk']; + } - }else if($type == 4) { - $holder = ($winner) ? pow((($rdp*$moralbonus)/$rap),$Mfactor) : pow(($rap/($rdp*$moralbonus)),$Mfactor); - $holder = $holder / (1 + $holder); - // Attacker - $result[1] = $winner ? $holder : 1 - $holder; - // Defender - $result[2] = $winner ? 1 - $holder : $holder; - $ram -= round($ram*$result[1]/100); - $catp -= round($catp*$result[1]/100); - }else if($type == 3){ - // Attacker - - $result[1] = ($winner)? round(pow((($rdp*$moralbonus)/$rap),$Mfactor),8) : 1; - if ($result[1]>1) {$result[1]=1;$winner=false;$result['Winner'] = "defender";} - - // Defender - $result[2] = (!$winner)? round(pow(($rap/($rdp*$moralbonus)),$Mfactor),8) : 1; - if ($result[1]==1) {$result[2]=round(pow(($rap/($rdp*$moralbonus)),$Mfactor),8);} - if ($result[2]>1) {$result[2]=1;$result['Winner'] = "attacker";$winner=true;} - // If attacked with "Hero" - $ku = ($att_tribe-1)*10+9; - $kings = (int) $Attacker['u'.$ku]; + if ($offhero!=0 || $hero_strenght!=0) { + $atkhero=$this->getBattleHeroSim($offhero); + $ap *= $atkhero['ob']; + $cap *= $atkhero['ob']; + $ap += $hero_strenght; + } + if ($deffhero!=0) { + $dfdhero=$this->getBattleHeroSim($deffhero); + $dp *= $dfdhero['ob']; + $cdp *= $dfdhero['ob']; + } + } + // Formula for calculating the bonus defensive wall and Residence - $aviables= $kings-round($kings * (int) $result[1]); - if ($aviables>0){ - switch($aviables){ - case 1:$fealthy = rand(20,30);break; - case 2:$fealthy = rand(40,60);break; - case 3:$fealthy = rand(60,80);break; - case 4:$fealthy = rand(80,100);break; - default:$fealthy = 100;break; - } - $result['hero_fealthy'] = $fealthy; - } - $ram -= ($winner)? round($ram*$result[1]/100) : round($ram*$result[2]/100); - $catp -= ($winner)? round($catp*$result[1]/100) : round($catp*$result[2]/100); - } - // Formula for the calculation of catapults needed - if($catp > 0 && $tblevel != 0) { - $wctp = pow(($rap/$rdp),1.5); - $wctp = ($wctp >= 1)? 1-0.5/$wctp : 0.5*$wctp; - $wctp *= $catp+($att_ab8/1.5); - $artowner = $villageOwners[$DefenderWref]; - $bartefact = count($database->getOwnUniqueArtefactInfo2($artowner,1,3,0)); - $bartefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,1,1,1)); - $bartefact2 = count($database->getOwnUniqueArtefactInfo2($artowner,1,2,0)); - if($bartefact > 0){ - $strongerbuildings = 5; - }elseif($bartefact1 > 0){ - $strongerbuildings = 4; - }elseif($bartefact2 > 0){ - $strongerbuildings = 3; - }else{ - $strongerbuildings = 1; - } - $good_effect = $bad_effect = 1; - $foolartefact = $database->getFoolArtefactInfo(3,$DefenderWref,$artowner); - if(count($foolartefact) > 0){ - foreach($foolartefact as $arte){ - if($arte['bad_effect'] == 1){ - $bad_effect = $arte['effect2']; - }else{ - $good_effect = $arte['effect2']; - } - } - } - - if($stonemason==0){ - $need = round((($moralbonus * (pow($tblevel,2) + $tblevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab8))/200) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); - }else{ - $need = round((($moralbonus * (pow($tblevel,2) + $tblevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab8))/200) / ($bid34[$stonemason]['attri']/100) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); - } - - // Number catapults to take down the building - $result[3] = $need; - //Number catapults nego - $result[4] = $wctp; - $result[5] = $moralbonus; - $result[9] = $att_ab8; - $result[10]=$strongerbuildings / $good_effect * $bad_effect; - } - if($ram > 0 && $walllevel != 0) { - $wctp = pow(($rap/$rdp),1.5); - $wctp = ($wctp >= 1)? 1-0.5/$wctp : 0.5*$wctp; - $wctp *= ($ram/2) + ($att_ab7/1.5); - $artowner = $villageOwners[$DefenderWref]; - $bartefact = count($database->getOwnUniqueArtefactInfo2($artowner,1,3,0)); - $bartefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,1,1,1)); - $bartefact2 = count($database->getOwnUniqueArtefactInfo2($artowner,1,2,0)); - if($bartefact > 0){ - $strongerbuildings = 5; - }else if($bartefact1 > 0){ - $strongerbuildings = 4; - }else if($bartefact2 > 0){ - $strongerbuildings = 3; - }else{ - $strongerbuildings = 1; - } - $good_effect = $bad_effect = 1; - $foolartefact = $database->getFoolArtefactInfo(3,$DefenderWref,$artowner); - if(count($foolartefact) > 0){ - foreach($foolartefact as $arte){ - if($arte['bad_effect'] == 1){ - $bad_effect = $arte['effect2']; - }else{ - $good_effect = $arte['effect2']; - } - } - } - if($stonemason==0){ - $need = round((($moralbonus * (pow($walllevel,2) + $walllevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab7))/200) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); - }else{ - $need = round((($moralbonus * (pow($walllevel,2) + $walllevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab7))/200) / ($bid34[$stonemason]['attri']/100) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); - } - // Number catapults to take down the building - $result[7] = $need; + if($def_wall > 0) { + // Set the factor calculation for the "wall" as the type of the civilization + // Factor = 1030 Wall Roman + // Factor = 1020 Wall Teuton + // Factor = 1025 Wall Goul + $factor = ($def_tribe == 1)? 1.030 : (($def_tribe == 2)? 1.020 : 1.025); + // Defense infantry = Infantry * Wall (%) + // Defense calvary calvary = * Wall (%) + if ($dp>0 || $cdp >0) { + if($type==1) { + $dp *= pow($factor,$def_wall); + $dp1 = 10 * pow($factor,$def_wall) * $def_wall; + $dp +=$dp1; + }else{ + $dp *= pow($factor,$def_wall); + $cdp *= pow($factor,$def_wall); - // Number catapults to action - $result[8] = $wctp; - - } + // Calculation of the Basic defense bonus "Residence" + $dp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); + $cdp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); + } + } else { + $dp = 10 * pow($factor,$def_wall) * $def_wall; + // Defense calvary calvary = * Wall (%) + $cdp = 10 * pow($factor,$def_wall) * $def_wall; + if($type!=1) { + // Calculation of the Basic defense bonus "Residence" + $dp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); + $cdp += ((2*(pow($residence,2)))*(pow($factor,$def_wall))); + }else $cdp=0; + } + }elseif($type!=1) { + // Calculation of the Basic defense bonus "Residence" + $dp += (2*(pow($residence,2))); + $cdp += (2*(pow($residence,2))); + } - $result[6] = pow($rap/$rdp*$moralbonus,$Mfactor); + // Formula for calculating points attackers (Infantry & Cavalry) - $total_att_units = count($units['Att_unit']); - $start = intval(($att_tribe-1)*10+1); - $end = intval(($att_tribe*10)); + if($AttackerWref != 0){ + $rap = ($ap+$cap)+(($ap+$cap)/100*(isset($bid35[$this->getTypeLevel(35,$AttackerWref)]) ? $bid35[$this->getTypeLevel(35,$AttackerWref)]['attri'] : 0)); + }else{ + $rap = $ap+$cap; + } - for($i=$start;$i <= $end;$i++){ - $y = $i-(($att_tribe-1)*10); - $result['casualties_attacker'][$y] = round($result[1]*$units['Att_unit'][$i]); + // Formula for calculating Defensive Points - } - - if (isset($units['Att_unit']['hero']) && $units['Att_unit']['hero'] >0){ - - $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $atkhero['heroid']); - $fdb = mysqli_fetch_array($_result); - $hero_id=(int) $fdb['heroid']; - $hero_health=$fdb['health']; - $damage_health=round(100*$result[1]); - - if ($hero_health<=$damage_health or $damage_health>90){ - //hero die - $result['casualties_attacker']['11'] = 1; - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); - }else{ - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); - } - } - unset($_result,$fdb,$hero_id,$hero_health,$damage_health); + if ($rap==0) + $rdp = ($dp) + ($cdp) + 10; + else + $rdp = ($dp * ($ap/$rap)) + ($cdp * ($cap/$rap)) + 10; - if (isset($units['Def_unit']['hero']) && $units['Def_unit']['hero'] >0){ + // The Winner is....: + $result['Attack_points'] = $rap; + $result['Defend_points'] = $rdp; + $winner = ($rap > $rdp); - $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $defenderhero['heroid']); - $fdb = mysqli_fetch_array($_result); - $hero_id=(int) $fdb['heroid']; - $hero_health=$fdb['health']; - $damage_health=round(100*$result[2]); - if ($hero_health<=$damage_health or $damage_health>90){ - //hero die - $result['deadherodef'] = 1; - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); - }else{ - $result['deadherodef'] = 0; - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); - } - } - unset($_result,$fdb,$hero_id,$hero_health,$damage_health); + // Formula for calculating the Moral + if($attpop > $defpop) { + if ($rap < $rdp) { + $moralbonus = min(1.5, pow($attpop / $defpop, (0.2*($rap/$rdp)))); + }else{ + if($defpop==0){ + $moralbonus = min(1.5, pow($attpop, 0.2)); + }else{ + $moralbonus = min(1.5, pow($attpop / $defpop, 0.2)); + } + } + }else{ + $moralbonus = 1.0; + } - if(!empty($DefendersAll)){ - $battleHeroesCache = []; - foreach($DefendersAll as $defenders) { - if($defenders['hero']>0) { - if(!empty($heroarray)) { reset($heroarray); } - if (!isset($villageOwners[$defenders['from']])) { - $villageOwners[$defenders['from']] = $database->getVillageField($defenders['from'],"owner"); - $battleHeroesCache[$defenders['from']] = $this->getBattleHero($villageOwners[$defenders['from']]); - } - $heroarraydefender = $battleHeroesCache[$defenders['from']]; - $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $heroarraydefender['heroid']); - $fdb = mysqli_fetch_array($_result); - $hero_id=(int) $fdb['heroid']; - $hero_health=$fdb['health']; - $damage_health=round(100*$result[2]); - if ($hero_health<=$damage_health or $damage_health>90){ - //hero die - $result['deadheroref'][$defenders['id']] = 1; - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); - }else{ - $result['deadheroref'][$defenders['id']] = 0; - mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); - } - } - } - } - unset($_result,$fdb,$hero_id,$hero_health,$damage_health); + if($involve >= 1000) { + $Mfactor = round(2*(1.8592-pow($involve,0.015)),4); + }else{ + $Mfactor = 1.5; + } + if ($Mfactor < 1.25778){$Mfactor=1.25778;}elseif ($Mfactor > 1.5){$Mfactor=1.5;} + // Formula for calculating lost drives + // $type = 1 scout, 2? + // $type = 3 Normal, 4 Raid + if($type == 1){ + $holder = pow((($rdp*$moralbonus)/$rap),$Mfactor); + if($holder>1) $holder=1; + if ($rdp>$rap) $holder=1; + + // Attacker + $result[1] = $holder; + if ($att_tribe==5) $result[1] = 0; //Birds of Prey cannot die when scout + + // Defender + $result[2] = 0; + }else if($type == 2){ + + }else if($type == 4) { + $holder = ($winner) ? pow((($rdp*$moralbonus)/$rap),$Mfactor) : pow(($rap/($rdp*$moralbonus)),$Mfactor); + $holder = $holder / (1 + $holder); + // Attacker + $result[1] = $winner ? $holder : 1 - $holder; + // Defender + $result[2] = $winner ? 1 - $holder : $holder; + $ram -= round($ram*$result[1]/100); + $catp -= round($catp*$result[1]/100); + }else if($type == 3){ + // Attacker + + $result[1] = ($winner)? round(pow((($rdp*$moralbonus)/$rap),$Mfactor),8) : 1; + if ($result[1]>1) {$result[1]=1;$winner=false;$result['Winner'] = "defender";} + + // Defender + $result[2] = (!$winner)? round(pow(($rap/($rdp*$moralbonus)),$Mfactor),8) : 1; + if ($result[1]==1) {$result[2]=round(pow(($rap/($rdp*$moralbonus)),$Mfactor),8);} + if ($result[2]>1) {$result[2]=1;$result['Winner'] = "attacker";$winner=true;} + // If attacked with "Hero" + $ku = ($att_tribe-1)*10+9; + $kings = (int) $Attacker['u'.$ku]; + + $aviables= $kings-round($kings * (int) $result[1]); + if ($aviables>0){ + switch($aviables){ + case 1:$fealthy = rand(20,30);break; + case 2:$fealthy = rand(40,60);break; + case 3:$fealthy = rand(60,80);break; + case 4:$fealthy = rand(80,100);break; + default:$fealthy = 100;break; + } + $result['hero_fealthy'] = $fealthy; + } + $ram -= ($winner)? round($ram*$result[1]/100) : round($ram*$result[2]/100); + $catp -= ($winner)? round($catp*$result[1]/100) : round($catp*$result[2]/100); + } + // Formula for the calculation of catapults needed + if($catp > 0 && $tblevel != 0) { + $wctp = pow(($rap/$rdp),1.5); + $wctp = ($wctp >= 1)? 1-0.5/$wctp : 0.5*$wctp; + $wctp *= $catp+($att_ab8/1.5); + $artowner = $villageOwners[$DefenderWref]; + $bartefact = count($database->getOwnUniqueArtefactInfo2($artowner,1,3,0)); + $bartefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,1,1,1)); + $bartefact2 = count($database->getOwnUniqueArtefactInfo2($artowner,1,2,0)); + if($bartefact > 0){ + $strongerbuildings = 5; + }elseif($bartefact1 > 0){ + $strongerbuildings = 4; + }elseif($bartefact2 > 0){ + $strongerbuildings = 3; + }else{ + $strongerbuildings = 1; + } + $good_effect = $bad_effect = 1; + $foolartefact = $database->getFoolArtefactInfo(3,$DefenderWref,$artowner); + if(count($foolartefact) > 0){ + foreach($foolartefact as $arte){ + if($arte['bad_effect'] == 1){ + $bad_effect = $arte['effect2']; + }else{ + $good_effect = $arte['effect2']; + } + } + } + + if($stonemason==0){ + $need = round((($moralbonus * (pow($tblevel,2) + $tblevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab8))/200) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); + }else{ + $need = round((($moralbonus * (pow($tblevel,2) + $tblevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab8))/200) / ($bid34[$stonemason]['attri']/100) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); + } + + // Number catapults to take down the building + $result[3] = $need; + //Number catapults nego + $result[4] = $wctp; + $result[5] = $moralbonus; + $result[9] = $att_ab8; + $result[10]=$strongerbuildings / $good_effect * $bad_effect; + } + if($ram > 0 && $walllevel != 0) { + $wctp = pow(($rap/$rdp),1.5); + $wctp = ($wctp >= 1)? 1-0.5/$wctp : 0.5*$wctp; + $wctp *= ($ram/2) + ($att_ab7/1.5); + $artowner = $villageOwners[$DefenderWref]; + $bartefact = count($database->getOwnUniqueArtefactInfo2($artowner,1,3,0)); + $bartefact1 = count($database->getOwnUniqueArtefactInfo2($DefenderWref,1,1,1)); + $bartefact2 = count($database->getOwnUniqueArtefactInfo2($artowner,1,2,0)); + if($bartefact > 0){ + $strongerbuildings = 5; + }else if($bartefact1 > 0){ + $strongerbuildings = 4; + }else if($bartefact2 > 0){ + $strongerbuildings = 3; + }else{ + $strongerbuildings = 1; + } + $good_effect = $bad_effect = 1; + $foolartefact = $database->getFoolArtefactInfo(3,$DefenderWref,$artowner); + if(count($foolartefact) > 0){ + foreach($foolartefact as $arte){ + if($arte['bad_effect'] == 1){ + $bad_effect = $arte['effect2']; + }else{ + $good_effect = $arte['effect2']; + } + } + } + if($stonemason==0){ + $need = round((($moralbonus * (pow($walllevel,2) + $walllevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab7))/200) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); + }else{ + $need = round((($moralbonus * (pow($walllevel,2) + $walllevel + 1)) / (8 * (round(200 * pow(1.0205,$att_ab7))/200) / ($bid34[$stonemason]['attri']/100) / $strongerbuildings / $good_effect * $bad_effect)) + 0.5); + } + // Number catapults to take down the building + $result[7] = $need; + + // Number catapults to action + $result[8] = $wctp; + + } + + $result[6] = pow($rap/$rdp*$moralbonus,$Mfactor); + + $total_att_units = count($units['Att_unit']); + $start = intval(($att_tribe-1)*10+1); + $end = intval(($att_tribe*10)); + + for($i=$start;$i <= $end;$i++){ + $y = $i-(($att_tribe-1)*10); + $result['casualties_attacker'][$y] = round($result[1]*$units['Att_unit'][$i]); + + } + + if (isset($units['Att_unit']['hero']) && $units['Att_unit']['hero'] >0){ + + $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $atkhero['heroid']); + $fdb = mysqli_fetch_array($_result); + $hero_id=(int) $fdb['heroid']; + $hero_health=$fdb['health']; + $damage_health=round(100*$result[1]); + + if ($hero_health<=$damage_health or $damage_health>90){ + //hero die + $result['casualties_attacker']['11'] = 1; + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); + }else{ + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); + } + } + unset($_result,$fdb,$hero_id,$hero_health,$damage_health); - // Work out bounty - $start = ($att_tribe-1)*10+1; - $end = ($att_tribe*10); + if (isset($units['Def_unit']['hero']) && $units['Def_unit']['hero'] >0){ - $max_bounty = 0; + $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $defenderhero['heroid']); + $fdb = mysqli_fetch_array($_result); + $hero_id=(int) $fdb['heroid']; + $hero_health=$fdb['health']; + $damage_health=round(100*$result[2]); + if ($hero_health<=$damage_health or $damage_health>90){ + //hero die + $result['deadherodef'] = 1; + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); + }else{ + $result['deadherodef'] = 0; + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); + } + } + unset($_result,$fdb,$hero_id,$hero_health,$damage_health); - for($i=$start;$i<=$end;$i++) { - $j = $i-$start+1; - $y = $i-(($att_tribe-1)*10); + if(!empty($DefendersAll)){ + $battleHeroesCache = []; + foreach($DefendersAll as $defenders) { + if($defenders['hero']>0) { + if(!empty($heroarray)) { reset($heroarray); } + if (!isset($villageOwners[$defenders['from']])) { + $villageOwners[$defenders['from']] = $database->getVillageField($defenders['from'],"owner"); + $battleHeroesCache[$defenders['from']] = $this->getBattleHero($villageOwners[$defenders['from']]); + } + $heroarraydefender = $battleHeroesCache[$defenders['from']]; + $_result=mysqli_query($GLOBALS['link'],"select heroid, health from " . TB_PREFIX . "hero where `dead`='0' and `heroid`=".(int) $heroarraydefender['heroid']); + $fdb = mysqli_fetch_array($_result); + $hero_id=(int) $fdb['heroid']; + $hero_health=$fdb['health']; + $damage_health=round(100*$result[2]); + if ($hero_health<=$damage_health or $damage_health>90){ + //hero die + $result['deadheroref'][$defenders['id']] = 1; + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `dead` = 1, `health` = 0 where `heroid`=".(int) $hero_id); + }else{ + $result['deadheroref'][$defenders['id']] = 0; + mysqli_query($GLOBALS['link'],"update " . TB_PREFIX . "hero set `health`=`health`-".(int) $damage_health." where `heroid`=".(int) $hero_id); + } + } + } + } + unset($_result,$fdb,$hero_id,$hero_health,$damage_health); - $max_bounty += ((int) $Attacker['u'.$i] - (int) $result['casualties_attacker'][$y]) * (int) ${'u'.$i}['cap']; - } + // Work out bounty + $start = ($att_tribe-1)*10+1; + $end = ($att_tribe*10); - $result['bounty'] = $max_bounty; + $max_bounty = 0; - - return $result; - } + for($i=$start;$i<=$end;$i++) { + $j = $i-$start+1; + $y = $i-(($att_tribe-1)*10); - public function getDataDefScout($defenders,$def_ab,$defender_artefact,$AttackerWref,$AttackerID) { - global $database; - $abcount=1; - $invol=0; - $dp=0; - $cdp=0; - $detected=0; - - for($y=4;$y<=54;$y++) { - if($y == 4 || $y == 14 || $y == 23 || $y == 44){ - global ${'u'.$y}; - - if($defenders['u'.$y]>0 && $def_ab[$y] > 0) { - $dp += (20 + (20 + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.00696, $def_ab[$y]) - 1)) * $defenders['u'.$y] * $defender_artefact; + $max_bounty += ((int) $Attacker['u'.$i] - (int) $result['casualties_attacker'][$y]) * (int) ${'u'.$i}['cap']; - $def_foolartefact = $database->getFoolArtefactInfo(3,$AttackerWref,$AttackerID); - if(count($def_foolartefact) > 0){ - foreach($def_foolartefact as $arte){ - if($arte['bad_effect'] == 1){ - $dp *= $arte['effect2']; - }else{ - $dp /= $arte['effect2']; - $dp = round($dp); - } - } - } - }else { - if($defenders['u'.$y]>0) { - $dp += $defenders['u'.$y]* 20 * $defender_artefact; - } - - $units['Def_unit'][$y] = $defenders['u'.$y]; - if($units['Def_unit'][$y] > 0){ - $detected = 1; - } - } - $invol += $defenders['u'.$y]; //total troops - $units['Def_unit'][$y] = $defenders['u'.$y]; - } - } - - $datadef['dp']=$dp; - $datadef['cdp']=$cdp; - $datadef['detect']=($detected==1)? 1:0; - $datadef['involve']=$invol; - return $datadef; - } - public function getDataDef($defenders,$def_ab) { + } - $dp=0; - $cdp=0; - $invol=0; - for($y=1;$y<=50;$y++) { - global ${'u'.$y}; - if ($defenders['u'.$y]>0) { - if (!isset($def_ab[$y])) { - $def_ab[$y] = 0; - } - if ($def_ab[$y]>0) { - $dp += (${'u'.$y}['di'] + (${'u'.$y}['di'] + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.007, $def_ab[$y]) - 1)) * $defenders['u'.$y]; - $cdp += (${'u'.$y}['dc'] + (${'u'.$y}['dc'] + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.007, $def_ab[$y]) - 1)) * $defenders['u'.$y]; - }else{ - $dp += $defenders['u'.$y]*${'u'.$y}['di']; - $cdp += $defenders['u'.$y]*${'u'.$y}['dc']; - } - - } - $invol += $defenders['u'.$y]; //total troops - $units['Def_unit'][$y] = $defenders['u'.$y]; - } - $datadef['dp']=$dp; - $datadef['cdp']=$cdp; - $datadef['involve']=$invol; - - return $datadef; - - } + $result['bounty'] = $max_bounty; + + + return $result; + } + + public function getDataDefScout($defenders,$def_ab,$defender_artefact,$AttackerWref,$AttackerID) { + global $database; + $abcount=1; + $invol=0; + $dp=0; + $cdp=0; + $detected=0; + + for($y=4;$y<=54;$y++) { + if($y == 4 || $y == 14 || $y == 23 || $y == 44){ + global ${'u'.$y}; + + if($defenders['u'.$y]>0 && $def_ab[$y] > 0) { + $dp += (20 + (20 + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.00696, $def_ab[$y]) - 1)) * $defenders['u'.$y] * $defender_artefact; + + $def_foolartefact = $database->getFoolArtefactInfo(3,$AttackerWref,$AttackerID); + if(count($def_foolartefact) > 0){ + foreach($def_foolartefact as $arte){ + if($arte['bad_effect'] == 1){ + $dp *= $arte['effect2']; + }else{ + $dp /= $arte['effect2']; + $dp = round($dp); + } + } + } + }else { + if($defenders['u'.$y]>0) { + $dp += $defenders['u'.$y]* 20 * $defender_artefact; + } + + $units['Def_unit'][$y] = $defenders['u'.$y]; + if($units['Def_unit'][$y] > 0){ + $detected = 1; + } + } + $invol += $defenders['u'.$y]; //total troops + $units['Def_unit'][$y] = $defenders['u'.$y]; + } + } + + $datadef['dp']=$dp; + $datadef['cdp']=$cdp; + $datadef['detect']=($detected==1)? 1:0; + $datadef['involve']=$invol; + return $datadef; + } + + public function getDataDef($defenders,$def_ab) { + + $dp=0; + $cdp=0; + $invol=0; + for($y=1;$y<=50;$y++) { + global ${'u'.$y}; + if ($defenders['u'.$y]>0) { + if (!isset($def_ab[$y])) { + $def_ab[$y] = 0; + } + if ($def_ab[$y]>0) { + $dp += (${'u'.$y}['di'] + (${'u'.$y}['di'] + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.007, $def_ab[$y]) - 1)) * $defenders['u'.$y]; + $cdp += (${'u'.$y}['dc'] + (${'u'.$y}['dc'] + 300 * ${'u'.$y}['pop'] / 7) * (pow(1.007, $def_ab[$y]) - 1)) * $defenders['u'.$y]; + }else{ + $dp += $defenders['u'.$y]*${'u'.$y}['di']; + $cdp += $defenders['u'.$y]*${'u'.$y}['dc']; + } + + } + $invol += $defenders['u'.$y]; //total troops + $units['Def_unit'][$y] = $defenders['u'.$y]; + } + $datadef['dp']=$dp; + $datadef['cdp']=$cdp; + $datadef['involve']=$invol; + + return $datadef; + + } }; $battle = new Battle; diff --git a/GameEngine/Database.php b/GameEngine/Database.php index e89ad749..82a4b4a8 100755 --- a/GameEngine/Database.php +++ b/GameEngine/Database.php @@ -92,6 +92,112 @@ class MYSQLi_DB implements IDbConnection { */ $replaceQueryCount = 0; + // variables for DB-cached data for this request + private static + /** + * @var array Cache of user fields and their values. + */ + $fieldsCache = [], + + /** + * @var array Cache of village fields and their values. + */ + $villageFieldsCache = [], + + /** + * @var array Cache of village IDs for users. + */ + $villageIDsCache = [], + + /** + * @var array Cache of village battle data. + */ + $villageBattleDataCache = [], + + /** + * @var array Cache of users count. + */ + $usersCountCache = [], + + /** + * @var array Cache of alliances count. + */ + $allianceCountCache = [], + + /** + * @var array Cache of alliance data from the DB. + */ + $allianceDataCache = [], + + /** + * @var array Cache of alliance permissions. + */ + $alliancePermissionsCache = [], + + /** + * @var array Cache of alliance members. + */ + $allianceMembersCache = [], + + /** + * @var array Cache of user summary fields. + */ + $userSumFieldCache = [], + + /** + * @var array Cache of artefact infos. + */ + $artefactDataCache = [], + + /** + * @var array Cache of fool artefacts. + */ + $foolArtefactCache = [], + + /** + * @var array Cache of heroes. + */ + $heroCache = [], + + /** + * @var array Cache of dead heroes. + */ + $heroDeadCache = [], + + /** + * @var array Cache of hero field values. + */ + $heroFieldCache = [], + + /** + * @var array Cache of market field values. + */ + $marketFieldCache = [], + + /** + * @var array Cache of market movement values. + */ + $marketMovementCache = [], + + /** + * @var array Cache of coordinates for village IDs. + */ + $coordsCache = [], + + /** + * @var array Cache of messages to be sent out to players, + * so we can collect them and send them out together + * at the end of script execution. + */ + $sendMessageQueryCache = [], + + /** + * @var int Maximum number of INSERT query values to cache in the sendMessageQueryCache. + * Once this amount is reached, the cache is flushed and a single query with all + * the cached values is executed. + */ + $sendMessageQueryCacheMaxRecords = 75; + public $dblink; /** @@ -305,6 +411,26 @@ class MYSQLi_DB implements IDbConnection { return ($this->dblink ? true : false); } + /** + * Returns a value previously cached from the database, if present. + * + * @param $arrayVariable array Reference to the static array in Database class to use for the lookup. + * @param $arrayFieldName string The actual array field name to look a cached value for. + * + * @return Returns the requested cached value or null if it's not cached yet. + */ + private static function returnCachedContent(&$arrayVariable, $arrayStructure) { + if (!isset($arrayVariable[$arrayStructure])) { + $arrayVariable[$arrayStructure] = []; + } + + if (isset($arrayVariable[$arrayStructure]) && !is_null($arrayVariable[$arrayStructure])) { + return $arrayVariable[$arrayStructure]; + } else { + return null; + } + } + function escape($value) { $value = stripslashes($value); return mysqli_real_escape_string($this->dblink, $value); @@ -406,34 +532,35 @@ class MYSQLi_DB implements IDbConnection { } function updateUserField($ref, $field, $value, $switch) { - list($ref, $field, $value, $switch) = $this->escape_input($ref, $field, $value, $switch); + list($ref) = $this->escape_input($ref); + + if (!is_array($field)) { + $field = [$field]; + $value = [$value]; + } + + $pairs = []; + foreach ($field as $index => $fieldName) { + $pairs[] = $this->escape($fieldName) . ' = ' . (Math::isInt($value[$index]) ? $value[$index] : '"'.$this->escape($value[$index]).'"'); + } if(!$switch) { - $q = "UPDATE " . TB_PREFIX . "users set $field = '$value' where username = '$ref'"; + $q = "UPDATE " . TB_PREFIX . "users SET ".implode(', ', $pairs)." where username = '$ref'"; } else { - $q = "UPDATE " . TB_PREFIX . "users set $field = '$value' where id = " . (int) $ref; + $q = "UPDATE " . TB_PREFIX . "users SET ".implode(', ', $pairs)." where id = " . (int) $ref; } - return mysqli_query($this->dblink,$q); + + // update cached values + if ($ret = mysqli_query($this->dblink,$q)) { + foreach ($field as $index => $fieldName) { + if (isset(self::$fieldsCache[$ref.$switch][$fieldName])) + self::$fieldsCache[$ref.$switch][$fieldName] = $value[$index]; + } + } + + return $ret; } - function updateUserFields($ref, $fields, $values, $switch) { - list($ref, $switch) = $this->escape_input($ref, $switch); - - // prepare field-value pairs - $pairs = []; - foreach ($fields as $index => $fieldName) { - $pairs[] = $fieldName.' = '.(Math::isInt($values[$index]) ? $values[$index] : '"'.$this->escape($values[$index]).'"'); - } - - if(!$switch) { - $q = "UPDATE " . TB_PREFIX . "users SET ".implode(', ', $pairs)." WHERE username = '$ref'"; - } else { - $q = "UPDATE " . TB_PREFIX . "users SET ".implode(', ', $pairs)." WHERE id = " . (int) $ref; - } - - return mysqli_query($this->dblink,$q); - } - function getSitee($uid) { list($uid) = $this->escape_input((int) $uid); @@ -473,31 +600,53 @@ class MYSQLi_DB implements IDbConnection { mysqli_query($this->dblink,$q2); } - function getUserField($ref, $field, $mode) { - list($ref, $field, $mode) = $this->escape_input($ref, $field, $mode); - + function getUserField($ref, $field, $mode, $use_cache = true) { + // return all data, don't waste time by selecting fields one by one + $userArray = $this->getUserArray($ref, !$mode, $use_cache); + return (isset($userArray[$field]) ? $userArray[$field] : null); + + /*list($ref, $field, $mode) = $this->escape_input($ref, $field, $mode); + + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$fieldsCache, $ref.$mode)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue[$field])) { + return $cachedValue[$field]; + } + } + // update for Multihunter's username and ID if (($mode && $ref == '') || (!$mode && $ref == 0)) { $ref = 'Multihunter'; $mode = 1; } - + if(!$mode) { $q = "SELECT $field FROM " . TB_PREFIX . "users where id = " . (int) $ref; } else { $q = "SELECT $field FROM " . TB_PREFIX . "users where username = '$ref'"; } + $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); - if($result) { + + if ($result) { $dbarray = mysqli_fetch_array($result); - return $dbarray[$field]; - }elseif($field=="username"){ - return "??"; - }else return 0; + self::$fieldsCache[$ref.$mode][$field] = $dbarray[$field]; + } elseif($field=="username") { + self::$fieldsCache[$ref.$mode][$field] = "??"; + } else { + self::$fieldsCache[$ref.$mode][$field] = 0; + } + + return self::$fieldsCache[$ref.$mode][$field];*/ } - function getUserFields($ref, $fields, $mode) { - list($ref, $fields, $mode) = $this->escape_input($ref, $fields, $mode); + function getUserFields($ref, $fields, $mode, $use_cache = true) { + // return all data, don't waste time by selecting fields one by one + return $this->getUserArray($ref, !$mode, $use_cache); + + /*list($ref, $fields, $mode) = $this->escape_input($ref, $fields, $mode); // update for Multihunter's username and ID if (($mode && $ref == '') || (!$mode && $ref == 0)) { @@ -505,16 +654,50 @@ class MYSQLi_DB implements IDbConnection { $mode = 1; } + // check fields one by one to see which ones we can return cached + if ($use_cache) { + $allFieldsFound = false; + $fieldsLeft = []; + $fieldValues = []; + + // split fields + $fields = explode(',', str_replace(', ', ',', $fields)); + + // iterate over all the fields and see what we have cached + foreach ($fields as $fieldName) { + if (($cached = self::returnCachedContent(self::$fieldsCache, $ref.$mode)) && !is_null($cached) && isset($cached[$fieldName])) { + $fieldValues[$fieldName] = $cached[$fieldName]; + } else { + $fieldsLeft[] = $fieldName; + } + } + + // check if we should return here (if we have all the values) or continue with the rest below + if (!count($fieldsLeft)) { + return $fieldValues; + } + } + if(!$mode) { - $q = "SELECT $fields FROM " . TB_PREFIX . "users where id = " . (int) $ref; + $q = "SELECT ".implode(', ', $fieldsLeft)." FROM " . TB_PREFIX . "users where id = " . (int) $ref; } else { - $q = "SELECT $fields FROM " . TB_PREFIX . "users where username = '$ref'"; + $q = "SELECT ".implode(', ', $fieldsLeft)." FROM " . TB_PREFIX . "users where username = '$ref'"; } $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); if($result) { - return mysqli_fetch_array($result, MYSQLI_ASSOC); - } else return 0; + $ret = mysqli_fetch_array($result, MYSQLI_ASSOC); + } else { + $ret = [0]; + } + + // cache results and return everything that we have + foreach ($ret as $fieldName => $fieldValue) { + $fieldValues[$fieldName] = $fieldValue; + self::$fieldsCache[$ref.$mode][$fieldName] = $fieldValue; + } + + return $fieldValues;*/ } function getInvitedUser($uid) { @@ -681,16 +864,24 @@ class MYSQLi_DB implements IDbConnection { References: Alliance ID *****************************************/ - function getUserArray($ref, $mode) { + function getUserArray($ref, $mode, $use_cache = true) { list($ref, $mode) = $this->escape_input($ref, $mode); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$fieldsCache, $ref.$mode)) && !is_null($cachedValue)) { + return $cachedValue; + } + if(!$mode) { $q = "SELECT * FROM " . TB_PREFIX . "users where username = '$ref'"; } else { $q = "SELECT * FROM " . TB_PREFIX . "users where id = " . (int) $ref; } $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_array($result); + + self::$fieldsCache[$ref.$mode] = mysqli_fetch_array($result); + return self::$fieldsCache[$ref.$mode]; } function activeModify($username, $mode) { @@ -788,7 +979,7 @@ class MYSQLi_DB implements IDbConnection { return mysqli_query($this->dblink,$q); } } - + // if $respect_gametime is false, we generate user base really anywhere // and that means we can generate farms closer to the middle of the map as well // ... otherwise we'd only generate farms at corner edges in late game, which @@ -796,57 +987,61 @@ class MYSQLi_DB implements IDbConnection { function generateBase($sector, $mode=1, $respect_gametime = true) { list($sector, $mode) = $this->escape_input($sector, $mode); - // don't let SQL time out when 30-500 seconds (depending on php.ini) is not enough - @set_time_limit(0); - $num_rows = 0; - $count_while = 0; + // don't let SQL time out when 30-500 seconds (depending on php.ini) is not enough + @set_time_limit(0); + $num_rows = 0; + $count_while = 0; - // random position on the map - used when generating farms via Admin - if (!$respect_gametime) { - $rand = rand(1,4); - } - - while (!$num_rows){ - if (!$mode) { - $gamesday=time()-COMMENCE; - if ((!$respect_gametime && $rand === 1) || ($respect_gametime && $gamesday<3600*24*10 && $count_while==0)) { //10 day - $wide1=1; - $wide2=20; - } elseif ((!$respect_gametime && $rand === 2) || ($respect_gametime && $gamesday<3600*24*20 && $count_while==1)) { //20 day - $wide1=20; - $wide2=40; - } elseif ((!$respect_gametime && $rand === 3) || ($respect_gametime && $gamesday<3600*24*30 && $count_while==2)) { //30 day - $wide1=40; - $wide2=80; - } else { // over 30 day - $wide1=80; - $wide2=WORLD_MAX; + // random position on the map - used when generating farms via Admin + if (!$respect_gametime) { + $rand = rand(1,4); } - } - else { - $wide1=1; - $wide2=WORLD_MAX; - } - switch($sector) { - case 1: - $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x < -$wide1 and x > -$wide2) and (y > $wide1 and y < $wide2) and occupied = 0"; //x- y+ - break; - case 2: - $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x > $wide1 and x < $wide2) and (y > $wide1 and y < $wide2) and occupied = 0"; //x+ y+ - break; - case 3: - $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x < -$wide1 and x > -$wide2) and (y < -$wide1 and y > -$wide2) and occupied = 0"; //x- y- - break; - default: - $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x > $wide1 and x < $wide2) and (y < -$wide1 and y > -$wide2) and occupied = 0"; //x+ y- - } - $result = mysqli_query($this->dblink,$q); - $num_rows = mysqli_num_rows($result); - $count_while++; - } - $result = $this->mysqli_fetch_all($result); - $base = rand(0, ($num_rows-1)); - return $result[$base]['id']; + + while (!$num_rows) { + if (!$mode) { + $gamesday = time() - COMMENCE; + // TODO: scale these with game speed? + if ((!$respect_gametime && $rand === 1) || ($respect_gametime && $gamesday<3600*24*10 && $count_while==0)) { //10 day + $wide1=1; + $wide2=20; + } elseif ((!$respect_gametime && $rand === 2) || ($respect_gametime && $gamesday<3600*24*20 && $count_while==1)) { //20 day + $wide1=20; + $wide2=40; + } elseif ((!$respect_gametime && $rand === 3) || ($respect_gametime && $gamesday<3600*24*30 && $count_while==2)) { //30 day + $wide1=40; + $wide2=80; + } else { // over 30 day + $wide1=80; + $wide2=WORLD_MAX; + } + } + else { + $wide1=1; + $wide2=WORLD_MAX; + } + + switch($sector) { + case 1: + $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x < -$wide1 and x > -$wide2) and (y > $wide1 and y < $wide2) and occupied = 0"; //x- y+ + break; + case 2: + $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x > $wide1 and x < $wide2) and (y > $wide1 and y < $wide2) and occupied = 0"; //x+ y+ + break; + case 3: + $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x < -$wide1 and x > -$wide2) and (y < -$wide1 and y > -$wide2) and occupied = 0"; //x- y- + break; + default: + $q = "Select * from ".TB_PREFIX."wdata where fieldtype = 3 and (x > $wide1 and x < $wide2) and (y < -$wide1 and y > -$wide2) and occupied = 0"; //x+ y- + } + $result = mysqli_query($this->dblink,$q); + $num_rows = mysqli_num_rows($result); + $count_while++; + } + + $result = $this->mysqli_fetch_all($result); + $base = rand(0, ($num_rows-1)); + + return $result[$base]['id']; } function setFieldTaken($id) { @@ -867,7 +1062,7 @@ class MYSQLi_DB implements IDbConnection { } $time = time(); $q = "INSERT into " . TB_PREFIX . "vdata (wref, owner, name, capital, pop, cp, celebration, wood, clay, iron, maxstore, crop, maxcrop, lastupdate, created) values ($wid, $uid, '$vname', $capital, 2, 1, 0, 750, 750, 750, ".STORAGE_BASE.", 750, ".STORAGE_BASE.", $time, $time)"; - return mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); + return mysqli_query($this->dblink,$q); } function addResourceFields($vid, $type) { @@ -1052,13 +1247,24 @@ class MYSQLi_DB implements IDbConnection { Function to retrieve type of village via ID References: Village ID ***************************/ - function getVillageType($wref) { + function getVillageType($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['fieldtype'])) { + return $cachedValue['fieldtype']; + } + } + $q = "SELECT id, fieldtype FROM " . TB_PREFIX . "wdata where id = ".$wref; $result = mysqli_query($this->dblink,$q); $dbarray = mysqli_fetch_array($result); - return $dbarray['fieldtype']; + + self::$villageFieldsCache[$wref]['fieldtype'] = $dbarray['fieldtype']; + return self::$villageFieldsCache[$wref]['fieldtype']; } @@ -1067,17 +1273,25 @@ class MYSQLi_DB implements IDbConnection { Function to retrieve if is ocuped via ID References: Village ID *****************************************/ - function getVillageState($wref) { + function getVillageState($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['occupied']) && isset($cachedValue['oasistype'])) { + return ($dbarray['occupied'] != 0 || $dbarray['oasistype'] != 0); + } + } + $q = "SELECT oasistype,occupied FROM " . TB_PREFIX . "wdata where id = ".$wref; $result = mysqli_query($this->dblink,$q); $dbarray = mysqli_fetch_array($result); - if($dbarray['occupied'] != 0 || $dbarray['oasistype'] != 0) { - return true; - } else { - return false; - } + + self::$villageFieldsCache[$wref]['occupied'] = $dbarray['occupied']; + self::$villageFieldsCache[$wref]['oasistype'] = $dbarray['oasistype']; + return (self::$villageFieldsCache[$wref]['occupied'] != 0 || self::$villageFieldsCache[$wref]['oasistype'] != 0); } function getProfileVillages($uid) { @@ -1106,27 +1320,44 @@ class MYSQLi_DB implements IDbConnection { } - function getVillageID($uid) { + function getVillageID($uid, $use_cache = true) { list($uid) = $this->escape_input((int) $uid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageIDsCache, $uid)) && !is_null($cachedValue)) { + return $cachedValue[0]; + } + $q = "SELECT wref FROM " . TB_PREFIX . "vdata WHERE owner = $uid"; $result = mysqli_query($this->dblink,$q); $dbarray = mysqli_fetch_array($result); - return $dbarray['wref']; + + self::$villageIDsCache[$uid] = [$dbarray]['wref']; + return self::$villageIDsCache[$uid][0]; } - function getVillagesID($uid) { + function getVillagesID($uid, $use_cache = true) { list($uid) = $this->escape_input((int) $uid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageIDsCache, $uid)) && !is_null($cachedValue)) { + return $cachedValue[0]['wref']; + } + $q = "SELECT wref from " . TB_PREFIX . "vdata where owner = $uid order by capital DESC,pop DESC"; $result = mysqli_query($this->dblink,$q); $array = $this->mysqli_fetch_all($result); $newarray = array(); + for($i = 0; $i < count($array); $i++) { array_push($newarray, $array[$i]['wref']); } - return $newarray; + + self::$villageIDsCache[$uid] = $newarray; + return self::$villageIDsCache[$uid]; } function getVillagesID2($uid) { @@ -1138,20 +1369,36 @@ class MYSQLi_DB implements IDbConnection { return $array; } - function getVillage($vid) { + function getVillage($vid, $use_cache = true) { list($vid) = $this->escape_input((int) $vid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $vid)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT * FROM " . TB_PREFIX . "vdata where wref = $vid"; $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_array($result); + + self::$villageFieldsCache[$vid] = mysqli_fetch_array($result, MYSQLI_ASSOC); + return self::$villageFieldsCache[$vid]; } - public function getVillageBattleData($vid) { + public function getVillageBattleData($vid, $use_cache = true) { list($vid) = $this->escape_input((int) $vid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageBattleDataCache, $vid)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT u.id,u.tribe,v.capital,f.f40 AS wall FROM ".TB_PREFIX."users u,".TB_PREFIX."fdata f,".TB_PREFIX."vdata v WHERE u.id=v.owner AND f.vref=v.wref AND v.wref=".$vid; $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_array($result); + + self::$villageBattleDataCache[$vid] = mysqli_fetch_array($result, MYSQLI_ASSOC); + return self::$villageBattleDataCache[$vid]; } public function getPopulation($uid) { @@ -1243,9 +1490,17 @@ class MYSQLi_DB implements IDbConnection { } function setVillageField($ref, $field, $value) { - list($ref, $field, $value) = $this->escape_input((int) $ref, $field, $value); + if (!is_array($field)) { + $field = [$field]; + $value = [$value]; + } - $q = "UPDATE " . TB_PREFIX . "vdata set $field = '$value' where wref = $ref"; + $pairs = []; + foreach ($field as $index => $fieldValue) { + $pairs[] = $this->escape($fieldValue).' = '.((Math::isInt($value[$index]) || Math::isFloat($value[$index])) ? $value[$index] : '"'.$this->escape($value[$index]).'"'); + } + + $q = "UPDATE " . TB_PREFIX . "vdata SET ".implode(', ', $pairs)." WHERE wref = ".(int) $ref; return mysqli_query($this->dblink,$q); } @@ -1278,7 +1533,7 @@ class MYSQLi_DB implements IDbConnection { } $q = "UPDATE " . TB_PREFIX . "fdata set ".implode(', ', $fieldValues)." where vref = " . $ref; - return mysqli_query($this->dblink,$q) OR DIE (mysqli_error($this->dblink) . ' ... ' . $q); + return mysqli_query($this->dblink,$q); } function getResourceLevel($vid) { @@ -1318,14 +1573,25 @@ class MYSQLi_DB implements IDbConnection { } //end fix - function getCoor($wref) { + function getCoor($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$coordsCache, $wref)) && !is_null($cachedValue)) { + return $cachedValue; + } + if ($wref !=""){ - $q = "SELECT x,y FROM " . TB_PREFIX . "wdata where id = $wref"; - $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_array($result); - } + $q = "SELECT x,y FROM " . TB_PREFIX . "wdata where id = $wref"; + $result = mysqli_query($this->dblink,$q); + + self::$coordsCache[$wref] = mysqli_fetch_array($result); + } else { + self::$coordsCache[$wref] = false; + } + + return self::$coordsCache[$wref]; } function CheckForum($id) { @@ -1832,12 +2098,20 @@ class MYSQLi_DB implements IDbConnection { return $dbarray[$field]; } - function getAlliance($id) { + function getAlliance($id, $use_cache = true) { $id = (int) $id; + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$allianceDataCache, $id)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT * from " . TB_PREFIX . "alidata where id = $id"; $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_assoc($result); + + self::$allianceDataCache[$id] = mysqli_fetch_assoc($result); + return self::$allianceDataCache[$id]; } function setAlliName($aid, $name, $tag) { @@ -2016,7 +2290,25 @@ class MYSQLi_DB implements IDbConnection { $q = "INSERT into " . TB_PREFIX . "ali_permission values(0,'$uid','$aid','$rank','$opt1','$opt2','$opt3','$opt4','$opt5','$opt6','$opt7','$opt8')"; mysqli_query($this->dblink,$q); - return mysqli_insert_id($this->dblink); + + // update cache + $insertID = mysqli_insert_id($this->dblink); + self::$alliancePermissionsCache[$uid.$aid] = [ + 'id' => $insertID, + 'uid' => $uid, + 'alliance' => $aid, + 'rank' => $rank, + 'opt1' => $opt1, + 'opt2' => $opt2, + 'opt3' => $opt3, + 'opt4' => $opt4, + 'opt5' => $opt5, + 'opt6' => $opt6, + 'opt7' => $opt7, + 'opt8' => $opt8 + ]; + + return $insertID; } /***************************************** @@ -2036,6 +2328,18 @@ class MYSQLi_DB implements IDbConnection { function updateAlliPermissions($uid, $aid, $rank, $opt1, $opt2, $opt3, $opt4, $opt5, $opt6, $opt7) { list($uid, $aid, $rank, $opt1, $opt2, $opt3, $opt4, $opt5, $opt6, $opt7) = $this->escape_input((int) $uid, (int) $aid, $rank, $opt1, $opt2, $opt3, $opt4, $opt5, $opt6, $opt7); + // update cache + if (isset(self::$alliancePermissionsCache[$uid.$aid])) { + self::$alliancePermissionsCache[ $uid . $aid ]['rank'] = $rank; + self::$alliancePermissionsCache[ $uid . $aid ]['opt1'] = $opt1; + self::$alliancePermissionsCache[ $uid . $aid ]['opt2'] = $opt2; + self::$alliancePermissionsCache[ $uid . $aid ]['opt3'] = $opt3; + self::$alliancePermissionsCache[ $uid . $aid ]['opt4'] = $opt4; + self::$alliancePermissionsCache[ $uid . $aid ]['opt5'] = $opt5; + self::$alliancePermissionsCache[ $uid . $aid ]['opt6'] = $opt6; + self::$alliancePermissionsCache[ $uid . $aid ]['opt7'] = $opt7; + self::$alliancePermissionsCache[ $uid . $aid ]['opt8'] = $opt8; + } $q = "UPDATE " . TB_PREFIX . "ali_permission SET rank = '$rank', opt1 = '$opt1', opt2 = '$opt2', opt3 = '$opt3', opt4 = '$opt4', opt5 = '$opt5', opt6 = '$opt6', opt7 = '$opt7' where uid = $uid && alliance =$aid"; return mysqli_query($this->dblink,$q); @@ -2045,12 +2349,20 @@ class MYSQLi_DB implements IDbConnection { Function to read alliance permissions References: ID, notice, description *****************************************/ - function getAlliPermissions($uid, $aid) { + function getAlliPermissions($uid, $aid, $use_cache = true) { list($uid, $aid) = $this->escape_input((int) $uid, (int) $aid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$alliancePermissionsCache, $uid.$aid)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT * FROM " . TB_PREFIX . "ali_permission where uid = $uid && alliance = $aid"; $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_assoc($result); + + self::$alliancePermissionsCache[$uid.$aid] = mysqli_fetch_assoc($result); + return self::$alliancePermissionsCache[$uid.$aid]; } /***************************************** @@ -2738,17 +3050,25 @@ class MYSQLi_DB implements IDbConnection { return $vill; } - function getVSumField($uid, $field) { + function getVSumField($uid, $field, $use_cache = true) { list($uid, $field) = $this->escape_input((int) $uid, $field); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$userSumFieldCache, $uid.$field)) && !is_null($cachedValue)) { + return $cachedValue; + } + if($field != "cp"){ - $q = "SELECT sum(" . $field . ") FROM " . TB_PREFIX . "vdata where owner = $uid"; + $q = "SELECT sum(" . $field . ") FROM " . TB_PREFIX . "vdata where owner = $uid"; }else{ - $q = "SELECT sum(" . $field . ") FROM " . TB_PREFIX . "vdata where owner = $uid and natar = 0"; + $q = "SELECT sum(" . $field . ") FROM " . TB_PREFIX . "vdata where owner = $uid and natar = 0"; } $result = mysqli_query($this->dblink,$q); $row = mysqli_fetch_row($result); - return $row[0]; + + self::$userSumFieldCache[$uid.$field] = $row[0]; + return self::$userSumFieldCache[$uid.$field]; } function updateVillage($vid) { @@ -2876,10 +3196,28 @@ class MYSQLi_DB implements IDbConnection { } $time = time(); - $q = "INSERT INTO " . TB_PREFIX . "mdata values (0,$client,$owner,'$topic','$message',0,0,$send,$time,0,0,$alliance,$player,$coor,$report)"; - return mysqli_query($this->dblink,$q); + + // add this message to the query cache, so we save some queries + // if we need to send multiple messages at once + self::$sendMessageQueryCache[] = "(0,$client,$owner,'$topic','$message',0,0,$send,$time,0,0,$alliance,$player,$coor,$report)"; + + // check if we don't have too many messages to be sent out cached, + // in which case we'll flush the cache and start again + $retValue = true; + if (count(self::$sendMessageQueryCache) >= self::$sendMessageQueryCacheMaxRecords) { + $retValue = mysqli_query($this->dblink, "INSERT INTO " . TB_PREFIX . "mdata VALUES " . implode(', ', self::$sendMessageQueryCache)); + self::$sendMessageQueryCache = []; + } + + return $retValue; } + public function sendPendingMessages() { + if (count(self::$sendMessageQueryCache)) { + mysqli_query($this->dblink, "INSERT INTO " . TB_PREFIX . "mdata VALUES " . implode(', ', self::$sendMessageQueryCache)); + } + } + function setArchived($id) { list($id) = $this->escape_input((int) $id); @@ -3823,9 +4161,15 @@ class MYSQLi_DB implements IDbConnection { References: id ***************************/ function setMarketAcc($id) { - list($id) = $this->escape_input((int) $id); + if (!is_array($id)) { + $id = [$id]; + } - $q = "UPDATE " . TB_PREFIX . "market set accept = 1 where id = $id"; + foreach ($id as $index => $value) { + $id[$index] = (int) $value; + } + + $q = "UPDATE " . TB_PREFIX . "market set accept = 1 where id IN(".implode(', ', $id ).")"; return mysqli_query($this->dblink,$q); } @@ -3836,14 +4180,30 @@ class MYSQLi_DB implements IDbConnection { References: Wood/ID, Clay, Iron, Crop, Mode ***************************/ function sendResource($ref, $clay, $iron, $crop, $merchant, $mode) { - list($ref, $clay, $iron, $crop, $merchant, $mode) = $this->escape_input((int) $ref, (int) $clay, (int) $iron, (int) $crop, (int) $merchant, $mode); + // always prepare for multiple inserts at once + if (!is_array($ref)) { + $ref = [$ref]; + $clay = [$clay]; + $iron = [$iron]; + $crop = [$crop]; + $merchant = [$merchant]; + } + + $pairs = []; + foreach ($ref as $index => $refValue) { + if(!$mode) { + $pairs[] = '(0, ' . (int) $refValue . ', ' . (int) $clay[$index] . ', ' . (int) $iron[$index] . ', ' . (int) $crop[$index] . ', ' . (int) $merchant[$index] . ')'; + } else { + $pairs[] = (int) $refValule; + } + } if(!$mode) { - $q = "INSERT INTO " . TB_PREFIX . "send values (0,$ref,$clay,$iron,$crop,$merchant)"; + $q = "INSERT INTO " . TB_PREFIX . "send VALUES ".implode(', ', $pairs); mysqli_query($this->dblink,$q); return mysqli_insert_id($this->dblink); } else { - $q = "DELETE FROM " . TB_PREFIX . "send where id = $ref"; + $q = "DELETE FROM " . TB_PREFIX . "send WHERE id IN(".implode(', ', $pairs).")"; return mysqli_query($this->dblink,$q); } } @@ -3882,15 +4242,64 @@ class MYSQLi_DB implements IDbConnection { Made by: Dzoki ***************************/ - function getMarketField($vref, $field) { + function getMarketField($vref, $field, $use_cache = true) { list($vref, $field) = $this->escape_input($vref, $field); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$marketFieldCache, $vref.$field)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT $field FROM " . TB_PREFIX . "market where vref = '$vref'"; $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); $dbarray = mysqli_fetch_array($result); - return $dbarray[$field]; + + self::$marketFieldCache[$vref.$field] = $dbarray[$field]; + return self::$marketFieldCache[$vref.$field]; } + function getMarketFields($vref, $fields, $use_cache = true) { + $vref = (int) $vref; + + if (!is_array($fields)) { + $fields = [$fields]; + } + + // check fields one by one to see which ones we can return cached + if ($use_cache) { + $allFieldsFound = false; + $fieldsLeft = []; + $fieldValues = []; + + // iterate over all the fields and see what we have cached + foreach ($fields as $fieldName) { + if (($cached = self::returnCachedContent(self::$marketFieldCache, $vref.$fieldName)) && !is_null($cached)) { + $fieldValues[$fieldName] = $cached; + } else { + $fieldsLeft[] = $fieldName; + } + } + + // check if we should return here (if we have all the values) or continue with the rest below + if (!count($fieldsLeft)) { + return $fieldValues; + } + } + + $q = "SELECT ".implode(', ', $fieldsLeft)." FROM " . TB_PREFIX . "market where vref = ".$vref; + $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); + $dbarray = mysqli_fetch_array($result, MYSQLI_ASSOC); + + // cache results and return everything that we have + foreach ($dbarray as $fieldName => $fieldValue) { + $fieldValues[$fieldName] = $fieldValue; + self::$marketFieldCache[$vref.$fieldName] = $fieldValue; + } + + return $fieldValues; + } + function removeAcceptedOffer($id) { list($id) = $this->escape_input((int) $id); @@ -3952,6 +4361,10 @@ class MYSQLi_DB implements IDbConnection { list($moveid) = $this->escape_input($moveid); } + // rather than re-selecting data and updating cache here, let's just + // flush the cache and let it re-cach itself as neccessary + self::$marketMovementCache = []; + $q = "UPDATE " . TB_PREFIX . "movement set proc = 1 where moveid IN($moveid)"; return mysqli_query($this->dblink,$q); } @@ -3976,9 +4389,15 @@ class MYSQLi_DB implements IDbConnection { return $row[0] + $row2[0] + $row3[0]; } - function getMovement($type, $village, $mode) { + function getMovement($type, $village, $mode, $use_cache = true) { list($type, $village, $mode) = $this->escape_input($type, $village, $mode); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$marketMovementCache, $type.$village.$mode)) && !is_null($cachedValue)) { + return $cachedValue; + } + $time = time(); if(!$mode) { $where = "from"; @@ -4022,7 +4441,9 @@ class MYSQLi_DB implements IDbConnection { } $result = mysqli_query($this->dblink,$q); $array = $this->mysqli_fetch_all($result); - return $array; + + self::$marketMovementCache[$type.$village.$mode] = $array; + return self::$marketMovementCache[$type.$village.$mode]; } function addA2b($ckey, $timestamp, $to, $t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10, $t11, $type) { @@ -4046,9 +4467,28 @@ class MYSQLi_DB implements IDbConnection { } function addMovement($type, $from, $to, $ref, $time, $endtime, $send = 1, $wood = 0, $clay = 0, $iron = 0, $crop = 0, $ref2 = 0) { - list($type, $from, $to, $ref, $time, $endtime, $send, $wood, $clay, $iron, $crop, $ref2) = $this->escape_input((int) $type, (int) $from, (int) $to, (int) $ref, (int) $time, (int) $endtime, (int) $send, (int) $wood, (int) $clay, (int) $iron, (int) $crop, (int) $ref2); + // always prepare for multiple inserts at once + if (!is_array($type)) { + $type = [$type]; + $from = [$from]; + $to = [$to]; + $ref = [$ref]; + $time = [$time]; + $endtime = [$endtime]; + $send = [$send]; + $wood = [$wood]; + $clay = [$clay]; + $iron = [$iron]; + $crop = [$crop]; + $ref2 = [$ref2]; + } - $q = "INSERT INTO " . TB_PREFIX . "movement values (0,$type,$from,$to,$ref,$ref2,$time,$endtime,0,$send,$wood,$clay,$iron,$crop)"; + $pairs = []; + foreach ($type as $index => $typeValue) { + $pairs[] = '(0, '.(int) $typeValue.', '.(int) $from[$index].', '.(int) $to[$index].', '.(int) $ref[$index].', '.(int) $ref2[$index].', '.(int) $time[$index].', '.(int) $endtime[$index].', 0, '.(int) $send[$index].', '.(int) $wood[$index].', '.(int) $clay[$index].', '.(int) $iron[$index].', '.(int) $crop[$index].')'; + } + + $q = "INSERT INTO " . TB_PREFIX . "movement VALUES ".implode(', ', $pairs); return mysqli_query($this->dblink,$q); } @@ -4121,20 +4561,24 @@ class MYSQLi_DB implements IDbConnection { return $this->mysqli_fetch_all($result); } - function getAllMember($aid) { + function getAllMember($aid, $limit = 0, $use_cache = true) { list($aid) = $this->escape_input((int) $aid); - $q = "SELECT * FROM " . TB_PREFIX . "users where alliance = $aid order by (SELECT sum(pop) FROM " . TB_PREFIX . "vdata WHERE owner = " . TB_PREFIX . "users.id) desc, " . TB_PREFIX . "users.id desc"; + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$allianceMembersCache, $aid)) && !is_null($cachedValue)) { + return $cachedValue; + } + + $q = "SELECT * FROM " . TB_PREFIX . "users where alliance = $aid order by (SELECT sum(pop) FROM " . TB_PREFIX . "vdata WHERE owner = " . TB_PREFIX . "users.id) desc, " . TB_PREFIX . "users.id desc".($limit > 0 ? ' LIMIT '.(int) $limit : ''); $result = mysqli_query($this->dblink,$q); - return $this->mysqli_fetch_all($result); + + self::$allianceMembersCache[$aid] = $this->mysqli_fetch_all($result); + return self::$allianceMembersCache[$aid]; } function getAllMember2($aid) { - list($aid) = $this->escape_input((int) $aid); - - $q = "SELECT * FROM " . TB_PREFIX . "users where alliance = $aid order by (SELECT sum(pop) FROM " . TB_PREFIX . "vdata WHERE owner = " . TB_PREFIX . "users.id) desc, " . TB_PREFIX . "users.id desc LIMIT 1"; - $result = mysqli_query($this->dblink,$q); - return mysqli_fetch_array($result); + return $this->getAllMember($aid, 1); } function addUnits($vid) { @@ -4183,9 +4627,15 @@ class MYSQLi_DB implements IDbConnection { return $totalunits; } - function getHero($uid=0, $all=0, $include_dead = false) { + function getHero($uid=0, $all=0, $include_dead = false, $use_cache = true) { list($uid,$all) = $this->escape_input((int) $uid,$all); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$heroCache, $uid.$all.($include_dead ? 1 : 0))) && !is_null($cachedValue)) { + return $cachedValue; + } + if ($all) { $q = "SELECT * FROM ".TB_PREFIX."hero WHERE uid=$uid ORDER BY lastupdate DESC"; } elseif (!$uid) { @@ -4193,19 +4643,31 @@ class MYSQLi_DB implements IDbConnection { } else { $q = "SELECT * FROM ".TB_PREFIX."hero WHERE ".($include_dead ? '' : "dead=0 AND ")."uid=$uid LIMIT 1"; } + $result = mysqli_query($this->dblink,$q); if (!empty($result)) { - return $this->mysqli_fetch_all($result); + self::$heroCache[$uid.$all.($include_dead ? 1 : 0)] = $this->mysqli_fetch_all($result); } else { - return NULL; + self::$heroCache[$uid.$all.($include_dead ? 1 : 0)] = null; } + + return self::$heroCache[$uid.$all.($include_dead ? 1 : 0)]; } - function getHeroField($uid,$field) { + function getHeroField($uid,$field, $use_cache = true) { list($uid,$field) = $this->escape_input((int) $uid,$field); - $q = "SELECT * FROM ".TB_PREFIX."hero WHERE uid = $uid AND dead = 0"; - $result = mysqli_query($this->dblink,$q); - return $this->mysqli_fetch_all($result); + + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$heroFieldCache, $uid.$field)) && !is_null($cachedValue)) { + return $cachedValue; + } + + $q = "SELECT * FROM ".TB_PREFIX."hero WHERE uid = $uid AND dead = 0"; + $result = mysqli_query($this->dblink,$q); + + self::$heroFieldCache[$uid.$field] = $this->mysqli_fetch_all($result); + return self::$heroFieldCache[$uid.$field]; } function modifyHero($column,$value,$heroid,$mode=0) { @@ -4774,18 +5236,34 @@ class MYSQLi_DB implements IDbConnection { return $this->mysqli_fetch_all($result); } - function countUser() { + function countUser($use_cache = true) { + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$usersCountCache, 0)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT count(id) FROM " . TB_PREFIX . "users where id > 5"; $result = mysqli_query($this->dblink,$q); $row = mysqli_fetch_row($result); - return $row[0]; + + self::$usersCountCache[0] = $row[0]; + return self::$usersCountCache[0]; } - function countAlli() { + function countAlli($use_cache = true) { + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$allianceCountCache, 0)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT count(id) FROM " . TB_PREFIX . "alidata where id != 0"; $result = mysqli_query($this->dblink,$q); $row = mysqli_fetch_row($result); - return $row[0]; + + self::$allianceCountCache[0] = $row[0]; + return self::$allianceCountCache[0]; } /*************************** @@ -4824,40 +5302,84 @@ class MYSQLi_DB implements IDbConnection { } //MARKET FIXES - function getWoodAvailable($wref) { + function getWoodAvailable($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['wood'])) { + return $cachedValue['wood']; + } + } + $q = "SELECT wood FROM " . TB_PREFIX . "vdata WHERE wref = $wref"; $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); $dbarray = mysqli_fetch_array($result); - return $dbarray['wood']; + + self::$villageFieldsCache[$wref]['wood'] = $dbarray['wood']; + return self::$villageFieldsCache[$wref]['wood']; } - function getClayAvailable($wref) { + function getClayAvailable($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['clay'])) { + return $cachedValue['clay']; + } + } + $q = "SELECT clay FROM " . TB_PREFIX . "vdata WHERE wref = $wref"; $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); $dbarray = mysqli_fetch_array($result); - return $dbarray['clay']; + + self::$villageFieldsCache[$wref]['clay'] = $dbarray['clay']; + return self::$villageFieldsCache[$wref]['clay']; } - function getIronAvailable($wref) { + function getIronAvailable($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['iron'])) { + return $cachedValue['iron']; + } + } + $q = "SELECT iron FROM " . TB_PREFIX . "vdata WHERE wref = $wref"; $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); $dbarray = mysqli_fetch_array($result); - return $dbarray['iron']; + + self::$villageFieldsCache[$wref]['iron'] = $dbarray['iron']; + return self::$villageFieldsCache[$wref]['iron']; } - function getCropAvailable($wref) { + function getCropAvailable($wref, $use_cache = true) { list($wref) = $this->escape_input((int) $wref); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$villageFieldsCache, $wref)) && !is_null($cachedValue)) { + // check if we have the requested field type cached + if (isset($cachedValue['crop'])) { + return $cachedValue['crop']; + } + } + $q = "SELECT crop FROM " . TB_PREFIX . "vdata WHERE wref = $wref"; $result = mysqli_query($this->dblink,$q) or die(mysqli_error($this->dblink)); $dbarray = mysqli_fetch_array($result); - return $dbarray['crop']; + + self::$villageFieldsCache[$wref]['crop'] = $dbarray['crop']; + return self::$villageFieldsCache[$wref]['crop']; } function Getowner($vid) { @@ -5144,24 +5666,36 @@ class MYSQLi_DB implements IDbConnection { return mysqli_fetch_array($result); } - function getOwnUniqueArtefactInfo2($id, $type, $size, $mode) { + function getOwnUniqueArtefactInfo2($id, $type, $size, $mode, $use_cache = true) { list($id, $type, $size, $mode) = $this->escape_input((int) $id, (int) $type, (int) $size, $mode); - if(!$mode){ - $q = "SELECT * FROM " . TB_PREFIX . "artefacts WHERE owner = $id AND active = 1 AND type = $type AND size=$size"; - }else{ - $q = "SELECT * FROM " . TB_PREFIX . "artefacts WHERE vref = $id AND active = 1 AND type = $type AND size=$size"; - } + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$artefactDataCache, $id.$type.$size.$mode)) && !is_null($cachedValue)) { + return $cachedValue; + } + + $q = "SELECT * FROM " . TB_PREFIX . "artefacts WHERE ".(!$mode ? 'owner' : 'vref')." = $id AND active = 1 AND type = $type AND size=$size"; $result = mysqli_query($this->dblink,$q); - return $this->mysqli_fetch_all($result); + + self::$artefactDataCache[$id.$type.$size.$mode] = $this->mysqli_fetch_all($result); + return self::$artefactDataCache[$id.$type.$size.$mode]; } - function getFoolArtefactInfo($type,$vid,$uid) { + function getFoolArtefactInfo($type,$vid,$uid, $use_cache = true) { list($type,$vid,$uid) = $this->escape_input((int) $type,(int) $vid,(int) $uid); + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$foolArtefactCache, $type.$vid.$uid)) && !is_null($cachedValue)) { + return $cachedValue; + } + $q = "SELECT * FROM " . TB_PREFIX . "artefacts WHERE vref = $vid AND ((type = 8 AND kind = $type) OR (owner = $uid AND size > 1 AND active = 1 AND type = 8 AND kind = $type))"; $result = mysqli_query($this->dblink,$q); - return $this->mysqli_fetch_all($result); + + self::$foolArtefactCache[$type.$vid.$uid] = $this->mysqli_fetch_all($result); + return self::$foolArtefactCache[$type.$vid.$uid]; } function claimArtefact($vref, $ovref, $id) { @@ -5638,15 +6172,23 @@ References: ***************************/ function getHeroDead($id) { - list($id) = $this->escape_input((int) $id); + list($id) = $this->escape_input((int) $id, $use_cache = true); - $q = "SELECT Count(*) as Total FROM " . TB_PREFIX . "hero WHERE `uid` = $id AND dead = 0"; - $result = mysqli_fetch_array(mysqli_query($this->dblink,$q), MYSQLI_ASSOC); - if ($result['Total'] > 0) { - return 0; - } else { - return 1; - } + // first of all, check if we should be using cache and whether the field + // required is already cached + if ($use_cache && ($cachedValue = self::returnCachedContent(self::$heroDeadCache, $id)) && !is_null($cachedValue)) { + return $cachedValue; + } + + $q = "SELECT Count(*) as Total FROM " . TB_PREFIX . "hero WHERE `uid` = $id AND dead = 0"; + $result = mysqli_fetch_array(mysqli_query($this->dblink,$q), MYSQLI_ASSOC); + if ($result['Total'] > 0) { + self::$heroDeadCache[$id] = 0; + } else { + self::$heroDeadCache[$id] = 1; + } + + return self::$heroDeadCache[$id]; } /*************************** @@ -5871,5 +6413,12 @@ if (!in_array($req_file, ['tutorial.php', 'anleitung.php'])) { $link = $database->return_link(); $GLOBALS['db'] = $database; $GLOBALS['link'] = $database->return_link(); + + // register all functions to be executed when the script is over, + // so we can flush any SQL caches we may still have pending + register_shutdown_function(function() { + global $database; + $database->sendPendingMessages(); + }); } ?> \ No newline at end of file diff --git a/GameEngine/Database/db_MYSQL.php b/GameEngine/Database/db_MYSQL.php deleted file mode 100755 index e69de29b..00000000 diff --git a/GameEngine/Market.php b/GameEngine/Market.php index ed2bc019..889d96bc 100755 --- a/GameEngine/Market.php +++ b/GameEngine/Market.php @@ -94,7 +94,10 @@ class Market $wtrans = str_replace("-", "", $wtrans); $ctrans = str_replace("-", "", $ctrans); $itrans = str_replace("-", "", $itrans); - $crtrans = str_replace("-", "", $crtrans); + $crtrans = str_replace("-", "", $crtrans); + // preload all village data, since we're retrieving some of those separately below + $database->getVillage($village->wid); + $availableWood = $database->getWoodAvailable($village->wid); $availableClay = $database->getClayAvailable($village->wid); $availableIron = $database->getIronAvailable($village->wid); @@ -130,8 +133,9 @@ class Market exit; } else - { - // something + { + // TODO: WTF??? :D + // something } } @@ -163,7 +167,11 @@ class Market $wood = ($post['rid1'] == 1)? $post['m1'] : 0; $clay = ($post['rid1'] == 2)? $post['m1'] : 0; $iron = ($post['rid1'] == 3)? $post['m1'] : 0; - $crop = ($post['rid1'] == 4)? $post['m1'] : 0; + $crop = ($post['rid1'] == 4)? $post['m1'] : 0; + + // preload all village data, since we're retrieving some of those separately below + $database->getVillage($village->wid); + $availableWood = $database->getWoodAvailable($village->wid); $availableClay = $database->getClayAvailable($village->wid); $availableIron = $database->getIronAvailable($village->wid); @@ -235,16 +243,23 @@ class Market } } $myresource = $hisresource = array(1=>0,0,0,0); - $myresource[$infoarray['wtype']] = $infoarray['wamt']; - $mysendid = $database->sendResource($myresource[1],$myresource[2],$myresource[3],$myresource[4],$reqMerc,0); - $hisresource[$infoarray['gtype']] = $infoarray['gamt']; - $hissendid = $database->sendResource($hisresource[1],$hisresource[2],$hisresource[3],$hisresource[4],$infoarray['merchant'],0); + $myresource[$infoarray['wtype']] = $infoarray['wamt']; + $mysendid = $database->sendResource($myresource[1],$myresource[2],$myresource[3],$myresource[4],$reqMerc,0); + $hisresource[$infoarray['gtype']] = $infoarray['gamt']; + $hissendid = $database->sendResource($hisresource[1],$hisresource[2],$hisresource[3],$hisresource[4],$infoarray['merchant'],0); $hiscoor = $database->getCoor($infoarray['vref']); $mytime = $generator->procDistanceTime($hiscoor,$village->coor,$session->tribe,0); $targettribe = $database->getUserField($database->getVillageField($infoarray['vref'],"owner"),"tribe",0); - $histime = $generator->procDistanceTime($village->coor,$hiscoor,$targettribe,0); - $database->addMovement(0,$village->wid,$infoarray['vref'],$mysendid,time(),$mytime+time()); - $database->addMovement(0,$infoarray['vref'],$village->wid,$hissendid,time(),$histime+time()); + $histime = $generator->procDistanceTime($village->coor,$hiscoor,$targettribe,0); + $timestamp = time(); + $database->addMovement( + [0, 0], + [$village->wid, $infoarray['vref']], + [$infoarray['vref'], $village->wid], + [$mysendid, $hissendid], + [$timestamp, $timestamp], + [$mytime + $timestamp, $histime + $timestamp] + ); $resource = array(1=>0,0,0,0); $resource[$infoarray['wtype']] = $infoarray['wamt']; $database->modifyResource($village->wid,$resource[1],$resource[2],$resource[3],$resource[4],0); @@ -346,11 +361,12 @@ class Market } else if (($post['m2'][0]+$post['m2'][1]+$post['m2'][2]+$post['m2'][3])<=(round($village->awood)+round($village->aclay)+round($village->airon)+round($village->acrop))) { - $database->setVillageField($village->wid,"wood",$post['m2'][0]); - $database->setVillageField($village->wid,"clay",$post['m2'][1]); - $database->setVillageField($village->wid,"iron",$post['m2'][2]); - $database->setVillageField($village->wid,"crop",$post['m2'][3]); - $database->modifyGold($session->uid,3,0); + $database->setVillageField( + $village->wid, + ["wood", "clay", "iron", "crop"], + [$post['m2'][0], $post['m2'][1], $post['m2'][2], $post['m2'][3]] + ); + $database->modifyGold($session->uid,3,0); header("Location: build.php?id=".$post['id']."&t=3&c");; exit; } diff --git a/GameEngine/Message.php b/GameEngine/Message.php index f13d1a70..fc1d8dfe 100755 --- a/GameEngine/Message.php +++ b/GameEngine/Message.php @@ -40,9 +40,9 @@ class Message { break; case "m2": if ($post['an'] == "[ally]"){ - $this->sendAMessage($post['be'],addslashes($post['message'])); + $this->sendAMessage($post['be'],addslashes($post['message'])); }else{ - $this->sendMessage($post['an'],$post['be'],addslashes($post['message'])); + $this->sendMessage($post['an'],$post['be'],addslashes($post['message'])); } header("Location: nachrichten.php?t=2"); exit; @@ -51,8 +51,8 @@ class Message { case "m4": case "m5": if(isset($post['delmsg_x'])) { - $this->removeMessage($post); - $this->header($get); + $this->removeMessage($post); + $this->header($get); } if(isset($post['archive_x'])) { $this->archiveMessage($post); @@ -346,75 +346,83 @@ class Message { $allmembersQ = mysqli_query($GLOBALS['link'],"SELECT id FROM ".TB_PREFIX."users WHERE alliance='".$session->alliance."'"); $userally = $database->getUserField($session->uid,"alliance",0); $permission=mysqli_fetch_array(mysqli_query($GLOBALS['link'],"SELECT opt7 FROM ".TB_PREFIX."ali_permission WHERE uid='".$session->uid."'")); + if(WORD_CENSOR) { - $topic = $this->wordCensor($topic); - $text = $this->wordCensor($text); + $topic = $this->wordCensor($topic); + $text = $this->wordCensor($text); } + if($topic == "") { - $topic = "No subject"; + $topic = "No subject"; } + if(!preg_match('/\[message\]/',$text) && !preg_match('/\[\/message\]/',$text)){ - $text = "[message]".$text."[/message]"; - $alliance = $player = $coor = $report = 0; - for($i=0;$i<=$alliance;$i++){ - if(preg_match('/\[alliance'.$i.'\]/',$text) && preg_match('/\[\/alliance'.$i.'\]/',$text)){ - $alliance1 = preg_replace('/\[message\](.*?)\[\/alliance'.$i.'\]/is', '', $text); - if(preg_match('/\[alliance'.$i.'\]/',$alliance1) && preg_match('/\[\/alliance'.$i.'\]/',$alliance1)){ - $j = $i+1; - $alliance2 = preg_replace('/\[\/alliance'.$i.'\](.*?)\[\/message\]/is', '', $text); - $alliance1 = preg_replace('/\[alliance'.$i.'\]/', '[alliance'.$j.']', $alliance1); - $alliance1 = preg_replace('/\[\/alliance'.$i.'\]/', '[/alliance'.$j.']', $alliance1); - $text = $alliance2."[/alliance".$i."]".$alliance1; - $alliance += 1; - } - } - } - for($i=0;$i<=$player;$i++){ - if(preg_match('/\[player'.$i.'\]/',$text) && preg_match('/\[\/player'.$i.'\]/',$text)){ - $player1 = preg_replace('/\[message\](.*?)\[\/player'.$i.'\]/is', '', $text); - if(preg_match('/\[player'.$i.'\]/',$player1) && preg_match('/\[\/player'.$i.'\]/',$player1)){ - $j = $i+1; - $player2 = preg_replace('/\[\/player'.$i.'\](.*?)\[\/message\]/is', '', $text); - $player1 = preg_replace('/\[player'.$i.'\]/', '[player'.$j.']', $player1); - $player1 = preg_replace('/\[\/player'.$i.'\]/', '[/player'.$j.']', $player1); - $text = $player2."[/player".$i."]".$player1; - $player += 1; - } - } - } - for($i=0;$i<=$coor;$i++){ - if(preg_match('/\[coor'.$i.'\]/',$text) && preg_match('/\[\/coor'.$i.'\]/',$text)){ - $coor1 = preg_replace('/\[message\](.*?)\[\/coor'.$i.'\]/is', '', $text); - if(preg_match('/\[coor'.$i.'\]/',$coor1) && preg_match('/\[\/coor'.$i.'\]/',$coor1)){ - $j = $i+1; - $coor2 = preg_replace('/\[\/coor'.$i.'\](.*?)\[\/message\]/is', '', $text); - $coor1 = preg_replace('/\[coor'.$i.'\]/', '[coor'.$j.']', $coor1); - $coor1 = preg_replace('/\[\/coor'.$i.'\]/', '[/coor'.$j.']', $coor1); - $text = $coor2."[/coor".$i."]".$coor1; - $coor += 1; - } - } - } - for($i=0;$i<=$report;$i++){ - if(preg_match('/\[report'.$i.'\]/',$text) && preg_match('/\[\/report'.$i.'\]/',$text)){ - $report1 = preg_replace('/\[message\](.*?)\[\/report'.$i.'\]/is', '', $text); - if(preg_match('/\[report'.$i.'\]/',$report1) && preg_match('/\[\/report'.$i.'\]/',$report1)){ - $j = $i+1; - $report2 = preg_replace('/\[\/report'.$i.'\](.*?)\[\/message\]/is', '', $text); - $report1 = preg_replace('/\[report'.$i.'\]/', '[report'.$j.']', $report1); - $report1 = preg_replace('/\[\/report'.$i.'\]/', '[/report'.$j.']', $report1); - $text = $report2."[/report".$i."]".$report1; - $report += 1; - } - } - } - if($permission[opt7]==1){ - if ($userally != 0) { - while ($allmembers = mysqli_fetch_array($allmembersQ)) { - $database->sendMessage($allmembers[id],$session->uid,htmlspecialchars(addslashes($topic)),htmlspecialchars(addslashes($text)),0,$alliance,$player,$coor,$report); - } - } - } + $text = "[message]".$text."[/message]"; + $alliance = $player = $coor = $report = 0; + + for ( $i = 0; $i <= $alliance; $i ++ ) { + if ( preg_match( '/\[alliance' . $i . '\]/', $text ) && preg_match( '/\[\/alliance' . $i . '\]/', $text ) ) { + $alliance1 = preg_replace( '/\[message\](.*?)\[\/alliance' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[alliance' . $i . '\]/', $alliance1 ) && preg_match( '/\[\/alliance' . $i . '\]/', $alliance1 ) ) { + $j = $i + 1; + $alliance2 = preg_replace( '/\[\/alliance' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $alliance1 = preg_replace( '/\[alliance' . $i . '\]/', '[alliance' . $j . ']', $alliance1 ); + $alliance1 = preg_replace( '/\[\/alliance' . $i . '\]/', '[/alliance' . $j . ']', $alliance1 ); + $text = $alliance2 . "[/alliance" . $i . "]" . $alliance1; + $alliance += 1; + } + } + } + + for ( $i = 0; $i <= $player; $i ++ ) { + if ( preg_match( '/\[player' . $i . '\]/', $text ) && preg_match( '/\[\/player' . $i . '\]/', $text ) ) { + $player1 = preg_replace( '/\[message\](.*?)\[\/player' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[player' . $i . '\]/', $player1 ) && preg_match( '/\[\/player' . $i . '\]/', $player1 ) ) { + $j = $i + 1; + $player2 = preg_replace( '/\[\/player' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $player1 = preg_replace( '/\[player' . $i . '\]/', '[player' . $j . ']', $player1 ); + $player1 = preg_replace( '/\[\/player' . $i . '\]/', '[/player' . $j . ']', $player1 ); + $text = $player2 . "[/player" . $i . "]" . $player1; + $player += 1; + } + } + } + + for ( $i = 0; $i <= $coor; $i ++ ) { + if ( preg_match( '/\[coor' . $i . '\]/', $text ) && preg_match( '/\[\/coor' . $i . '\]/', $text ) ) { + $coor1 = preg_replace( '/\[message\](.*?)\[\/coor' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[coor' . $i . '\]/', $coor1 ) && preg_match( '/\[\/coor' . $i . '\]/', $coor1 ) ) { + $j = $i + 1; + $coor2 = preg_replace( '/\[\/coor' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $coor1 = preg_replace( '/\[coor' . $i . '\]/', '[coor' . $j . ']', $coor1 ); + $coor1 = preg_replace( '/\[\/coor' . $i . '\]/', '[/coor' . $j . ']', $coor1 ); + $text = $coor2 . "[/coor" . $i . "]" . $coor1; + $coor += 1; + } + } + } + + for ( $i = 0; $i <= $report; $i ++ ) { + if ( preg_match( '/\[report' . $i . '\]/', $text ) && preg_match( '/\[\/report' . $i . '\]/', $text ) ) { + $report1 = preg_replace( '/\[message\](.*?)\[\/report' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[report' . $i . '\]/', $report1 ) && preg_match( '/\[\/report' . $i . '\]/', $report1 ) ) { + $j = $i + 1; + $report2 = preg_replace( '/\[\/report' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $report1 = preg_replace( '/\[report' . $i . '\]/', '[report' . $j . ']', $report1 ); + $report1 = preg_replace( '/\[\/report' . $i . '\]/', '[/report' . $j . ']', $report1 ); + $text = $report2 . "[/report" . $i . "]" . $report1; + $report += 1; + } + } + } + + if($permission['opt7']==1){ + if ($userally != 0) { + while ($allmembers = mysqli_fetch_array($allmembersQ)) { + $database->sendMessage($allmembers[id],$session->uid,htmlspecialchars(addslashes($topic)),htmlspecialchars(addslashes($text)),0,$alliance,$player,$coor,$report); + } + } + } } } @@ -438,69 +446,75 @@ class Message { $topic = $this->wordCensor($topic); $text = $this->wordCensor($text); } + if($topic == "") { $topic = "No subject"; } - if(!preg_match('/\[message\]/',$text) && !preg_match('/\[\/message\]/',$text)){ - $text = "[message]".$text."[/message]"; - $alliance = $player = $coor = $report = 0; - for($i=0;$i<=$alliance;$i++){ - if(preg_match('/\[alliance'.$i.'\]/',$text) && preg_match('/\[\/alliance'.$i.'\]/',$text)){ - $alliance1 = preg_replace('/\[message\](.*?)\[\/alliance'.$i.'\]/is', '', $text); - if(preg_match('/\[alliance'.$i.'\]/',$alliance1) && preg_match('/\[\/alliance'.$i.'\]/',$alliance1)){ - $j = $i+1; - $alliance2 = preg_replace('/\[\/alliance'.$i.'\](.*?)\[\/message\]/is', '', $text); - $alliance1 = preg_replace('/\[alliance'.$i.'\]/', '[alliance'.$j.']', $alliance1); - $alliance1 = preg_replace('/\[\/alliance'.$i.'\]/', '[/alliance'.$j.']', $alliance1); - $text = $alliance2."[/alliance".$i."]".$alliance1; - $alliance += 1; - } - } - } - for($i=0;$i<=$player;$i++){ - if(preg_match('/\[player'.$i.'\]/',$text) && preg_match('/\[\/player'.$i.'\]/',$text)){ - $player1 = preg_replace('/\[message\](.*?)\[\/player'.$i.'\]/is', '', $text); - if(preg_match('/\[player'.$i.'\]/',$player1) && preg_match('/\[\/player'.$i.'\]/',$player1)){ - $j = $i+1; - $player2 = preg_replace('/\[\/player'.$i.'\](.*?)\[\/message\]/is', '', $text); - $player1 = preg_replace('/\[player'.$i.'\]/', '[player'.$j.']', $player1); - $player1 = preg_replace('/\[\/player'.$i.'\]/', '[/player'.$j.']', $player1); - $text = $player2."[/player".$i."]".$player1; - $player += 1; - } - } - } - for($i=0;$i<=$coor;$i++){ - if(preg_match('/\[coor'.$i.'\]/',$text) && preg_match('/\[\/coor'.$i.'\]/',$text)){ - $coor1 = preg_replace('/\[message\](.*?)\[\/coor'.$i.'\]/is', '', $text); - if(preg_match('/\[coor'.$i.'\]/',$coor1) && preg_match('/\[\/coor'.$i.'\]/',$coor1)){ - $j = $i+1; - $coor2 = preg_replace('/\[\/coor'.$i.'\](.*?)\[\/message\]/is', '', $text); - $coor1 = preg_replace('/\[coor'.$i.'\]/', '[coor'.$j.']', $coor1); - $coor1 = preg_replace('/\[\/coor'.$i.'\]/', '[/coor'.$j.']', $coor1); - $text = $coor2."[/coor".$i."]".$coor1; - $coor += 1; - } - } - } - for($i=0;$i<=$report;$i++){ - if(preg_match('/\[report'.$i.'\]/',$text) && preg_match('/\[\/report'.$i.'\]/',$text)){ - $report1 = preg_replace('/\[message\](.*?)\[\/report'.$i.'\]/is', '', $text); - if(preg_match('/\[report'.$i.'\]/',$report1) && preg_match('/\[\/report'.$i.'\]/',$report1)){ - $j = $i+1; - $report2 = preg_replace('/\[\/report'.$i.'\](.*?)\[\/message\]/is', '', $text); - $report1 = preg_replace('/\[report'.$i.'\]/', '[report'.$j.']', $report1); - $report1 = preg_replace('/\[\/report'.$i.'\]/', '[/report'.$j.']', $report1); - $text = $report2."[/report".$i."]".$report1; - $report += 1; - } - } - } - - // check if we're not sending this as support - $support_from_admin_allowed = (($session->access == MULTIHUNTER || $session->access == ADMIN) && ADMIN_RECEIVE_SUPPORT_MESSAGES); - $database->sendMessage($user, ((!empty($_POST['as_support']) && $support_from_admin_allowed) ? 1 : $session->uid), htmlspecialchars(addslashes($topic)), htmlspecialchars(addslashes($text)), 0, $alliance, $player, $coor, $report); - } + + if ( ! preg_match( '/\[message\]/', $text ) && ! preg_match( '/\[\/message\]/', $text ) ) { + $text = "[message]" . $text . "[/message]"; + $alliance = $player = $coor = $report = 0; + + for ( $i = 0; $i <= $alliance; $i ++ ) { + if ( preg_match( '/\[alliance' . $i . '\]/', $text ) && preg_match( '/\[\/alliance' . $i . '\]/', $text ) ) { + $alliance1 = preg_replace( '/\[message\](.*?)\[\/alliance' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[alliance' . $i . '\]/', $alliance1 ) && preg_match( '/\[\/alliance' . $i . '\]/', $alliance1 ) ) { + $j = $i + 1; + $alliance2 = preg_replace( '/\[\/alliance' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $alliance1 = preg_replace( '/\[alliance' . $i . '\]/', '[alliance' . $j . ']', $alliance1 ); + $alliance1 = preg_replace( '/\[\/alliance' . $i . '\]/', '[/alliance' . $j . ']', $alliance1 ); + $text = $alliance2 . "[/alliance" . $i . "]" . $alliance1; + $alliance += 1; + } + } + } + + for ( $i = 0; $i <= $player; $i ++ ) { + if ( preg_match( '/\[player' . $i . '\]/', $text ) && preg_match( '/\[\/player' . $i . '\]/', $text ) ) { + $player1 = preg_replace( '/\[message\](.*?)\[\/player' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[player' . $i . '\]/', $player1 ) && preg_match( '/\[\/player' . $i . '\]/', $player1 ) ) { + $j = $i + 1; + $player2 = preg_replace( '/\[\/player' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $player1 = preg_replace( '/\[player' . $i . '\]/', '[player' . $j . ']', $player1 ); + $player1 = preg_replace( '/\[\/player' . $i . '\]/', '[/player' . $j . ']', $player1 ); + $text = $player2 . "[/player" . $i . "]" . $player1; + $player += 1; + } + } + } + + for ( $i = 0; $i <= $coor; $i ++ ) { + if ( preg_match( '/\[coor' . $i . '\]/', $text ) && preg_match( '/\[\/coor' . $i . '\]/', $text ) ) { + $coor1 = preg_replace( '/\[message\](.*?)\[\/coor' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[coor' . $i . '\]/', $coor1 ) && preg_match( '/\[\/coor' . $i . '\]/', $coor1 ) ) { + $j = $i + 1; + $coor2 = preg_replace( '/\[\/coor' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $coor1 = preg_replace( '/\[coor' . $i . '\]/', '[coor' . $j . ']', $coor1 ); + $coor1 = preg_replace( '/\[\/coor' . $i . '\]/', '[/coor' . $j . ']', $coor1 ); + $text = $coor2 . "[/coor" . $i . "]" . $coor1; + $coor += 1; + } + } + } + + for ( $i = 0; $i <= $report; $i ++ ) { + if ( preg_match( '/\[report' . $i . '\]/', $text ) && preg_match( '/\[\/report' . $i . '\]/', $text ) ) { + $report1 = preg_replace( '/\[message\](.*?)\[\/report' . $i . '\]/is', '', $text ); + if ( preg_match( '/\[report' . $i . '\]/', $report1 ) && preg_match( '/\[\/report' . $i . '\]/', $report1 ) ) { + $j = $i + 1; + $report2 = preg_replace( '/\[\/report' . $i . '\](.*?)\[\/message\]/is', '', $text ); + $report1 = preg_replace( '/\[report' . $i . '\]/', '[report' . $j . ']', $report1 ); + $report1 = preg_replace( '/\[\/report' . $i . '\]/', '[/report' . $j . ']', $report1 ); + $text = $report2 . "[/report" . $i . "]" . $report1; + $report += 1; + } + } + } + + // check if we're not sending this as support + $support_from_admin_allowed = ( ( $session->access == MULTIHUNTER || $session->access == ADMIN ) && ADMIN_RECEIVE_SUPPORT_MESSAGES ); + $database->sendMessage( $user, ( ( ! empty( $_POST['as_support'] ) && $support_from_admin_allowed ) ? 1 : $session->uid ), htmlspecialchars( addslashes( $topic ) ), htmlspecialchars( addslashes( $text ) ), 0, $alliance, $player, $coor, $report ); + } } //7 = village, attacker, att tribe, u1 - u10, lost %, w,c,i,c , cap @@ -511,15 +525,15 @@ class Message { public function sendWelcome($uid, $username) { global $database; + $welcomemsg = file_get_contents("GameEngine/Admin/welcome.tpl"); - $welcomemsg = preg_replace("'%USER%'", $username, $welcomemsg); - $welcomemsg = preg_replace("'%START%'", date("y.m.d", COMMENCE), $welcomemsg); - $welcomemsg = preg_replace("'%TIME%'", date("H:i", COMMENCE), $welcomemsg); - $welcomemsg = preg_replace("'%PLAYERS%'", $database->countUser(), $welcomemsg); - $welcomemsg = preg_replace("'%ALLI%'", $database->countAlli(), $welcomemsg); - $welcomemsg = preg_replace("'%SERVER_NAME%'", SERVER_NAME, $welcomemsg); - $welcomemsg = preg_replace("'%PROTECTION%'", (PROTECTION/3600), $welcomemsg); - $welcomemsg = "[message]".$welcomemsg."[/message]"; + + $welcomemsg = "[message]".preg_replace( + ["'%USER%'", "'%START%'", "'%TIME%'", "'%PLAYERS%'", "'%ALLI%'", "'%SERVER_NAME%'", "'%PROTECTION%'"], + [$username, date("y.m.d", COMMENCE), date("H:i", COMMENCE), $database->countUser(), $database->countAlli(), SERVER_NAME, round((PROTECTION/3600))], + $welcomemsg + )."[/message]"; + return $database->sendMessage($uid, 1, WEL_TOPIC, addslashes($welcomemsg), 0, 0, 0, 0, 0); } @@ -578,41 +592,47 @@ class Message { public function addFriends($post) { global $database; - for($i=0;$i<=19;$i++) { - if($post['addfriends'.$i] != ""){ - $uid = $database->getUserField($post['addfriends'.$i], "id", 1); - $added = 0; - for($j=0;$j<=$i;$j++) { - if($added == 0){ - $user = $database->getUserField($post['myid'], "friend".$j, 0); - $userwait = $database->getUserField($post['myid'], "friend".$j."wait", 0); - $exist = 0; - for($k=0;$k<=19;$k++){ - $user1 = $database->getUserField($post['myid'], "friend".$k, 0); - if($user1 == $uid or $uid == $post['myid']){ - $exist = 1; - } - } - if($user == 0 && $userwait == 0 && $exist == 0){ - $added1 = 0; - for($l=0;$l<=19;$l++){ - $user2 = $database->getUserField($uid, "friend".$l, 0); - $userwait2 = $database->getUserField($uid, "friend".$l."wait", 0); - if($user2 == 0 && $userwait2 == 0 && $added1 == 0){ - $database->addFriend($uid,"friend".$l."wait",$post['myid']); - $added1 = 1; - } - } - $database->addFriend($post['myid'],"friend".$j,$uid); - $database->addFriend($post['myid'],"friend".$j."wait",$uid); - $added = 1; - } - } - } - } - } - header("Location: nachrichten.php?t=1"); - exit; + for ( $i = 0; $i <= 19; $i ++ ) { + if ( $post[ 'addfriends' . $i ] != "" ) { + $uid = $database->getUserField( $post[ 'addfriends' . $i ], "id", 1 ); + $added = 0; + + for ( $j = 0; $j <= $i; $j ++ ) { + if ( $added == 0 ) { + $user = $database->getUserField( $post['myid'], "friend" . $j, 0 ); + $userwait = $database->getUserField( $post['myid'], "friend" . $j . "wait", 0 ); + $exist = 0; + + for ( $k = 0; $k <= 19; $k ++ ) { + $user1 = $database->getUserField( $post['myid'], "friend" . $k, 0 ); + if ( $user1 == $uid or $uid == $post['myid'] ) { + $exist = 1; + } + } + + if ( $user == 0 && $userwait == 0 && $exist == 0 ) { + $added1 = 0; + + for ( $l = 0; $l <= 19; $l ++ ) { + $user2 = $database->getUserField( $uid, "friend" . $l, 0 ); + $userwait2 = $database->getUserField( $uid, "friend" . $l . "wait", 0 ); + + if ( $user2 == 0 && $userwait2 == 0 && $added1 == 0 ) { + $database->addFriend( $uid, "friend" . $l . "wait", $post['myid'] ); + $added1 = 1; + } + } + + $database->addFriend( $post['myid'], "friend" . $j, $uid ); + $database->addFriend( $post['myid'], "friend" . $j . "wait", $uid ); + $added = 1; + } + } + } + } + } + header( "Location: nachrichten.php?t=1" ); + exit; } } diff --git a/GameEngine/Profile.php b/GameEngine/Profile.php index 88928ae1..145a6a25 100755 --- a/GameEngine/Profile.php +++ b/GameEngine/Profile.php @@ -97,8 +97,7 @@ class Profile { for($i=0;$i<=count($varray)-1;$i++) { $k = trim($post['dname'.$i]); $name = preg_replace("/[^a-zA-Z0-9_-\s]/", "", $k); - $database->setVillageName($database->RemoveXSS($varray[$i]['wref']),$name); - $database->setVillageName($database->RemoveXSS($varray[$i]['wref']),$k); + $database->setVillageName($varray[$i]['wref'],$database->RemoveXSS($name)); } header("Location: spieler.php?uid=".$post['uid']); exit; @@ -146,13 +145,14 @@ class Profile { private function updateAccount($post) { global $database,$session,$form; + if($post['pw2'] == $post['pw3']) { if($database->login($session->username,$post['pw1'])) { if ($_POST['uid'] != $session->uid){ - die("Hacking Attempr"); - } else { - $database->updateUserField($post['uid'],"password",password_hash($post['pw2'], PASSWORD_BCRYPT,['cost' => 12]),1); - } + die("Hacking Attempr"); + } else { + $database->updateUserField($post['uid'],"password",password_hash($post['pw2'], PASSWORD_BCRYPT,['cost' => 12]),1); + } } else { $form->addError("pw",LOGIN_PW_ERROR); @@ -161,18 +161,24 @@ class Profile { else { $form->addError("pw",PASS_MISMATCH); } + + if($post['email_alt'] == $session->userinfo['email']) { $database->updateUserField($post['uid'],"email",$post['email_neu'],1); } else { $form->addError("email",EMAIL_ERROR); } + + if($post['del'] && password_verify($post['del_pw'], $session->userinfo['password'])) { $database->setDeleting($post['uid'],0); } else { $form->addError("del",PASS_MISMATCH); } + + if($post['v1'] != "") { $sitid = $database->getUserField($post['v1'],"id",1); if($sitid == $session->userinfo['sit1'] || $sitid == $session->userinfo['sit2']) { @@ -187,6 +193,7 @@ class Profile { } } } + $_SESSION['errorarray'] = $form->getErrors(); header("Location: spieler.php?s=3"); exit; @@ -194,12 +201,15 @@ class Profile { private function removeSitter($get) { global $database,$session; + if($get['a'] == $session->checker) { if($session->userinfo['sit'.$get['type']] == $get['id']) { $database->updateUserField($session->uid,"sit".$get['type'],0,1); } + $session->changeChecker(); } + header("Location: spieler.php?s=".$get['s']); exit; } @@ -213,13 +223,16 @@ class Profile { private function removeMeSit($get) { global $database,$session; + if($get['a'] == $session->checker) { $database->removeMeSit($get['id'],$session->uid); $session->changeChecker(); } + header("Location: spieler.php?s=".$get['s']); exit; } }; + $profile = new Profile; ?> diff --git a/GameEngine/Session.php b/GameEngine/Session.php index 2442b6d0..7eb87689 100755 --- a/GameEngine/Session.php +++ b/GameEngine/Session.php @@ -102,7 +102,9 @@ class Session { $user_sanitized = $database->escape($user); $_SESSION['checker'] = $generator->generateRandStr(3); $_SESSION['mchecker'] = $generator->generateRandStr(5); - $_SESSION['qst'] = $database->getUserField($user_sanitized, "quest", 1); + + $userFields = $database->getUserFields($user_sanitized, "quest, id", 1, true); + $_SESSION['qst'] = $userFields["quest"]; $result = mysqli_query($GLOBALS['link'],"SELECT id, village_select FROM `". TB_PREFIX."users` WHERE `username`='".$user_sanitized."'"); $dbarray = mysqli_fetch_assoc($result); @@ -113,7 +115,7 @@ class Session { if($selected_village!='') { $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `wref` = '.$selected_village); }else{ - $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `owner` = ' . (int) $database->getUserField($user_sanitized, "id", 1) . ' LIMIT 1'); + $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `owner` = ' . $userFields["id"] . ' LIMIT 1'); } $data = mysqli_fetch_assoc($query); $_SESSION['wid'] = $data['wref']; @@ -122,7 +124,7 @@ class Session { if($selected_village!='') { $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `wref` = '.$selected_village); }else{ - $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `owner` = ' . (int) $database->getUserField($user_sanitized, "id", 1) . ' LIMIT 1'); + $query = mysqli_query($GLOBALS['link'],'SELECT wref FROM `' . TB_PREFIX . 'vdata` WHERE `owner` = ' . $userFields["id"] . ' LIMIT 1'); } $data = mysqli_fetch_assoc($query); $_SESSION['wid'] = $data['wref']; @@ -196,7 +198,7 @@ class Session { $database->updateUserField($user, "timestamp", $this->time, 0); return true; } else { - return false; + return false; } } diff --git a/GameEngine/Village.php b/GameEngine/Village.php index c87f1906..db39cd5a 100755 --- a/GameEngine/Village.php +++ b/GameEngine/Village.php @@ -37,10 +37,11 @@ class Village { } //add new line code //check exist village if from village destroy to avoid error msg. - if (!$database-> checkVilExist($this->wid)) { + if ( !$database->checkVilExist($this->wid) ) { $this->wid=$database->getVillageID($session->uid); $_SESSION['wid']=$this->wid; } + $this->LoadTown(); $this->calculateProduction(); $this->processProduction();