diff --git a/GameEngine/Alliance.php b/GameEngine/Alliance.php index a8d312dc..2f92457e 100755 --- a/GameEngine/Alliance.php +++ b/GameEngine/Alliance.php @@ -748,6 +748,14 @@ class Alliance { $newOwner = $database->getAllMember2($session->alliance); $newLeader = $newOwner['id']; + // Dăm permisiuni complete noului lider + $database->updateAlliPermissions( + $newFounderID, + (int)$session->alliance, + 'Alliance Founder', + 1, 1, 1, 1, 1, 1, 1, 1 + ); + // Actualizăm liderul alianței (SQL mai sigur) $database->query( "UPDATE " . TB_PREFIX . "alidata @@ -755,11 +763,6 @@ class Alliance { WHERE id = " . (int)$session->alliance ); - // Dăm permisiuni complete noului lider - $database->updateAlliPermissions( - $newLeader, - 1, 1, 1, 1, 1, 1, 1, 1, 1 - ); Automation::updateMax($newLeader); } @@ -851,6 +854,14 @@ class Alliance { $form->addError("founder", 'Invalid founder.'); return; } + + // Dăm permisiuni complete noului lider + $database->updateAlliPermissions( + $newFounderID, + (int)$session->alliance, + 'Alliance Founder', + 1, 1, 1, 1, 1, 1, 1, 1 + ); // Actualizăm liderul alianței $_SESSION['alliance_user'] = 0; @@ -860,12 +871,6 @@ class Alliance { WHERE id = " . (int)$session->alliance ); - // Dăm permisiuni complete noului lider - $database->updateAlliPermissions( - $newFounderID, - 1, 1, 1, 1, 1, 1, 1, 1, 1 - ); - Automation::updateMax($newFounderID); // Trimitem mesaj în joc noului lider diff --git a/GameEngine/Artifacts.php b/GameEngine/Artifacts.php index c005d218..4167334a 100644 --- a/GameEngine/Artifacts.php +++ b/GameEngine/Artifacts.php @@ -1,4 +1,20 @@ loadMarket(); - if(isset($_SESSION['loadMarket'])) - { + + if (isset($_SESSION['loadMarket'])) { $this->loadOnsale(); unset($_SESSION['loadMarket']); } - if(isset($post['ft'])) - { - switch($post['ft']) - { - case "mk1": $this->sendResource($post); break; - case "mk2": $this->addOffer($post); break; - case "mk3": $this->tradeResource($post); break; - } + + if (!isset($post['ft'])) { + return; + } + + switch ($post['ft']) { + case 'mk1': + $this->sendResource($post); + break; + + case 'mk2': + $this->addOffer($post); + break; + + case 'mk3': + $this->tradeResource($post); + break; } } + /** + * Remove / accept market actions. + */ public function procRemove($get) { global $database, $village, $session; - if(isset($get['t']) && $get['t'] == 1) - { + if (isset($get['t']) && $get['t'] == 1) { $this->filterNeed($get); - } - else if(isset($get['t']) && $get['t'] == 2 && isset($get['a']) && $get['a'] == 5 && isset($get['del'])) - { - //GET ALL FIELDS FROM MARKET - $type = $database->getMarketField($village->wid, $get['del'], "gtype"); - $amt = $database->getMarketField($village->wid, $get['del'], "gamt"); + } elseif ( + isset($get['t'], $get['a'], $get['del']) && + $get['t'] == 2 && + $get['a'] == 5 + ) { + // Get all fields from market + $type = $database->getMarketField($village->wid, $get['del'], 'gtype'); + $amt = $database->getMarketField($village->wid, $get['del'], 'gamt'); + $database->getResourcesBack($village->wid, $type, $amt); $database->addMarket($village->wid, $get['del'], 0, 0, 0, 0, 0, 0, 1); - header("Location: build.php?id=".$get['id']."&t=2"); + + header('Location: build.php?id=' . $get['id'] . '&t=2'); exit; } - if(isset($get['t']) && $get['t'] == 1 && isset($get['a']) && $get['a'] == $session->mchecker && !isset($get['del'])) - { + + if ( + isset($get['t'], $get['a']) && + $get['t'] == 1 && + $get['a'] == $session->mchecker && + !isset($get['del']) + ) { $session->changeChecker(); - $this->acceptOffer($get); + $this->acceptOffer($get); } } + /** + * Available merchants. + */ public function merchantAvail() { return $this->merchant - $this->used; } + + /** + * Remember cached value for current request. + */ + private function remember($key, callable $callback) + { + if (isset($this->cache[$key])) { + return $this->cache[$key]; + } + $this->cache[$key] = $callback(); + + return $this->cache[$key]; + } + + /** + * Forget cache entry or entire cache. + */ + private function forget($key = null) + { + if ($key === null) { + $this->cache = []; + return; + } + + unset($this->cache[$key]); + } + + /** + * Load market data. + */ private function loadMarket() { - global $session,$building,$bid28,$bid17,$database,$village; + global $session, $building, $bid28, $bid17, $database, $village; + + $this->recieving = $database->getMovement(0, $village->wid, 1); + $this->sending = $database->getMovement(0, $village->wid, 0); + $this->return = $database->getMovement(2, $village->wid, 1); + + $this->merchant = ($building->getTypeLevel(17) > 0) + ? $bid17[$building->getTypeLevel(17)]['attri'] + : 0; + + $this->used = $this->remember( + 'merchant_used_' . $village->wid, + function () use ($database, $village) { + return $database->totalMerchantUsed($village->wid); + } + ); + + $this->onmarket = $this->remember( + 'market_' . $village->wid, + function () use ($database, $village) { + return $database->getMarket($village->wid, 0); + } + ); + + // Merchant carry capacity + $this->maxcarry = ($session->tribe == 1) + ? 500 + : (($session->tribe == 2) ? 1000 : 750); - $this->recieving = $database->getMovement(0,$village->wid,1); - $this->sending = $database->getMovement(0,$village->wid,0); - $this->return = $database->getMovement(2,$village->wid,1); - $this->merchant = ($building->getTypeLevel(17) > 0)? $bid17[$building->getTypeLevel(17)]['attri'] : 0; - $this->used = $database->totalMerchantUsed($village->wid); - $this->onmarket = $database->getMarket($village->wid,0); - $this->maxcarry = ($session->tribe == 1)? 500 : (($session->tribe == 2)? 1000 : 750); $this->maxcarry *= TRADER_CAPACITY; - if($building->getTypeLevel(28) != 0) - { + + // Trade office bonus + if ($building->getTypeLevel(28) != 0) { $this->maxcarry *= $bid28[$building->getTypeLevel(28)]['attri'] / 100; } } + /** + * Send resources. + */ private function sendResource($post) { global $database, $village, $session, $generator, $logging, $form; - $wtrans = (isset($post['r1']) && !empty($post['r1']))? $post['r1'] : 0; - $ctrans = (isset($post['r2']) && !empty($post['r2']))? $post['r2'] : 0; - $itrans = (isset($post['r3']) && !empty($post['r3']))? $post['r3'] : 0; - $crtrans = (isset($post['r4']) && !empty($post['r4']))? $post['r4'] : 0; - $wtrans = str_replace("-", "", $wtrans); - $ctrans = str_replace("-", "", $ctrans); - $itrans = str_replace("-", "", $itrans); - $crtrans = str_replace("-", "", $crtrans); - - // preload all village data, since we're retrieving some of those separately below + $wtrans = (isset($post['r1']) && !empty($post['r1'])) ? $post['r1'] : 0; + $ctrans = (isset($post['r2']) && !empty($post['r2'])) ? $post['r2'] : 0; + $itrans = (isset($post['r3']) && !empty($post['r3'])) ? $post['r3'] : 0; + $crtrans = (isset($post['r4']) && !empty($post['r4'])) ? $post['r4'] : 0; + + // Prevent negative values + $wtrans = str_replace('-', '', $wtrans); + $ctrans = str_replace('-', '', $ctrans); + $itrans = str_replace('-', '', $itrans); + $crtrans = str_replace('-', '', $crtrans); + + // Preload village data $database->getVillage($village->wid); - $availableWood = $database->getWoodAvailable($village->wid); - $availableClay = $database->getClayAvailable($village->wid); - $availableIron = $database->getIronAvailable($village->wid); - $availableCrop = $database->getCropAvailable($village->wid); - - //check if on vacation: - if($database->getvacmodexy($id)) $form->addError("error", USER_ON_VACATION); + $resourcesAvailable = $this->remember( + 'resources_' . $village->wid, + function () use ($database, $village) { + return [ + 'wood' => $database->getWoodAvailable($village->wid), + 'clay' => $database->getClayAvailable($village->wid), + 'iron' => $database->getIronAvailable($village->wid), + 'crop' => $database->getCropAvailable($village->wid), + ]; + } + ); - if(!$database->checkVilExist($post['getwref'])) $form->addError("error", NO_COORDINATES_SELECTED); - elseif($post['getwref'] == $village->wid) $form->addError("error", CANNOT_SEND_RESOURCES); - elseif($post['send3'] < 1 || $post['send3'] > 3 || ($post['send3'] > 1 && !$session->goldclub)) $form->addError("error", INVALID_MERCHANTS_REPETITION); - elseif($availableWood >= $post['r1'] && $availableClay >= $post['r2'] && $availableIron >= $post['r3'] && $availableCrop >= $post['r4']) - { - $resource = [$wtrans, $ctrans, $itrans, $crtrans]; - $reqMerc = ceil((array_sum($resource) - 0.1) / $this->maxcarry); + $availableWood = $resourcesAvailable['wood']; + $availableClay = $resourcesAvailable['clay']; + $availableIron = $resourcesAvailable['iron']; + $availableCrop = $resourcesAvailable['crop']; - // Acquire merchant lock to prevent race condition - $database->getMerchantLock($village->wid); - $this->used = $database->totalMerchantUsed($village->wid, false); + // Resource array + $resource = [ + $wtrans, + $ctrans, + $itrans, + $crtrans + ]; - if($this->merchantAvail() > 0 && $reqMerc <= $this->merchantAvail()) - { - $id = $post['getwref']; - $coor = $database->getCoor($id); - if($database->getVillageState($id)) - { - $timetaken = $generator->procDistanceTime($coor, $village->coor, $session->tribe, 0); - $res = $resource[0] + $resource[1] + $resource[2] + $resource[3]; - if($res != 0){ - $reference = $database->sendResource($resource[0], $resource[1], $resource[2], $resource[3], $reqMerc, 0); - $database->modifyResource($village->wid, $resource[0], $resource[1], $resource[2], $resource[3], 0); - $database->addMovement(0, $village->wid, $id, $reference, time(), time() + $timetaken, $post['send3']); - $logging->addMarketLog($village->wid, 1, [$resource[0], $resource[1], $resource[2], $resource[3], $id]); - } - } - $database->releaseMerchantLock($village->wid); - header("Location: build.php?id=".$post['id']); - exit; - } - else - { - $database->releaseMerchantLock($village->wid); - $form->addError("error", TOO_FEW_MERCHANTS); - } + // NOTE: + // Original code referenced $id before definition. + // Keeping logic safe while preserving compatibility. + $id = isset($post['getwref']) ? (int)$post['getwref'] : 0; + + // Check vacation mode + if ($database->getvacmodexy($id)) { + $form->addError('error', USER_ON_VACATION); + } + + if (!$database->checkVilExist($post['getwref'])) { + $form->addError('error', NO_COORDINATES_SELECTED); + } elseif ($post['getwref'] == $village->wid) { + $form->addError('error', CANNOT_SEND_RESOURCES); + } elseif ( + $post['send3'] < 1 || + $post['send3'] > 3 || + ($post['send3'] > 1 && !$session->goldclub) + ) { + $form->addError('error', INVALID_MERCHANTS_REPETITION); + } elseif ( + $availableWood >= $post['r1'] && + $availableClay >= $post['r2'] && + $availableIron >= $post['r3'] && + $availableCrop >= $post['r4'] + ) { + $reqMerc = ceil((array_sum($resource) - 0.1) / $this->maxcarry); + + // Acquire merchant lock to prevent race conditions + $database->getMerchantLock($village->wid); + + $this->forget('merchant_used_' . $village->wid); + + $this->used = $this->remember( + 'merchant_used_' . $village->wid, + function () use ($database, $village) { + return $database->totalMerchantUsed($village->wid, false); + } + ); + + if ($this->merchantAvail() > 0 && $reqMerc <= $this->merchantAvail()) { + + $coor = $database->getCoor($id); + + if ($database->getVillageState($id)) { + + $timetaken = $generator->procDistanceTime( + $coor, + $village->coor, + $session->tribe, + 0 + ); + + $res = array_sum($resource); + + if ($res != 0) { + + $reference = $database->sendResource( + $resource[0], + $resource[1], + $resource[2], + $resource[3], + $reqMerc, + 0 + ); + + $database->modifyResource( + $village->wid, + $resource[0], + $resource[1], + $resource[2], + $resource[3], + 0 + ); + + $database->addMovement( + 0, + $village->wid, + $id, + $reference, + time(), + time() + $timetaken, + $post['send3'] + ); + $this->forget(); + $logging->addMarketLog( + $village->wid, + 1, + [ + $resource[0], + $resource[1], + $resource[2], + $resource[3], + $id + ] + ); + } + } + + $database->releaseMerchantLock($village->wid); + + header('Location: build.php?id=' . $post['id']); + exit; + } else { + + $database->releaseMerchantLock($village->wid); + + $form->addError('error', TOO_FEW_MERCHANTS); + } + } else { + + $form->addError('error', TOO_FEW_RESOURCES); } - else $form->addError("error", TOO_FEW_RESOURCES); } + /** + * Add market offer. + */ private function addOffer($post) { - global $database,$village,$session; + global $database, $village, $session; + // Invalid: same resource type + if ($post['rid1'] == $post['rid2']) { - if($post['rid1'] == $post['rid2']) - { - // Trading res for res of same type (invalid) - header("Location: build.php?id=".$post['id']."&t=2&e2"); + header('Location: build.php?id=' . $post['id'] . '&t=2&e2'); exit; } - elseif(!isset($post['m1']) || !isset($post['m2']) || $post['m1'] <= 0 || $post['m2'] <= 0) - { - // No resources selected (invalid) - header("Location: build.php?id=".$post['id']."&t=2&e2"); + + // Invalid values + if ( + !isset($post['m1'], $post['m2']) || + $post['m1'] <= 0 || + $post['m2'] <= 0 + ) { + + header('Location: build.php?id=' . $post['id'] . '&t=2&e2'); exit; } - elseif($post['m1'] > (2 * $post['m2'])) - { - // Trade is for more than 2x (invalid) - header("Location: build.php?id=".$post['id']."&t=2&e2"); + + // Max 2:1 trade ratio + if ($post['m1'] > (2 * $post['m2'])) { + + header('Location: build.php?id=' . $post['id'] . '&t=2&e2'); exit; } - elseif($post['m2'] > (2 * $post['m1'])) - { - // Trade is for less than 0.5x (invalid) - header("Location: build.php?id=".$post['id']."&t=2&e2"); + + // Min 1:2 trade ratio + if ($post['m2'] > (2 * $post['m1'])) { + + header('Location: build.php?id=' . $post['id'] . '&t=2&e2'); exit; } - elseif($post['rid1'] < 1 || $post['rid1'] > 4 || $post['rid2'] < 1 || $post['rid2'] > 4) - { - // Inexistent resources type (invalid) - header("Location: build.php?id=".$post['id']."&t=2&e2"); + + // Invalid resource ids + if ( + $post['rid1'] < 1 || + $post['rid1'] > 4 || + $post['rid2'] < 1 || + $post['rid2'] > 4 + ) { + + header('Location: build.php?id=' . $post['id'] . '&t=2&e2'); exit; } - else - { - $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; - // preload all village data, since we're retrieving some of those separately below - $database->getVillage($village->wid); + // Offered resources + $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; - $availableWood = $database->getWoodAvailable($village->wid); - $availableClay = $database->getClayAvailable($village->wid); - $availableIron = $database->getIronAvailable($village->wid); - $availableCrop = $database->getCropAvailable($village->wid); + // Preload village data + $database->getVillage($village->wid); - if($availableWood >= $wood && $availableClay >= $clay && $availableIron >= $iron && $availableCrop >= $crop) - { - $reqMerc = 1; + $resourcesAvailable = $this->remember( + 'resources_' . $village->wid, + function () use ($database, $village) { + return [ + 'wood' => $database->getWoodAvailable($village->wid), + 'clay' => $database->getClayAvailable($village->wid), + 'iron' => $database->getIronAvailable($village->wid), + 'crop' => $database->getCropAvailable($village->wid), + ]; + } + ); - if(($wood+$clay+$iron+$crop) > $this->maxcarry) - { - $reqMerc = round(($wood+$clay+$iron+$crop)/$this->maxcarry); + $availableWood = $resourcesAvailable['wood']; + $availableClay = $resourcesAvailable['clay']; + $availableIron = $resourcesAvailable['iron']; + $availableCrop = $resourcesAvailable['crop']; - if(($wood+$clay+$iron+$crop) > $this->maxcarry*$reqMerc) $reqMerc += 1; - } - // Acquire merchant lock to prevent race condition - $database->getMerchantLock($village->wid); - $this->used = $database->totalMerchantUsed($village->wid, false); + if ( + $availableWood >= $wood && + $availableClay >= $clay && + $availableIron >= $iron && + $availableCrop >= $crop + ) { - if($this->merchantAvail() > 0 && $reqMerc <= $this->merchantAvail()) - { - if($database->modifyResource($village->wid,$wood,$clay,$iron,$crop,0)) - { - $time = 0; - if(isset($_POST['d1'])) $time = $_POST['d2'] * 3600; - $alliance = (isset($post['ally']) && $post['ally'] == 1)? $session->userinfo['alliance'] : 0; - $database->addMarket($village->wid,$post['rid1'],$post['m1'],$post['rid2'],$post['m2'],$time,$alliance,$reqMerc,0); - } - // Enough merchants - $database->releaseMerchantLock($village->wid); - header("Location: build.php?id=".$post['id']."&t=2"); - exit; - } - else - { - // Not enough merchants - $database->releaseMerchantLock($village->wid); - header("Location: build.php?id=".$post['id']."&t=2&e3"); - exit; + $totalRes = $wood + $clay + $iron + $crop; + + $reqMerc = 1; + + if ($totalRes > $this->maxcarry) { + + $reqMerc = round($totalRes / $this->maxcarry); + + if ($totalRes > ($this->maxcarry * $reqMerc)) { + $reqMerc += 1; } } - else - { - // not enough resources - header("Location: build.php?id=".$post['id']."&t=2&e1"); + + // Acquire merchant lock + $database->getMerchantLock($village->wid); + + $this->forget('merchant_used_' . $village->wid); + + $this->used = $this->remember( + 'merchant_used_' . $village->wid, + function () use ($database, $village) { + return $database->totalMerchantUsed($village->wid, false); + } + ); + + if ($this->merchantAvail() > 0 && $reqMerc <= $this->merchantAvail()) { + + if ( + $database->modifyResource( + $village->wid, + $wood, + $clay, + $iron, + $crop, + 0 + ) + ) { + + $time = 0; + + if (isset($_POST['d1'])) { + $time = $_POST['d2'] * 3600; + } + + $alliance = ( + isset($post['ally']) && + $post['ally'] == 1 + ) + ? $session->userinfo['alliance'] + : 0; + + $database->addMarket( + $village->wid, + $post['rid1'], + $post['m1'], + $post['rid2'], + $post['m2'], + $time, + $alliance, + $reqMerc, + 0 + ); + } + $this->forget(); + $database->releaseMerchantLock($village->wid); + + header('Location: build.php?id=' . $post['id'] . '&t=2'); exit; } + + // Not enough merchants + $database->releaseMerchantLock($village->wid); + + header('Location: build.php?id=' . $post['id'] . '&t=2&e3'); + exit; } + + // Not enough resources + header('Location: build.php?id=' . $post['id'] . '&t=2&e1'); + exit; } + /** + * Accept market offer. + */ private function acceptOffer($get) { - global $database,$village,$session,$logging,$generator; + global $database, $village, $session, $logging, $generator; $infoarray = $database->getMarketInfo($get['g']); + $reqMerc = 1; - if($infoarray['wamt'] > $this->maxcarry) - { - $reqMerc = round($infoarray['wamt']/$this->maxcarry); - if($infoarray['wamt'] > $this->maxcarry*$reqMerc) - { + + if ($infoarray['wamt'] > $this->maxcarry) { + + $reqMerc = round($infoarray['wamt'] / $this->maxcarry); + + if ($infoarray['wamt'] > ($this->maxcarry * $reqMerc)) { $reqMerc += 1; } } - - // We don't have enough resources - if($infoarray['wamt'] > ([$village->awood, $village->aclay, $village->airon, $village->acrop])[$infoarray['wtype'] - 1]) - { - header("Location: build.php?id=".$get['id']."&t=1&e1"); - exit; - } // We're accepting the offering from the same village/of another alliance/with a too high maxtime - elseif - (($infoarray['vref'] == $village->wid) || - ($infoarray['alliance'] > 0 && $infoarray['alliance'] != $session->alliance) || - ($infoarray['maxtime'] > 0 && ($infoarray['maxtime'] * 3600) < $generator->procDistanceTime($database->getCoor($infoarray['vref']), $village->coor, $session->tribe, 0))) - { - header("Location: build.php?id=".$get['id']."&t=1&e2"); - exit; - } // We don't have enough merchants (initial check before lock) - elseif($reqMerc > $this->merchantAvail()){ - header("Location: build.php?id=".$get['id']."&t=1&e3"); + + $villageResources = [ + $village->awood, + $village->aclay, + $village->airon, + $village->acrop + ]; + + // Not enough resources + if ( + $infoarray['wamt'] > + $villageResources[$infoarray['wtype'] - 1] + ) { + + header('Location: build.php?id=' . $get['id'] . '&t=1&e1'); exit; } - // Acquire merchant lock to prevent race condition + // Invalid offer + if ( + ($infoarray['vref'] == $village->wid) || + ( + $infoarray['alliance'] > 0 && + $infoarray['alliance'] != $session->alliance + ) || + ( + $infoarray['maxtime'] > 0 && + ($infoarray['maxtime'] * 3600) < + $generator->procDistanceTime( + $database->getCoor($infoarray['vref']), + $village->coor, + $session->tribe, + 0 + ) + ) + ) { + + header('Location: build.php?id=' . $get['id'] . '&t=1&e2'); + exit; + } + + // Not enough merchants + if ($reqMerc > $this->merchantAvail()) { + + header('Location: build.php?id=' . $get['id'] . '&t=1&e3'); + exit; + } + + // Acquire merchant lock $database->getMerchantLock($village->wid); - $this->used = $database->totalMerchantUsed($village->wid, false); - if($reqMerc > $this->merchantAvail()) - { + $this->forget('merchant_used_' . $village->wid); + + $this->used = $this->remember( + 'merchant_used_' . $village->wid, + function () use ($database, $village) { + return $database->totalMerchantUsed($village->wid, false); + } + ); + + // Double-check after lock + if ($reqMerc > $this->merchantAvail()) { + $this->forget(); $database->releaseMerchantLock($village->wid); - header("Location: build.php?id=".$get['id']."&t=1&e3"); + + header('Location: build.php?id=' . $get['id'] . '&t=1&e3'); exit; } - $myresource = $hisresource = [ 1=> 0, 0, 0, 0]; + // Prepare resources + $myresource = [1 => 0, 0, 0, 0]; + $hisresource = [1 => 0, 0, 0, 0]; + $myresource[$infoarray['wtype']] = $infoarray['wamt']; - $mysendid = $database->sendResource($myresource[1],$myresource[2],$myresource[3],$myresource[4],$reqMerc,0); + + $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); + + $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); + + $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 + ); + $timestamp = time(); + $database->addMovement( [0, 0], [$village->wid, $infoarray['vref']], @@ -304,112 +655,217 @@ class Market [$timestamp, $timestamp], [$mytime + $timestamp, $histime + $timestamp] ); + $resource = [1 => 0, 0, 0, 0]; - $resource[$infoarray['wtype']] = $infoarray['wamt']; - $database->modifyResource($village->wid, $resource[1], $resource[2], $resource[3], $resource[4], 0); - $database->setMarketAcc($get['g']); - $database->removeAcceptedOffer($get['g']); - $logging->addMarketLog($village->wid, 2, [$infoarray['vref'], $get['g']]); - $database->releaseMerchantLock($village->wid); - header("Location: build.php?id=" . $get['id']); + $resource[$infoarray['wtype']] = $infoarray['wamt']; + + $database->modifyResource( + $village->wid, + $resource[1], + $resource[2], + $resource[3], + $resource[4], + 0 + ); + + $database->setMarketAcc($get['g']); + $database->removeAcceptedOffer($get['g']); + + $logging->addMarketLog( + $village->wid, + 2, + [$infoarray['vref'], $get['g']] + ); + + $database->releaseMerchantLock($village->wid); + + header('Location: build.php?id=' . $get['id']); exit; } + /** + * Load onsale offers. + */ private function loadOnsale() { - global $database,$village,$session,$multisort,$generator; + global $database, $village, $session, $multisort, $generator; + + $displayarray = $database->getMarket($village->wid, 1); - $displayarray = $database->getMarket($village->wid,1); $holderarray = []; - foreach($displayarray as $value) - { + + foreach ($displayarray as $value) { + $targetcoor = $database->getCoor($value['vref']); - $duration = $generator->procDistanceTime($targetcoor, $village->coor, $session->tribe, 0); - if($duration <= ($value['maxtime'] * 3600) || $value['maxtime'] == 0) - { + + $duration = $generator->procDistanceTime( + $targetcoor, + $village->coor, + $session->tribe, + 0 + ); + + if ( + $duration <= ($value['maxtime'] * 3600) || + $value['maxtime'] == 0 + ) { + $value['duration'] = $duration; - array_push($holderarray,$value); + + $holderarray[] = $value; } } - $this->onsale = $multisort->sorte($holderarray, "duration", true, 2); + + $this->onsale = $multisort->sorte( + $holderarray, + 'duration', + true, + 2 + ); } + /** + * Filter market offers. + */ private function filterNeed($get) { - if(isset($get['v']) || isset($get['s']) || isset($get['b'])){ - $holder = $holder2 = []; - if(isset($get['v']) && $get['v'] == "1:1"){ - foreach($this->onsale as $equal){ - if($equal['wamt'] <= $equal['gamt']){ - array_push($holder, $equal); - } - } - } - else $holder = $this->onsale; - - foreach($holder as $sale){ - if(isset($get['s']) && isset($get['b'])){ - if($sale['gtype'] == $get['s'] && $sale['wtype'] == $get['b']){ - array_push($holder2, $sale); - } - }else if(isset($get['s']) && !isset($get['b'])){ - if($sale['gtype'] == $get['s']){ - array_push($holder2, $sale); - } - }else if(isset($get['b']) && !isset($get['s'])){ - if($sale['wtype'] == $get['b']){ - array_push($holder2, $sale); - } - } - else $holder2 = $holder; - } - $this->onsale = $holder2; + if ( + !isset($get['v']) && + !isset($get['s']) && + !isset($get['b']) + ) { + + $this->loadOnsale(); + return; } - else $this->loadOnsale(); - } - private function tradeResource($post) - { - global $session,$database,$village; + $holder = []; + $holder2 = []; + + // 1:1 trades + if (isset($get['v']) && $get['v'] == '1:1') { + + foreach ($this->onsale as $equal) { + + if ($equal['wamt'] <= $equal['gamt']) { + $holder[] = $equal; + } + } + } else { + + $holder = $this->onsale; + } + + foreach ($holder as $sale) { + + if (isset($get['s']) && isset($get['b'])) { - $wwvillage = $database->getResourceLevel($village->wid); - if($wwvillage['f99t'] != 40){ - if($session->userinfo['gold'] >= 3){ - // check that we're not trying to sell more resources that we actually have if ( - (int) $post['m2'][0] < 0 && round($village->awood) + (int) $post['m2'][0] < 0 - || - (int) $post['m2'][1] < 0 && round($village->aclay) + (int) $post['m2'][1] < 0 - || - (int) $post['m2'][2] < 0 && round($village->airon) + (int) $post['m2'][2] < 0 - || - (int) $post['m2'][3] < 0 && round($village->acrop) + (int) $post['m2'][3] < 0 + $sale['gtype'] == $get['s'] && + $sale['wtype'] == $get['b'] ) { - header("Location: build.php?id=".$post['id']."&t=3"); - exit; + $holder2[] = $sale; } + } elseif (isset($get['s']) && !isset($get['b'])) { - //Check if there are too many resources - if ( ((int) $post['m2'][0] + (int) $post['m2'][1] + (int) $post['m2'][2] + (int) $post['m2'][3] ) <= ( round($village->awood) + round($village->aclay) + round($village->airon) + round($village->acrop) ) ) { - $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; - } else { - header("Location: build.php?id=".$post['id']."&t=3"); - exit; + if ($sale['gtype'] == $get['s']) { + $holder2[] = $sale; } - }else{ - header("Location: build.php?id=".$post['id']."&t=3"); - exit; + } elseif (isset($get['b']) && !isset($get['s'])) { + + if ($sale['wtype'] == $get['b']) { + $holder2[] = $sale; + } + } else { + + $holder2 = $holder; } } + + $this->onsale = $holder2; } -}; + + /** + * NPC merchant trade. + */ + private function tradeResource($post) + { + global $session, $database, $village; + + $wwvillage = $database->getResourceLevel($village->wid); + + // Prevent WW villages + if ($wwvillage['f99t'] == 40) { + return; + } + + // Not enough gold + if ($session->userinfo['gold'] < 3) { + + header('Location: build.php?id=' . $post['id'] . '&t=3'); + exit; + } + + // Prevent selling more resources than available + if ( + ( + (int)$post['m2'][0] < 0 && + round($village->awood) + (int)$post['m2'][0] < 0 + ) || + ( + (int)$post['m2'][1] < 0 && + round($village->aclay) + (int)$post['m2'][1] < 0 + ) || + ( + (int)$post['m2'][2] < 0 && + round($village->airon) + (int)$post['m2'][2] < 0 + ) || + ( + (int)$post['m2'][3] < 0 && + round($village->acrop) + (int)$post['m2'][3] < 0 + ) + ) { + + header('Location: build.php?id=' . $post['id'] . '&t=3'); + exit; + } + + $newTotal = + (int)$post['m2'][0] + + (int)$post['m2'][1] + + (int)$post['m2'][2] + + (int)$post['m2'][3]; + + $currentTotal = + round($village->awood) + + round($village->aclay) + + round($village->airon) + + round($village->acrop); + + // Too many resources requested + if ($newTotal > $currentTotal) { + + header('Location: build.php?id=' . $post['id'] . '&t=3'); + exit; + } + + $database->setVillageField( + $village->wid, + ['wood', 'clay', 'iron', 'crop'], + [ + $post['m2'][0], + $post['m2'][1], + $post['m2'][2], + $post['m2'][3] + ] + ); + $this->forget(); + $database->modifyGold($session->uid, 3, 0); + + header('Location: build.php?id=' . $post['id'] . '&t=3&c'); + exit; + } +} $market = new Market; -?> +?> \ No newline at end of file diff --git a/GameEngine/Message.php b/GameEngine/Message.php index f8e40995..5567f63f 100755 --- a/GameEngine/Message.php +++ b/GameEngine/Message.php @@ -1,686 +1,912 @@ unread = $this->checkUnread(); + + $this->unread = $this->checkUnread(); $this->nunread = $this->checkNUnread(); - if($req_file == 'nachrichten.php'){ - if(isset($_GET['t'])){ - switch($_GET['t']){ - // send messages page or a single sent message - case 2 : - case '2a' : - $this->getMessages(2); - break; - - // archived messages page - case 3 : - $this->getMessages(3); - break; - } - } - else $this->getMessages(1); // inbox - received messages page - } + if ($req_file == 'nachrichten.php') { + if (isset($_GET['t'])) { + switch ($_GET['t']) { - if ($req_file == 'berichte.php') $this->getNotice(); + // Sent messages page / single sent message + case 2: + case '2a': + $this->getMessages(2); + break; - if(isset($_SESSION['reply'])) { - $this->reply = $_SESSION['reply']; - unset($_SESSION['reply']); - } - } + // Archived messages page + case 3: + $this->getMessages(3); + break; + } + } else { + // Inbox / received messages page + $this->getMessages(1); + } + } + if ($req_file == 'berichte.php') { + $this->getNotice(); + } + if (isset($_SESSION['reply'])) { + $this->reply = $_SESSION['reply']; + unset($_SESSION['reply']); + } + } - public function procMessage($post) { + public function procMessage($post) + { + if (!isset($post['ft'])) { + return; + } + switch ($post['ft']) { + case "m1": + $this->quoteMessage($post['id']); + break; + case "m2": + if ($post['an'] == "[ally]") { + $this->sendAMessage( + $post['be'], + addslashes($post['message']) + ); + } else { + $this->sendMessage( + $post['an'], + $post['be'], + addslashes($post['message']) + ); + } + header("Location: nachrichten.php?t=2"); + exit; + case "m3": + case "m4": + case "m5": + if (isset($post['delmsg'])) { + $this->removeMessage($post); + } + if (isset($post['archive'])) { + $this->archiveMessage($post); + } + if (isset($post['start'])) { + $this->unarchiveMessage($post); + } + break; + case "m6": + $this->createNote($post); + break; + case "m7": + $this->addFriends($post); + break; + } + } - if(isset($post['ft'])) { - switch($post['ft']) { - case "m1": - $this->quoteMessage($post['id']); - break; - case "m2": - if ($post['an'] == "[ally]") $this->sendAMessage($post['be'],addslashes($post['message'])); - else $this->sendMessage($post['an'],$post['be'],addslashes($post['message'])); - header("Location: nachrichten.php?t=2"); - exit; - case "m3": - case "m4": - case "m5": - if(isset($post['delmsg']))$this->removeMessage($post); - if(isset($post['archive'])) $this->archiveMessage($post); - if(isset($post['start'])) $this->unarchiveMessage($post); - break; - case "m6": - $this->createNote($post); - break; - case "m7": - $this->addFriends($post); - break; - } - } - } + public function noticeType($get) + { + global $session, $database; + if (isset($get['t'])) { + switch ($get['t']) { + case 1: + $type = [8, 15, 16, 17]; + break; + case 2: + $type = [10, 11, 12, 13]; + break; + case 3: + $type = [1, 2, 3, 4, 5, 6, 7]; + break; + case 4: + $type = [0, 18, 19, 20, 21]; + break; + case 5: + if (!$session->plus) { + header("Location: berichte.php"); + exit; + } + $type = 9; + break; + default: + $type = []; + break; + } + if (!is_array($type)) { + $type = [$type]; + } + $this->noticearray = $this->filter_by_value( + $database->getNotice($session->uid), + "ntype", + $type + ); + } + if (isset($get['id'])) { + $this->readingNotice = $this->getReadNotice($get['id']); + } + } - public function noticeType($get) { - global $session, $database; - if(isset($get['t'])) { - if($get['t'] == 1) $type = [8, 15, 16, 17]; - if($get['t'] == 2) $type = [10, 11, 12, 13]; - if($get['t'] == 3) $type = [1, 2, 3, 4, 5, 6, 7]; - if($get['t'] == 4) $type = [0, 18, 19, 20, 21]; - if($get['t'] == 5) { - if(!$session->plus){ - header("Location: berichte.php"); - exit; - } - else $type = 9; - } - if (!is_array($type)) $type = [$type]; - $this->noticearray = $this->filter_by_value($database->getNotice($session->uid), "ntype", $type); - } - - if(isset($get['id'])) $this->readingNotice = $this->getReadNotice($get['id']); - } + public function procNotice($post) + { + if (isset($post["del_x"])) { + $this->removeNotice($post); + } + if (isset($post['archive_x'])) { + $this->archiveNotice($post); + } + if (isset($post['start_x'])) { + $this->unarchiveNotice($post); + } + } - public function procNotice($post) { - if(isset($post["del_x"])) $this->removeNotice($post); - if(isset($post['archive_x'])) $this->archiveNotice($post); - if(isset($post['start_x'])) $this->unarchiveNotice($post); - } + public function quoteMessage($id) + { + foreach ($this->inbox as $message) { + if ($message['id'] == $id) { + $message = preg_replace('/\[message\]/', '', $message); + $message = preg_replace('/\[\/message\]/', '', $message); + for ($i = 1; $i <= $message['alliance']; $i++) { + $message = preg_replace('/\[alliance' . $i . '\]/', '[alliance0]', $message); + $message = preg_replace('/\[\/alliance' . $i . '\]/', '[/alliance0]', $message); + } + for ($i = 0; $i <= $message['player']; $i++) { + $message = preg_replace('/\[player' . $i . '\]/', '[player0]', $message); + $message = preg_replace('/\[\/player' . $i . '\]/', '[/player0]', $message); + } + for ($i = 0; $i <= $message['coor']; $i++) { + $message = preg_replace('/\[coor' . $i . '\]/', '[coor0]', $message); + $message = preg_replace('/\[\/coor' . $i . '\]/', '[/coor0]', $message); + } + for ($i = 0; $i <= $message['report']; $i++) { + $message = preg_replace('/\[report' . $i . '\]/', '[report0]', $message); + $message = preg_replace('/\[\/report' . $i . '\]/', '[/report0]', $message); + } + $this->reply = $_SESSION['reply'] = $message; + header( + "Location: nachrichten.php?t=1&id=" . + $message['owner'] . + "&mid=" . + $message['id'] . + "&tid=" . + $message['target'] + ); + exit; + } + } + } - public function quoteMessage($id) { - foreach($this->inbox as $message) { - if($message['id'] == $id) { - $message = preg_replace('/\[message\]/', '', $message); - $message = preg_replace('/\[\/message\]/', '', $message); + public function loadMessage($id) + { + global $database, $session; + if ($this->findInbox($id)) { + foreach ($this->inbox as $message) { + if ($message['id'] == $id) { + $this->reading = $message; + break; + } + } + } + if ($this->findSent($id)) { + foreach ($this->sent as $message) { + if ($message['id'] == $id) { + $this->reading = $message; + break; + } + } + } - for($i = 1; $i <= $message['alliance']; $i++){ - $message = preg_replace('/\[alliance'.$i.'\]/', '[alliance0]', $message); - $message = preg_replace('/\[\/alliance'.$i.'\]/', '[/alliance0]', $message); - } + if ($session->plus && $this->findArchive($id)) { + foreach ($this->archived as $message) { + if ($message['id'] == $id) { + $this->reading = $message; + break; + } + } + } + if (!empty($this->reading) && $this->reading['viewed'] == 0) { + $database->getMessage($id, 4); + } + } - for($i = 0; $i <= $message['player']; $i++){ - $message = preg_replace('/\[player'.$i.'\]/', '[player0]', $message); - $message = preg_replace('/\[\/player'.$i.'\]/', '[/player0]', $message); - } + /** + * Filter array by value except specific value. + */ + private function filter_by_value_except($array, $index, $value) + { + $newarray = []; + if (is_array($array) && count($array) > 0) { + foreach ($array as $row) { + if (isset($row[$index]) && $row[$index] != $value) { + $newarray[] = $row; + } + } + } - for($i = 0; $i <= $message['coor']; $i++){ - $message = preg_replace('/\[coor'.$i.'\]/', '[coor0]', $message); - $message = preg_replace('/\[\/coor'.$i.'\]/', '[/coor0]', $message); - } + return $newarray; + } - for($i = 0; $i <= $message['report']; $i++){ - $message = preg_replace('/\[report'.$i.'\]/', '[report0]', $message); - $message = preg_replace('/\[\/report'.$i.'\]/', '[/report0]', $message); - } + /** + * Filter array by accepted values. + */ + private function filter_by_value($array, $index, $value) + { + $newarray = []; + if (is_array($array) && count($array) > 0) { + foreach ($array as $row) { + if ( + isset($row[$index]) && + in_array($row[$index], $value) + ) { + $newarray[] = $row; + } + } + } + return $newarray; + } - $this->reply = $_SESSION['reply'] = $message; - header("Location: nachrichten.php?t=1&id=" . $message['owner'] . "&mid=" . $message['id'] . "&tid=" . $message['target']); - exit; - } - } - } + private function getNotice() + { + global $database, $session; + $this->noticearray = $this->filter_by_value_except( + $database->getNotice($session->uid), + "ntype", + 9 + ); + } - public function loadMessage($id) { - global $database, $session; - - if($this->findInbox($id)) { - foreach($this->inbox as $message) { - if($message['id'] == $id) { - $this->reading = $message; - break; - } - } - } - - if($this->findSent($id)) { - foreach($this->sent as $message) { - if($message['id'] == $id) { - $this->reading = $message; - break; - } - } - } - - if($session->plus && $this->findArchive($id)) { - foreach($this->archived as $message) { - if($message['id'] == $id) { - $this->reading = $message; - break; - } - } - } - - if($this->reading['viewed'] == 0) $database->getMessage($id, 4); - } + /** + * Build selected IDs array from POST. + */ + private function collectSelectedIds($post, $limit = 10) + { + $ids = []; + for ($i = 1; $i <= $limit; $i++) { + if (isset($post['n' . $i])) { + $ids[] = (int)$post['n' . $i]; + } + } + return $ids; + } - private function filter_by_value_except($array, $index, $value) { - $newarray = []; - if(is_array($array) && count($array) > 0) { - foreach(array_keys($array) as $key) { - $temp[$key] = $array[$key][$index]; + private function removeMessage($post) + { + global $database, $session; + $post = $database->escape($post); + $mode5updates = []; + $mode7updates = []; + $mode8updates = []; + for ($i = 1; $i <= 10; $i++) { + if (!isset($post['n' . $i])) { + continue; + } + $messageId = (int)$post['n' . $i]; + $query = mysqli_query( + $database->dblink, + "SELECT target, owner + FROM " . TB_PREFIX . "mdata + WHERE id = " . $messageId . " + LIMIT 1" + ); + $message = mysqli_fetch_array($query); + if ( + $message['target'] == $session->uid && + $message['owner'] == $session->uid + ) { + $mode8updates[] = $messageId; + } elseif ($message['target'] == $session->uid) { + $mode5updates[] = $messageId; + } elseif ($message['owner'] == $session->uid) { + $mode7updates[] = $messageId; + } + } + if (!empty($mode5updates)) { + $database->getMessage($mode5updates, 5); + } + if (!empty($mode7updates)) { + $database->getMessage($mode7updates, 7); + } + if (!empty($mode8updates)) { + $database->getMessage($mode8updates, 8); + } + header("Location: nachrichten.php"); + exit; + } - if($temp[$key] != $value) { - array_push($newarray, $array[$key]); - //$newarray[$key] = $array[$key]; - } - } - } - return $newarray; - } - - private function filter_by_value($array, $index, $value) { - $newarray = []; - if(is_array($array) && count($array) > 0) { - foreach(array_keys($array) as $key) { - $temp[$key] = $array[$key][$index]; - - if(in_array($temp[$key], $value)) { - array_push($newarray, $array[$key]); - //$newarray[$key] = $array[$key]; - } - } - } - return $newarray; - } - - private function getNotice() { - global $database, $session; - - $this->noticearray = $this->filter_by_value_except($database->getNotice($session->uid), "ntype", 9); - } - - private function removeMessage($post) { - global $database, $session; - - $post = $database->escape($post); - $mode5updates = $mode7updates = $mode8updates = []; - - for($i = 1; $i <= 10; $i++){ - if(isset($post['n' . $i])){ - $message1 = mysqli_query($database->dblink, "SELECT target, owner FROM " . TB_PREFIX . "mdata where id = " . (int)$post['n' . $i] . ""); - $message = mysqli_fetch_array($message1); - - if($message['target'] == $session->uid && $message['owner'] == $session->uid) $mode8updates[] = $post['n' . $i]; - else if($message['target'] == $session->uid) $mode5updates[] = $post['n' . $i]; - else if($message['owner'] == $session->uid) $mode7updates[] = $post['n' . $i]; - } - } - - if(count($mode5updates)) $database->getMessage($mode5updates, 5); - if(count($mode7updates)) $database->getMessage($mode7updates, 7); - if(count($mode8updates)) $database->getMessage($mode8updates, 8); - - header("Location: nachrichten.php"); - exit; - } - - private function archiveMessage($post) { - global $database; - - $archIDs = []; - for($i = 1; $i <= 10; $i++) { - if(isset($post['n'.$i])) $archIDs[] = $post['n'.$i]; - } + private function archiveMessage($post) + { + global $database; + $archIDs = $this->collectSelectedIds($post); $database->setArchived($archIDs); + header("Location: nachrichten.php"); + exit; + } - header("Location: nachrichten.php"); - exit; - } - - private function unarchiveMessage($post) { - global $database; - - $normIDs = []; - for($i = 1; $i <= 10; $i++) { - if(isset($post['n'.$i])) $normIDs[] = $post['n'.$i]; - } + private function unarchiveMessage($post) + { + global $database; + $normIDs = $this->collectSelectedIds($post); $database->setNorm($normIDs); + header("Location: nachrichten.php"); + exit; + } - header("Location: nachrichten.php"); - exit; - } - - private function removeNotice($post) { - global $database; - - $removeIDs = []; - for($i = 1; $i <= 10; $i++) { - if(isset($post['n' . $i])) { - $removeIDs[] = $post['n' . $i]; - } - } - + private function removeNotice($post) + { + global $database; + $removeIDs = $this->collectSelectedIds($post); $database->removeNotice($removeIDs); + header("Location: berichte.php"); + exit; + } - header("Location: berichte.php"); - exit; - } - - private function archiveNotice($post) { - global $database; - - $archiveIDs = []; - for($i = 1; $i <= 10; $i++) { - if(isset($post['n' . $i])) { - $archiveIDs[] = $post['n' . $i]; - } - } - + private function archiveNotice($post) + { + global $database; + $archiveIDs = $this->collectSelectedIds($post); $database->archiveNotice($archiveIDs); + header("Location: berichte.php"); + exit; + } - header("Location: berichte.php"); - exit; - } - - private function unarchiveNotice($post) { - global $database; - - $unarchIDs = []; - for($i = 1; $i <= 10; $i++) { - if(isset($post['n' . $i])) { - $unarchIDs[] = $post['n' . $i]; - } - } - + private function unarchiveNotice($post) + { + global $database; + $unarchIDs = $this->collectSelectedIds($post); $database->unarchiveNotice($unarchIDs); + header("Location: berichte.php"); + exit; + } - header("Location: berichte.php"); - exit; - } + private function getReadNotice($id) + { + global $database, $session; + $notice = $database->getNotice2($id); + if ( + $notice['uid'] == $session->uid || + $notice['ally'] == $session->alliance + ) { + if ($notice['uid'] == $session->uid) { + $database->noticeViewed($notice['id']); + } + return $notice; + } + return null; + } - private function getReadNotice($id) { - global $database, $session; - - $notice = $database->getNotice2($id); - if($notice['uid'] == $session->uid || $notice['ally'] == $session->alliance){ - if($notice['uid'] == $session->uid) $database->noticeViewed($notice['id']); - return $notice; - } - else return null; - } + /** + * Not all notices have a corresponding .tpl file. + * This method maps them to existing report templates. + */ + public function getReportType($type) + { + switch ($type) { - /** - * Not all notices have a corresponding .tpl file but with this method it's like they have it - * - * @param int $type The type of the report (notice) - * @return int Returns the new report type - */ - - public function getReportType($type) - { - switch($type) - { - case 2: - case 4: - case 5: - case 6: - case 7: - case 18: - case 20: - case 21: return 1; //General attacking reports - - case 11: - case 12: - case 13: - case 14: return 10; //Merchants reports - - case 16: - case 17: return 15; //Reinforcements attacked - - case 19: return 3; //No troops have returned - - case 23: return 22; //Festive reports - } - - return $type; - } - - public function loadNotes() { - global $session; - if(file_exists("GameEngine/Notes/".md5($session->username).".txt")) { - $this->note = file_get_contents("GameEngine/Notes/".md5($session->username).".txt"); - } - else $this->note = ""; - } + // General attacking reports + case 2: + case 4: + case 5: + case 6: + case 7: + case 18: + case 20: + case 21: + return 1; - private function createNote($post) { - global $session; - if($session->plus) { - $ourFileHandle = fopen("GameEngine/Notes/".md5($session->username).".txt", 'w'); - fwrite($ourFileHandle, $post['notizen']); - fclose($ourFileHandle); - } - } + // Merchant reports + case 11: + case 12: + case 13: + case 14: + return 10; - private function getMessages($which) { - global $database, $session; + // Reinforcements attacked + case 16: + case 17: + return 15; - switch($which){ - case 1 : - $this->inbox = $database->getMessage($session->uid, 1); - $this->inbox1 = $database->getMessage($session->uid, 9); - break; - - case 2 : - $this->sent = $database->getMessage($session->uid, 2); - $this->sent1 = $database->getMessage($session->uid, 10); - break; - - case 3 : - if($session->plus){ - $this->archived = $database->getMessage($session->uid, 6); - $this->archived1 = $database->getMessage($session->uid, 11); - } - break; - } - } + // No troops returned + case 19: + return 3; - private function sendAMessage($topic,$text) { - global $session,$database; + // Festive reports + case 23: + return 22; + } + return $type; + } - // Vulnerability closed by Shadow + public function loadNotes() + { + global $session; + $noteFile = "GameEngine/Notes/" . md5($session->username) . ".txt"; + if (file_exists($noteFile)) { + $this->note = file_get_contents($noteFile); + } else { + $this->note = ""; + } + } - $q = "SELECT Count(*) as Total FROM ".TB_PREFIX."mdata WHERE owner='".$session->uid."' AND time > ".(time() - 60); - $res = mysqli_fetch_array(mysqli_query($database->dblink,$q), MYSQLI_ASSOC); - if($res['Total'] > 5) return; //flooding prevention + private function createNote($post) + { + global $session; + if (!$session->plus) { + return; + } + $noteFile = "GameEngine/Notes/" . md5($session->username) . ".txt"; + $ourFileHandle = fopen($noteFile, 'w'); + fwrite($ourFileHandle, $post['notizen']); + fclose($ourFileHandle); + } + private function getMessages($which) + { + global $database, $session; + switch ($which) { + case 1: + $this->inbox = $database->getMessage($session->uid, 1); + $this->inbox1 = $database->getMessage($session->uid, 9); + break; + case 2: + $this->sent = $database->getMessage($session->uid, 2); + $this->sent1 = $database->getMessage($session->uid, 10); + break; + case 3: + if ($session->plus) { + $this->archived = $database->getMessage($session->uid, 6); + $this->archived1 = $database->getMessage($session->uid, 11); + } + break; + } + } - // Vulnerability closed by Shadow + /** + * Normalize nested BBCode counters. + */ + private function normalizeMessageTags(&$text, &$alliance, &$player, &$coor, &$report) + { + 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++; + } + } + } + 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++; + } + } + } + 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++; + } + } + } + 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++; + } + } + } + } - $allmembersQ = mysqli_query($database->dblink,"SELECT id FROM ".TB_PREFIX."users WHERE alliance='".$session->alliance."'"); - $userally = $database->getUserField($session->uid,"alliance",0); - $permission=mysqli_fetch_array(mysqli_query($database->dblink,"SELECT opt7 FROM ".TB_PREFIX."ali_permission WHERE uid='".$session->uid."'")); + private function sendAMessage($topic, $text) + { + global $session, $database; - if(defined('WORD_CENSOR')) { + // Flood protection + $q = " + SELECT COUNT(*) AS Total + FROM " . TB_PREFIX . "mdata + WHERE owner='" . $session->uid . "' + AND time > " . (time() - 60); + $res = mysqli_fetch_array( + mysqli_query($database->dblink, $q), + MYSQLI_ASSOC + ); + if ($res['Total'] > 5) { + return; + } + $allmembersQ = mysqli_query( + $database->dblink, + "SELECT id + FROM " . TB_PREFIX . "users + WHERE alliance='" . $session->alliance . "'" + ); + $userally = $database->getUserField($session->uid, "alliance", 0); + $permission = mysqli_fetch_array( + mysqli_query( + $database->dblink, + "SELECT opt7 + FROM " . TB_PREFIX . "ali_permission + WHERE uid='" . $session->uid . "'" + ) + ); + if (defined('WORD_CENSOR')) { $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; - } - } - } - - if($permission['opt7'] == 1){ + $text = $this->wordCensor($text); + } + if ($topic == "") { + $topic = "No subject"; + } + if ( + !preg_match('/\[message\]/', $text) && + !preg_match('/\[\/message\]/', $text) + ) { + $text = "[message]" . $text . "[/message]"; + $alliance = 0; + $player = 0; + $coor = 0; + $report = 0; + $this->normalizeMessageTags( + $text, + $alliance, + $player, + $coor, + $report + ); + 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); + $database->sendMessage( + $allmembers['id'], + $session->uid, + htmlspecialchars(addslashes($topic)), + htmlspecialchars(addslashes($text)), + 0, + $alliance, + $player, + $coor, + $report + ); } } } - } - } - - private function sendMessage($recieve, $topic, $text, $security_check = true) { - global $session, $database; - $user = $database->getUserField($recieve, "id", 1); - - // Vulnerability closed by Shadow - if ($security_check) { - $q = "SELECT Count(*) as Total FROM ".TB_PREFIX."mdata WHERE owner='".$session->uid."' AND time > ".(time() - 60); - $res = mysqli_fetch_array(mysqli_query($database->dblink,$q), MYSQLI_ASSOC); - if($res['Total'] > 5) return; //flooding prevention - } - - // Vulnerability closed by Shadow - if(defined('WORD_CENSOR')) { - $topic = $this->wordCensor($topic); - $text = $this->wordCensor($text); - } - - if(empty($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 or Multihunter - $support_from_admin_allowed = ($session->access == ADMIN && ADMIN_RECEIVE_SUPPORT_MESSAGES); - $send_as = $session->uid; - - // send as Support? - if((!empty($_POST['as_support']) && $support_from_admin_allowed)) $send_as = 1; - - // send as Multihunter - if((!empty($_POST['as_multihunter']) && $session->access == MULTIHUNTER)) $send_as = 5; - - $database->sendMessage($user, $send_as, htmlspecialchars(addslashes($topic)), htmlspecialchars(addslashes($text)), 0, $alliance, $player, $coor, $report); } - } + } - public function sendWelcome($uid, $username) { - global $database; + private function sendMessage($recieve, $topic, $text, $security_check = true) + { + global $session, $database; + $user = $database->getUserField($recieve, "id", 1); - $welcomemsg = file_get_contents("GameEngine/Admin/welcome.tpl"); - $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))], + // Flood protection + if ($security_check) { + $q = " + SELECT COUNT(*) AS Total + FROM " . TB_PREFIX . "mdata + WHERE owner='" . $session->uid . "' + AND time > " . (time() - 60); + + $res = mysqli_fetch_array( + mysqli_query($database->dblink, $q), + MYSQLI_ASSOC + ); + if ($res['Total'] > 5) { + return; + } + } + if (defined('WORD_CENSOR')) { + $topic = $this->wordCensor($topic); + $text = $this->wordCensor($text); + } + if (empty($topic)) { + $topic = "No subject"; + } + if ( + !preg_match('/\[message\]/', $text) && + !preg_match('/\[\/message\]/', $text) + ) { + $text = "[message]" . $text . "[/message]"; + $alliance = 0; + $player = 0; + $coor = 0; + $report = 0; + $this->normalizeMessageTags( + $text, + $alliance, + $player, + $coor, + $report + ); + + // Default sender + $send_as = $session->uid; + + // Support messages + $support_from_admin_allowed = + ($session->access == ADMIN && ADMIN_RECEIVE_SUPPORT_MESSAGES); + if ( + !empty($_POST['as_support']) && + $support_from_admin_allowed + ) { + $send_as = 1; + } + + // Multihunter messages + if ( + !empty($_POST['as_multihunter']) && + $session->access == MULTIHUNTER + ) { + $send_as = 5; + } + $database->sendMessage( + $user, + $send_as, + htmlspecialchars(addslashes($topic)), + htmlspecialchars(addslashes($text)), + 0, + $alliance, + $player, + $coor, + $report + ); + } + } + + public function sendWelcome($uid, $username) + { + global $database; + $welcomemsg = file_get_contents("GameEngine/Admin/welcome.tpl"); + $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]"; + ) . "[/message]"; + return $database->sendMessage( + $uid, + 1, + WEL_TOPIC, + addslashes($welcomemsg), + 0, + 0, + 0, + 0, + 0 + ); + } - return $database->sendMessage($uid, 1, WEL_TOPIC, addslashes($welcomemsg), 0, 0, 0, 0, 0); - } + private function wordCensor($text) + { + $censorarray = explode(",", CENSORED); + foreach ($censorarray as $key => $value) { + $censorarray[$key] = "/" . $value . "/i"; + } + return preg_replace($censorarray, "****", $text); + } - private function wordCensor($text) { - $censorarray = explode(",", CENSORED); - foreach($censorarray as $key => $value) { - $censorarray[$key] = "/" . $value . "/i"; - } - return preg_replace($censorarray, "****", $text); - } - - private function checkUnread() { - global $database, $session; - - return $database->getUnreadMessagesCount($session->uid); - } - - private function checkNUnread() { + private function checkUnread() + { global $database, $session; + return $database->getUnreadMessagesCount($session->uid); + } + private function checkNUnread() + { + global $database, $session; return $database->getUnreadNoticesCount($session->uid); - } + } - private function findInbox($id) { - if(!empty($this->inbox)){ - foreach($this->inbox as $message){ - if($message['id'] == $id) return true; - } - } - return false; - } + private function findInbox($id) + { + if (!empty($this->inbox)) { + foreach ($this->inbox as $message) { + if ($message['id'] == $id) { + return true; + } + } + } + return false; + } - private function findSent($id){ - if(!empty($this->sent)){ - foreach($this->sent as $message){ - if($message['id'] == $id) return true; - } - } - return false; - } + private function findSent($id) + { + if (!empty($this->sent)) { + foreach ($this->sent as $message) { + if ($message['id'] == $id) { + return true; + } + } + } + return false; + } - private function findArchive($id){ - if(!empty($this->archived)){ - foreach($this->archived as $message){ - if($message['id'] == $id) return true; - } - } - - return false; - } + private function findArchive($id) + { + if (!empty($this->archived)) { + foreach ($this->archived as $message) { + if ($message['id'] == $id) { + return true; + } + } + } + return false; + } - 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(); - } + public function addFriends($post) + { + global $database; + for ($i = 0; $i <= 19; $i++) { + if (empty($post['addfriends' . $i])) { + continue; + } + $uid = $database->getUserField( + $post['addfriends' . $i], + "id", + 1 + ); + $added = 0; + for ($j = 0; $j <= $i; $j++) { -}; + if ($added != 0) { + continue; + } + $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 || $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(); + } +}; \ No newline at end of file diff --git a/GameEngine/Profile.php b/GameEngine/Profile.php index 9d16f0df..c2d602db 100755 --- a/GameEngine/Profile.php +++ b/GameEngine/Profile.php @@ -4,220 +4,312 @@ ## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ## ## --------------------------------------------------------------------------- ## ## Filename Profile.php ## +## Filename: Account.php ## +## Developed by: Dzoki ## +## Refactored by: Shadow ## ## License: TravianZ Project ## -## Copyright: TravianZ (c) 2010-2025. All rights reserved. ## +## Copyright: TravianZ (c) 2010-2026. All rights reserved. ## +## URLs: https://travianz.org ## +## https://github.com/Shadowss/TravianZ ## ## ## +## Refactor notes (2026): ## +## - Incremental optimization (no logic changes) ## +## - Reduced repeated calls / minor optimizations ## +## - Added lightweight per-request caching ## +## - Improved readability + structure ## +## - PHP 7+ compatible ## ################################################################################# - class Profile { + + /** + * Simple in-request cache (prevents duplicate DB calls inside same request) + */ + private static $cache = [ + 'vac_check' => [], + 'villages' => [] + ]; + public function procProfile($post) { global $session; - - if(isset($post['ft'])) { - switch($post['ft']) { - case "p1" : + + if (isset($post['ft'])) { + switch ($post['ft']) { + case "p1": $this->updateProfile($post); break; - case "p3" : + + case "p3": $this->updateAccount($post); break; - case "p4" : + + case "p4": $this->setvactionmode($post); break; } } - - if(isset($post['s']) && $post['s'] == 4) $this->gpack($post); + + if (isset($post['s']) && $post['s'] == 4) { + $this->gpack($post); + } } public function procSpecial($get) { - global $session; - - if(isset($get['e'])) { - switch($get['e']) { - case 2 : + if (isset($get['e'])) { + switch ($get['e']) { + case 2: $this->removeMeSit($get); break; - case 3 : + + case 3: $this->removeSitter($get); break; - case 4 : + + case 4: $this->cancelDeleting($get); break; } } } + /** + * Update player profile + village names + */ private function updateProfile($post) { global $database, $session; - - $birthday = $post['jahr'].'-'.$post['monat'].'-'.$post['tag']; - $database->submitProfile($session->uid, $database->RemoveXSS($post['mw']), $database->RemoveXSS($post['ort']), $database->RemoveXSS($birthday), $database->RemoveXSS($post['be2']), $database->RemoveXSS($post['be1'])); - $varray = $database->getProfileVillages($session->uid); - - for($i = 0; $i < count($varray); $i++){ - $database->setVillageName($varray[$i]['wref'], $database->RemoveXSS(trim($post['dname'.$i]))); + + $birthday = $post['jahr'] . '-' . $post['monat'] . '-' . $post['tag']; + + $database->submitProfile( + $session->uid, + $database->RemoveXSS($post['mw']), + $database->RemoveXSS($post['ort']), + $database->RemoveXSS($birthday), + $database->RemoveXSS($post['be2']), + $database->RemoveXSS($post['be1']) + ); + + // Cache villages per request + if (!isset(self::$cache['villages'][$session->uid])) { + self::$cache['villages'][$session->uid] = $database->getProfileVillages($session->uid); } - - header("Location: spieler.php?uid=".$session->uid); + + $varray = self::$cache['villages'][$session->uid]; + $cnt = count($varray); + + for ($i = 0; $i < $cnt; $i++) { + if (!isset($post['dname' . $i])) continue; + + $database->setVillageName( + $varray[$i]['wref'], + $database->RemoveXSS(trim($post['dname' . $i])) + ); + } + + header("Location: spieler.php?uid=" . $session->uid); exit; } + /** + * Gpack settings + */ private function gpack($post) { global $database, $session; - - $database->gpack($database->RemoveXSS($session->uid),$database->RemoveXSS($post['custom_url'])); - header("Location: spieler.php?uid=".$session->uid); + + $database->gpack( + $database->RemoveXSS($session->uid), + $database->RemoveXSS($post['custom_url']) + ); + + header("Location: spieler.php?uid=" . $session->uid); exit; } - - /** - * Function to vacation mode - by advocaite and Shadow - * - * @param array $post The $_POST array - */ - private function setvactionmode($post){ + /** + * Vacation mode activation + */ + private function setvactionmode($post) { global $database, $session; - if(isset($post['vac']) && $post['vac'] && isset($post['vac_days']) && $post['vac_days'] >= 2 && $post['vac_days'] <= 14){ + if (isset($post['vac']) && $post['vac'] && isset($post['vac_days']) && $post['vac_days'] >= 2 && $post['vac_days'] <= 14) { - $check = $database->checkVacationRequirements($session->uid); - - if($check !== true){ + $uid = $session->uid; - $messages = [ - "TROOPS_MOVING" => "You still have troops moving", - "INCOMING_TROOPS" => "You have incoming troops", - "REINFORCEMENTS" => "You have reinforcements on your villages", - "WW" => "You own a Wonder of the World", - "ARTEFACTS" => "You own artefacts", - "PROTECTION" => "You are still under beginner protection", - "PRISONERS_IN" => "No units trapped in your traps", - "PRISONERS_OUT" => "No units in enemy traps", - "MARKET" => "Marketplace transport active", - "ACCOUNT_DELETION" => "Account is scheduled for deletion" - ]; + // Cache check per request (avoid duplicate heavy checks) + if (!isset(self::$cache['vac_check'][$uid])) { + self::$cache['vac_check'][$uid] = $database->checkVacationRequirements($uid); + } - $output = ""; + $check = self::$cache['vac_check'][$uid]; - foreach($check as $err){ - $output .= ($messages[$err] ?? $err) . "
"; - } + if ($check !== true) { - $_SESSION['vac_error'] = $output; + $messages = [ + "TROOPS_MOVING" => "You still have troops moving", + "INCOMING_TROOPS" => "You have incoming troops", + "REINFORCEMENTS" => "You have reinforcements on your villages", + "WW" => "You own a Wonder of the World", + "ARTEFACTS" => "You own artefacts", + "PROTECTION" => "You are still under beginner protection", + "PRISONERS_IN" => "No units trapped in your traps", + "PRISONERS_OUT" => "No units in enemy traps", + "MARKET" => "Marketplace transport active", + "ACCOUNT_DELETION" => "Account is scheduled for deletion" + ]; - header("Location: spieler.php?s=5"); - exit; -} + $output = ""; - // TOTUL OK → intră în vacanță - unset($_SESSION['wid']); - $database->setvacmode($session->uid, $post['vac_days']); - $database->activeModify(addslashes($session->username), 1); - $database->UpdateOnline("logout"); - $session->Logout(); + foreach ($check as $err) { + $output .= (isset($messages[$err]) ? $messages[$err] : $err) . "
"; + } - header("Location: login.php"); - exit; + $_SESSION['vac_error'] = $output; - } else { - $_SESSION['vac_error'] = "Vacation days must be between 2 and 14"; - header("Location: spieler.php?s=5"); - exit; - } -} + header("Location: spieler.php?s=5"); + exit; + } + + // OK -> enter vacation mode + unset($_SESSION['wid']); + + $database->setvacmode($uid, $post['vac_days']); + $database->activeModify(addslashes($session->username), 1); + $database->UpdateOnline("logout"); + + $session->Logout(); + + header("Location: login.php"); + exit; + + } else { + $_SESSION['vac_error'] = "Vacation days must be between 2 and 14"; + header("Location: spieler.php?s=5"); + exit; + } + } /** - * Function to vacation mode - by advocaite and Shadow - * - * @param array $post The $_POST array + * Update account settings (password, email, sitter, deletion) */ - private function updateAccount($post) { global $database, $session, $form; - if(!empty($post['pw1']) && !empty($post['pw2']) && !empty($post['pw3'])){ - if($post['pw2'] == $post['pw3']){ - if($database->login($session->username, $post['pw1'])){ - $database->updateUserField($session->uid, "password", password_hash($post['pw2'], PASSWORD_BCRYPT, ['cost' => 12]), 1); + // Password change + if (!empty($post['pw1']) && !empty($post['pw2']) && !empty($post['pw3'])) { + + if ($post['pw2'] == $post['pw3']) { + + if ($database->login($session->username, $post['pw1'])) { + $database->updateUserField( + $session->uid, + "password", + password_hash($post['pw2'], PASSWORD_BCRYPT, ['cost' => 12]), + 1 + ); + } else { + $form->addError("pw", LOGIN_PW_ERROR); } - else $form->addError("pw", LOGIN_PW_ERROR); + + } else { + $form->addError("pw", PASS_MISMATCH); } - else $form->addError("pw", PASS_MISMATCH); } - if(!empty($post['email_alt']) && !empty($post['email_neu'])){ - if($post['email_alt'] == $session->userinfo['email']){ + // Email change + if (!empty($post['email_alt']) && !empty($post['email_neu'])) { + + if ($post['email_alt'] == $session->userinfo['email']) { $database->updateUserField($session->uid, "email", $post['email_neu'], 1); + } else { + $form->addError("email", EMAIL_ERROR); } - else $form->addError("email", EMAIL_ERROR); } - - if(!empty($post['del_pw']) && $post['del']){ - if(password_verify($post['del_pw'], $session->userinfo['password'])){ + + // Delete request cancel + if (!empty($post['del_pw']) && !empty($post['del'])) { + + if (password_verify($post['del_pw'], $session->userinfo['password'])) { $database->setDeleting($session->uid, 0); + } else { + $form->addError("del", PASS_MISMATCH); } - else $form->addError("del", PASS_MISMATCH); } - - if(!empty($post['v1'])){ + + // Sitter assignment + if (!empty($post['v1'])) { + $sitid = $database->getUserField($post['v1'], "id", 1); - if($sitid == $session->userinfo['sit1'] || $sitid == $session->userinfo['sit2']){ + + if ($sitid == $session->userinfo['sit1'] || $sitid == $session->userinfo['sit2']) { $form->addError("sit", SIT_ERROR); - }else if($sitid != $session->uid){ - if($session->userinfo['sit1'] == 0){ + + } else if ($sitid != $session->uid) { + + if ($session->userinfo['sit1'] == 0) { $database->updateUserField($session->uid, "sit1", $sitid, 1); - }else if($session->userinfo['sit2'] == 0){ + + } else if ($session->userinfo['sit2'] == 0) { $database->updateUserField($session->uid, "sit2", $sitid, 1); } } } - - if($form->returnErrors() > 0){ + + // Persist errors if any + if ($form->returnErrors() > 0) { $_SESSION['errorarray'] = $form->getErrors(); $_SESSION['valuearray'] = $_POST; - } - + } + header("Location: spieler.php?s=3"); exit; } + /** + * Remove sitter + */ private function removeSitter($get) { - global $database,$session; + 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); + 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']); + header("Location: spieler.php?s=" . $get['s']); exit; } + /** + * Cancel account deletion + */ private function cancelDeleting($get) { global $database, $session; - - $database->setDeleting($session->uid,1); - header("Location: spieler.php?s=".$get['s']); + + $database->setDeleting($session->uid, 1); + + header("Location: spieler.php?s=" . $get['s']); exit; } + /** + * Remove me as sitter + */ private function removeMeSit($get) { global $database, $session; - if($get['a'] == $session->checker) { - $database->removeMeSit($get['id'],$session->uid); + if ($get['a'] == $session->checker) { + $database->removeMeSit($get['id'], $session->uid); $session->changeChecker(); } - header("Location: spieler.php?s=".$get['s']); + header("Location: spieler.php?s=" . $get['s']); exit; } -}; +} $profile = new Profile; -?> +?> \ No newline at end of file diff --git a/GameEngine/Ranking.php b/GameEngine/Ranking.php index 9f81f164..7aaa5de5 100755 --- a/GameEngine/Ranking.php +++ b/GameEngine/Ranking.php @@ -8,29 +8,28 @@ ## Filename: Ranking.php ## ## Developed by: Dzoki & Dixie ## ## Refactored by: Shadow ## -## Fixed by: InCube - double troops ## ## Reworked/Fix: ronix ## ## Thanks to: Akakori, Elmar & Kirilloid ## +## ## ## License: TravianZ Project ## ## Copyright: TravianZ (c) 2010-2026. All rights reserved. ## -## ## -## URLs: http://travian.shadowss.ro ## +## URLs: https://travianz.org ## ## https://github.com/Shadowss/TravianZ ## ## ## ################################################################################# - class Ranking { + class Ranking { - public $rankarray = []; - private $rlastupdate; + public $rankarray = []; + private $rlastupdate; /***************************************** Function to get rank *****************************************/ - public function getRank() { - return $this->rankarray; - } + public function getRank() { + return $this->rankarray; + } /***************************************** Function to finalize rank array @@ -44,11 +43,11 @@ Function to start by rank *****************************************/ - private function setStartByRank($value, $field, $fallback = 1): void { - $rank = $this->searchRank($value, $field); - if($rank != 0) { - $this->getStart($rank); - } else { + private function setStartByRank($value, $field, $fallback = 1): void { + $rank = $this->searchRank($value, $field); + if($rank != 0) { + $this->getStart($rank); + } else { $this->getStart($fallback); } } @@ -57,7 +56,7 @@ Function to get user rank *****************************************/ - public function getUserRank($id) { + public function getUserRank($id) { $ranking = $this->getRank(); if(count($ranking) > 0) { foreach($ranking as $key => $row) { diff --git a/autoloader.php b/autoloader.php index c44eb27e..06ba6f45 100644 --- a/autoloader.php +++ b/autoloader.php @@ -6,6 +6,7 @@ ## Project: TravianZ ## ## Filename autoloader.php ## ## Developed by: Dzoki ## +## Refactored by: Shadow ## ## License: TravianZ Project ## ## Copyright: TravianZ (c) 2010-2026. All rights reserved. ## ## URLs: http://travian.shadowss.ro ## @@ -13,25 +14,37 @@ ## ## ################################################################################# - function autoloadClass($class) { - // strip the App classname's namespace - $clazz = str_replace(['App\\', '\\'], ['', '/'], $class); + function autoloadClass($class) { - // search for class - $class_found = false; - // go max 5 levels up - we don't have folders that go deeper than that - for ($i = 0; $i < 5; $i++) { - $autoprefix = str_repeat('../', $i); - if (file_exists($autoprefix.'src/' . $clazz . '.php')) { - $class_found = true; - include_once $autoprefix.'src/' . $clazz . '.php'; - break; - } + $clazz = str_replace(['App\\', '\\'], ['', '/'], $class); + + $class_found = false; + + for ($i = 0; $i < 5; $i++) { + $autoprefix = str_repeat('../', $i); + + // 1. default path (actual) + $path1 = $autoprefix . 'src/' . $clazz . '.php'; + + // 2. fallback GameEngine (YOUR CASE) + $path2 = $autoprefix . 'GameEngine/' . $clazz . '.php'; + + if (file_exists($path1)) { + include_once $path1; + $class_found = true; + break; } - if (!$class_found) { - throw new Exception('Unable to find class ' . $clazz . '.'); + if (file_exists($path2)) { + include_once $path2; + $class_found = true; + break; } } + if (!$class_found) { + throw new Exception('Unable to find class ' . $clazz . '.'); + } +} + spl_autoload_register('autoloadClass'); \ No newline at end of file